You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@airflow.apache.org by "AlejandroMorgante (via GitHub)" <gi...@apache.org> on 2026/05/26 04:58:48 UTC

[PR] Add `DmsModifyTaskOperator` [airflow]

AlejandroMorgante opened a new pull request, #67524:
URL: https://github.com/apache/airflow/pull/67524

   ## What
   
   Adds `DmsModifyTaskOperator`, `DmsTaskStoppedTrigger`, and a `modify_replication_task` hook method to the Amazon provider.
   
   ## Motivation
   
   AWS DMS CDC tasks sometimes lose their binlog position (e.g. after a source failover or a long outage). Today there is no way to update a task's table mappings or CDC start position from within Airflow — users have to delete and recreate the task manually. A dedicated modify operator closes that gap and enables fully automated backfill workflows.
   
   ## Why these changes are needed
   
   - `DmsModifyTaskOperator` — wraps `modify_replication_task` and handles the full pre-modify lifecycle (stop-if-running, wait-if-modifying, then modify).
   - `DmsTaskStoppedTrigger` — deferrable trigger that waits for a running task to reach `stopped` state before the modify is issued, avoiding blocking a worker slot.
   - `DmsHook.modify_replication_task` — thin wrapper around the boto3 API, serialising dict arguments to JSON.
   
   ## Files changed
   
   | File | Change |
   |---|---|
   | `hooks/dms.py` | Add `modify_replication_task()` |
   | `triggers/dms.py` | Add `DmsTaskStoppedTrigger` |
   | `operators/dms.py` | Add `DmsModifyTaskOperator` (sync + deferrable) |
   | `tests/.../test_dms.py` | 10 new unit tests for the operator |
   | `tests/system/.../example_dms.py` | Add howto snippet |
   | `docs/operators/dms.rst` | Add "Modify a replication task" section |
   
   ## Testing
   
   - All 10 new unit tests pass (`pytest providers/amazon/tests/provider_tests/amazon/aws/operators/test_dms.py::TestDmsModifyTaskOperator`).
   - Validated end-to-end against real AWS (us-east-1, `dms.t3.small`): ran a DAG that modified `TableMappings` from `original_schema/%` to `backfill_schema/specific_table` and back; confirmed via `describe-replication-tasks` that the change was applied correctly.
   - `ruff check` passes on all modified Python files.


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: commits-unsubscribe@airflow.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] Add `DmsModifyTaskOperator` [airflow]

Posted by "SameerMesiah97 (via GitHub)" <gi...@apache.org>.
SameerMesiah97 commented on code in PR #67524:
URL: https://github.com/apache/airflow/pull/67524#discussion_r3329166985


##########
providers/amazon/src/airflow/providers/amazon/aws/operators/dms.py:
##########
@@ -118,6 +121,274 @@ def execute(self, context: Context):
         return task_arn
 
 
+class DmsModifyTaskOperator(AwsBaseOperator[DmsHook]):
+    """
+    Modifies an existing AWS DMS replication task.
+
+    If the task is not already stopped, set ``stop_task_before=True`` to stop it first.
+    To restart the task after modification, set ``restart_task_after=True``.
+
+    .. seealso::
+        For more information on how to use this operator, take a look at the guide:
+        :ref:`howto/operator:DmsModifyTaskOperator`
+
+    :param replication_task_arn: Replication task ARN
+    :param table_mappings: New table mappings. If not provided, existing mappings are kept.
+    :param migration_type: Migration type ('full-load'|'cdc'|'full-load-and-cdc').
+        If not provided, existing type is kept.
+    :param replication_task_settings: Task settings dict. If not provided, existing settings are kept.
+    :param cdc_start_time: Start time for CDC.
+    :param cdc_start_position: Indicates when to start CDC (checkpoint or LSN/SCN format).
+        Mutually exclusive with cdc_start_time.
+    :param cdc_stop_position: Indicates when to stop CDC.
+    :param stop_task_before: If True, stop the task before modifying if it is not already stopped.
+    :param restart_task_after: If True, restart the task after modifying.
+    :param start_replication_task_type: Start type used when restarting the task.
+        One of 'start-replication', 'resume-processing', or 'reload-target'.
+        Defaults to 'resume-processing'. Only used when ``restart_task_after=True``.
+    :param wait_for_completion: Only applies when the task is already in ``modifying`` state
+        when ``execute()`` is called. If True, wait for the modification to finish before
+        proceeding. If False, raises immediately instead of waiting.
+    :param deferrable: Run the operator in deferrable mode.
+    :param waiter_delay: Seconds between waiter polls (default: 30).
+    :param waiter_max_attempts: Maximum waiter poll attempts (default: 60).
+    :param aws_conn_id: The Airflow connection used for AWS credentials.
+        If this is ``None`` or empty then the default boto3 behaviour is used. If
+        running Airflow in a distributed manner and aws_conn_id is None or
+        empty, then default boto3 configuration would be used (and must be
+        maintained on each worker node).
+    :param region_name: AWS region_name. If not specified then the default boto3 behaviour is used.
+    :param verify: Whether or not to verify SSL certificates. See:
+        https://boto3.amazonaws.com/v1/documentation/api/latest/reference/core/session.html
+    :param botocore_config: Configuration dictionary (key-values) for botocore client. See:
+        https://botocore.amazonaws.com/v1/documentation/api/latest/reference/config.html
+    """
+
+    STOPPED_STATES = ("stopped", "ready", "failed", "created")
+    TERMINAL_STATES = frozenset({"failed", "stopped", "ready", "created", "deleting"})

Review Comment:
   I believe it would be better to move this state category i.e `MODIFIABLE_STATES` in to the hook itself so that you can use them in both the operator and trigger without risk of code drift. Also, after inspecting the hook more closely, it seems like it would be better to just reuse the existing enum class (adding any additional `ENUM` attributes you require) instead of creating a new enum class. Keep in mind that it is acceptable to compose new `ENUM` attributes using existing ones for e.g. `MODIFIABLE_STATES = (STOPPED, READY, FAILED)`
   
   I apologize if I was not as clear before. I did not look at the hook as closely when I made that suggestion. 



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: commits-unsubscribe@airflow.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] Add `DmsModifyTaskOperator` [airflow]

Posted by "AlejandroMorgante (via GitHub)" <gi...@apache.org>.
AlejandroMorgante commented on code in PR #67524:
URL: https://github.com/apache/airflow/pull/67524#discussion_r3349559024


##########
providers/amazon/src/airflow/providers/amazon/aws/waiters/dms.json:
##########
@@ -95,6 +95,85 @@
                     "state": "success"
                 }
             ]
+        },
+        "replication_task_modified": {
+            "operation": "DescribeReplicationTasks",
+            "delay": 30,
+            "maxAttempts": 60,
+            "acceptors": [
+                {
+                    "matcher": "path",
+                    "argument": "ReplicationTasks[0].Status",
+                    "expected": "modifying",
+                    "state": "retry"
+                },
+                {
+                    "matcher": "path",
+                    "argument": "ReplicationTasks[0].Status",
+                    "expected": "stopped",
+                    "state": "success"
+                },
+                {
+                    "matcher": "path",
+                    "argument": "ReplicationTasks[0].Status",
+                    "expected": "ready",
+                    "state": "success"
+                },
+                {
+                    "matcher": "path",
+                    "argument": "ReplicationTasks[0].Status",
+                    "expected": "failed",
+                    "state": "success"

Review Comment:
   Yes, in this waiter `success` means the async modification phase has completed, not that the replication task is healthy/runnable.
   
   DMS does not expose a separate `modify-failed` task state. If the `ModifyReplicationTask` API call itself fails,
   boto3 raises an error immediately before the waiter starts. Once the API call is accepted, the task enters `modifying`, and this waiter only waits for it to leave that state. 
   
   `stopped`, `ready`, and `failed` are all terminal states for that wait. `failed` is included because users may modify a failed task to fix its configuration, and the task can remain in `failed` until they explicitly start/retry it afterwards.
   
     So `failed` here means "the modification wait is complete", not "replication succeeded".



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: commits-unsubscribe@airflow.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] Add `DmsModifyTaskOperator` [airflow]

Posted by "SameerMesiah97 (via GitHub)" <gi...@apache.org>.
SameerMesiah97 commented on code in PR #67524:
URL: https://github.com/apache/airflow/pull/67524#discussion_r3329244622


##########
providers/amazon/src/airflow/providers/amazon/aws/operators/dms.py:
##########
@@ -118,6 +120,178 @@ def execute(self, context: Context):
         return task_arn
 
 
+class DmsModifyTaskOperator(AwsBaseOperator[DmsHook]):
+    """
+    Modifies an existing AWS DMS replication task.
+
+    The task must already be stopped before modification. Use :class:`DmsStopTaskOperator`
+    upstream in the Dag to stop it, and :class:`DmsStartTaskOperator` downstream to restart
+    it afterwards if needed.
+
+    .. seealso::
+        For more information on how to use this operator, take a look at the guide:
+        :ref:`howto/operator:DmsModifyTaskOperator`
+
+    :param replication_task_arn: Replication task ARN
+    :param table_mappings: New table mappings. If not provided, existing mappings are kept.
+    :param migration_type: Migration type ('full-load'|'cdc'|'full-load-and-cdc').
+        If not provided, existing type is kept.
+    :param replication_task_settings: Task settings dict. If not provided, existing settings are kept.
+    :param cdc_start_time: Start time for CDC.
+    :param cdc_start_position: Indicates when to start CDC (checkpoint or LSN/SCN format).
+        Mutually exclusive with cdc_start_time.
+    :param cdc_stop_position: Indicates when to stop CDC.
+    :param wait_for_completion: If True, wait for the modification to finish before returning.
+        In deferrable mode the operator defers rather than blocking. Defaults to True.
+    :param deferrable: Run the operator in deferrable mode. Defaults to False.
+    :param waiter_delay: Seconds between waiter polls (default: 30).
+    :param waiter_max_attempts: Maximum waiter poll attempts (default: 60).
+    :param aws_conn_id: The Airflow connection used for AWS credentials.
+        If this is ``None`` or empty then the default boto3 behaviour is used. If
+        running Airflow in a distributed manner and aws_conn_id is None or
+        empty, then default boto3 configuration would be used (and must be
+        maintained on each worker node).
+    :param region_name: AWS region_name. If not specified then the default boto3 behaviour is used.
+    :param verify: Whether or not to verify SSL certificates. See:
+        https://boto3.amazonaws.com/v1/documentation/api/latest/reference/core/session.html
+    :param botocore_config: Configuration dictionary (key-values) for botocore client. See:
+        https://botocore.amazonaws.com/v1/documentation/api/latest/reference/config.html
+    """
+
+    MODIFIABLE_STATES = frozenset({DmsTaskState.STOPPED, DmsTaskState.READY, DmsTaskState.FAILED})
+
+    aws_hook_class = DmsHook
+    template_fields: Sequence[str] = aws_template_fields(
+        "replication_task_arn",
+        "table_mappings",
+        "migration_type",
+        "replication_task_settings",
+        "cdc_start_time",
+        "cdc_start_position",
+        "cdc_stop_position",
+    )
+    template_fields_renderers: ClassVar[dict] = {
+        "table_mappings": "json",
+        "replication_task_settings": "json",
+    }
+
+    def __init__(
+        self,
+        *,
+        replication_task_arn: str,
+        table_mappings: dict | None = None,
+        migration_type: str | None = None,
+        replication_task_settings: dict | None = None,
+        cdc_start_time: datetime | None = None,
+        cdc_start_position: str | None = None,
+        cdc_stop_position: str | None = None,
+        wait_for_completion: bool = True,
+        deferrable: bool = conf.getboolean("operators", "default_deferrable", fallback=False),
+        waiter_delay: int = 30,
+        waiter_max_attempts: int = 60,
+        **kwargs,
+    ):
+        super().__init__(**kwargs)
+        if cdc_start_time and cdc_start_position:
+            raise ValueError("Only one of cdc_start_time or cdc_start_position can be provided.")
+        self.replication_task_arn = replication_task_arn
+        self.table_mappings = table_mappings
+        self.migration_type = migration_type
+        self.replication_task_settings = replication_task_settings
+        self.cdc_start_time = cdc_start_time
+        self.cdc_start_position = cdc_start_position
+        self.cdc_stop_position = cdc_stop_position
+        self.wait_for_completion = wait_for_completion
+        self.deferrable = deferrable
+        self.waiter_delay = waiter_delay
+        self.waiter_max_attempts = waiter_max_attempts
+
+    def execute(self, context: Context) -> dict:
+        tasks = self.hook.find_replication_tasks_by_arn(
+            replication_task_arn=self.replication_task_arn, without_settings=True
+        )
+        if not tasks:
+            raise ValueError(f"Replication task {self.replication_task_arn} not found.")
+
+        current_status = tasks[0].get("Status", "").lower()
+        self.log.info(
+            "Current status of replication task(%s) is '%s'.", self.replication_task_arn, current_status
+        )
+
+        if current_status == DmsTaskState.MODIFYING:
+            # boto3 stopped/ready waiters treat 'modifying' as a terminal failure — use poll loop.
+            self._wait_until_not_modifying()
+        elif current_status not in self.MODIFIABLE_STATES:
+            raise RuntimeError(
+                f"Replication task {self.replication_task_arn} is in state '{current_status}' "
+                f"and must be stopped before modification. "
+                f"Use DmsStopTaskOperator to stop it first."
+            )
+
+        result = self.hook.modify_replication_task(
+            replication_task_arn=self.replication_task_arn,
+            table_mappings=self.table_mappings,
+            migration_type=self.migration_type,
+            replication_task_settings=self.replication_task_settings,
+            cdc_start_time=self.cdc_start_time,
+            cdc_start_position=self.cdc_start_position,
+            cdc_stop_position=self.cdc_stop_position,
+        )
+        self.log.info("DMS replication task(%s) has been modified.", self.replication_task_arn)
+
+        if self.wait_for_completion:
+            if self.deferrable:
+                self.defer(
+                    trigger=DmsTaskModifyCompleteTrigger(
+                        replication_task_arn=self.replication_task_arn,
+                        waiter_delay=self.waiter_delay,
+                        waiter_max_attempts=self.waiter_max_attempts,
+                        aws_conn_id=self.aws_conn_id,
+                    ),
+                    method_name="execute_complete",
+                )
+            # modify_replication_task is async — poll until the task exits 'modifying'.
+            self._wait_until_not_modifying()
+
+        return result
+
+    def execute_complete(self, context: Context, event: dict | None = None) -> None:
+        validated_event = validate_execute_complete_event(event)
+        if validated_event["status"] != "success":
+            raise RuntimeError(f"Error waiting for DMS task modification to complete: {validated_event}")
+        self.log.info("DMS replication task(%s) modification complete.", self.replication_task_arn)
+
+    def _wait_until_not_modifying(self) -> None:
+        """
+        Poll until the task leaves the 'modifying' state.
+
+        boto3 waiters for replication_task_stopped and replication_task_ready both
+        treat 'modifying' as a terminal failure, so a polling loop is necessary.
+        """
+        for _ in range(self.waiter_max_attempts):
+            tasks = self.hook.find_replication_tasks_by_arn(
+                replication_task_arn=self.replication_task_arn, without_settings=True
+            )

Review Comment:
   I think you should add this here as well:
   
   ```
         if not tasks:
             raise ValueError(f"Replication task {self.replication_task_arn} not found.")
   ```



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: commits-unsubscribe@airflow.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] Add `DmsModifyTaskOperator` [airflow]

Posted by "AlejandroMorgante (via GitHub)" <gi...@apache.org>.
AlejandroMorgante commented on code in PR #67524:
URL: https://github.com/apache/airflow/pull/67524#discussion_r3345126579


##########
providers/amazon/src/airflow/providers/amazon/aws/operators/dms.py:
##########
@@ -118,6 +120,192 @@ def execute(self, context: Context):
         return task_arn
 
 
+class DmsModifyTaskOperator(AwsBaseOperator[DmsHook]):
+    """
+    Modifies an existing AWS DMS replication task.
+
+    The task must already be stopped before modification. Use :class:`DmsStopTaskOperator`
+    upstream in the Dag to stop it, and :class:`DmsStartTaskOperator` downstream to restart
+    it afterwards if needed.
+
+    .. seealso::
+        For more information on how to use this operator, take a look at the guide:
+        :ref:`howto/operator:DmsModifyTaskOperator`
+
+    :param replication_task_arn: Replication task ARN
+    :param table_mappings: New table mappings. If not provided, existing mappings are kept.
+    :param migration_type: Migration type ('full-load'|'cdc'|'full-load-and-cdc').
+        If not provided, existing type is kept.
+    :param replication_task_settings: Task settings dict. If not provided, existing settings are kept.
+    :param cdc_start_time: Start time for CDC.
+    :param cdc_start_position: Indicates when to start CDC (checkpoint or LSN/SCN format).
+        Mutually exclusive with cdc_start_time.
+    :param cdc_stop_position: Indicates when to stop CDC.
+    :param wait_for_completion: If True, wait for the modification to finish before returning.
+        In deferrable mode the operator defers rather than blocking. Defaults to True.
+    :param deferrable: Run the operator in deferrable mode. Defaults to False.
+    :param waiter_delay: Seconds between waiter polls (default: 30).
+    :param waiter_max_attempts: Maximum waiter poll attempts (default: 60).
+    :param aws_conn_id: The Airflow connection used for AWS credentials.
+        If this is ``None`` or empty then the default boto3 behaviour is used. If
+        running Airflow in a distributed manner and aws_conn_id is None or
+        empty, then default boto3 configuration would be used (and must be
+        maintained on each worker node).
+    :param region_name: AWS region_name. If not specified then the default boto3 behaviour is used.
+    :param verify: Whether or not to verify SSL certificates. See:
+        https://boto3.amazonaws.com/v1/documentation/api/latest/reference/core/session.html
+    :param botocore_config: Configuration dictionary (key-values) for botocore client. See:
+        https://botocore.amazonaws.com/v1/documentation/api/latest/reference/config.html
+    """
+
+    MODIFIABLE_STATES = DMS_MODIFIABLE_STATES
+
+    aws_hook_class = DmsHook
+    template_fields: Sequence[str] = aws_template_fields(
+        "replication_task_arn",
+        "table_mappings",
+        "migration_type",
+        "replication_task_settings",
+        "cdc_start_time",
+        "cdc_start_position",
+        "cdc_stop_position",
+    )
+    template_fields_renderers: ClassVar[dict] = {
+        "table_mappings": "json",
+        "replication_task_settings": "json",
+    }
+
+    def __init__(
+        self,
+        *,
+        replication_task_arn: str,
+        table_mappings: dict | None = None,
+        migration_type: str | None = None,
+        replication_task_settings: dict | None = None,
+        cdc_start_time: datetime | None = None,
+        cdc_start_position: str | None = None,
+        cdc_stop_position: str | None = None,
+        wait_for_completion: bool = True,
+        deferrable: bool = conf.getboolean("operators", "default_deferrable", fallback=False),
+        waiter_delay: int = 30,
+        waiter_max_attempts: int = 60,
+        aws_conn_id: str | None = "aws_default",
+        **kwargs,
+    ):
+        super().__init__(aws_conn_id=aws_conn_id, **kwargs)
+        if cdc_start_time and cdc_start_position:
+            raise ValueError("Only one of cdc_start_time or cdc_start_position can be provided.")
+        self.replication_task_arn = replication_task_arn
+        self.table_mappings = table_mappings
+        self.migration_type = migration_type
+        self.replication_task_settings = replication_task_settings
+        self.cdc_start_time = cdc_start_time
+        self.cdc_start_position = cdc_start_position
+        self.cdc_stop_position = cdc_stop_position
+        self.wait_for_completion = wait_for_completion
+        self.deferrable = deferrable
+        self.waiter_delay = waiter_delay
+        self.waiter_max_attempts = waiter_max_attempts
+
+    def execute(self, context: Context) -> dict:
+        tasks = self.hook.find_replication_tasks_by_arn(
+            replication_task_arn=self.replication_task_arn, without_settings=True
+        )
+        if not tasks:
+            raise ValueError(f"Replication task {self.replication_task_arn} not found.")
+
+        current_status = tasks[0].get("Status", "").lower()
+        self.log.info(
+            "Current status of replication task(%s) is '%s'.", self.replication_task_arn, current_status
+        )
+
+        if current_status == DmsTaskState.MODIFYING:
+            # boto3 stopped/ready waiters treat 'modifying' as a terminal failure — use poll loop.
+            current_status = self._wait_until_not_modifying()
+
+        if current_status not in self.MODIFIABLE_STATES:
+            raise RuntimeError(
+                f"Replication task {self.replication_task_arn} is in state '{current_status}' "
+                f"and must be in a modifiable state (stopped, ready, or failed) before modification. "
+                f"Use DmsStopTaskOperator to stop it first."
+            )
+
+        result = self.hook.modify_replication_task(
+            replication_task_arn=self.replication_task_arn,
+            table_mappings=self.table_mappings,
+            migration_type=self.migration_type,
+            replication_task_settings=self.replication_task_settings,
+            cdc_start_time=self.cdc_start_time,
+            cdc_start_position=self.cdc_start_position,
+            cdc_stop_position=self.cdc_stop_position,
+        )
+        self.log.info("DMS replication task(%s) has been modified.", self.replication_task_arn)
+
+        if self.wait_for_completion:
+            if self.deferrable:
+                self.defer(
+                    trigger=DmsTaskModifyCompleteTrigger(
+                        replication_task_arn=self.replication_task_arn,
+                        waiter_delay=self.waiter_delay,
+                        waiter_max_attempts=self.waiter_max_attempts,
+                        aws_conn_id=self.aws_conn_id,
+                    ),
+                    method_name="execute_complete",
+                    kwargs={"result": result},
+                )
+            else:
+                # modify_replication_task is async — poll until the task exits 'modifying'.
+                final_status = self._wait_until_not_modifying()
+                if final_status not in self.MODIFIABLE_STATES:
+                    raise RuntimeError(
+                        f"Replication task {self.replication_task_arn} ended in unexpected state "
+                        f"'{final_status}' after modification."
+                    )
+
+        return result
+
+    def execute_complete(
+        self, context: Context, event: dict | None = None, result: dict | None = None
+    ) -> dict:
+        validated_event = validate_execute_complete_event(event)
+        if validated_event["status"] != "success":
+            raise RuntimeError(f"Error waiting for DMS task modification to complete: {validated_event}")
+        self.log.info("DMS replication task(%s) modification complete.", self.replication_task_arn)

Review Comment:
   I updated this in the latest revision so `execute_complete` now uses the ARN from the trigger event instead of `self.replication_task_arn`.
   
   The trigger includes `replication_task_arn` in the `TriggerEvent`, and `execute_complete` reads it from `validated_event["replication_task_arn"]`



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: commits-unsubscribe@airflow.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] Add `DmsModifyTaskOperator` [airflow]

Posted by "SameerMesiah97 (via GitHub)" <gi...@apache.org>.
SameerMesiah97 commented on code in PR #67524:
URL: https://github.com/apache/airflow/pull/67524#discussion_r3313681815


##########
providers/amazon/docs/changelog.rst:
##########
@@ -32,6 +32,7 @@ Changelog
 Features
 ~~~~~~~~
 
+* ``Add DmsModifyTaskOperator to modify DMS replication tasks with stop/restart lifecycle (#67524)``

Review Comment:
   This file does not need to be edited manually. 



##########
providers/amazon/src/airflow/providers/amazon/aws/operators/dms.py:
##########
@@ -118,6 +121,274 @@ def execute(self, context: Context):
         return task_arn
 
 
+class DmsModifyTaskOperator(AwsBaseOperator[DmsHook]):
+    """
+    Modifies an existing AWS DMS replication task.
+
+    If the task is not already stopped, set ``stop_task_before=True`` to stop it first.
+    To restart the task after modification, set ``restart_task_after=True``.
+
+    .. seealso::
+        For more information on how to use this operator, take a look at the guide:
+        :ref:`howto/operator:DmsModifyTaskOperator`
+
+    :param replication_task_arn: Replication task ARN
+    :param table_mappings: New table mappings. If not provided, existing mappings are kept.
+    :param migration_type: Migration type ('full-load'|'cdc'|'full-load-and-cdc').
+        If not provided, existing type is kept.
+    :param replication_task_settings: Task settings dict. If not provided, existing settings are kept.
+    :param cdc_start_time: Start time for CDC.
+    :param cdc_start_position: Indicates when to start CDC (checkpoint or LSN/SCN format).
+        Mutually exclusive with cdc_start_time.
+    :param cdc_stop_position: Indicates when to stop CDC.
+    :param stop_task_before: If True, stop the task before modifying if it is not already stopped.
+    :param restart_task_after: If True, restart the task after modifying.
+    :param start_replication_task_type: Start type used when restarting the task.
+        One of 'start-replication', 'resume-processing', or 'reload-target'.
+        Defaults to 'resume-processing'. Only used when ``restart_task_after=True``.
+    :param wait_for_completion: Only applies when the task is already in ``modifying`` state
+        when ``execute()`` is called. If True, wait for the modification to finish before
+        proceeding. If False, raises immediately instead of waiting.
+    :param deferrable: Run the operator in deferrable mode.
+    :param waiter_delay: Seconds between waiter polls (default: 30).
+    :param waiter_max_attempts: Maximum waiter poll attempts (default: 60).
+    :param aws_conn_id: The Airflow connection used for AWS credentials.
+        If this is ``None`` or empty then the default boto3 behaviour is used. If
+        running Airflow in a distributed manner and aws_conn_id is None or
+        empty, then default boto3 configuration would be used (and must be
+        maintained on each worker node).
+    :param region_name: AWS region_name. If not specified then the default boto3 behaviour is used.
+    :param verify: Whether or not to verify SSL certificates. See:
+        https://boto3.amazonaws.com/v1/documentation/api/latest/reference/core/session.html
+    :param botocore_config: Configuration dictionary (key-values) for botocore client. See:
+        https://botocore.amazonaws.com/v1/documentation/api/latest/reference/config.html
+    """
+
+    STOPPED_STATES = ("stopped", "ready", "failed", "created")
+    TERMINAL_STATES = frozenset({"failed", "stopped", "ready", "created", "deleting"})
+
+    aws_hook_class = DmsHook
+    template_fields: Sequence[str] = aws_template_fields(
+        "replication_task_arn",
+        "table_mappings",
+        "migration_type",
+        "replication_task_settings",
+        "cdc_start_time",
+        "cdc_start_position",
+        "cdc_stop_position",
+        "start_replication_task_type",
+    )
+    template_fields_renderers: ClassVar[dict] = {
+        "table_mappings": "json",
+        "replication_task_settings": "json",
+    }
+
+    def __init__(
+        self,
+        *,
+        replication_task_arn: str,
+        table_mappings: dict | None = None,
+        migration_type: str | None = None,
+        replication_task_settings: dict | None = None,
+        cdc_start_time: datetime | None = None,
+        cdc_start_position: str | None = None,
+        cdc_stop_position: str | None = None,
+        stop_task_before: bool = False,
+        restart_task_after: bool = False,
+        start_replication_task_type: str = "resume-processing",
+        wait_for_completion: bool = True,
+        deferrable: bool = conf.getboolean("operators", "default_deferrable", fallback=False),
+        waiter_delay: int = 30,
+        waiter_max_attempts: int = 60,
+        **kwargs,
+    ):
+        super().__init__(**kwargs)
+        if cdc_start_time and cdc_start_position:
+            raise ValueError("Only one of cdc_start_time or cdc_start_position can be provided.")
+        self.replication_task_arn = replication_task_arn
+        self.table_mappings = table_mappings
+        self.migration_type = migration_type
+        self.replication_task_settings = replication_task_settings
+        self.cdc_start_time = cdc_start_time
+        self.cdc_start_position = cdc_start_position
+        self.cdc_stop_position = cdc_stop_position
+        self.stop_task_before = stop_task_before
+        self.restart_task_after = restart_task_after
+        self.start_replication_task_type = start_replication_task_type
+        self.wait_for_completion = wait_for_completion
+        self.deferrable = deferrable
+        self.waiter_delay = waiter_delay
+        self.waiter_max_attempts = waiter_max_attempts
+
+    def execute(self, context: Context) -> dict:
+        tasks = self.hook.find_replication_tasks_by_arn(
+            replication_task_arn=self.replication_task_arn, without_settings=True
+        )
+        if not tasks:
+            raise AirflowException(f"Replication task {self.replication_task_arn} not found.")
+
+        current_status = tasks[0].get("Status", "").lower()
+        self.log.info(
+            "Current status of replication task(%s) is '%s'.", self.replication_task_arn, current_status
+        )
+
+        if current_status == "modifying":
+            # boto3 stopped/ready waiters treat 'modifying' as a terminal failure — use poll loop.
+            if not self.wait_for_completion:
+                raise AirflowException(

Review Comment:
   Avoid using `AirflowException` in provider code. Maybe consider `RuntimeError` or `ValueError`. This applies to the rest of the diff as well.



##########
providers/amazon/src/airflow/providers/amazon/aws/operators/dms.py:
##########
@@ -118,6 +121,274 @@ def execute(self, context: Context):
         return task_arn
 
 
+class DmsModifyTaskOperator(AwsBaseOperator[DmsHook]):
+    """
+    Modifies an existing AWS DMS replication task.
+
+    If the task is not already stopped, set ``stop_task_before=True`` to stop it first.
+    To restart the task after modification, set ``restart_task_after=True``.
+
+    .. seealso::
+        For more information on how to use this operator, take a look at the guide:
+        :ref:`howto/operator:DmsModifyTaskOperator`
+
+    :param replication_task_arn: Replication task ARN
+    :param table_mappings: New table mappings. If not provided, existing mappings are kept.
+    :param migration_type: Migration type ('full-load'|'cdc'|'full-load-and-cdc').
+        If not provided, existing type is kept.
+    :param replication_task_settings: Task settings dict. If not provided, existing settings are kept.
+    :param cdc_start_time: Start time for CDC.
+    :param cdc_start_position: Indicates when to start CDC (checkpoint or LSN/SCN format).
+        Mutually exclusive with cdc_start_time.
+    :param cdc_stop_position: Indicates when to stop CDC.
+    :param stop_task_before: If True, stop the task before modifying if it is not already stopped.
+    :param restart_task_after: If True, restart the task after modifying.
+    :param start_replication_task_type: Start type used when restarting the task.
+        One of 'start-replication', 'resume-processing', or 'reload-target'.
+        Defaults to 'resume-processing'. Only used when ``restart_task_after=True``.
+    :param wait_for_completion: Only applies when the task is already in ``modifying`` state
+        when ``execute()`` is called. If True, wait for the modification to finish before
+        proceeding. If False, raises immediately instead of waiting.
+    :param deferrable: Run the operator in deferrable mode.
+    :param waiter_delay: Seconds between waiter polls (default: 30).
+    :param waiter_max_attempts: Maximum waiter poll attempts (default: 60).
+    :param aws_conn_id: The Airflow connection used for AWS credentials.
+        If this is ``None`` or empty then the default boto3 behaviour is used. If
+        running Airflow in a distributed manner and aws_conn_id is None or
+        empty, then default boto3 configuration would be used (and must be
+        maintained on each worker node).
+    :param region_name: AWS region_name. If not specified then the default boto3 behaviour is used.
+    :param verify: Whether or not to verify SSL certificates. See:
+        https://boto3.amazonaws.com/v1/documentation/api/latest/reference/core/session.html
+    :param botocore_config: Configuration dictionary (key-values) for botocore client. See:
+        https://botocore.amazonaws.com/v1/documentation/api/latest/reference/config.html
+    """
+
+    STOPPED_STATES = ("stopped", "ready", "failed", "created")
+    TERMINAL_STATES = frozenset({"failed", "stopped", "ready", "created", "deleting"})
+
+    aws_hook_class = DmsHook
+    template_fields: Sequence[str] = aws_template_fields(
+        "replication_task_arn",
+        "table_mappings",
+        "migration_type",
+        "replication_task_settings",
+        "cdc_start_time",
+        "cdc_start_position",
+        "cdc_stop_position",
+        "start_replication_task_type",
+    )
+    template_fields_renderers: ClassVar[dict] = {
+        "table_mappings": "json",
+        "replication_task_settings": "json",
+    }
+
+    def __init__(
+        self,
+        *,
+        replication_task_arn: str,
+        table_mappings: dict | None = None,
+        migration_type: str | None = None,
+        replication_task_settings: dict | None = None,
+        cdc_start_time: datetime | None = None,
+        cdc_start_position: str | None = None,
+        cdc_stop_position: str | None = None,
+        stop_task_before: bool = False,
+        restart_task_after: bool = False,
+        start_replication_task_type: str = "resume-processing",
+        wait_for_completion: bool = True,
+        deferrable: bool = conf.getboolean("operators", "default_deferrable", fallback=False),
+        waiter_delay: int = 30,
+        waiter_max_attempts: int = 60,
+        **kwargs,
+    ):
+        super().__init__(**kwargs)
+        if cdc_start_time and cdc_start_position:
+            raise ValueError("Only one of cdc_start_time or cdc_start_position can be provided.")
+        self.replication_task_arn = replication_task_arn
+        self.table_mappings = table_mappings
+        self.migration_type = migration_type
+        self.replication_task_settings = replication_task_settings
+        self.cdc_start_time = cdc_start_time
+        self.cdc_start_position = cdc_start_position
+        self.cdc_stop_position = cdc_stop_position
+        self.stop_task_before = stop_task_before
+        self.restart_task_after = restart_task_after
+        self.start_replication_task_type = start_replication_task_type
+        self.wait_for_completion = wait_for_completion
+        self.deferrable = deferrable
+        self.waiter_delay = waiter_delay
+        self.waiter_max_attempts = waiter_max_attempts
+
+    def execute(self, context: Context) -> dict:
+        tasks = self.hook.find_replication_tasks_by_arn(
+            replication_task_arn=self.replication_task_arn, without_settings=True
+        )
+        if not tasks:
+            raise AirflowException(f"Replication task {self.replication_task_arn} not found.")
+
+        current_status = tasks[0].get("Status", "").lower()
+        self.log.info(
+            "Current status of replication task(%s) is '%s'.", self.replication_task_arn, current_status
+        )
+
+        if current_status == "modifying":
+            # boto3 stopped/ready waiters treat 'modifying' as a terminal failure — use poll loop.
+            if not self.wait_for_completion:
+                raise AirflowException(
+                    f"Replication task {self.replication_task_arn} is already being modified. "
+                    f"Set wait_for_completion=True to wait for it to finish."
+                )
+            self._wait_until_not_modifying()
+        elif current_status not in self.STOPPED_STATES:
+            if not self.stop_task_before:
+                raise AirflowException(
+                    f"Replication task {self.replication_task_arn} is in state '{current_status}' "
+                    f"and must be stopped before modification. Set stop_task_before=True to stop it "
+                    f"automatically, or stop the task first."
+                )
+            if current_status == "starting":
+                # DMS rejects StopReplicationTask while the task is still starting up.
+                self.log.info(
+                    "Replication task(%s) is starting, waiting for it to reach 'running'.",
+                    self.replication_task_arn,
+                )
+                self._wait_for_status("running")
+            self.log.info("Stopping replication task(%s).", self.replication_task_arn)
+            self.hook.stop_replication_task(replication_task_arn=self.replication_task_arn)
+            self.log.info("Waiting for replication task(%s) to stop.", self.replication_task_arn)
+            if self.deferrable:

Review Comment:
   I am not fully convinced the deferrable mode provides much value here unless DMS modification/state transitions are expected to be long-running in practice. There is still a substantial amount of synchronous polling logic in the operator itself, so the current implementation feels somewhat hybrid rather than fully deferred.



##########
providers/amazon/src/airflow/providers/amazon/aws/operators/dms.py:
##########
@@ -118,6 +121,274 @@ def execute(self, context: Context):
         return task_arn
 
 
+class DmsModifyTaskOperator(AwsBaseOperator[DmsHook]):
+    """
+    Modifies an existing AWS DMS replication task.
+
+    If the task is not already stopped, set ``stop_task_before=True`` to stop it first.
+    To restart the task after modification, set ``restart_task_after=True``.
+
+    .. seealso::
+        For more information on how to use this operator, take a look at the guide:
+        :ref:`howto/operator:DmsModifyTaskOperator`
+
+    :param replication_task_arn: Replication task ARN
+    :param table_mappings: New table mappings. If not provided, existing mappings are kept.
+    :param migration_type: Migration type ('full-load'|'cdc'|'full-load-and-cdc').
+        If not provided, existing type is kept.
+    :param replication_task_settings: Task settings dict. If not provided, existing settings are kept.
+    :param cdc_start_time: Start time for CDC.
+    :param cdc_start_position: Indicates when to start CDC (checkpoint or LSN/SCN format).
+        Mutually exclusive with cdc_start_time.
+    :param cdc_stop_position: Indicates when to stop CDC.
+    :param stop_task_before: If True, stop the task before modifying if it is not already stopped.
+    :param restart_task_after: If True, restart the task after modifying.
+    :param start_replication_task_type: Start type used when restarting the task.
+        One of 'start-replication', 'resume-processing', or 'reload-target'.
+        Defaults to 'resume-processing'. Only used when ``restart_task_after=True``.
+    :param wait_for_completion: Only applies when the task is already in ``modifying`` state
+        when ``execute()`` is called. If True, wait for the modification to finish before
+        proceeding. If False, raises immediately instead of waiting.
+    :param deferrable: Run the operator in deferrable mode.
+    :param waiter_delay: Seconds between waiter polls (default: 30).
+    :param waiter_max_attempts: Maximum waiter poll attempts (default: 60).
+    :param aws_conn_id: The Airflow connection used for AWS credentials.
+        If this is ``None`` or empty then the default boto3 behaviour is used. If
+        running Airflow in a distributed manner and aws_conn_id is None or
+        empty, then default boto3 configuration would be used (and must be
+        maintained on each worker node).
+    :param region_name: AWS region_name. If not specified then the default boto3 behaviour is used.
+    :param verify: Whether or not to verify SSL certificates. See:
+        https://boto3.amazonaws.com/v1/documentation/api/latest/reference/core/session.html
+    :param botocore_config: Configuration dictionary (key-values) for botocore client. See:
+        https://botocore.amazonaws.com/v1/documentation/api/latest/reference/config.html
+    """
+
+    STOPPED_STATES = ("stopped", "ready", "failed", "created")
+    TERMINAL_STATES = frozenset({"failed", "stopped", "ready", "created", "deleting"})

Review Comment:
   There is currently too much overlap between these 2 sequences. And I think they do no acurrately map to the lifecycle semantics of this operator. I would suggest creating an enum class like this in the hook:
   
   ```
   class DmsTaskState(str, Enum):
       """AWS DMS replication task states."""
   
       CREATING = "creating"
       READY = "ready"
       STARTING = "starting"
       RUNNING = "running"
       STOPPING = "stopping"
       STOPPED = "stopped"
       MODIFYING = "modifying"
       FAILED = "failed"
       DELETING = "deleting"
   
   ```
   
   Then create 2 sequences called `MODIFIABLE_STATES` and `NON_MODIFIABLE_STATES`, which each have the appropriate ENUMs. 



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: commits-unsubscribe@airflow.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] Add `DmsModifyTaskOperator` [airflow]

Posted by "SameerMesiah97 (via GitHub)" <gi...@apache.org>.
SameerMesiah97 commented on code in PR #67524:
URL: https://github.com/apache/airflow/pull/67524#discussion_r3329150950


##########
providers/amazon/src/airflow/providers/amazon/aws/operators/dms.py:
##########
@@ -118,6 +120,178 @@ def execute(self, context: Context):
         return task_arn
 
 
+class DmsModifyTaskOperator(AwsBaseOperator[DmsHook]):
+    """
+    Modifies an existing AWS DMS replication task.
+
+    The task must already be stopped before modification. Use :class:`DmsStopTaskOperator`
+    upstream in the Dag to stop it, and :class:`DmsStartTaskOperator` downstream to restart
+    it afterwards if needed.
+
+    .. seealso::
+        For more information on how to use this operator, take a look at the guide:
+        :ref:`howto/operator:DmsModifyTaskOperator`
+
+    :param replication_task_arn: Replication task ARN
+    :param table_mappings: New table mappings. If not provided, existing mappings are kept.
+    :param migration_type: Migration type ('full-load'|'cdc'|'full-load-and-cdc').
+        If not provided, existing type is kept.
+    :param replication_task_settings: Task settings dict. If not provided, existing settings are kept.
+    :param cdc_start_time: Start time for CDC.
+    :param cdc_start_position: Indicates when to start CDC (checkpoint or LSN/SCN format).
+        Mutually exclusive with cdc_start_time.
+    :param cdc_stop_position: Indicates when to stop CDC.
+    :param wait_for_completion: If True, wait for the modification to finish before returning.
+        In deferrable mode the operator defers rather than blocking. Defaults to True.
+    :param deferrable: Run the operator in deferrable mode. Defaults to False.
+    :param waiter_delay: Seconds between waiter polls (default: 30).
+    :param waiter_max_attempts: Maximum waiter poll attempts (default: 60).
+    :param aws_conn_id: The Airflow connection used for AWS credentials.
+        If this is ``None`` or empty then the default boto3 behaviour is used. If
+        running Airflow in a distributed manner and aws_conn_id is None or
+        empty, then default boto3 configuration would be used (and must be
+        maintained on each worker node).
+    :param region_name: AWS region_name. If not specified then the default boto3 behaviour is used.
+    :param verify: Whether or not to verify SSL certificates. See:
+        https://boto3.amazonaws.com/v1/documentation/api/latest/reference/core/session.html
+    :param botocore_config: Configuration dictionary (key-values) for botocore client. See:
+        https://botocore.amazonaws.com/v1/documentation/api/latest/reference/config.html
+    """
+
+    MODIFIABLE_STATES = frozenset({DmsTaskState.STOPPED, DmsTaskState.READY, DmsTaskState.FAILED})
+
+    aws_hook_class = DmsHook
+    template_fields: Sequence[str] = aws_template_fields(
+        "replication_task_arn",
+        "table_mappings",
+        "migration_type",
+        "replication_task_settings",
+        "cdc_start_time",
+        "cdc_start_position",
+        "cdc_stop_position",
+    )
+    template_fields_renderers: ClassVar[dict] = {
+        "table_mappings": "json",
+        "replication_task_settings": "json",
+    }
+
+    def __init__(
+        self,
+        *,
+        replication_task_arn: str,
+        table_mappings: dict | None = None,
+        migration_type: str | None = None,
+        replication_task_settings: dict | None = None,
+        cdc_start_time: datetime | None = None,
+        cdc_start_position: str | None = None,
+        cdc_stop_position: str | None = None,
+        wait_for_completion: bool = True,
+        deferrable: bool = conf.getboolean("operators", "default_deferrable", fallback=False),
+        waiter_delay: int = 30,
+        waiter_max_attempts: int = 60,
+        **kwargs,
+    ):
+        super().__init__(**kwargs)
+        if cdc_start_time and cdc_start_position:
+            raise ValueError("Only one of cdc_start_time or cdc_start_position can be provided.")
+        self.replication_task_arn = replication_task_arn
+        self.table_mappings = table_mappings
+        self.migration_type = migration_type
+        self.replication_task_settings = replication_task_settings
+        self.cdc_start_time = cdc_start_time
+        self.cdc_start_position = cdc_start_position
+        self.cdc_stop_position = cdc_stop_position
+        self.wait_for_completion = wait_for_completion
+        self.deferrable = deferrable
+        self.waiter_delay = waiter_delay
+        self.waiter_max_attempts = waiter_max_attempts
+
+    def execute(self, context: Context) -> dict:
+        tasks = self.hook.find_replication_tasks_by_arn(
+            replication_task_arn=self.replication_task_arn, without_settings=True
+        )
+        if not tasks:
+            raise ValueError(f"Replication task {self.replication_task_arn} not found.")
+
+        current_status = tasks[0].get("Status", "").lower()
+        self.log.info(
+            "Current status of replication task(%s) is '%s'.", self.replication_task_arn, current_status
+        )
+
+        if current_status == DmsTaskState.MODIFYING:
+            # boto3 stopped/ready waiters treat 'modifying' as a terminal failure — use poll loop.
+            self._wait_until_not_modifying()
+        elif current_status not in self.MODIFIABLE_STATES:
+            raise RuntimeError(
+                f"Replication task {self.replication_task_arn} is in state '{current_status}' "
+                f"and must be stopped before modification. "
+                f"Use DmsStopTaskOperator to stop it first."
+            )
+
+        result = self.hook.modify_replication_task(
+            replication_task_arn=self.replication_task_arn,
+            table_mappings=self.table_mappings,
+            migration_type=self.migration_type,
+            replication_task_settings=self.replication_task_settings,
+            cdc_start_time=self.cdc_start_time,
+            cdc_start_position=self.cdc_start_position,
+            cdc_stop_position=self.cdc_stop_position,
+        )
+        self.log.info("DMS replication task(%s) has been modified.", self.replication_task_arn)
+
+        if self.wait_for_completion:
+            if self.deferrable:
+                self.defer(
+                    trigger=DmsTaskModifyCompleteTrigger(
+                        replication_task_arn=self.replication_task_arn,
+                        waiter_delay=self.waiter_delay,
+                        waiter_max_attempts=self.waiter_max_attempts,
+                        aws_conn_id=self.aws_conn_id,
+                    ),
+                    method_name="execute_complete",
+                )
+            # modify_replication_task is async — poll until the task exits 'modifying'.
+            self._wait_until_not_modifying()
+
+        return result
+
+    def execute_complete(self, context: Context, event: dict | None = None) -> None:
+        validated_event = validate_execute_complete_event(event)
+        if validated_event["status"] != "success":
+            raise RuntimeError(f"Error waiting for DMS task modification to complete: {validated_event}")
+        self.log.info("DMS replication task(%s) modification complete.", self.replication_task_arn)

Review Comment:
   The synchronous path returns the modified task details, while the deferrable path returns `None` from `execute_complete()`. Should the return value be consistent across execution modes?



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: commits-unsubscribe@airflow.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] Add `DmsModifyTaskOperator` [airflow]

Posted by "SameerMesiah97 (via GitHub)" <gi...@apache.org>.
SameerMesiah97 commented on code in PR #67524:
URL: https://github.com/apache/airflow/pull/67524#discussion_r3329167919


##########
providers/amazon/src/airflow/providers/amazon/aws/triggers/dms.py:
##########
@@ -219,3 +222,79 @@ def hook(self) -> AwsGenericHook:
             verify=self.verify,
             config=self.botocore_config,
         )
+
+
+class DmsTaskModifyCompleteTrigger(BaseTrigger):
+    """
+    Trigger that polls until a DMS classic replication task exits the ``modifying`` state.
+
+    The boto3 ``replication_task_stopped`` waiter treats ``modifying`` as a terminal failure,
+    so a custom polling loop is required here.
+
+    :param replication_task_arn: The ARN of the replication task.
+    :param waiter_delay: Seconds between polls.
+    :param waiter_max_attempts: Maximum number of poll attempts before giving up.
+    :param aws_conn_id: The Airflow connection used for AWS credentials.
+    :param verify: Whether or not to verify SSL certificates.
+    :param botocore_config: Configuration dictionary (key-values) for botocore client.
+    """
+
+    def __init__(
+        self,
+        replication_task_arn: str,
+        waiter_delay: int = 30,
+        waiter_max_attempts: int = 60,
+        aws_conn_id: str | None = "aws_default",
+        verify: bool | str | None = None,
+        botocore_config: dict | None = None,
+    ) -> None:
+        super().__init__()
+        self.replication_task_arn = replication_task_arn
+        self.waiter_delay = waiter_delay
+        self.waiter_max_attempts = waiter_max_attempts
+        self.aws_conn_id = aws_conn_id
+        self.verify = verify
+        self.botocore_config = botocore_config
+
+    def serialize(self) -> tuple[str, dict]:
+        return (
+            "airflow.providers.amazon.aws.triggers.dms.DmsTaskModifyCompleteTrigger",
+            {
+                "replication_task_arn": self.replication_task_arn,
+                "waiter_delay": self.waiter_delay,
+                "waiter_max_attempts": self.waiter_max_attempts,
+                "aws_conn_id": self.aws_conn_id,
+                "verify": self.verify,
+                "botocore_config": self.botocore_config,
+            },
+        )
+
+    async def run(self) -> AsyncIterator[TriggerEvent]:
+        hook = DmsHook(aws_conn_id=self.aws_conn_id, verify=self.verify, config=self.botocore_config)
+        try:
+            for _ in range(self.waiter_max_attempts):
+                status = await hook.get_task_status_async(self.replication_task_arn)
+                if status != "modifying":

Review Comment:
   I would use the `ENUM` for the task state instead of raw strings to be consistent with the operator. If you follow my suggestion in the other comment, this line will become:
   
   `if status != DmsTaskWaiterStatus.MODIFYING`
   
   Also, besides this there is another more significant issue. It appears you are collapsing all non-'MODIFYING' statuses and yielding a success event. I think we should define `SUCCESS` and `FAILURE` states and handle TriggerEvent emission explicitly for both. Unknown/unexpected states and max waiter attempts can yield their own error events. And errors unrelated to the state machine can yield error events with the error message (you do this already). 



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: commits-unsubscribe@airflow.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] Add `DmsModifyTaskOperator` [airflow]

Posted by "AlejandroMorgante (via GitHub)" <gi...@apache.org>.
AlejandroMorgante commented on code in PR #67524:
URL: https://github.com/apache/airflow/pull/67524#discussion_r3314858522


##########
providers/amazon/src/airflow/providers/amazon/aws/operators/dms.py:
##########
@@ -118,6 +121,274 @@ def execute(self, context: Context):
         return task_arn
 
 
+class DmsModifyTaskOperator(AwsBaseOperator[DmsHook]):
+    """
+    Modifies an existing AWS DMS replication task.
+
+    If the task is not already stopped, set ``stop_task_before=True`` to stop it first.
+    To restart the task after modification, set ``restart_task_after=True``.
+
+    .. seealso::
+        For more information on how to use this operator, take a look at the guide:
+        :ref:`howto/operator:DmsModifyTaskOperator`
+
+    :param replication_task_arn: Replication task ARN
+    :param table_mappings: New table mappings. If not provided, existing mappings are kept.
+    :param migration_type: Migration type ('full-load'|'cdc'|'full-load-and-cdc').
+        If not provided, existing type is kept.
+    :param replication_task_settings: Task settings dict. If not provided, existing settings are kept.
+    :param cdc_start_time: Start time for CDC.
+    :param cdc_start_position: Indicates when to start CDC (checkpoint or LSN/SCN format).
+        Mutually exclusive with cdc_start_time.
+    :param cdc_stop_position: Indicates when to stop CDC.
+    :param stop_task_before: If True, stop the task before modifying if it is not already stopped.
+    :param restart_task_after: If True, restart the task after modifying.
+    :param start_replication_task_type: Start type used when restarting the task.
+        One of 'start-replication', 'resume-processing', or 'reload-target'.
+        Defaults to 'resume-processing'. Only used when ``restart_task_after=True``.
+    :param wait_for_completion: Only applies when the task is already in ``modifying`` state
+        when ``execute()`` is called. If True, wait for the modification to finish before
+        proceeding. If False, raises immediately instead of waiting.
+    :param deferrable: Run the operator in deferrable mode.
+    :param waiter_delay: Seconds between waiter polls (default: 30).
+    :param waiter_max_attempts: Maximum waiter poll attempts (default: 60).
+    :param aws_conn_id: The Airflow connection used for AWS credentials.
+        If this is ``None`` or empty then the default boto3 behaviour is used. If
+        running Airflow in a distributed manner and aws_conn_id is None or
+        empty, then default boto3 configuration would be used (and must be
+        maintained on each worker node).
+    :param region_name: AWS region_name. If not specified then the default boto3 behaviour is used.
+    :param verify: Whether or not to verify SSL certificates. See:
+        https://boto3.amazonaws.com/v1/documentation/api/latest/reference/core/session.html
+    :param botocore_config: Configuration dictionary (key-values) for botocore client. See:
+        https://botocore.amazonaws.com/v1/documentation/api/latest/reference/config.html
+    """
+
+    STOPPED_STATES = ("stopped", "ready", "failed", "created")
+    TERMINAL_STATES = frozenset({"failed", "stopped", "ready", "created", "deleting"})
+
+    aws_hook_class = DmsHook
+    template_fields: Sequence[str] = aws_template_fields(
+        "replication_task_arn",
+        "table_mappings",
+        "migration_type",
+        "replication_task_settings",
+        "cdc_start_time",
+        "cdc_start_position",
+        "cdc_stop_position",
+        "start_replication_task_type",
+    )
+    template_fields_renderers: ClassVar[dict] = {
+        "table_mappings": "json",
+        "replication_task_settings": "json",
+    }
+
+    def __init__(
+        self,
+        *,
+        replication_task_arn: str,
+        table_mappings: dict | None = None,
+        migration_type: str | None = None,
+        replication_task_settings: dict | None = None,
+        cdc_start_time: datetime | None = None,
+        cdc_start_position: str | None = None,
+        cdc_stop_position: str | None = None,
+        stop_task_before: bool = False,
+        restart_task_after: bool = False,
+        start_replication_task_type: str = "resume-processing",
+        wait_for_completion: bool = True,
+        deferrable: bool = conf.getboolean("operators", "default_deferrable", fallback=False),
+        waiter_delay: int = 30,
+        waiter_max_attempts: int = 60,
+        **kwargs,
+    ):
+        super().__init__(**kwargs)
+        if cdc_start_time and cdc_start_position:
+            raise ValueError("Only one of cdc_start_time or cdc_start_position can be provided.")
+        self.replication_task_arn = replication_task_arn
+        self.table_mappings = table_mappings
+        self.migration_type = migration_type
+        self.replication_task_settings = replication_task_settings
+        self.cdc_start_time = cdc_start_time
+        self.cdc_start_position = cdc_start_position
+        self.cdc_stop_position = cdc_stop_position
+        self.stop_task_before = stop_task_before
+        self.restart_task_after = restart_task_after
+        self.start_replication_task_type = start_replication_task_type
+        self.wait_for_completion = wait_for_completion
+        self.deferrable = deferrable
+        self.waiter_delay = waiter_delay
+        self.waiter_max_attempts = waiter_max_attempts
+
+    def execute(self, context: Context) -> dict:
+        tasks = self.hook.find_replication_tasks_by_arn(
+            replication_task_arn=self.replication_task_arn, without_settings=True
+        )
+        if not tasks:
+            raise AirflowException(f"Replication task {self.replication_task_arn} not found.")
+
+        current_status = tasks[0].get("Status", "").lower()
+        self.log.info(
+            "Current status of replication task(%s) is '%s'.", self.replication_task_arn, current_status
+        )
+
+        if current_status == "modifying":
+            # boto3 stopped/ready waiters treat 'modifying' as a terminal failure — use poll loop.
+            if not self.wait_for_completion:
+                raise AirflowException(
+                    f"Replication task {self.replication_task_arn} is already being modified. "
+                    f"Set wait_for_completion=True to wait for it to finish."
+                )
+            self._wait_until_not_modifying()
+        elif current_status not in self.STOPPED_STATES:
+            if not self.stop_task_before:
+                raise AirflowException(
+                    f"Replication task {self.replication_task_arn} is in state '{current_status}' "
+                    f"and must be stopped before modification. Set stop_task_before=True to stop it "
+                    f"automatically, or stop the task first."
+                )
+            if current_status == "starting":
+                # DMS rejects StopReplicationTask while the task is still starting up.
+                self.log.info(
+                    "Replication task(%s) is starting, waiting for it to reach 'running'.",
+                    self.replication_task_arn,
+                )
+                self._wait_for_status("running")
+            self.log.info("Stopping replication task(%s).", self.replication_task_arn)
+            self.hook.stop_replication_task(replication_task_arn=self.replication_task_arn)
+            self.log.info("Waiting for replication task(%s) to stop.", self.replication_task_arn)
+            if self.deferrable:

Review Comment:
   Yes, the modify phase itself is short (~1-2 min in practice, as we confirmed against real AWS). You're right that stopping a running task is where the wait can get significant, but that's now on DmsStopTaskOperator rather than here.
   
   The deferrable option is kept as opt-in (default is False), so it doesn't change behaviour for anyone not asking for it. Happy to drop it if the preference is to keep the operator minimal.



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: commits-unsubscribe@airflow.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] Add `DmsModifyTaskOperator` [airflow]

Posted by "potiuk (via GitHub)" <gi...@apache.org>.
potiuk commented on PR #67524:
URL: https://github.com/apache/airflow/pull/67524#issuecomment-4582981698

   @SameerMesiah97 -> are you fine with the changes ? They seemed to simplify a lot 


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: commits-unsubscribe@airflow.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] Add `DmsModifyTaskOperator` [airflow]

Posted by "SameerMesiah97 (via GitHub)" <gi...@apache.org>.
SameerMesiah97 commented on code in PR #67524:
URL: https://github.com/apache/airflow/pull/67524#discussion_r3329217580


##########
providers/amazon/tests/unit/amazon/aws/operators/test_dms.py:
##########
@@ -180,6 +181,214 @@ def test_default_conn_passed_to_hook(self):
         assert op.hook.aws_conn_id == DEFAULT_CONN
 
 
+class TestDmsModifyTaskOperator:
+    TASK_ARN = "arn:aws:dms:us-east-1:123456789012:task:EXAMPLE"
+    TABLE_MAPPINGS = {
+        "rules": [
+            {
+                "rule-type": "selection",
+                "rule-id": "1",
+                "rule-name": "1",
+                "object-locator": {"schema-name": "myschema", "table-name": "mytable"},
+                "rule-action": "include",
+            }
+        ]
+    }
+
+    def _stopped_task(self):
+        return [{"ReplicationTaskArn": self.TASK_ARN, "Status": "stopped"}]
+
+    def _running_task(self):
+        return [{"ReplicationTaskArn": self.TASK_ARN, "Status": "running"}]
+
+    def _modifying_task(self):
+        return [{"ReplicationTaskArn": self.TASK_ARN, "Status": "modifying"}]
+
+    def test_init(self):
+        op = DmsModifyTaskOperator(
+            task_id="modify_task",
+            replication_task_arn=self.TASK_ARN,
+            table_mappings=self.TABLE_MAPPINGS,
+            migration_type="cdc",
+            aws_conn_id="fake-conn-id",
+            region_name="us-east-1",
+        )
+        assert op.replication_task_arn == self.TASK_ARN
+        assert op.table_mappings == self.TABLE_MAPPINGS
+        assert op.migration_type == "cdc"
+        assert op.wait_for_completion is True
+        assert op.deferrable is False
+        assert op.hook.aws_conn_id == "fake-conn-id"
+        assert op.hook._region_name == "us-east-1"
+
+    def test_init_defaults(self):
+        op = DmsModifyTaskOperator(task_id="modify_task", replication_task_arn=self.TASK_ARN)
+        assert op.table_mappings is None
+        assert op.migration_type is None
+        assert op.replication_task_settings is None
+        assert op.cdc_start_time is None
+        assert op.cdc_start_position is None
+        assert op.cdc_stop_position is None
+        assert op.wait_for_completion is True
+        assert op.deferrable is False
+
+    def test_init_raises_if_both_cdc_start_params_provided(self):
+        from datetime import datetime
+
+        with pytest.raises(ValueError, match="Only one of"):
+            DmsModifyTaskOperator(
+                task_id="modify_task",
+                replication_task_arn=self.TASK_ARN,
+                cdc_start_time=datetime(2024, 1, 1),
+                cdc_start_position="mysql-bin.000001:4",
+            )
+
+    @mock.patch.object(DmsHook, "find_replication_tasks_by_arn")
+    @mock.patch.object(DmsHook, "get_conn")
+    def test_modify_task_already_stopped(self, mock_conn, mock_find):
+        mock_find.return_value = self._stopped_task()
+        expected = {"ReplicationTaskArn": self.TASK_ARN}
+        with mock.patch.object(DmsHook, "modify_replication_task", return_value=expected) as mock_modify:
+            op = DmsModifyTaskOperator(
+                task_id="modify_task",
+                replication_task_arn=self.TASK_ARN,
+                table_mappings=self.TABLE_MAPPINGS,
+                wait_for_completion=False,
+            )
+            result = op.execute(None)
+
+            mock_modify.assert_called_once_with(
+                replication_task_arn=self.TASK_ARN,
+                table_mappings=self.TABLE_MAPPINGS,
+                migration_type=None,
+                replication_task_settings=None,
+                cdc_start_time=None,
+                cdc_start_position=None,
+                cdc_stop_position=None,
+            )
+            assert result == expected
+
+    @mock.patch.object(DmsHook, "find_replication_tasks_by_arn")
+    @mock.patch.object(DmsHook, "get_conn")
+    def test_modify_task_raises_if_running(self, mock_conn, mock_find):
+        mock_find.return_value = self._running_task()
+        op = DmsModifyTaskOperator(
+            task_id="modify_task",
+            replication_task_arn=self.TASK_ARN,
+        )
+        with pytest.raises(RuntimeError, match="must be stopped"):
+            op.execute(None)
+
+    @mock.patch.object(DmsHook, "find_replication_tasks_by_arn")
+    @mock.patch.object(DmsHook, "get_conn")
+    def test_modify_task_raises_if_not_found(self, mock_conn, mock_find):
+        mock_find.return_value = []
+        op = DmsModifyTaskOperator(task_id="modify_task", replication_task_arn=self.TASK_ARN)
+        with pytest.raises(ValueError, match="not found"):
+            op.execute(None)
+
+    @mock.patch.object(DmsHook, "find_replication_tasks_by_arn")
+    @mock.patch.object(DmsHook, "get_conn")
+    def test_modify_task_defers_for_completion(self, mock_conn, mock_find):
+        from airflow.exceptions import TaskDeferred
+        from airflow.providers.amazon.aws.triggers.dms import DmsTaskModifyCompleteTrigger

Review Comment:
   I think you should move this import at the top of the file too where the other triggers are already being imported. 



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: commits-unsubscribe@airflow.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] Add `DmsModifyTaskOperator` [airflow]

Posted by "SameerMesiah97 (via GitHub)" <gi...@apache.org>.
SameerMesiah97 commented on code in PR #67524:
URL: https://github.com/apache/airflow/pull/67524#discussion_r3329253252


##########
providers/amazon/src/airflow/providers/amazon/aws/operators/dms.py:
##########
@@ -118,6 +120,178 @@ def execute(self, context: Context):
         return task_arn
 
 
+class DmsModifyTaskOperator(AwsBaseOperator[DmsHook]):
+    """
+    Modifies an existing AWS DMS replication task.
+
+    The task must already be stopped before modification. Use :class:`DmsStopTaskOperator`
+    upstream in the Dag to stop it, and :class:`DmsStartTaskOperator` downstream to restart
+    it afterwards if needed.
+
+    .. seealso::
+        For more information on how to use this operator, take a look at the guide:
+        :ref:`howto/operator:DmsModifyTaskOperator`
+
+    :param replication_task_arn: Replication task ARN
+    :param table_mappings: New table mappings. If not provided, existing mappings are kept.
+    :param migration_type: Migration type ('full-load'|'cdc'|'full-load-and-cdc').
+        If not provided, existing type is kept.
+    :param replication_task_settings: Task settings dict. If not provided, existing settings are kept.
+    :param cdc_start_time: Start time for CDC.
+    :param cdc_start_position: Indicates when to start CDC (checkpoint or LSN/SCN format).
+        Mutually exclusive with cdc_start_time.
+    :param cdc_stop_position: Indicates when to stop CDC.
+    :param wait_for_completion: If True, wait for the modification to finish before returning.
+        In deferrable mode the operator defers rather than blocking. Defaults to True.
+    :param deferrable: Run the operator in deferrable mode. Defaults to False.
+    :param waiter_delay: Seconds between waiter polls (default: 30).
+    :param waiter_max_attempts: Maximum waiter poll attempts (default: 60).
+    :param aws_conn_id: The Airflow connection used for AWS credentials.
+        If this is ``None`` or empty then the default boto3 behaviour is used. If
+        running Airflow in a distributed manner and aws_conn_id is None or
+        empty, then default boto3 configuration would be used (and must be
+        maintained on each worker node).
+    :param region_name: AWS region_name. If not specified then the default boto3 behaviour is used.
+    :param verify: Whether or not to verify SSL certificates. See:
+        https://boto3.amazonaws.com/v1/documentation/api/latest/reference/core/session.html
+    :param botocore_config: Configuration dictionary (key-values) for botocore client. See:
+        https://botocore.amazonaws.com/v1/documentation/api/latest/reference/config.html
+    """
+
+    MODIFIABLE_STATES = frozenset({DmsTaskState.STOPPED, DmsTaskState.READY, DmsTaskState.FAILED})
+
+    aws_hook_class = DmsHook
+    template_fields: Sequence[str] = aws_template_fields(
+        "replication_task_arn",
+        "table_mappings",
+        "migration_type",
+        "replication_task_settings",
+        "cdc_start_time",
+        "cdc_start_position",
+        "cdc_stop_position",
+    )
+    template_fields_renderers: ClassVar[dict] = {
+        "table_mappings": "json",
+        "replication_task_settings": "json",
+    }
+
+    def __init__(
+        self,
+        *,
+        replication_task_arn: str,
+        table_mappings: dict | None = None,
+        migration_type: str | None = None,
+        replication_task_settings: dict | None = None,
+        cdc_start_time: datetime | None = None,
+        cdc_start_position: str | None = None,
+        cdc_stop_position: str | None = None,
+        wait_for_completion: bool = True,
+        deferrable: bool = conf.getboolean("operators", "default_deferrable", fallback=False),
+        waiter_delay: int = 30,
+        waiter_max_attempts: int = 60,

Review Comment:
   I would add the following explicit parameter declaration too to make it consistent with the other DMS operators:
   
   `aws_conn_id: str | None = "aws_default"`



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: commits-unsubscribe@airflow.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] Add `DmsModifyTaskOperator` [airflow]

Posted by "SameerMesiah97 (via GitHub)" <gi...@apache.org>.
SameerMesiah97 commented on code in PR #67524:
URL: https://github.com/apache/airflow/pull/67524#discussion_r3314754510


##########
providers/amazon/src/airflow/providers/amazon/aws/operators/dms.py:
##########
@@ -118,6 +121,274 @@ def execute(self, context: Context):
         return task_arn
 
 
+class DmsModifyTaskOperator(AwsBaseOperator[DmsHook]):
+    """
+    Modifies an existing AWS DMS replication task.
+
+    If the task is not already stopped, set ``stop_task_before=True`` to stop it first.
+    To restart the task after modification, set ``restart_task_after=True``.
+
+    .. seealso::
+        For more information on how to use this operator, take a look at the guide:
+        :ref:`howto/operator:DmsModifyTaskOperator`
+
+    :param replication_task_arn: Replication task ARN
+    :param table_mappings: New table mappings. If not provided, existing mappings are kept.
+    :param migration_type: Migration type ('full-load'|'cdc'|'full-load-and-cdc').
+        If not provided, existing type is kept.
+    :param replication_task_settings: Task settings dict. If not provided, existing settings are kept.
+    :param cdc_start_time: Start time for CDC.
+    :param cdc_start_position: Indicates when to start CDC (checkpoint or LSN/SCN format).
+        Mutually exclusive with cdc_start_time.
+    :param cdc_stop_position: Indicates when to stop CDC.
+    :param stop_task_before: If True, stop the task before modifying if it is not already stopped.
+    :param restart_task_after: If True, restart the task after modifying.
+    :param start_replication_task_type: Start type used when restarting the task.
+        One of 'start-replication', 'resume-processing', or 'reload-target'.
+        Defaults to 'resume-processing'. Only used when ``restart_task_after=True``.
+    :param wait_for_completion: Only applies when the task is already in ``modifying`` state
+        when ``execute()`` is called. If True, wait for the modification to finish before
+        proceeding. If False, raises immediately instead of waiting.
+    :param deferrable: Run the operator in deferrable mode.
+    :param waiter_delay: Seconds between waiter polls (default: 30).
+    :param waiter_max_attempts: Maximum waiter poll attempts (default: 60).
+    :param aws_conn_id: The Airflow connection used for AWS credentials.
+        If this is ``None`` or empty then the default boto3 behaviour is used. If
+        running Airflow in a distributed manner and aws_conn_id is None or
+        empty, then default boto3 configuration would be used (and must be
+        maintained on each worker node).
+    :param region_name: AWS region_name. If not specified then the default boto3 behaviour is used.
+    :param verify: Whether or not to verify SSL certificates. See:
+        https://boto3.amazonaws.com/v1/documentation/api/latest/reference/core/session.html
+    :param botocore_config: Configuration dictionary (key-values) for botocore client. See:
+        https://botocore.amazonaws.com/v1/documentation/api/latest/reference/config.html
+    """
+
+    STOPPED_STATES = ("stopped", "ready", "failed", "created")
+    TERMINAL_STATES = frozenset({"failed", "stopped", "ready", "created", "deleting"})
+
+    aws_hook_class = DmsHook
+    template_fields: Sequence[str] = aws_template_fields(
+        "replication_task_arn",
+        "table_mappings",
+        "migration_type",
+        "replication_task_settings",
+        "cdc_start_time",
+        "cdc_start_position",
+        "cdc_stop_position",
+        "start_replication_task_type",
+    )
+    template_fields_renderers: ClassVar[dict] = {
+        "table_mappings": "json",
+        "replication_task_settings": "json",
+    }
+
+    def __init__(
+        self,
+        *,
+        replication_task_arn: str,
+        table_mappings: dict | None = None,
+        migration_type: str | None = None,
+        replication_task_settings: dict | None = None,
+        cdc_start_time: datetime | None = None,
+        cdc_start_position: str | None = None,
+        cdc_stop_position: str | None = None,
+        stop_task_before: bool = False,
+        restart_task_after: bool = False,
+        start_replication_task_type: str = "resume-processing",
+        wait_for_completion: bool = True,
+        deferrable: bool = conf.getboolean("operators", "default_deferrable", fallback=False),
+        waiter_delay: int = 30,
+        waiter_max_attempts: int = 60,
+        **kwargs,
+    ):
+        super().__init__(**kwargs)
+        if cdc_start_time and cdc_start_position:
+            raise ValueError("Only one of cdc_start_time or cdc_start_position can be provided.")
+        self.replication_task_arn = replication_task_arn
+        self.table_mappings = table_mappings
+        self.migration_type = migration_type
+        self.replication_task_settings = replication_task_settings
+        self.cdc_start_time = cdc_start_time
+        self.cdc_start_position = cdc_start_position
+        self.cdc_stop_position = cdc_stop_position
+        self.stop_task_before = stop_task_before
+        self.restart_task_after = restart_task_after
+        self.start_replication_task_type = start_replication_task_type
+        self.wait_for_completion = wait_for_completion
+        self.deferrable = deferrable
+        self.waiter_delay = waiter_delay
+        self.waiter_max_attempts = waiter_max_attempts
+
+    def execute(self, context: Context) -> dict:
+        tasks = self.hook.find_replication_tasks_by_arn(
+            replication_task_arn=self.replication_task_arn, without_settings=True
+        )
+        if not tasks:
+            raise AirflowException(f"Replication task {self.replication_task_arn} not found.")
+
+        current_status = tasks[0].get("Status", "").lower()
+        self.log.info(
+            "Current status of replication task(%s) is '%s'.", self.replication_task_arn, current_status
+        )
+
+        if current_status == "modifying":
+            # boto3 stopped/ready waiters treat 'modifying' as a terminal failure — use poll loop.
+            if not self.wait_for_completion:
+                raise AirflowException(
+                    f"Replication task {self.replication_task_arn} is already being modified. "
+                    f"Set wait_for_completion=True to wait for it to finish."
+                )
+            self._wait_until_not_modifying()
+        elif current_status not in self.STOPPED_STATES:
+            if not self.stop_task_before:
+                raise AirflowException(
+                    f"Replication task {self.replication_task_arn} is in state '{current_status}' "
+                    f"and must be stopped before modification. Set stop_task_before=True to stop it "
+                    f"automatically, or stop the task first."
+                )
+            if current_status == "starting":
+                # DMS rejects StopReplicationTask while the task is still starting up.
+                self.log.info(
+                    "Replication task(%s) is starting, waiting for it to reach 'running'.",
+                    self.replication_task_arn,
+                )
+                self._wait_for_status("running")
+            self.log.info("Stopping replication task(%s).", self.replication_task_arn)
+            self.hook.stop_replication_task(replication_task_arn=self.replication_task_arn)
+            self.log.info("Waiting for replication task(%s) to stop.", self.replication_task_arn)
+            if self.deferrable:

Review Comment:
   1 min is a bit too short to justify deferrable mode for the modification part of the cycle. What is the typical period of time until the DMS replication task is modifiable? Arguably, that part could benefit more from deferrable mode 



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: commits-unsubscribe@airflow.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] Add `DmsModifyTaskOperator` [airflow]

Posted by "SameerMesiah97 (via GitHub)" <gi...@apache.org>.
SameerMesiah97 commented on code in PR #67524:
URL: https://github.com/apache/airflow/pull/67524#discussion_r3329212259


##########
providers/amazon/tests/unit/amazon/aws/operators/test_dms.py:
##########
@@ -180,6 +181,214 @@ def test_default_conn_passed_to_hook(self):
         assert op.hook.aws_conn_id == DEFAULT_CONN
 
 
+class TestDmsModifyTaskOperator:
+    TASK_ARN = "arn:aws:dms:us-east-1:123456789012:task:EXAMPLE"
+    TABLE_MAPPINGS = {
+        "rules": [
+            {
+                "rule-type": "selection",
+                "rule-id": "1",
+                "rule-name": "1",
+                "object-locator": {"schema-name": "myschema", "table-name": "mytable"},
+                "rule-action": "include",
+            }
+        ]
+    }
+
+    def _stopped_task(self):
+        return [{"ReplicationTaskArn": self.TASK_ARN, "Status": "stopped"}]
+
+    def _running_task(self):
+        return [{"ReplicationTaskArn": self.TASK_ARN, "Status": "running"}]
+
+    def _modifying_task(self):
+        return [{"ReplicationTaskArn": self.TASK_ARN, "Status": "modifying"}]
+
+    def test_init(self):
+        op = DmsModifyTaskOperator(
+            task_id="modify_task",
+            replication_task_arn=self.TASK_ARN,
+            table_mappings=self.TABLE_MAPPINGS,
+            migration_type="cdc",
+            aws_conn_id="fake-conn-id",
+            region_name="us-east-1",
+        )
+        assert op.replication_task_arn == self.TASK_ARN
+        assert op.table_mappings == self.TABLE_MAPPINGS
+        assert op.migration_type == "cdc"
+        assert op.wait_for_completion is True
+        assert op.deferrable is False
+        assert op.hook.aws_conn_id == "fake-conn-id"
+        assert op.hook._region_name == "us-east-1"
+
+    def test_init_defaults(self):
+        op = DmsModifyTaskOperator(task_id="modify_task", replication_task_arn=self.TASK_ARN)
+        assert op.table_mappings is None
+        assert op.migration_type is None
+        assert op.replication_task_settings is None
+        assert op.cdc_start_time is None
+        assert op.cdc_start_position is None
+        assert op.cdc_stop_position is None
+        assert op.wait_for_completion is True
+        assert op.deferrable is False
+

Review Comment:
   `test_init` and `test_init_defaults` are not needed as they are essentialy testing native Python behavior.



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: commits-unsubscribe@airflow.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] Add `DmsModifyTaskOperator` [airflow]

Posted by "AlejandroMorgante (via GitHub)" <gi...@apache.org>.
AlejandroMorgante commented on code in PR #67524:
URL: https://github.com/apache/airflow/pull/67524#discussion_r3329271826


##########
providers/amazon/tests/system/amazon/aws/example_dms.py:
##########
@@ -374,6 +375,24 @@ def delete_security_group(security_group_id: str, security_group_name: str):
     )
     # [END howto_operator_dms_stop_task]
 
+    # [START howto_operator_dms_modify_task]
+    modify_task = DmsModifyTaskOperator(
+        task_id="modify_task",
+        replication_task_arn=task_arn,
+        table_mappings={
+            "rules": [
+                {
+                    "rule-type": "selection",
+                    "rule-id": "1",
+                    "rule-name": "1",
+                    "object-locator": {"schema-name": "%", "table-name": "%"},
+                    "rule-action": "include",
+                }
+            ]
+        },
+    )
+    # [END howto_operator_dms_modify_task]

Review Comment:
   Done, reordered to `stop_task -> await_task_stop -> modify_task`.



##########
providers/amazon/tests/unit/amazon/aws/operators/test_dms.py:
##########
@@ -180,6 +181,214 @@ def test_default_conn_passed_to_hook(self):
         assert op.hook.aws_conn_id == DEFAULT_CONN
 
 
+class TestDmsModifyTaskOperator:
+    TASK_ARN = "arn:aws:dms:us-east-1:123456789012:task:EXAMPLE"
+    TABLE_MAPPINGS = {
+        "rules": [
+            {
+                "rule-type": "selection",
+                "rule-id": "1",
+                "rule-name": "1",
+                "object-locator": {"schema-name": "myschema", "table-name": "mytable"},
+                "rule-action": "include",
+            }
+        ]
+    }
+
+    def _stopped_task(self):
+        return [{"ReplicationTaskArn": self.TASK_ARN, "Status": "stopped"}]
+
+    def _running_task(self):
+        return [{"ReplicationTaskArn": self.TASK_ARN, "Status": "running"}]
+
+    def _modifying_task(self):
+        return [{"ReplicationTaskArn": self.TASK_ARN, "Status": "modifying"}]
+
+    def test_init(self):
+        op = DmsModifyTaskOperator(
+            task_id="modify_task",
+            replication_task_arn=self.TASK_ARN,
+            table_mappings=self.TABLE_MAPPINGS,
+            migration_type="cdc",
+            aws_conn_id="fake-conn-id",
+            region_name="us-east-1",
+        )
+        assert op.replication_task_arn == self.TASK_ARN
+        assert op.table_mappings == self.TABLE_MAPPINGS
+        assert op.migration_type == "cdc"
+        assert op.wait_for_completion is True
+        assert op.deferrable is False
+        assert op.hook.aws_conn_id == "fake-conn-id"
+        assert op.hook._region_name == "us-east-1"
+
+    def test_init_defaults(self):
+        op = DmsModifyTaskOperator(task_id="modify_task", replication_task_arn=self.TASK_ARN)
+        assert op.table_mappings is None
+        assert op.migration_type is None
+        assert op.replication_task_settings is None
+        assert op.cdc_start_time is None
+        assert op.cdc_start_position is None
+        assert op.cdc_stop_position is None
+        assert op.wait_for_completion is True
+        assert op.deferrable is False
+

Review Comment:
   Removed both.



##########
providers/amazon/tests/unit/amazon/aws/operators/test_dms.py:
##########
@@ -180,6 +181,214 @@ def test_default_conn_passed_to_hook(self):
         assert op.hook.aws_conn_id == DEFAULT_CONN
 
 
+class TestDmsModifyTaskOperator:
+    TASK_ARN = "arn:aws:dms:us-east-1:123456789012:task:EXAMPLE"
+    TABLE_MAPPINGS = {
+        "rules": [
+            {
+                "rule-type": "selection",
+                "rule-id": "1",
+                "rule-name": "1",
+                "object-locator": {"schema-name": "myschema", "table-name": "mytable"},
+                "rule-action": "include",
+            }
+        ]
+    }
+
+    def _stopped_task(self):
+        return [{"ReplicationTaskArn": self.TASK_ARN, "Status": "stopped"}]
+
+    def _running_task(self):
+        return [{"ReplicationTaskArn": self.TASK_ARN, "Status": "running"}]
+
+    def _modifying_task(self):
+        return [{"ReplicationTaskArn": self.TASK_ARN, "Status": "modifying"}]
+
+    def test_init(self):
+        op = DmsModifyTaskOperator(
+            task_id="modify_task",
+            replication_task_arn=self.TASK_ARN,
+            table_mappings=self.TABLE_MAPPINGS,
+            migration_type="cdc",
+            aws_conn_id="fake-conn-id",
+            region_name="us-east-1",
+        )
+        assert op.replication_task_arn == self.TASK_ARN
+        assert op.table_mappings == self.TABLE_MAPPINGS
+        assert op.migration_type == "cdc"
+        assert op.wait_for_completion is True
+        assert op.deferrable is False
+        assert op.hook.aws_conn_id == "fake-conn-id"
+        assert op.hook._region_name == "us-east-1"
+
+    def test_init_defaults(self):
+        op = DmsModifyTaskOperator(task_id="modify_task", replication_task_arn=self.TASK_ARN)
+        assert op.table_mappings is None
+        assert op.migration_type is None
+        assert op.replication_task_settings is None
+        assert op.cdc_start_time is None
+        assert op.cdc_start_position is None
+        assert op.cdc_stop_position is None
+        assert op.wait_for_completion is True
+        assert op.deferrable is False
+
+    def test_init_raises_if_both_cdc_start_params_provided(self):
+        from datetime import datetime
+
+        with pytest.raises(ValueError, match="Only one of"):
+            DmsModifyTaskOperator(
+                task_id="modify_task",
+                replication_task_arn=self.TASK_ARN,
+                cdc_start_time=datetime(2024, 1, 1),
+                cdc_start_position="mysql-bin.000001:4",
+            )
+
+    @mock.patch.object(DmsHook, "find_replication_tasks_by_arn")
+    @mock.patch.object(DmsHook, "get_conn")
+    def test_modify_task_already_stopped(self, mock_conn, mock_find):
+        mock_find.return_value = self._stopped_task()
+        expected = {"ReplicationTaskArn": self.TASK_ARN}
+        with mock.patch.object(DmsHook, "modify_replication_task", return_value=expected) as mock_modify:
+            op = DmsModifyTaskOperator(
+                task_id="modify_task",
+                replication_task_arn=self.TASK_ARN,
+                table_mappings=self.TABLE_MAPPINGS,
+                wait_for_completion=False,
+            )
+            result = op.execute(None)
+
+            mock_modify.assert_called_once_with(
+                replication_task_arn=self.TASK_ARN,
+                table_mappings=self.TABLE_MAPPINGS,
+                migration_type=None,
+                replication_task_settings=None,
+                cdc_start_time=None,
+                cdc_start_position=None,
+                cdc_stop_position=None,
+            )
+            assert result == expected
+
+    @mock.patch.object(DmsHook, "find_replication_tasks_by_arn")
+    @mock.patch.object(DmsHook, "get_conn")
+    def test_modify_task_raises_if_running(self, mock_conn, mock_find):
+        mock_find.return_value = self._running_task()
+        op = DmsModifyTaskOperator(
+            task_id="modify_task",
+            replication_task_arn=self.TASK_ARN,
+        )
+        with pytest.raises(RuntimeError, match="must be stopped"):
+            op.execute(None)
+
+    @mock.patch.object(DmsHook, "find_replication_tasks_by_arn")
+    @mock.patch.object(DmsHook, "get_conn")
+    def test_modify_task_raises_if_not_found(self, mock_conn, mock_find):
+        mock_find.return_value = []
+        op = DmsModifyTaskOperator(task_id="modify_task", replication_task_arn=self.TASK_ARN)
+        with pytest.raises(ValueError, match="not found"):
+            op.execute(None)
+
+    @mock.patch.object(DmsHook, "find_replication_tasks_by_arn")
+    @mock.patch.object(DmsHook, "get_conn")
+    def test_modify_task_defers_for_completion(self, mock_conn, mock_find):
+        from airflow.exceptions import TaskDeferred

Review Comment:
   Done.



##########
providers/amazon/tests/unit/amazon/aws/operators/test_dms.py:
##########
@@ -180,6 +181,214 @@ def test_default_conn_passed_to_hook(self):
         assert op.hook.aws_conn_id == DEFAULT_CONN
 
 
+class TestDmsModifyTaskOperator:
+    TASK_ARN = "arn:aws:dms:us-east-1:123456789012:task:EXAMPLE"
+    TABLE_MAPPINGS = {
+        "rules": [
+            {
+                "rule-type": "selection",
+                "rule-id": "1",
+                "rule-name": "1",
+                "object-locator": {"schema-name": "myschema", "table-name": "mytable"},
+                "rule-action": "include",
+            }
+        ]
+    }
+
+    def _stopped_task(self):
+        return [{"ReplicationTaskArn": self.TASK_ARN, "Status": "stopped"}]
+
+    def _running_task(self):
+        return [{"ReplicationTaskArn": self.TASK_ARN, "Status": "running"}]
+
+    def _modifying_task(self):
+        return [{"ReplicationTaskArn": self.TASK_ARN, "Status": "modifying"}]
+
+    def test_init(self):
+        op = DmsModifyTaskOperator(
+            task_id="modify_task",
+            replication_task_arn=self.TASK_ARN,
+            table_mappings=self.TABLE_MAPPINGS,
+            migration_type="cdc",
+            aws_conn_id="fake-conn-id",
+            region_name="us-east-1",
+        )
+        assert op.replication_task_arn == self.TASK_ARN
+        assert op.table_mappings == self.TABLE_MAPPINGS
+        assert op.migration_type == "cdc"
+        assert op.wait_for_completion is True
+        assert op.deferrable is False
+        assert op.hook.aws_conn_id == "fake-conn-id"
+        assert op.hook._region_name == "us-east-1"
+
+    def test_init_defaults(self):
+        op = DmsModifyTaskOperator(task_id="modify_task", replication_task_arn=self.TASK_ARN)
+        assert op.table_mappings is None
+        assert op.migration_type is None
+        assert op.replication_task_settings is None
+        assert op.cdc_start_time is None
+        assert op.cdc_start_position is None
+        assert op.cdc_stop_position is None
+        assert op.wait_for_completion is True
+        assert op.deferrable is False
+
+    def test_init_raises_if_both_cdc_start_params_provided(self):
+        from datetime import datetime
+
+        with pytest.raises(ValueError, match="Only one of"):
+            DmsModifyTaskOperator(
+                task_id="modify_task",
+                replication_task_arn=self.TASK_ARN,
+                cdc_start_time=datetime(2024, 1, 1),
+                cdc_start_position="mysql-bin.000001:4",
+            )
+
+    @mock.patch.object(DmsHook, "find_replication_tasks_by_arn")
+    @mock.patch.object(DmsHook, "get_conn")
+    def test_modify_task_already_stopped(self, mock_conn, mock_find):
+        mock_find.return_value = self._stopped_task()
+        expected = {"ReplicationTaskArn": self.TASK_ARN}
+        with mock.patch.object(DmsHook, "modify_replication_task", return_value=expected) as mock_modify:
+            op = DmsModifyTaskOperator(
+                task_id="modify_task",
+                replication_task_arn=self.TASK_ARN,
+                table_mappings=self.TABLE_MAPPINGS,
+                wait_for_completion=False,
+            )
+            result = op.execute(None)
+
+            mock_modify.assert_called_once_with(
+                replication_task_arn=self.TASK_ARN,
+                table_mappings=self.TABLE_MAPPINGS,
+                migration_type=None,
+                replication_task_settings=None,
+                cdc_start_time=None,
+                cdc_start_position=None,
+                cdc_stop_position=None,
+            )
+            assert result == expected
+
+    @mock.patch.object(DmsHook, "find_replication_tasks_by_arn")
+    @mock.patch.object(DmsHook, "get_conn")
+    def test_modify_task_raises_if_running(self, mock_conn, mock_find):
+        mock_find.return_value = self._running_task()
+        op = DmsModifyTaskOperator(
+            task_id="modify_task",
+            replication_task_arn=self.TASK_ARN,
+        )
+        with pytest.raises(RuntimeError, match="must be stopped"):
+            op.execute(None)
+
+    @mock.patch.object(DmsHook, "find_replication_tasks_by_arn")
+    @mock.patch.object(DmsHook, "get_conn")
+    def test_modify_task_raises_if_not_found(self, mock_conn, mock_find):
+        mock_find.return_value = []
+        op = DmsModifyTaskOperator(task_id="modify_task", replication_task_arn=self.TASK_ARN)
+        with pytest.raises(ValueError, match="not found"):
+            op.execute(None)
+
+    @mock.patch.object(DmsHook, "find_replication_tasks_by_arn")
+    @mock.patch.object(DmsHook, "get_conn")
+    def test_modify_task_defers_for_completion(self, mock_conn, mock_find):
+        from airflow.exceptions import TaskDeferred
+        from airflow.providers.amazon.aws.triggers.dms import DmsTaskModifyCompleteTrigger

Review Comment:
   Done.



##########
providers/amazon/tests/unit/amazon/aws/operators/test_dms.py:
##########
@@ -180,6 +181,214 @@ def test_default_conn_passed_to_hook(self):
         assert op.hook.aws_conn_id == DEFAULT_CONN
 
 
+class TestDmsModifyTaskOperator:
+    TASK_ARN = "arn:aws:dms:us-east-1:123456789012:task:EXAMPLE"
+    TABLE_MAPPINGS = {
+        "rules": [
+            {
+                "rule-type": "selection",
+                "rule-id": "1",
+                "rule-name": "1",
+                "object-locator": {"schema-name": "myschema", "table-name": "mytable"},
+                "rule-action": "include",
+            }
+        ]
+    }
+
+    def _stopped_task(self):
+        return [{"ReplicationTaskArn": self.TASK_ARN, "Status": "stopped"}]
+
+    def _running_task(self):
+        return [{"ReplicationTaskArn": self.TASK_ARN, "Status": "running"}]
+
+    def _modifying_task(self):
+        return [{"ReplicationTaskArn": self.TASK_ARN, "Status": "modifying"}]
+
+    def test_init(self):
+        op = DmsModifyTaskOperator(
+            task_id="modify_task",
+            replication_task_arn=self.TASK_ARN,
+            table_mappings=self.TABLE_MAPPINGS,
+            migration_type="cdc",
+            aws_conn_id="fake-conn-id",
+            region_name="us-east-1",
+        )
+        assert op.replication_task_arn == self.TASK_ARN
+        assert op.table_mappings == self.TABLE_MAPPINGS
+        assert op.migration_type == "cdc"
+        assert op.wait_for_completion is True
+        assert op.deferrable is False
+        assert op.hook.aws_conn_id == "fake-conn-id"
+        assert op.hook._region_name == "us-east-1"
+
+    def test_init_defaults(self):
+        op = DmsModifyTaskOperator(task_id="modify_task", replication_task_arn=self.TASK_ARN)
+        assert op.table_mappings is None
+        assert op.migration_type is None
+        assert op.replication_task_settings is None
+        assert op.cdc_start_time is None
+        assert op.cdc_start_position is None
+        assert op.cdc_stop_position is None
+        assert op.wait_for_completion is True
+        assert op.deferrable is False
+
+    def test_init_raises_if_both_cdc_start_params_provided(self):
+        from datetime import datetime
+
+        with pytest.raises(ValueError, match="Only one of"):
+            DmsModifyTaskOperator(
+                task_id="modify_task",
+                replication_task_arn=self.TASK_ARN,
+                cdc_start_time=datetime(2024, 1, 1),
+                cdc_start_position="mysql-bin.000001:4",
+            )
+
+    @mock.patch.object(DmsHook, "find_replication_tasks_by_arn")
+    @mock.patch.object(DmsHook, "get_conn")
+    def test_modify_task_already_stopped(self, mock_conn, mock_find):
+        mock_find.return_value = self._stopped_task()
+        expected = {"ReplicationTaskArn": self.TASK_ARN}
+        with mock.patch.object(DmsHook, "modify_replication_task", return_value=expected) as mock_modify:
+            op = DmsModifyTaskOperator(
+                task_id="modify_task",
+                replication_task_arn=self.TASK_ARN,
+                table_mappings=self.TABLE_MAPPINGS,
+                wait_for_completion=False,
+            )
+            result = op.execute(None)
+
+            mock_modify.assert_called_once_with(
+                replication_task_arn=self.TASK_ARN,
+                table_mappings=self.TABLE_MAPPINGS,
+                migration_type=None,
+                replication_task_settings=None,
+                cdc_start_time=None,
+                cdc_start_position=None,
+                cdc_stop_position=None,
+            )
+            assert result == expected
+
+    @mock.patch.object(DmsHook, "find_replication_tasks_by_arn")
+    @mock.patch.object(DmsHook, "get_conn")
+    def test_modify_task_raises_if_running(self, mock_conn, mock_find):
+        mock_find.return_value = self._running_task()
+        op = DmsModifyTaskOperator(
+            task_id="modify_task",
+            replication_task_arn=self.TASK_ARN,
+        )
+        with pytest.raises(RuntimeError, match="must be stopped"):
+            op.execute(None)
+
+    @mock.patch.object(DmsHook, "find_replication_tasks_by_arn")
+    @mock.patch.object(DmsHook, "get_conn")
+    def test_modify_task_raises_if_not_found(self, mock_conn, mock_find):
+        mock_find.return_value = []
+        op = DmsModifyTaskOperator(task_id="modify_task", replication_task_arn=self.TASK_ARN)
+        with pytest.raises(ValueError, match="not found"):
+            op.execute(None)
+
+    @mock.patch.object(DmsHook, "find_replication_tasks_by_arn")
+    @mock.patch.object(DmsHook, "get_conn")
+    def test_modify_task_defers_for_completion(self, mock_conn, mock_find):
+        from airflow.exceptions import TaskDeferred
+        from airflow.providers.amazon.aws.triggers.dms import DmsTaskModifyCompleteTrigger
+
+        mock_find.return_value = self._stopped_task()
+        expected = {"ReplicationTaskArn": self.TASK_ARN}
+        with mock.patch.object(DmsHook, "modify_replication_task", return_value=expected):
+            op = DmsModifyTaskOperator(
+                task_id="modify_task",
+                replication_task_arn=self.TASK_ARN,
+                deferrable=True,
+                wait_for_completion=True,
+            )
+            with pytest.raises(TaskDeferred) as exc_info:
+                op.execute(None)
+
+        assert isinstance(exc_info.value.trigger, DmsTaskModifyCompleteTrigger)
+        assert exc_info.value.method_name == "execute_complete"
+
+    @mock.patch.object(DmsHook, "find_replication_tasks_by_arn")
+    @mock.patch.object(DmsHook, "get_conn")
+    def test_modify_task_with_all_params(self, mock_conn, mock_find):
+        from datetime import datetime

Review Comment:
   Done.



##########
providers/amazon/tests/unit/amazon/aws/operators/test_dms.py:
##########
@@ -180,6 +181,214 @@ def test_default_conn_passed_to_hook(self):
         assert op.hook.aws_conn_id == DEFAULT_CONN
 
 
+class TestDmsModifyTaskOperator:
+    TASK_ARN = "arn:aws:dms:us-east-1:123456789012:task:EXAMPLE"
+    TABLE_MAPPINGS = {
+        "rules": [
+            {
+                "rule-type": "selection",
+                "rule-id": "1",
+                "rule-name": "1",
+                "object-locator": {"schema-name": "myschema", "table-name": "mytable"},
+                "rule-action": "include",
+            }
+        ]
+    }
+
+    def _stopped_task(self):
+        return [{"ReplicationTaskArn": self.TASK_ARN, "Status": "stopped"}]
+
+    def _running_task(self):
+        return [{"ReplicationTaskArn": self.TASK_ARN, "Status": "running"}]
+
+    def _modifying_task(self):
+        return [{"ReplicationTaskArn": self.TASK_ARN, "Status": "modifying"}]
+
+    def test_init(self):
+        op = DmsModifyTaskOperator(
+            task_id="modify_task",
+            replication_task_arn=self.TASK_ARN,
+            table_mappings=self.TABLE_MAPPINGS,
+            migration_type="cdc",
+            aws_conn_id="fake-conn-id",
+            region_name="us-east-1",
+        )
+        assert op.replication_task_arn == self.TASK_ARN
+        assert op.table_mappings == self.TABLE_MAPPINGS
+        assert op.migration_type == "cdc"
+        assert op.wait_for_completion is True
+        assert op.deferrable is False
+        assert op.hook.aws_conn_id == "fake-conn-id"
+        assert op.hook._region_name == "us-east-1"
+
+    def test_init_defaults(self):
+        op = DmsModifyTaskOperator(task_id="modify_task", replication_task_arn=self.TASK_ARN)
+        assert op.table_mappings is None
+        assert op.migration_type is None
+        assert op.replication_task_settings is None
+        assert op.cdc_start_time is None
+        assert op.cdc_start_position is None
+        assert op.cdc_stop_position is None
+        assert op.wait_for_completion is True
+        assert op.deferrable is False
+
+    def test_init_raises_if_both_cdc_start_params_provided(self):
+        from datetime import datetime

Review Comment:
   Done.



##########
providers/amazon/tests/unit/amazon/aws/operators/test_dms.py:
##########
@@ -180,6 +181,214 @@ def test_default_conn_passed_to_hook(self):
         assert op.hook.aws_conn_id == DEFAULT_CONN
 
 
+class TestDmsModifyTaskOperator:
+    TASK_ARN = "arn:aws:dms:us-east-1:123456789012:task:EXAMPLE"
+    TABLE_MAPPINGS = {
+        "rules": [
+            {
+                "rule-type": "selection",
+                "rule-id": "1",
+                "rule-name": "1",
+                "object-locator": {"schema-name": "myschema", "table-name": "mytable"},
+                "rule-action": "include",
+            }
+        ]
+    }
+
+    def _stopped_task(self):
+        return [{"ReplicationTaskArn": self.TASK_ARN, "Status": "stopped"}]
+
+    def _running_task(self):
+        return [{"ReplicationTaskArn": self.TASK_ARN, "Status": "running"}]
+
+    def _modifying_task(self):
+        return [{"ReplicationTaskArn": self.TASK_ARN, "Status": "modifying"}]
+
+    def test_init(self):
+        op = DmsModifyTaskOperator(
+            task_id="modify_task",
+            replication_task_arn=self.TASK_ARN,
+            table_mappings=self.TABLE_MAPPINGS,
+            migration_type="cdc",
+            aws_conn_id="fake-conn-id",
+            region_name="us-east-1",
+        )
+        assert op.replication_task_arn == self.TASK_ARN
+        assert op.table_mappings == self.TABLE_MAPPINGS
+        assert op.migration_type == "cdc"
+        assert op.wait_for_completion is True
+        assert op.deferrable is False
+        assert op.hook.aws_conn_id == "fake-conn-id"
+        assert op.hook._region_name == "us-east-1"
+
+    def test_init_defaults(self):
+        op = DmsModifyTaskOperator(task_id="modify_task", replication_task_arn=self.TASK_ARN)
+        assert op.table_mappings is None
+        assert op.migration_type is None
+        assert op.replication_task_settings is None
+        assert op.cdc_start_time is None
+        assert op.cdc_start_position is None
+        assert op.cdc_stop_position is None
+        assert op.wait_for_completion is True
+        assert op.deferrable is False
+
+    def test_init_raises_if_both_cdc_start_params_provided(self):
+        from datetime import datetime
+
+        with pytest.raises(ValueError, match="Only one of"):
+            DmsModifyTaskOperator(
+                task_id="modify_task",
+                replication_task_arn=self.TASK_ARN,
+                cdc_start_time=datetime(2024, 1, 1),
+                cdc_start_position="mysql-bin.000001:4",
+            )
+
+    @mock.patch.object(DmsHook, "find_replication_tasks_by_arn")
+    @mock.patch.object(DmsHook, "get_conn")
+    def test_modify_task_already_stopped(self, mock_conn, mock_find):
+        mock_find.return_value = self._stopped_task()
+        expected = {"ReplicationTaskArn": self.TASK_ARN}
+        with mock.patch.object(DmsHook, "modify_replication_task", return_value=expected) as mock_modify:
+            op = DmsModifyTaskOperator(
+                task_id="modify_task",
+                replication_task_arn=self.TASK_ARN,
+                table_mappings=self.TABLE_MAPPINGS,
+                wait_for_completion=False,
+            )
+            result = op.execute(None)
+
+            mock_modify.assert_called_once_with(
+                replication_task_arn=self.TASK_ARN,
+                table_mappings=self.TABLE_MAPPINGS,
+                migration_type=None,
+                replication_task_settings=None,
+                cdc_start_time=None,
+                cdc_start_position=None,
+                cdc_stop_position=None,
+            )
+            assert result == expected
+
+    @mock.patch.object(DmsHook, "find_replication_tasks_by_arn")
+    @mock.patch.object(DmsHook, "get_conn")
+    def test_modify_task_raises_if_running(self, mock_conn, mock_find):
+        mock_find.return_value = self._running_task()
+        op = DmsModifyTaskOperator(
+            task_id="modify_task",
+            replication_task_arn=self.TASK_ARN,
+        )
+        with pytest.raises(RuntimeError, match="must be stopped"):
+            op.execute(None)
+
+    @mock.patch.object(DmsHook, "find_replication_tasks_by_arn")
+    @mock.patch.object(DmsHook, "get_conn")
+    def test_modify_task_raises_if_not_found(self, mock_conn, mock_find):
+        mock_find.return_value = []
+        op = DmsModifyTaskOperator(task_id="modify_task", replication_task_arn=self.TASK_ARN)
+        with pytest.raises(ValueError, match="not found"):
+            op.execute(None)
+
+    @mock.patch.object(DmsHook, "find_replication_tasks_by_arn")
+    @mock.patch.object(DmsHook, "get_conn")
+    def test_modify_task_defers_for_completion(self, mock_conn, mock_find):
+        from airflow.exceptions import TaskDeferred
+        from airflow.providers.amazon.aws.triggers.dms import DmsTaskModifyCompleteTrigger
+
+        mock_find.return_value = self._stopped_task()
+        expected = {"ReplicationTaskArn": self.TASK_ARN}
+        with mock.patch.object(DmsHook, "modify_replication_task", return_value=expected):
+            op = DmsModifyTaskOperator(
+                task_id="modify_task",
+                replication_task_arn=self.TASK_ARN,
+                deferrable=True,
+                wait_for_completion=True,
+            )
+            with pytest.raises(TaskDeferred) as exc_info:
+                op.execute(None)
+
+        assert isinstance(exc_info.value.trigger, DmsTaskModifyCompleteTrigger)
+        assert exc_info.value.method_name == "execute_complete"
+
+    @mock.patch.object(DmsHook, "find_replication_tasks_by_arn")
+    @mock.patch.object(DmsHook, "get_conn")
+    def test_modify_task_with_all_params(self, mock_conn, mock_find):
+        from datetime import datetime
+
+        mock_find.return_value = self._stopped_task()
+        cdc_start = datetime(2024, 1, 1)
+        expected = {"ReplicationTaskArn": self.TASK_ARN}
+        with mock.patch.object(DmsHook, "modify_replication_task", return_value=expected) as mock_modify:
+            op = DmsModifyTaskOperator(
+                task_id="modify_task",
+                replication_task_arn=self.TASK_ARN,
+                table_mappings=self.TABLE_MAPPINGS,
+                migration_type="full-load-and-cdc",
+                replication_task_settings={"TargetMetadata": {}},
+                cdc_start_time=cdc_start,
+                cdc_stop_position="2024-01-31:00:00:00",
+            )
+            op.execute(None)
+
+            mock_modify.assert_called_once_with(
+                replication_task_arn=self.TASK_ARN,
+                table_mappings=self.TABLE_MAPPINGS,
+                migration_type="full-load-and-cdc",
+                replication_task_settings={"TargetMetadata": {}},
+                cdc_start_time=cdc_start,
+                cdc_start_position=None,
+                cdc_stop_position="2024-01-31:00:00:00",
+            )
+
+    @mock.patch.object(DmsHook, "find_replication_tasks_by_arn")
+    @mock.patch.object(DmsHook, "get_conn")
+    def test_modify_task_waits_if_modifying(self, mock_conn, mock_find):
+        stopped_task = self._stopped_task()
+        expected = {"ReplicationTaskArn": self.TASK_ARN}
+        # execute() sees 'modifying' → _wait_until_not_modifying polls once → 'stopped';
+        # modify is called; wait_for_completion=True → _wait_until_not_modifying polls once → 'stopped'.
+        mock_find.side_effect = [
+            self._modifying_task(),
+            stopped_task,
+            stopped_task,
+        ]
+        with mock.patch.object(DmsHook, "modify_replication_task", return_value=expected) as mock_modify:
+            op = DmsModifyTaskOperator(
+                task_id="modify_task",
+                replication_task_arn=self.TASK_ARN,
+                table_mappings=self.TABLE_MAPPINGS,
+                wait_for_completion=True,
+                waiter_delay=0,
+            )
+            op.execute(None)
+
+            mock_modify.assert_called_once()
+
+    def test_execute_complete_success(self):

Review Comment:
   Added `TestDmsTaskModifyCompleteTrigger` in `tests/unit/amazon/aws/triggers/test_dms.py` covering serialization, success, task not found, timeout, unexpected state, and exception.



##########
providers/amazon/tests/unit/amazon/aws/operators/test_dms.py:
##########
@@ -180,6 +181,214 @@ def test_default_conn_passed_to_hook(self):
         assert op.hook.aws_conn_id == DEFAULT_CONN
 
 
+class TestDmsModifyTaskOperator:
+    TASK_ARN = "arn:aws:dms:us-east-1:123456789012:task:EXAMPLE"
+    TABLE_MAPPINGS = {
+        "rules": [
+            {
+                "rule-type": "selection",
+                "rule-id": "1",
+                "rule-name": "1",
+                "object-locator": {"schema-name": "myschema", "table-name": "mytable"},
+                "rule-action": "include",
+            }
+        ]
+    }
+
+    def _stopped_task(self):
+        return [{"ReplicationTaskArn": self.TASK_ARN, "Status": "stopped"}]
+
+    def _running_task(self):
+        return [{"ReplicationTaskArn": self.TASK_ARN, "Status": "running"}]
+
+    def _modifying_task(self):
+        return [{"ReplicationTaskArn": self.TASK_ARN, "Status": "modifying"}]
+
+    def test_init(self):
+        op = DmsModifyTaskOperator(
+            task_id="modify_task",
+            replication_task_arn=self.TASK_ARN,
+            table_mappings=self.TABLE_MAPPINGS,
+            migration_type="cdc",
+            aws_conn_id="fake-conn-id",
+            region_name="us-east-1",
+        )
+        assert op.replication_task_arn == self.TASK_ARN
+        assert op.table_mappings == self.TABLE_MAPPINGS
+        assert op.migration_type == "cdc"
+        assert op.wait_for_completion is True
+        assert op.deferrable is False
+        assert op.hook.aws_conn_id == "fake-conn-id"
+        assert op.hook._region_name == "us-east-1"
+
+    def test_init_defaults(self):
+        op = DmsModifyTaskOperator(task_id="modify_task", replication_task_arn=self.TASK_ARN)
+        assert op.table_mappings is None
+        assert op.migration_type is None
+        assert op.replication_task_settings is None
+        assert op.cdc_start_time is None
+        assert op.cdc_start_position is None
+        assert op.cdc_stop_position is None
+        assert op.wait_for_completion is True
+        assert op.deferrable is False
+
+    def test_init_raises_if_both_cdc_start_params_provided(self):
+        from datetime import datetime
+
+        with pytest.raises(ValueError, match="Only one of"):
+            DmsModifyTaskOperator(
+                task_id="modify_task",
+                replication_task_arn=self.TASK_ARN,
+                cdc_start_time=datetime(2024, 1, 1),
+                cdc_start_position="mysql-bin.000001:4",
+            )
+
+    @mock.patch.object(DmsHook, "find_replication_tasks_by_arn")
+    @mock.patch.object(DmsHook, "get_conn")
+    def test_modify_task_already_stopped(self, mock_conn, mock_find):

Review Comment:
   Done, generalized to `test_modify_task_modifiable_states` parametrized over stopped, ready, and failed.



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: commits-unsubscribe@airflow.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] Add `DmsModifyTaskOperator` [airflow]

Posted by "AlejandroMorgante (via GitHub)" <gi...@apache.org>.
AlejandroMorgante commented on code in PR #67524:
URL: https://github.com/apache/airflow/pull/67524#discussion_r3329271062


##########
providers/amazon/src/airflow/providers/amazon/aws/operators/dms.py:
##########
@@ -118,6 +120,178 @@ def execute(self, context: Context):
         return task_arn
 
 
+class DmsModifyTaskOperator(AwsBaseOperator[DmsHook]):
+    """
+    Modifies an existing AWS DMS replication task.
+
+    The task must already be stopped before modification. Use :class:`DmsStopTaskOperator`
+    upstream in the Dag to stop it, and :class:`DmsStartTaskOperator` downstream to restart
+    it afterwards if needed.
+
+    .. seealso::
+        For more information on how to use this operator, take a look at the guide:
+        :ref:`howto/operator:DmsModifyTaskOperator`
+
+    :param replication_task_arn: Replication task ARN
+    :param table_mappings: New table mappings. If not provided, existing mappings are kept.
+    :param migration_type: Migration type ('full-load'|'cdc'|'full-load-and-cdc').
+        If not provided, existing type is kept.
+    :param replication_task_settings: Task settings dict. If not provided, existing settings are kept.
+    :param cdc_start_time: Start time for CDC.
+    :param cdc_start_position: Indicates when to start CDC (checkpoint or LSN/SCN format).
+        Mutually exclusive with cdc_start_time.
+    :param cdc_stop_position: Indicates when to stop CDC.
+    :param wait_for_completion: If True, wait for the modification to finish before returning.
+        In deferrable mode the operator defers rather than blocking. Defaults to True.
+    :param deferrable: Run the operator in deferrable mode. Defaults to False.
+    :param waiter_delay: Seconds between waiter polls (default: 30).
+    :param waiter_max_attempts: Maximum waiter poll attempts (default: 60).
+    :param aws_conn_id: The Airflow connection used for AWS credentials.
+        If this is ``None`` or empty then the default boto3 behaviour is used. If
+        running Airflow in a distributed manner and aws_conn_id is None or
+        empty, then default boto3 configuration would be used (and must be
+        maintained on each worker node).
+    :param region_name: AWS region_name. If not specified then the default boto3 behaviour is used.
+    :param verify: Whether or not to verify SSL certificates. See:
+        https://boto3.amazonaws.com/v1/documentation/api/latest/reference/core/session.html
+    :param botocore_config: Configuration dictionary (key-values) for botocore client. See:
+        https://botocore.amazonaws.com/v1/documentation/api/latest/reference/config.html
+    """
+
+    MODIFIABLE_STATES = frozenset({DmsTaskState.STOPPED, DmsTaskState.READY, DmsTaskState.FAILED})
+
+    aws_hook_class = DmsHook
+    template_fields: Sequence[str] = aws_template_fields(
+        "replication_task_arn",
+        "table_mappings",
+        "migration_type",
+        "replication_task_settings",
+        "cdc_start_time",
+        "cdc_start_position",
+        "cdc_stop_position",
+    )
+    template_fields_renderers: ClassVar[dict] = {
+        "table_mappings": "json",
+        "replication_task_settings": "json",
+    }
+
+    def __init__(
+        self,
+        *,
+        replication_task_arn: str,
+        table_mappings: dict | None = None,
+        migration_type: str | None = None,
+        replication_task_settings: dict | None = None,
+        cdc_start_time: datetime | None = None,
+        cdc_start_position: str | None = None,
+        cdc_stop_position: str | None = None,
+        wait_for_completion: bool = True,
+        deferrable: bool = conf.getboolean("operators", "default_deferrable", fallback=False),
+        waiter_delay: int = 30,
+        waiter_max_attempts: int = 60,
+        **kwargs,
+    ):
+        super().__init__(**kwargs)
+        if cdc_start_time and cdc_start_position:
+            raise ValueError("Only one of cdc_start_time or cdc_start_position can be provided.")
+        self.replication_task_arn = replication_task_arn
+        self.table_mappings = table_mappings
+        self.migration_type = migration_type
+        self.replication_task_settings = replication_task_settings
+        self.cdc_start_time = cdc_start_time
+        self.cdc_start_position = cdc_start_position
+        self.cdc_stop_position = cdc_stop_position
+        self.wait_for_completion = wait_for_completion
+        self.deferrable = deferrable
+        self.waiter_delay = waiter_delay
+        self.waiter_max_attempts = waiter_max_attempts
+
+    def execute(self, context: Context) -> dict:
+        tasks = self.hook.find_replication_tasks_by_arn(
+            replication_task_arn=self.replication_task_arn, without_settings=True
+        )
+        if not tasks:
+            raise ValueError(f"Replication task {self.replication_task_arn} not found.")
+
+        current_status = tasks[0].get("Status", "").lower()
+        self.log.info(
+            "Current status of replication task(%s) is '%s'.", self.replication_task_arn, current_status
+        )
+
+        if current_status == DmsTaskState.MODIFYING:
+            # boto3 stopped/ready waiters treat 'modifying' as a terminal failure — use poll loop.
+            self._wait_until_not_modifying()
+        elif current_status not in self.MODIFIABLE_STATES:
+            raise RuntimeError(
+                f"Replication task {self.replication_task_arn} is in state '{current_status}' "
+                f"and must be stopped before modification. "
+                f"Use DmsStopTaskOperator to stop it first."

Review Comment:
   Good catch, fixed — message now reads "must be in a modifiable state (stopped, ready, or failed)".



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: commits-unsubscribe@airflow.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] Add `DmsModifyTaskOperator` [airflow]

Posted by "SameerMesiah97 (via GitHub)" <gi...@apache.org>.
SameerMesiah97 commented on PR #67524:
URL: https://github.com/apache/airflow/pull/67524#issuecomment-4584567906

   > @SameerMesiah97 -> are you fine with the changes ? They seemed to simplify a lot
   
   I think @AlejandroMorgante has done well to streamline the approach but I believe this needs a bit more before it can be merged. I just completed a line by line review just now. Also, it would not hurt to get opinions from @vincbeck and/or @o-nikolas on this as they are likely to have more DMS expertise.. 


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: commits-unsubscribe@airflow.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] Add `DmsModifyTaskOperator` [airflow]

Posted by "AlejandroMorgante (via GitHub)" <gi...@apache.org>.
AlejandroMorgante commented on code in PR #67524:
URL: https://github.com/apache/airflow/pull/67524#discussion_r3329424530


##########
providers/amazon/src/airflow/providers/amazon/aws/triggers/dms.py:
##########
@@ -219,3 +222,79 @@ def hook(self) -> AwsGenericHook:
             verify=self.verify,
             config=self.botocore_config,
         )
+
+
+class DmsTaskModifyCompleteTrigger(BaseTrigger):
+    """
+    Trigger that polls until a DMS classic replication task exits the ``modifying`` state.
+
+    The boto3 ``replication_task_stopped`` waiter treats ``modifying`` as a terminal failure,
+    so a custom polling loop is required here.
+
+    :param replication_task_arn: The ARN of the replication task.
+    :param waiter_delay: Seconds between polls.
+    :param waiter_max_attempts: Maximum number of poll attempts before giving up.
+    :param aws_conn_id: The Airflow connection used for AWS credentials.
+    :param verify: Whether or not to verify SSL certificates.
+    :param botocore_config: Configuration dictionary (key-values) for botocore client.
+    """
+
+    def __init__(
+        self,
+        replication_task_arn: str,
+        waiter_delay: int = 30,
+        waiter_max_attempts: int = 60,
+        aws_conn_id: str | None = "aws_default",
+        verify: bool | str | None = None,
+        botocore_config: dict | None = None,
+    ) -> None:
+        super().__init__()
+        self.replication_task_arn = replication_task_arn
+        self.waiter_delay = waiter_delay
+        self.waiter_max_attempts = waiter_max_attempts
+        self.aws_conn_id = aws_conn_id
+        self.verify = verify
+        self.botocore_config = botocore_config
+
+    def serialize(self) -> tuple[str, dict]:
+        return (
+            "airflow.providers.amazon.aws.triggers.dms.DmsTaskModifyCompleteTrigger",
+            {
+                "replication_task_arn": self.replication_task_arn,
+                "waiter_delay": self.waiter_delay,
+                "waiter_max_attempts": self.waiter_max_attempts,
+                "aws_conn_id": self.aws_conn_id,
+                "verify": self.verify,
+                "botocore_config": self.botocore_config,
+            },
+        )
+
+    async def run(self) -> AsyncIterator[TriggerEvent]:
+        hook = DmsHook(aws_conn_id=self.aws_conn_id, verify=self.verify, config=self.botocore_config)
+        try:
+            for _ in range(self.waiter_max_attempts):
+                status = await hook.get_task_status_async(self.replication_task_arn)
+                if status != "modifying":

Review Comment:
   Done — using `DmsTaskState.MODIFYING` now. (`DmsTaskWaiterStatus` doesn't include `MODIFYING` — it only covers the four states boto3 waiters target: deleted, ready, running, stopped.)
   
   On the state handling: the trigger checks `status is None` (task not found → error), then validates the final state against `DMS_MODIFIABLE_STATES` (stopped, ready, failed → success; anything else → error with the unexpected state in the message). Timeout and exceptions each yield their own error events.



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: commits-unsubscribe@airflow.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] Add `DmsModifyTaskOperator` [airflow]

Posted by "boring-cyborg[bot] (via GitHub)" <gi...@apache.org>.
boring-cyborg[bot] commented on PR #67524:
URL: https://github.com/apache/airflow/pull/67524#issuecomment-4540210086

   Congratulations on your first Pull Request and welcome to the Apache Airflow community! If you have any issues or are unsure about any anything please check our [Contributors' Guide](https://github.com/apache/airflow/blob/main/contributing-docs/README.rst)
   Here are some useful points:
   - Pay attention to the quality of your code (ruff, mypy and type annotations). Our [prek-hooks]( https://github.com/apache/airflow/blob/main/contributing-docs/08_static_code_checks.rst#prerequisites-for-prek-hooks) will help you with that.
   - In case of a new feature add useful documentation (in docstrings or in `docs/` directory). Adding a new operator? Check this short [guide](https://github.com/apache/airflow/blob/main/airflow-core/docs/howto/custom-operator.rst) Consider adding an example Dag that shows how users should use it.
   - Consider using [Breeze environment](https://github.com/apache/airflow/blob/main/dev/breeze/doc/README.rst) for testing locally, it's a heavy docker but it ships with a working Airflow and a lot of integrations.
   - Be patient and persistent. It might take some time to get a review or get the final approval from Committers.
   - Please follow [ASF Code of Conduct](https://www.apache.org/foundation/policies/conduct) for all communication including (but not limited to) comments on Pull Requests, Mailing list and Slack.
   - Be sure to read the [Airflow Coding style]( https://github.com/apache/airflow/blob/main/contributing-docs/05_pull_requests.rst#coding-style-and-best-practices).
   - Always keep your Pull Requests rebased, otherwise your build might fail due to changes not related to your commits.
   Apache Airflow is a community-driven project and together we are making it better 🚀.
   In case of doubts contact the developers at:
   Mailing List: dev@airflow.apache.org
   Slack: https://s.apache.org/airflow-slack
   


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: commits-unsubscribe@airflow.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] Add `DmsModifyTaskOperator` [airflow]

Posted by "SameerMesiah97 (via GitHub)" <gi...@apache.org>.
SameerMesiah97 commented on code in PR #67524:
URL: https://github.com/apache/airflow/pull/67524#discussion_r3329150397


##########
providers/amazon/src/airflow/providers/amazon/aws/operators/dms.py:
##########
@@ -118,6 +120,178 @@ def execute(self, context: Context):
         return task_arn
 
 
+class DmsModifyTaskOperator(AwsBaseOperator[DmsHook]):
+    """
+    Modifies an existing AWS DMS replication task.
+
+    The task must already be stopped before modification. Use :class:`DmsStopTaskOperator`
+    upstream in the Dag to stop it, and :class:`DmsStartTaskOperator` downstream to restart
+    it afterwards if needed.
+
+    .. seealso::
+        For more information on how to use this operator, take a look at the guide:
+        :ref:`howto/operator:DmsModifyTaskOperator`
+
+    :param replication_task_arn: Replication task ARN
+    :param table_mappings: New table mappings. If not provided, existing mappings are kept.
+    :param migration_type: Migration type ('full-load'|'cdc'|'full-load-and-cdc').
+        If not provided, existing type is kept.
+    :param replication_task_settings: Task settings dict. If not provided, existing settings are kept.
+    :param cdc_start_time: Start time for CDC.
+    :param cdc_start_position: Indicates when to start CDC (checkpoint or LSN/SCN format).
+        Mutually exclusive with cdc_start_time.
+    :param cdc_stop_position: Indicates when to stop CDC.
+    :param wait_for_completion: If True, wait for the modification to finish before returning.
+        In deferrable mode the operator defers rather than blocking. Defaults to True.
+    :param deferrable: Run the operator in deferrable mode. Defaults to False.
+    :param waiter_delay: Seconds between waiter polls (default: 30).
+    :param waiter_max_attempts: Maximum waiter poll attempts (default: 60).
+    :param aws_conn_id: The Airflow connection used for AWS credentials.
+        If this is ``None`` or empty then the default boto3 behaviour is used. If
+        running Airflow in a distributed manner and aws_conn_id is None or
+        empty, then default boto3 configuration would be used (and must be
+        maintained on each worker node).
+    :param region_name: AWS region_name. If not specified then the default boto3 behaviour is used.
+    :param verify: Whether or not to verify SSL certificates. See:
+        https://boto3.amazonaws.com/v1/documentation/api/latest/reference/core/session.html
+    :param botocore_config: Configuration dictionary (key-values) for botocore client. See:
+        https://botocore.amazonaws.com/v1/documentation/api/latest/reference/config.html
+    """
+
+    MODIFIABLE_STATES = frozenset({DmsTaskState.STOPPED, DmsTaskState.READY, DmsTaskState.FAILED})
+
+    aws_hook_class = DmsHook
+    template_fields: Sequence[str] = aws_template_fields(
+        "replication_task_arn",
+        "table_mappings",
+        "migration_type",
+        "replication_task_settings",
+        "cdc_start_time",
+        "cdc_start_position",
+        "cdc_stop_position",
+    )
+    template_fields_renderers: ClassVar[dict] = {
+        "table_mappings": "json",
+        "replication_task_settings": "json",
+    }
+
+    def __init__(
+        self,
+        *,
+        replication_task_arn: str,
+        table_mappings: dict | None = None,
+        migration_type: str | None = None,
+        replication_task_settings: dict | None = None,
+        cdc_start_time: datetime | None = None,
+        cdc_start_position: str | None = None,
+        cdc_stop_position: str | None = None,
+        wait_for_completion: bool = True,
+        deferrable: bool = conf.getboolean("operators", "default_deferrable", fallback=False),
+        waiter_delay: int = 30,
+        waiter_max_attempts: int = 60,
+        **kwargs,
+    ):
+        super().__init__(**kwargs)
+        if cdc_start_time and cdc_start_position:
+            raise ValueError("Only one of cdc_start_time or cdc_start_position can be provided.")
+        self.replication_task_arn = replication_task_arn
+        self.table_mappings = table_mappings
+        self.migration_type = migration_type
+        self.replication_task_settings = replication_task_settings
+        self.cdc_start_time = cdc_start_time
+        self.cdc_start_position = cdc_start_position
+        self.cdc_stop_position = cdc_stop_position
+        self.wait_for_completion = wait_for_completion
+        self.deferrable = deferrable
+        self.waiter_delay = waiter_delay
+        self.waiter_max_attempts = waiter_max_attempts
+
+    def execute(self, context: Context) -> dict:
+        tasks = self.hook.find_replication_tasks_by_arn(
+            replication_task_arn=self.replication_task_arn, without_settings=True
+        )
+        if not tasks:
+            raise ValueError(f"Replication task {self.replication_task_arn} not found.")
+
+        current_status = tasks[0].get("Status", "").lower()
+        self.log.info(
+            "Current status of replication task(%s) is '%s'.", self.replication_task_arn, current_status
+        )
+
+        if current_status == DmsTaskState.MODIFYING:
+            # boto3 stopped/ready waiters treat 'modifying' as a terminal failure — use poll loop.
+            self._wait_until_not_modifying()
+        elif current_status not in self.MODIFIABLE_STATES:
+            raise RuntimeError(
+                f"Replication task {self.replication_task_arn} is in state '{current_status}' "
+                f"and must be stopped before modification. "
+                f"Use DmsStopTaskOperator to stop it first."
+            )
+
+        result = self.hook.modify_replication_task(
+            replication_task_arn=self.replication_task_arn,
+            table_mappings=self.table_mappings,
+            migration_type=self.migration_type,
+            replication_task_settings=self.replication_task_settings,
+            cdc_start_time=self.cdc_start_time,
+            cdc_start_position=self.cdc_start_position,
+            cdc_stop_position=self.cdc_stop_position,
+        )
+        self.log.info("DMS replication task(%s) has been modified.", self.replication_task_arn)
+
+        if self.wait_for_completion:
+            if self.deferrable:
+                self.defer(
+                    trigger=DmsTaskModifyCompleteTrigger(
+                        replication_task_arn=self.replication_task_arn,
+                        waiter_delay=self.waiter_delay,
+                        waiter_max_attempts=self.waiter_max_attempts,
+                        aws_conn_id=self.aws_conn_id,
+                    ),
+                    method_name="execute_complete",
+                )

Review Comment:
   nit: I would add an else here for `self._wait_until_not_modifying() `to make the separation between deferrable and non-deferrable code paths more explicit.



##########
providers/amazon/src/airflow/providers/amazon/aws/operators/dms.py:
##########
@@ -118,6 +120,178 @@ def execute(self, context: Context):
         return task_arn
 
 
+class DmsModifyTaskOperator(AwsBaseOperator[DmsHook]):
+    """
+    Modifies an existing AWS DMS replication task.
+
+    The task must already be stopped before modification. Use :class:`DmsStopTaskOperator`
+    upstream in the Dag to stop it, and :class:`DmsStartTaskOperator` downstream to restart
+    it afterwards if needed.
+
+    .. seealso::
+        For more information on how to use this operator, take a look at the guide:
+        :ref:`howto/operator:DmsModifyTaskOperator`
+
+    :param replication_task_arn: Replication task ARN
+    :param table_mappings: New table mappings. If not provided, existing mappings are kept.
+    :param migration_type: Migration type ('full-load'|'cdc'|'full-load-and-cdc').
+        If not provided, existing type is kept.
+    :param replication_task_settings: Task settings dict. If not provided, existing settings are kept.
+    :param cdc_start_time: Start time for CDC.
+    :param cdc_start_position: Indicates when to start CDC (checkpoint or LSN/SCN format).
+        Mutually exclusive with cdc_start_time.
+    :param cdc_stop_position: Indicates when to stop CDC.
+    :param wait_for_completion: If True, wait for the modification to finish before returning.
+        In deferrable mode the operator defers rather than blocking. Defaults to True.
+    :param deferrable: Run the operator in deferrable mode. Defaults to False.
+    :param waiter_delay: Seconds between waiter polls (default: 30).
+    :param waiter_max_attempts: Maximum waiter poll attempts (default: 60).
+    :param aws_conn_id: The Airflow connection used for AWS credentials.
+        If this is ``None`` or empty then the default boto3 behaviour is used. If
+        running Airflow in a distributed manner and aws_conn_id is None or
+        empty, then default boto3 configuration would be used (and must be
+        maintained on each worker node).
+    :param region_name: AWS region_name. If not specified then the default boto3 behaviour is used.
+    :param verify: Whether or not to verify SSL certificates. See:
+        https://boto3.amazonaws.com/v1/documentation/api/latest/reference/core/session.html
+    :param botocore_config: Configuration dictionary (key-values) for botocore client. See:
+        https://botocore.amazonaws.com/v1/documentation/api/latest/reference/config.html
+    """
+
+    MODIFIABLE_STATES = frozenset({DmsTaskState.STOPPED, DmsTaskState.READY, DmsTaskState.FAILED})
+
+    aws_hook_class = DmsHook
+    template_fields: Sequence[str] = aws_template_fields(
+        "replication_task_arn",
+        "table_mappings",
+        "migration_type",
+        "replication_task_settings",
+        "cdc_start_time",
+        "cdc_start_position",
+        "cdc_stop_position",
+    )
+    template_fields_renderers: ClassVar[dict] = {
+        "table_mappings": "json",
+        "replication_task_settings": "json",
+    }
+
+    def __init__(
+        self,
+        *,
+        replication_task_arn: str,
+        table_mappings: dict | None = None,
+        migration_type: str | None = None,
+        replication_task_settings: dict | None = None,
+        cdc_start_time: datetime | None = None,
+        cdc_start_position: str | None = None,
+        cdc_stop_position: str | None = None,
+        wait_for_completion: bool = True,
+        deferrable: bool = conf.getboolean("operators", "default_deferrable", fallback=False),
+        waiter_delay: int = 30,
+        waiter_max_attempts: int = 60,
+        **kwargs,
+    ):
+        super().__init__(**kwargs)
+        if cdc_start_time and cdc_start_position:
+            raise ValueError("Only one of cdc_start_time or cdc_start_position can be provided.")
+        self.replication_task_arn = replication_task_arn
+        self.table_mappings = table_mappings
+        self.migration_type = migration_type
+        self.replication_task_settings = replication_task_settings
+        self.cdc_start_time = cdc_start_time
+        self.cdc_start_position = cdc_start_position
+        self.cdc_stop_position = cdc_stop_position
+        self.wait_for_completion = wait_for_completion
+        self.deferrable = deferrable
+        self.waiter_delay = waiter_delay
+        self.waiter_max_attempts = waiter_max_attempts
+
+    def execute(self, context: Context) -> dict:
+        tasks = self.hook.find_replication_tasks_by_arn(
+            replication_task_arn=self.replication_task_arn, without_settings=True
+        )
+        if not tasks:
+            raise ValueError(f"Replication task {self.replication_task_arn} not found.")
+
+        current_status = tasks[0].get("Status", "").lower()
+        self.log.info(
+            "Current status of replication task(%s) is '%s'.", self.replication_task_arn, current_status
+        )
+
+        if current_status == DmsTaskState.MODIFYING:
+            # boto3 stopped/ready waiters treat 'modifying' as a terminal failure — use poll loop.
+            self._wait_until_not_modifying()
+        elif current_status not in self.MODIFIABLE_STATES:
+            raise RuntimeError(
+                f"Replication task {self.replication_task_arn} is in state '{current_status}' "
+                f"and must be stopped before modification. "
+                f"Use DmsStopTaskOperator to stop it first."
+            )
+
+        result = self.hook.modify_replication_task(
+            replication_task_arn=self.replication_task_arn,
+            table_mappings=self.table_mappings,
+            migration_type=self.migration_type,
+            replication_task_settings=self.replication_task_settings,
+            cdc_start_time=self.cdc_start_time,
+            cdc_start_position=self.cdc_start_position,
+            cdc_stop_position=self.cdc_stop_position,
+        )
+        self.log.info("DMS replication task(%s) has been modified.", self.replication_task_arn)
+
+        if self.wait_for_completion:
+            if self.deferrable:
+                self.defer(
+                    trigger=DmsTaskModifyCompleteTrigger(
+                        replication_task_arn=self.replication_task_arn,
+                        waiter_delay=self.waiter_delay,
+                        waiter_max_attempts=self.waiter_max_attempts,
+                        aws_conn_id=self.aws_conn_id,
+                    ),
+                    method_name="execute_complete",
+                )

Review Comment:
   nit: I would add an `else` here for `self._wait_until_not_modifying() `to make the separation between deferrable and non-deferrable code paths more explicit.



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: commits-unsubscribe@airflow.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] Add `DmsModifyTaskOperator` [airflow]

Posted by "SameerMesiah97 (via GitHub)" <gi...@apache.org>.
SameerMesiah97 commented on code in PR #67524:
URL: https://github.com/apache/airflow/pull/67524#discussion_r3329167919


##########
providers/amazon/src/airflow/providers/amazon/aws/triggers/dms.py:
##########
@@ -219,3 +222,79 @@ def hook(self) -> AwsGenericHook:
             verify=self.verify,
             config=self.botocore_config,
         )
+
+
+class DmsTaskModifyCompleteTrigger(BaseTrigger):
+    """
+    Trigger that polls until a DMS classic replication task exits the ``modifying`` state.
+
+    The boto3 ``replication_task_stopped`` waiter treats ``modifying`` as a terminal failure,
+    so a custom polling loop is required here.
+
+    :param replication_task_arn: The ARN of the replication task.
+    :param waiter_delay: Seconds between polls.
+    :param waiter_max_attempts: Maximum number of poll attempts before giving up.
+    :param aws_conn_id: The Airflow connection used for AWS credentials.
+    :param verify: Whether or not to verify SSL certificates.
+    :param botocore_config: Configuration dictionary (key-values) for botocore client.
+    """
+
+    def __init__(
+        self,
+        replication_task_arn: str,
+        waiter_delay: int = 30,
+        waiter_max_attempts: int = 60,
+        aws_conn_id: str | None = "aws_default",
+        verify: bool | str | None = None,
+        botocore_config: dict | None = None,
+    ) -> None:
+        super().__init__()
+        self.replication_task_arn = replication_task_arn
+        self.waiter_delay = waiter_delay
+        self.waiter_max_attempts = waiter_max_attempts
+        self.aws_conn_id = aws_conn_id
+        self.verify = verify
+        self.botocore_config = botocore_config
+
+    def serialize(self) -> tuple[str, dict]:
+        return (
+            "airflow.providers.amazon.aws.triggers.dms.DmsTaskModifyCompleteTrigger",
+            {
+                "replication_task_arn": self.replication_task_arn,
+                "waiter_delay": self.waiter_delay,
+                "waiter_max_attempts": self.waiter_max_attempts,
+                "aws_conn_id": self.aws_conn_id,
+                "verify": self.verify,
+                "botocore_config": self.botocore_config,
+            },
+        )
+
+    async def run(self) -> AsyncIterator[TriggerEvent]:
+        hook = DmsHook(aws_conn_id=self.aws_conn_id, verify=self.verify, config=self.botocore_config)
+        try:
+            for _ in range(self.waiter_max_attempts):
+                status = await hook.get_task_status_async(self.replication_task_arn)
+                if status != "modifying":

Review Comment:
   I would use the `ENUM` for the task state instead of raw strings to be consistent with the operator.



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: commits-unsubscribe@airflow.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] Add `DmsModifyTaskOperator` [airflow]

Posted by "SameerMesiah97 (via GitHub)" <gi...@apache.org>.
SameerMesiah97 commented on code in PR #67524:
URL: https://github.com/apache/airflow/pull/67524#discussion_r3329216476


##########
providers/amazon/tests/unit/amazon/aws/operators/test_dms.py:
##########
@@ -180,6 +181,214 @@ def test_default_conn_passed_to_hook(self):
         assert op.hook.aws_conn_id == DEFAULT_CONN
 
 
+class TestDmsModifyTaskOperator:
+    TASK_ARN = "arn:aws:dms:us-east-1:123456789012:task:EXAMPLE"
+    TABLE_MAPPINGS = {
+        "rules": [
+            {
+                "rule-type": "selection",
+                "rule-id": "1",
+                "rule-name": "1",
+                "object-locator": {"schema-name": "myschema", "table-name": "mytable"},
+                "rule-action": "include",
+            }
+        ]
+    }
+
+    def _stopped_task(self):
+        return [{"ReplicationTaskArn": self.TASK_ARN, "Status": "stopped"}]
+
+    def _running_task(self):
+        return [{"ReplicationTaskArn": self.TASK_ARN, "Status": "running"}]
+
+    def _modifying_task(self):
+        return [{"ReplicationTaskArn": self.TASK_ARN, "Status": "modifying"}]
+
+    def test_init(self):
+        op = DmsModifyTaskOperator(
+            task_id="modify_task",
+            replication_task_arn=self.TASK_ARN,
+            table_mappings=self.TABLE_MAPPINGS,
+            migration_type="cdc",
+            aws_conn_id="fake-conn-id",
+            region_name="us-east-1",
+        )
+        assert op.replication_task_arn == self.TASK_ARN
+        assert op.table_mappings == self.TABLE_MAPPINGS
+        assert op.migration_type == "cdc"
+        assert op.wait_for_completion is True
+        assert op.deferrable is False
+        assert op.hook.aws_conn_id == "fake-conn-id"
+        assert op.hook._region_name == "us-east-1"
+
+    def test_init_defaults(self):
+        op = DmsModifyTaskOperator(task_id="modify_task", replication_task_arn=self.TASK_ARN)
+        assert op.table_mappings is None
+        assert op.migration_type is None
+        assert op.replication_task_settings is None
+        assert op.cdc_start_time is None
+        assert op.cdc_start_position is None
+        assert op.cdc_stop_position is None
+        assert op.wait_for_completion is True
+        assert op.deferrable is False
+
+    def test_init_raises_if_both_cdc_start_params_provided(self):
+        from datetime import datetime
+
+        with pytest.raises(ValueError, match="Only one of"):
+            DmsModifyTaskOperator(
+                task_id="modify_task",
+                replication_task_arn=self.TASK_ARN,
+                cdc_start_time=datetime(2024, 1, 1),
+                cdc_start_position="mysql-bin.000001:4",
+            )
+
+    @mock.patch.object(DmsHook, "find_replication_tasks_by_arn")
+    @mock.patch.object(DmsHook, "get_conn")
+    def test_modify_task_already_stopped(self, mock_conn, mock_find):
+        mock_find.return_value = self._stopped_task()
+        expected = {"ReplicationTaskArn": self.TASK_ARN}
+        with mock.patch.object(DmsHook, "modify_replication_task", return_value=expected) as mock_modify:
+            op = DmsModifyTaskOperator(
+                task_id="modify_task",
+                replication_task_arn=self.TASK_ARN,
+                table_mappings=self.TABLE_MAPPINGS,
+                wait_for_completion=False,
+            )
+            result = op.execute(None)
+
+            mock_modify.assert_called_once_with(
+                replication_task_arn=self.TASK_ARN,
+                table_mappings=self.TABLE_MAPPINGS,
+                migration_type=None,
+                replication_task_settings=None,
+                cdc_start_time=None,
+                cdc_start_position=None,
+                cdc_stop_position=None,
+            )
+            assert result == expected
+
+    @mock.patch.object(DmsHook, "find_replication_tasks_by_arn")
+    @mock.patch.object(DmsHook, "get_conn")
+    def test_modify_task_raises_if_running(self, mock_conn, mock_find):
+        mock_find.return_value = self._running_task()
+        op = DmsModifyTaskOperator(
+            task_id="modify_task",
+            replication_task_arn=self.TASK_ARN,
+        )
+        with pytest.raises(RuntimeError, match="must be stopped"):
+            op.execute(None)
+
+    @mock.patch.object(DmsHook, "find_replication_tasks_by_arn")
+    @mock.patch.object(DmsHook, "get_conn")
+    def test_modify_task_raises_if_not_found(self, mock_conn, mock_find):
+        mock_find.return_value = []
+        op = DmsModifyTaskOperator(task_id="modify_task", replication_task_arn=self.TASK_ARN)
+        with pytest.raises(ValueError, match="not found"):
+            op.execute(None)
+
+    @mock.patch.object(DmsHook, "find_replication_tasks_by_arn")
+    @mock.patch.object(DmsHook, "get_conn")
+    def test_modify_task_defers_for_completion(self, mock_conn, mock_find):
+        from airflow.exceptions import TaskDeferred

Review Comment:
   Why re-import TaskDeferred here? You already have this at the top of the file:
   
   `from airflow.providers.common.compat.sdk import AirflowException, TaskDeferred`



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: commits-unsubscribe@airflow.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] Add `DmsModifyTaskOperator` [airflow]

Posted by "SameerMesiah97 (via GitHub)" <gi...@apache.org>.
SameerMesiah97 commented on code in PR #67524:
URL: https://github.com/apache/airflow/pull/67524#discussion_r3329218635


##########
providers/amazon/tests/unit/amazon/aws/operators/test_dms.py:
##########
@@ -180,6 +181,214 @@ def test_default_conn_passed_to_hook(self):
         assert op.hook.aws_conn_id == DEFAULT_CONN
 
 
+class TestDmsModifyTaskOperator:
+    TASK_ARN = "arn:aws:dms:us-east-1:123456789012:task:EXAMPLE"
+    TABLE_MAPPINGS = {
+        "rules": [
+            {
+                "rule-type": "selection",
+                "rule-id": "1",
+                "rule-name": "1",
+                "object-locator": {"schema-name": "myschema", "table-name": "mytable"},
+                "rule-action": "include",
+            }
+        ]
+    }
+
+    def _stopped_task(self):
+        return [{"ReplicationTaskArn": self.TASK_ARN, "Status": "stopped"}]
+
+    def _running_task(self):
+        return [{"ReplicationTaskArn": self.TASK_ARN, "Status": "running"}]
+
+    def _modifying_task(self):
+        return [{"ReplicationTaskArn": self.TASK_ARN, "Status": "modifying"}]
+
+    def test_init(self):
+        op = DmsModifyTaskOperator(
+            task_id="modify_task",
+            replication_task_arn=self.TASK_ARN,
+            table_mappings=self.TABLE_MAPPINGS,
+            migration_type="cdc",
+            aws_conn_id="fake-conn-id",
+            region_name="us-east-1",
+        )
+        assert op.replication_task_arn == self.TASK_ARN
+        assert op.table_mappings == self.TABLE_MAPPINGS
+        assert op.migration_type == "cdc"
+        assert op.wait_for_completion is True
+        assert op.deferrable is False
+        assert op.hook.aws_conn_id == "fake-conn-id"
+        assert op.hook._region_name == "us-east-1"
+
+    def test_init_defaults(self):
+        op = DmsModifyTaskOperator(task_id="modify_task", replication_task_arn=self.TASK_ARN)
+        assert op.table_mappings is None
+        assert op.migration_type is None
+        assert op.replication_task_settings is None
+        assert op.cdc_start_time is None
+        assert op.cdc_start_position is None
+        assert op.cdc_stop_position is None
+        assert op.wait_for_completion is True
+        assert op.deferrable is False
+
+    def test_init_raises_if_both_cdc_start_params_provided(self):
+        from datetime import datetime

Review Comment:
   This too. Top of the file.



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: commits-unsubscribe@airflow.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] Add `DmsModifyTaskOperator` [airflow]

Posted by "SameerMesiah97 (via GitHub)" <gi...@apache.org>.
SameerMesiah97 commented on code in PR #67524:
URL: https://github.com/apache/airflow/pull/67524#discussion_r3329245887


##########
providers/amazon/tests/unit/amazon/aws/operators/test_dms.py:
##########
@@ -180,6 +181,214 @@ def test_default_conn_passed_to_hook(self):
         assert op.hook.aws_conn_id == DEFAULT_CONN
 
 
+class TestDmsModifyTaskOperator:
+    TASK_ARN = "arn:aws:dms:us-east-1:123456789012:task:EXAMPLE"
+    TABLE_MAPPINGS = {
+        "rules": [
+            {
+                "rule-type": "selection",
+                "rule-id": "1",
+                "rule-name": "1",
+                "object-locator": {"schema-name": "myschema", "table-name": "mytable"},
+                "rule-action": "include",
+            }
+        ]
+    }
+
+    def _stopped_task(self):
+        return [{"ReplicationTaskArn": self.TASK_ARN, "Status": "stopped"}]
+
+    def _running_task(self):
+        return [{"ReplicationTaskArn": self.TASK_ARN, "Status": "running"}]
+
+    def _modifying_task(self):
+        return [{"ReplicationTaskArn": self.TASK_ARN, "Status": "modifying"}]
+
+    def test_init(self):
+        op = DmsModifyTaskOperator(
+            task_id="modify_task",
+            replication_task_arn=self.TASK_ARN,
+            table_mappings=self.TABLE_MAPPINGS,
+            migration_type="cdc",
+            aws_conn_id="fake-conn-id",
+            region_name="us-east-1",
+        )
+        assert op.replication_task_arn == self.TASK_ARN
+        assert op.table_mappings == self.TABLE_MAPPINGS
+        assert op.migration_type == "cdc"
+        assert op.wait_for_completion is True
+        assert op.deferrable is False
+        assert op.hook.aws_conn_id == "fake-conn-id"
+        assert op.hook._region_name == "us-east-1"
+
+    def test_init_defaults(self):
+        op = DmsModifyTaskOperator(task_id="modify_task", replication_task_arn=self.TASK_ARN)
+        assert op.table_mappings is None
+        assert op.migration_type is None
+        assert op.replication_task_settings is None
+        assert op.cdc_start_time is None
+        assert op.cdc_start_position is None
+        assert op.cdc_stop_position is None
+        assert op.wait_for_completion is True
+        assert op.deferrable is False
+
+    def test_init_raises_if_both_cdc_start_params_provided(self):
+        from datetime import datetime
+
+        with pytest.raises(ValueError, match="Only one of"):
+            DmsModifyTaskOperator(
+                task_id="modify_task",
+                replication_task_arn=self.TASK_ARN,
+                cdc_start_time=datetime(2024, 1, 1),
+                cdc_start_position="mysql-bin.000001:4",
+            )
+
+    @mock.patch.object(DmsHook, "find_replication_tasks_by_arn")
+    @mock.patch.object(DmsHook, "get_conn")
+    def test_modify_task_already_stopped(self, mock_conn, mock_find):
+        mock_find.return_value = self._stopped_task()
+        expected = {"ReplicationTaskArn": self.TASK_ARN}
+        with mock.patch.object(DmsHook, "modify_replication_task", return_value=expected) as mock_modify:
+            op = DmsModifyTaskOperator(
+                task_id="modify_task",
+                replication_task_arn=self.TASK_ARN,
+                table_mappings=self.TABLE_MAPPINGS,
+                wait_for_completion=False,
+            )
+            result = op.execute(None)
+
+            mock_modify.assert_called_once_with(
+                replication_task_arn=self.TASK_ARN,
+                table_mappings=self.TABLE_MAPPINGS,
+                migration_type=None,
+                replication_task_settings=None,
+                cdc_start_time=None,
+                cdc_start_position=None,
+                cdc_stop_position=None,
+            )
+            assert result == expected
+
+    @mock.patch.object(DmsHook, "find_replication_tasks_by_arn")
+    @mock.patch.object(DmsHook, "get_conn")
+    def test_modify_task_raises_if_running(self, mock_conn, mock_find):
+        mock_find.return_value = self._running_task()
+        op = DmsModifyTaskOperator(
+            task_id="modify_task",
+            replication_task_arn=self.TASK_ARN,
+        )
+        with pytest.raises(RuntimeError, match="must be stopped"):
+            op.execute(None)
+
+    @mock.patch.object(DmsHook, "find_replication_tasks_by_arn")
+    @mock.patch.object(DmsHook, "get_conn")
+    def test_modify_task_raises_if_not_found(self, mock_conn, mock_find):
+        mock_find.return_value = []
+        op = DmsModifyTaskOperator(task_id="modify_task", replication_task_arn=self.TASK_ARN)
+        with pytest.raises(ValueError, match="not found"):
+            op.execute(None)
+
+    @mock.patch.object(DmsHook, "find_replication_tasks_by_arn")
+    @mock.patch.object(DmsHook, "get_conn")
+    def test_modify_task_defers_for_completion(self, mock_conn, mock_find):
+        from airflow.exceptions import TaskDeferred
+        from airflow.providers.amazon.aws.triggers.dms import DmsTaskModifyCompleteTrigger
+
+        mock_find.return_value = self._stopped_task()
+        expected = {"ReplicationTaskArn": self.TASK_ARN}
+        with mock.patch.object(DmsHook, "modify_replication_task", return_value=expected):
+            op = DmsModifyTaskOperator(
+                task_id="modify_task",
+                replication_task_arn=self.TASK_ARN,
+                deferrable=True,
+                wait_for_completion=True,
+            )
+            with pytest.raises(TaskDeferred) as exc_info:
+                op.execute(None)
+
+        assert isinstance(exc_info.value.trigger, DmsTaskModifyCompleteTrigger)
+        assert exc_info.value.method_name == "execute_complete"
+
+    @mock.patch.object(DmsHook, "find_replication_tasks_by_arn")
+    @mock.patch.object(DmsHook, "get_conn")
+    def test_modify_task_with_all_params(self, mock_conn, mock_find):
+        from datetime import datetime
+
+        mock_find.return_value = self._stopped_task()
+        cdc_start = datetime(2024, 1, 1)
+        expected = {"ReplicationTaskArn": self.TASK_ARN}
+        with mock.patch.object(DmsHook, "modify_replication_task", return_value=expected) as mock_modify:
+            op = DmsModifyTaskOperator(
+                task_id="modify_task",
+                replication_task_arn=self.TASK_ARN,
+                table_mappings=self.TABLE_MAPPINGS,
+                migration_type="full-load-and-cdc",
+                replication_task_settings={"TargetMetadata": {}},
+                cdc_start_time=cdc_start,
+                cdc_stop_position="2024-01-31:00:00:00",
+            )
+            op.execute(None)
+
+            mock_modify.assert_called_once_with(
+                replication_task_arn=self.TASK_ARN,
+                table_mappings=self.TABLE_MAPPINGS,
+                migration_type="full-load-and-cdc",
+                replication_task_settings={"TargetMetadata": {}},
+                cdc_start_time=cdc_start,
+                cdc_start_position=None,
+                cdc_stop_position="2024-01-31:00:00:00",
+            )
+
+    @mock.patch.object(DmsHook, "find_replication_tasks_by_arn")
+    @mock.patch.object(DmsHook, "get_conn")
+    def test_modify_task_waits_if_modifying(self, mock_conn, mock_find):
+        stopped_task = self._stopped_task()
+        expected = {"ReplicationTaskArn": self.TASK_ARN}
+        # execute() sees 'modifying' → _wait_until_not_modifying polls once → 'stopped';
+        # modify is called; wait_for_completion=True → _wait_until_not_modifying polls once → 'stopped'.
+        mock_find.side_effect = [
+            self._modifying_task(),
+            stopped_task,
+            stopped_task,
+        ]
+        with mock.patch.object(DmsHook, "modify_replication_task", return_value=expected) as mock_modify:
+            op = DmsModifyTaskOperator(
+                task_id="modify_task",
+                replication_task_arn=self.TASK_ARN,
+                table_mappings=self.TABLE_MAPPINGS,
+                wait_for_completion=True,
+                waiter_delay=0,
+            )
+            op.execute(None)
+
+            mock_modify.assert_called_once()
+
+    def test_execute_complete_success(self):
+        op = DmsModifyTaskOperator(
+            task_id="modify_task",
+            replication_task_arn=self.TASK_ARN,
+        )
+        success_event = {"status": "success", "replication_task_arn": self.TASK_ARN}
+        result = op.execute_complete({}, success_event)
+        assert result is None
+
+    def test_execute_complete_error(self):
+        op = DmsModifyTaskOperator(
+            task_id="modify_task",
+            replication_task_arn=self.TASK_ARN,
+        )
+        error_event = {"status": "error", "message": "Timeout", "replication_task_arn": self.TASK_ARN}
+        with pytest.raises(RuntimeError, match="Error waiting for DMS task modification to complete"):
+            op.execute_complete({}, error_event)
+
+    def test_template_fields(self):
+        op = DmsModifyTaskOperator(
+            task_id="modify_task",
+            replication_task_arn=self.TASK_ARN,
+            table_mappings=self.TABLE_MAPPINGS,
+        )
+        validate_template_fields(op)

Review Comment:
   I think you should add tests for the following:
   
   1) `waiter_max_attempts` exceeded in sychronous path.
   2) ` wait_for_completion=False`
   3) tasks not during `_wait_until_not_modifying`



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: commits-unsubscribe@airflow.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] Add `DmsModifyTaskOperator` [airflow]

Posted by "SameerMesiah97 (via GitHub)" <gi...@apache.org>.
SameerMesiah97 commented on code in PR #67524:
URL: https://github.com/apache/airflow/pull/67524#discussion_r3329220149


##########
providers/amazon/tests/unit/amazon/aws/operators/test_dms.py:
##########
@@ -180,6 +181,214 @@ def test_default_conn_passed_to_hook(self):
         assert op.hook.aws_conn_id == DEFAULT_CONN
 
 
+class TestDmsModifyTaskOperator:
+    TASK_ARN = "arn:aws:dms:us-east-1:123456789012:task:EXAMPLE"
+    TABLE_MAPPINGS = {
+        "rules": [
+            {
+                "rule-type": "selection",
+                "rule-id": "1",
+                "rule-name": "1",
+                "object-locator": {"schema-name": "myschema", "table-name": "mytable"},
+                "rule-action": "include",
+            }
+        ]
+    }
+
+    def _stopped_task(self):
+        return [{"ReplicationTaskArn": self.TASK_ARN, "Status": "stopped"}]
+
+    def _running_task(self):
+        return [{"ReplicationTaskArn": self.TASK_ARN, "Status": "running"}]
+
+    def _modifying_task(self):
+        return [{"ReplicationTaskArn": self.TASK_ARN, "Status": "modifying"}]
+
+    def test_init(self):
+        op = DmsModifyTaskOperator(
+            task_id="modify_task",
+            replication_task_arn=self.TASK_ARN,
+            table_mappings=self.TABLE_MAPPINGS,
+            migration_type="cdc",
+            aws_conn_id="fake-conn-id",
+            region_name="us-east-1",
+        )
+        assert op.replication_task_arn == self.TASK_ARN
+        assert op.table_mappings == self.TABLE_MAPPINGS
+        assert op.migration_type == "cdc"
+        assert op.wait_for_completion is True
+        assert op.deferrable is False
+        assert op.hook.aws_conn_id == "fake-conn-id"
+        assert op.hook._region_name == "us-east-1"
+
+    def test_init_defaults(self):
+        op = DmsModifyTaskOperator(task_id="modify_task", replication_task_arn=self.TASK_ARN)
+        assert op.table_mappings is None
+        assert op.migration_type is None
+        assert op.replication_task_settings is None
+        assert op.cdc_start_time is None
+        assert op.cdc_start_position is None
+        assert op.cdc_stop_position is None
+        assert op.wait_for_completion is True
+        assert op.deferrable is False
+
+    def test_init_raises_if_both_cdc_start_params_provided(self):
+        from datetime import datetime
+
+        with pytest.raises(ValueError, match="Only one of"):
+            DmsModifyTaskOperator(
+                task_id="modify_task",
+                replication_task_arn=self.TASK_ARN,
+                cdc_start_time=datetime(2024, 1, 1),
+                cdc_start_position="mysql-bin.000001:4",
+            )
+
+    @mock.patch.object(DmsHook, "find_replication_tasks_by_arn")
+    @mock.patch.object(DmsHook, "get_conn")
+    def test_modify_task_already_stopped(self, mock_conn, mock_find):
+        mock_find.return_value = self._stopped_task()
+        expected = {"ReplicationTaskArn": self.TASK_ARN}
+        with mock.patch.object(DmsHook, "modify_replication_task", return_value=expected) as mock_modify:
+            op = DmsModifyTaskOperator(
+                task_id="modify_task",
+                replication_task_arn=self.TASK_ARN,
+                table_mappings=self.TABLE_MAPPINGS,
+                wait_for_completion=False,
+            )
+            result = op.execute(None)
+
+            mock_modify.assert_called_once_with(
+                replication_task_arn=self.TASK_ARN,
+                table_mappings=self.TABLE_MAPPINGS,
+                migration_type=None,
+                replication_task_settings=None,
+                cdc_start_time=None,
+                cdc_start_position=None,
+                cdc_stop_position=None,
+            )
+            assert result == expected
+
+    @mock.patch.object(DmsHook, "find_replication_tasks_by_arn")
+    @mock.patch.object(DmsHook, "get_conn")
+    def test_modify_task_raises_if_running(self, mock_conn, mock_find):
+        mock_find.return_value = self._running_task()
+        op = DmsModifyTaskOperator(
+            task_id="modify_task",
+            replication_task_arn=self.TASK_ARN,
+        )
+        with pytest.raises(RuntimeError, match="must be stopped"):
+            op.execute(None)
+
+    @mock.patch.object(DmsHook, "find_replication_tasks_by_arn")
+    @mock.patch.object(DmsHook, "get_conn")
+    def test_modify_task_raises_if_not_found(self, mock_conn, mock_find):
+        mock_find.return_value = []
+        op = DmsModifyTaskOperator(task_id="modify_task", replication_task_arn=self.TASK_ARN)
+        with pytest.raises(ValueError, match="not found"):
+            op.execute(None)
+
+    @mock.patch.object(DmsHook, "find_replication_tasks_by_arn")
+    @mock.patch.object(DmsHook, "get_conn")
+    def test_modify_task_defers_for_completion(self, mock_conn, mock_find):
+        from airflow.exceptions import TaskDeferred
+        from airflow.providers.amazon.aws.triggers.dms import DmsTaskModifyCompleteTrigger
+
+        mock_find.return_value = self._stopped_task()
+        expected = {"ReplicationTaskArn": self.TASK_ARN}
+        with mock.patch.object(DmsHook, "modify_replication_task", return_value=expected):
+            op = DmsModifyTaskOperator(
+                task_id="modify_task",
+                replication_task_arn=self.TASK_ARN,
+                deferrable=True,
+                wait_for_completion=True,
+            )
+            with pytest.raises(TaskDeferred) as exc_info:
+                op.execute(None)
+
+        assert isinstance(exc_info.value.trigger, DmsTaskModifyCompleteTrigger)
+        assert exc_info.value.method_name == "execute_complete"
+
+    @mock.patch.object(DmsHook, "find_replication_tasks_by_arn")
+    @mock.patch.object(DmsHook, "get_conn")
+    def test_modify_task_with_all_params(self, mock_conn, mock_find):
+        from datetime import datetime
+
+        mock_find.return_value = self._stopped_task()
+        cdc_start = datetime(2024, 1, 1)
+        expected = {"ReplicationTaskArn": self.TASK_ARN}
+        with mock.patch.object(DmsHook, "modify_replication_task", return_value=expected) as mock_modify:
+            op = DmsModifyTaskOperator(
+                task_id="modify_task",
+                replication_task_arn=self.TASK_ARN,
+                table_mappings=self.TABLE_MAPPINGS,
+                migration_type="full-load-and-cdc",
+                replication_task_settings={"TargetMetadata": {}},
+                cdc_start_time=cdc_start,
+                cdc_stop_position="2024-01-31:00:00:00",
+            )
+            op.execute(None)
+
+            mock_modify.assert_called_once_with(
+                replication_task_arn=self.TASK_ARN,
+                table_mappings=self.TABLE_MAPPINGS,
+                migration_type="full-load-and-cdc",
+                replication_task_settings={"TargetMetadata": {}},
+                cdc_start_time=cdc_start,
+                cdc_start_position=None,
+                cdc_stop_position="2024-01-31:00:00:00",
+            )
+
+    @mock.patch.object(DmsHook, "find_replication_tasks_by_arn")
+    @mock.patch.object(DmsHook, "get_conn")
+    def test_modify_task_waits_if_modifying(self, mock_conn, mock_find):
+        stopped_task = self._stopped_task()
+        expected = {"ReplicationTaskArn": self.TASK_ARN}
+        # execute() sees 'modifying' → _wait_until_not_modifying polls once → 'stopped';
+        # modify is called; wait_for_completion=True → _wait_until_not_modifying polls once → 'stopped'.
+        mock_find.side_effect = [
+            self._modifying_task(),
+            stopped_task,
+            stopped_task,
+        ]
+        with mock.patch.object(DmsHook, "modify_replication_task", return_value=expected) as mock_modify:
+            op = DmsModifyTaskOperator(
+                task_id="modify_task",
+                replication_task_arn=self.TASK_ARN,
+                table_mappings=self.TABLE_MAPPINGS,
+                wait_for_completion=True,
+                waiter_delay=0,
+            )
+            op.execute(None)
+
+            mock_modify.assert_called_once()
+
+    def test_execute_complete_success(self):

Review Comment:
   If you revamp the trigger, you may need to add more tests for the additional events you will have the trigger emit.



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: commits-unsubscribe@airflow.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] Add `DmsModifyTaskOperator` [airflow]

Posted by "SameerMesiah97 (via GitHub)" <gi...@apache.org>.
SameerMesiah97 commented on code in PR #67524:
URL: https://github.com/apache/airflow/pull/67524#discussion_r3329225232


##########
providers/amazon/tests/unit/amazon/aws/operators/test_dms.py:
##########
@@ -180,6 +181,214 @@ def test_default_conn_passed_to_hook(self):
         assert op.hook.aws_conn_id == DEFAULT_CONN
 
 
+class TestDmsModifyTaskOperator:
+    TASK_ARN = "arn:aws:dms:us-east-1:123456789012:task:EXAMPLE"
+    TABLE_MAPPINGS = {
+        "rules": [
+            {
+                "rule-type": "selection",
+                "rule-id": "1",
+                "rule-name": "1",
+                "object-locator": {"schema-name": "myschema", "table-name": "mytable"},
+                "rule-action": "include",
+            }
+        ]
+    }
+
+    def _stopped_task(self):
+        return [{"ReplicationTaskArn": self.TASK_ARN, "Status": "stopped"}]
+
+    def _running_task(self):
+        return [{"ReplicationTaskArn": self.TASK_ARN, "Status": "running"}]
+
+    def _modifying_task(self):
+        return [{"ReplicationTaskArn": self.TASK_ARN, "Status": "modifying"}]
+
+    def test_init(self):
+        op = DmsModifyTaskOperator(
+            task_id="modify_task",
+            replication_task_arn=self.TASK_ARN,
+            table_mappings=self.TABLE_MAPPINGS,
+            migration_type="cdc",
+            aws_conn_id="fake-conn-id",
+            region_name="us-east-1",
+        )
+        assert op.replication_task_arn == self.TASK_ARN
+        assert op.table_mappings == self.TABLE_MAPPINGS
+        assert op.migration_type == "cdc"
+        assert op.wait_for_completion is True
+        assert op.deferrable is False
+        assert op.hook.aws_conn_id == "fake-conn-id"
+        assert op.hook._region_name == "us-east-1"
+
+    def test_init_defaults(self):
+        op = DmsModifyTaskOperator(task_id="modify_task", replication_task_arn=self.TASK_ARN)
+        assert op.table_mappings is None
+        assert op.migration_type is None
+        assert op.replication_task_settings is None
+        assert op.cdc_start_time is None
+        assert op.cdc_start_position is None
+        assert op.cdc_stop_position is None
+        assert op.wait_for_completion is True
+        assert op.deferrable is False
+
+    def test_init_raises_if_both_cdc_start_params_provided(self):
+        from datetime import datetime
+
+        with pytest.raises(ValueError, match="Only one of"):
+            DmsModifyTaskOperator(
+                task_id="modify_task",
+                replication_task_arn=self.TASK_ARN,
+                cdc_start_time=datetime(2024, 1, 1),
+                cdc_start_position="mysql-bin.000001:4",
+            )
+
+    @mock.patch.object(DmsHook, "find_replication_tasks_by_arn")
+    @mock.patch.object(DmsHook, "get_conn")
+    def test_modify_task_already_stopped(self, mock_conn, mock_find):

Review Comment:
   Maybe you can generalize this to something like this:
   
   ```
   @pytest.mark.parametrize(
       "status",
       ["stopped", "ready", "failed"],
   )
   def test_modify_task_modifiable_states(..., status):
   ```
   
   This way you are covering "ready" and "failed" as well.



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: commits-unsubscribe@airflow.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] Add `DmsModifyTaskOperator` [airflow]

Posted by "AlejandroMorgante (via GitHub)" <gi...@apache.org>.
AlejandroMorgante commented on code in PR #67524:
URL: https://github.com/apache/airflow/pull/67524#discussion_r3329299896


##########
providers/amazon/src/airflow/providers/amazon/aws/operators/dms.py:
##########
@@ -118,6 +120,178 @@ def execute(self, context: Context):
         return task_arn
 
 
+class DmsModifyTaskOperator(AwsBaseOperator[DmsHook]):
+    """
+    Modifies an existing AWS DMS replication task.
+
+    The task must already be stopped before modification. Use :class:`DmsStopTaskOperator`
+    upstream in the Dag to stop it, and :class:`DmsStartTaskOperator` downstream to restart
+    it afterwards if needed.
+
+    .. seealso::
+        For more information on how to use this operator, take a look at the guide:
+        :ref:`howto/operator:DmsModifyTaskOperator`
+
+    :param replication_task_arn: Replication task ARN
+    :param table_mappings: New table mappings. If not provided, existing mappings are kept.
+    :param migration_type: Migration type ('full-load'|'cdc'|'full-load-and-cdc').
+        If not provided, existing type is kept.
+    :param replication_task_settings: Task settings dict. If not provided, existing settings are kept.
+    :param cdc_start_time: Start time for CDC.
+    :param cdc_start_position: Indicates when to start CDC (checkpoint or LSN/SCN format).
+        Mutually exclusive with cdc_start_time.
+    :param cdc_stop_position: Indicates when to stop CDC.
+    :param wait_for_completion: If True, wait for the modification to finish before returning.
+        In deferrable mode the operator defers rather than blocking. Defaults to True.
+    :param deferrable: Run the operator in deferrable mode. Defaults to False.
+    :param waiter_delay: Seconds between waiter polls (default: 30).
+    :param waiter_max_attempts: Maximum waiter poll attempts (default: 60).
+    :param aws_conn_id: The Airflow connection used for AWS credentials.
+        If this is ``None`` or empty then the default boto3 behaviour is used. If
+        running Airflow in a distributed manner and aws_conn_id is None or
+        empty, then default boto3 configuration would be used (and must be
+        maintained on each worker node).
+    :param region_name: AWS region_name. If not specified then the default boto3 behaviour is used.
+    :param verify: Whether or not to verify SSL certificates. See:
+        https://boto3.amazonaws.com/v1/documentation/api/latest/reference/core/session.html
+    :param botocore_config: Configuration dictionary (key-values) for botocore client. See:
+        https://botocore.amazonaws.com/v1/documentation/api/latest/reference/config.html
+    """
+
+    MODIFIABLE_STATES = frozenset({DmsTaskState.STOPPED, DmsTaskState.READY, DmsTaskState.FAILED})
+
+    aws_hook_class = DmsHook
+    template_fields: Sequence[str] = aws_template_fields(
+        "replication_task_arn",
+        "table_mappings",
+        "migration_type",
+        "replication_task_settings",
+        "cdc_start_time",
+        "cdc_start_position",
+        "cdc_stop_position",
+    )
+    template_fields_renderers: ClassVar[dict] = {
+        "table_mappings": "json",
+        "replication_task_settings": "json",
+    }
+
+    def __init__(
+        self,
+        *,
+        replication_task_arn: str,
+        table_mappings: dict | None = None,
+        migration_type: str | None = None,
+        replication_task_settings: dict | None = None,
+        cdc_start_time: datetime | None = None,
+        cdc_start_position: str | None = None,
+        cdc_stop_position: str | None = None,
+        wait_for_completion: bool = True,
+        deferrable: bool = conf.getboolean("operators", "default_deferrable", fallback=False),
+        waiter_delay: int = 30,
+        waiter_max_attempts: int = 60,

Review Comment:
   Added — `aws_conn_id: str | None = "aws_default"` is now an explicit parameter and passed to `super().__init__()`.



##########
providers/amazon/src/airflow/providers/amazon/aws/operators/dms.py:
##########
@@ -118,6 +120,178 @@ def execute(self, context: Context):
         return task_arn
 
 
+class DmsModifyTaskOperator(AwsBaseOperator[DmsHook]):
+    """
+    Modifies an existing AWS DMS replication task.
+
+    The task must already be stopped before modification. Use :class:`DmsStopTaskOperator`
+    upstream in the Dag to stop it, and :class:`DmsStartTaskOperator` downstream to restart
+    it afterwards if needed.
+
+    .. seealso::
+        For more information on how to use this operator, take a look at the guide:
+        :ref:`howto/operator:DmsModifyTaskOperator`
+
+    :param replication_task_arn: Replication task ARN
+    :param table_mappings: New table mappings. If not provided, existing mappings are kept.
+    :param migration_type: Migration type ('full-load'|'cdc'|'full-load-and-cdc').
+        If not provided, existing type is kept.
+    :param replication_task_settings: Task settings dict. If not provided, existing settings are kept.
+    :param cdc_start_time: Start time for CDC.
+    :param cdc_start_position: Indicates when to start CDC (checkpoint or LSN/SCN format).
+        Mutually exclusive with cdc_start_time.
+    :param cdc_stop_position: Indicates when to stop CDC.
+    :param wait_for_completion: If True, wait for the modification to finish before returning.
+        In deferrable mode the operator defers rather than blocking. Defaults to True.
+    :param deferrable: Run the operator in deferrable mode. Defaults to False.
+    :param waiter_delay: Seconds between waiter polls (default: 30).
+    :param waiter_max_attempts: Maximum waiter poll attempts (default: 60).
+    :param aws_conn_id: The Airflow connection used for AWS credentials.
+        If this is ``None`` or empty then the default boto3 behaviour is used. If
+        running Airflow in a distributed manner and aws_conn_id is None or
+        empty, then default boto3 configuration would be used (and must be
+        maintained on each worker node).
+    :param region_name: AWS region_name. If not specified then the default boto3 behaviour is used.
+    :param verify: Whether or not to verify SSL certificates. See:
+        https://boto3.amazonaws.com/v1/documentation/api/latest/reference/core/session.html
+    :param botocore_config: Configuration dictionary (key-values) for botocore client. See:
+        https://botocore.amazonaws.com/v1/documentation/api/latest/reference/config.html
+    """

Review Comment:
   Keeping them — the other classic task operators (`DmsCreateTaskOperator`, `DmsDeleteTaskOperator`, etc.) all document these same args. The serverless replication operators don't, but those are a different family.



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: commits-unsubscribe@airflow.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] Add `DmsModifyTaskOperator` [airflow]

Posted by "AlejandroMorgante (via GitHub)" <gi...@apache.org>.
AlejandroMorgante commented on code in PR #67524:
URL: https://github.com/apache/airflow/pull/67524#discussion_r3345133979


##########
providers/amazon/src/airflow/providers/amazon/aws/triggers/dms.py:
##########
@@ -219,3 +222,97 @@ def hook(self) -> AwsGenericHook:
             verify=self.verify,
             config=self.botocore_config,
         )
+
+
+class DmsTaskModifyCompleteTrigger(BaseTrigger):
+    """
+    Trigger that polls until a DMS classic replication task exits the ``modifying`` state.
+
+    The boto3 ``replication_task_stopped`` waiter treats ``modifying`` as a terminal failure,
+    so a custom polling loop is required here.
+
+    :param replication_task_arn: The ARN of the replication task.
+    :param waiter_delay: Seconds between polls.
+    :param waiter_max_attempts: Maximum number of poll attempts before giving up.
+    :param aws_conn_id: The Airflow connection used for AWS credentials.
+    :param verify: Whether or not to verify SSL certificates.
+    :param botocore_config: Configuration dictionary (key-values) for botocore client.
+    """
+
+    def __init__(
+        self,
+        replication_task_arn: str,
+        waiter_delay: int = 30,
+        waiter_max_attempts: int = 60,
+        aws_conn_id: str | None = "aws_default",
+        verify: bool | str | None = None,
+        botocore_config: dict | None = None,
+    ) -> None:
+        super().__init__()
+        self.replication_task_arn = replication_task_arn
+        self.waiter_delay = waiter_delay
+        self.waiter_max_attempts = waiter_max_attempts
+        self.aws_conn_id = aws_conn_id
+        self.verify = verify
+        self.botocore_config = botocore_config
+
+    def serialize(self) -> tuple[str, dict]:
+        return (
+            "airflow.providers.amazon.aws.triggers.dms.DmsTaskModifyCompleteTrigger",
+            {
+                "replication_task_arn": self.replication_task_arn,
+                "waiter_delay": self.waiter_delay,
+                "waiter_max_attempts": self.waiter_max_attempts,
+                "aws_conn_id": self.aws_conn_id,
+                "verify": self.verify,
+                "botocore_config": self.botocore_config,
+            },
+        )
+
+    async def run(self) -> AsyncIterator[TriggerEvent]:
+        hook = DmsHook(aws_conn_id=self.aws_conn_id, verify=self.verify, config=self.botocore_config)
+        try:
+            for _ in range(self.waiter_max_attempts):

Review Comment:
   I implemented this in the latest revision by adding a custom `replication_task_modified` waiter and wiring the trigger through `AwsBaseWaiterTrigger`. Thank you! 



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: commits-unsubscribe@airflow.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] Add `DmsModifyTaskOperator` [airflow]

Posted by "vincbeck (via GitHub)" <gi...@apache.org>.
vincbeck commented on code in PR #67524:
URL: https://github.com/apache/airflow/pull/67524#discussion_r3348754657


##########
providers/amazon/src/airflow/providers/amazon/aws/waiters/dms.json:
##########
@@ -95,6 +95,85 @@
                     "state": "success"
                 }
             ]
+        },
+        "replication_task_modified": {
+            "operation": "DescribeReplicationTasks",
+            "delay": 30,
+            "maxAttempts": 60,
+            "acceptors": [
+                {
+                    "matcher": "path",
+                    "argument": "ReplicationTasks[0].Status",
+                    "expected": "modifying",
+                    "state": "retry"
+                },
+                {
+                    "matcher": "path",
+                    "argument": "ReplicationTasks[0].Status",
+                    "expected": "stopped",
+                    "state": "success"
+                },
+                {
+                    "matcher": "path",
+                    "argument": "ReplicationTasks[0].Status",
+                    "expected": "ready",
+                    "state": "success"
+                },
+                {
+                    "matcher": "path",
+                    "argument": "ReplicationTasks[0].Status",
+                    "expected": "failed",
+                    "state": "success"

Review Comment:
   If the task failed, it is considered a success? Same for `stopped`?



##########
providers/amazon/src/airflow/providers/amazon/aws/hooks/dms.py:
##########
@@ -200,6 +226,48 @@ def delete_replication_task(self, replication_task_arn):
 
         self.wait_for_task_status(replication_task_arn, DmsTaskWaiterStatus.DELETED)
 
+    def modify_replication_task(

Review Comment:
   This should have unit tests associated to it



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: commits-unsubscribe@airflow.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] Add `DmsModifyTaskOperator` [airflow]

Posted by "vincbeck (via GitHub)" <gi...@apache.org>.
vincbeck merged PR #67524:
URL: https://github.com/apache/airflow/pull/67524


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: commits-unsubscribe@airflow.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] Add `DmsModifyTaskOperator` [airflow]

Posted by "AlejandroMorgante (via GitHub)" <gi...@apache.org>.
AlejandroMorgante commented on code in PR #67524:
URL: https://github.com/apache/airflow/pull/67524#discussion_r3349652337


##########
providers/amazon/src/airflow/providers/amazon/aws/hooks/dms.py:
##########
@@ -200,6 +226,48 @@ def delete_replication_task(self, replication_task_arn):
 
         self.wait_for_task_status(replication_task_arn, DmsTaskWaiterStatus.DELETED)
 
+    def modify_replication_task(

Review Comment:
   Added unit tests for `DmsHook.modify_replication_task`



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: commits-unsubscribe@airflow.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] Add `DmsModifyTaskOperator` [airflow]

Posted by "vincbeck (via GitHub)" <gi...@apache.org>.
vincbeck commented on code in PR #67524:
URL: https://github.com/apache/airflow/pull/67524#discussion_r3335293854


##########
providers/amazon/src/airflow/providers/amazon/aws/operators/dms.py:
##########
@@ -118,6 +120,192 @@ def execute(self, context: Context):
         return task_arn
 
 
+class DmsModifyTaskOperator(AwsBaseOperator[DmsHook]):
+    """
+    Modifies an existing AWS DMS replication task.
+
+    The task must already be stopped before modification. Use :class:`DmsStopTaskOperator`
+    upstream in the Dag to stop it, and :class:`DmsStartTaskOperator` downstream to restart
+    it afterwards if needed.
+
+    .. seealso::
+        For more information on how to use this operator, take a look at the guide:
+        :ref:`howto/operator:DmsModifyTaskOperator`
+
+    :param replication_task_arn: Replication task ARN
+    :param table_mappings: New table mappings. If not provided, existing mappings are kept.
+    :param migration_type: Migration type ('full-load'|'cdc'|'full-load-and-cdc').
+        If not provided, existing type is kept.
+    :param replication_task_settings: Task settings dict. If not provided, existing settings are kept.
+    :param cdc_start_time: Start time for CDC.
+    :param cdc_start_position: Indicates when to start CDC (checkpoint or LSN/SCN format).
+        Mutually exclusive with cdc_start_time.
+    :param cdc_stop_position: Indicates when to stop CDC.
+    :param wait_for_completion: If True, wait for the modification to finish before returning.
+        In deferrable mode the operator defers rather than blocking. Defaults to True.
+    :param deferrable: Run the operator in deferrable mode. Defaults to False.
+    :param waiter_delay: Seconds between waiter polls (default: 30).
+    :param waiter_max_attempts: Maximum waiter poll attempts (default: 60).
+    :param aws_conn_id: The Airflow connection used for AWS credentials.
+        If this is ``None`` or empty then the default boto3 behaviour is used. If
+        running Airflow in a distributed manner and aws_conn_id is None or
+        empty, then default boto3 configuration would be used (and must be
+        maintained on each worker node).
+    :param region_name: AWS region_name. If not specified then the default boto3 behaviour is used.
+    :param verify: Whether or not to verify SSL certificates. See:
+        https://boto3.amazonaws.com/v1/documentation/api/latest/reference/core/session.html
+    :param botocore_config: Configuration dictionary (key-values) for botocore client. See:
+        https://botocore.amazonaws.com/v1/documentation/api/latest/reference/config.html
+    """
+
+    MODIFIABLE_STATES = DMS_MODIFIABLE_STATES
+
+    aws_hook_class = DmsHook
+    template_fields: Sequence[str] = aws_template_fields(
+        "replication_task_arn",
+        "table_mappings",
+        "migration_type",
+        "replication_task_settings",
+        "cdc_start_time",
+        "cdc_start_position",
+        "cdc_stop_position",
+    )
+    template_fields_renderers: ClassVar[dict] = {
+        "table_mappings": "json",
+        "replication_task_settings": "json",
+    }
+
+    def __init__(
+        self,
+        *,
+        replication_task_arn: str,
+        table_mappings: dict | None = None,
+        migration_type: str | None = None,
+        replication_task_settings: dict | None = None,
+        cdc_start_time: datetime | None = None,
+        cdc_start_position: str | None = None,
+        cdc_stop_position: str | None = None,
+        wait_for_completion: bool = True,
+        deferrable: bool = conf.getboolean("operators", "default_deferrable", fallback=False),
+        waiter_delay: int = 30,
+        waiter_max_attempts: int = 60,
+        aws_conn_id: str | None = "aws_default",
+        **kwargs,
+    ):
+        super().__init__(aws_conn_id=aws_conn_id, **kwargs)
+        if cdc_start_time and cdc_start_position:
+            raise ValueError("Only one of cdc_start_time or cdc_start_position can be provided.")
+        self.replication_task_arn = replication_task_arn
+        self.table_mappings = table_mappings
+        self.migration_type = migration_type
+        self.replication_task_settings = replication_task_settings
+        self.cdc_start_time = cdc_start_time
+        self.cdc_start_position = cdc_start_position
+        self.cdc_stop_position = cdc_stop_position
+        self.wait_for_completion = wait_for_completion
+        self.deferrable = deferrable
+        self.waiter_delay = waiter_delay
+        self.waiter_max_attempts = waiter_max_attempts
+
+    def execute(self, context: Context) -> dict:
+        tasks = self.hook.find_replication_tasks_by_arn(
+            replication_task_arn=self.replication_task_arn, without_settings=True
+        )
+        if not tasks:
+            raise ValueError(f"Replication task {self.replication_task_arn} not found.")
+
+        current_status = tasks[0].get("Status", "").lower()
+        self.log.info(
+            "Current status of replication task(%s) is '%s'.", self.replication_task_arn, current_status
+        )
+
+        if current_status == DmsTaskState.MODIFYING:
+            # boto3 stopped/ready waiters treat 'modifying' as a terminal failure — use poll loop.
+            current_status = self._wait_until_not_modifying()
+
+        if current_status not in self.MODIFIABLE_STATES:
+            raise RuntimeError(
+                f"Replication task {self.replication_task_arn} is in state '{current_status}' "
+                f"and must be in a modifiable state (stopped, ready, or failed) before modification. "
+                f"Use DmsStopTaskOperator to stop it first."
+            )
+
+        result = self.hook.modify_replication_task(
+            replication_task_arn=self.replication_task_arn,
+            table_mappings=self.table_mappings,
+            migration_type=self.migration_type,
+            replication_task_settings=self.replication_task_settings,
+            cdc_start_time=self.cdc_start_time,
+            cdc_start_position=self.cdc_start_position,
+            cdc_stop_position=self.cdc_stop_position,
+        )
+        self.log.info("DMS replication task(%s) has been modified.", self.replication_task_arn)
+
+        if self.wait_for_completion:
+            if self.deferrable:
+                self.defer(
+                    trigger=DmsTaskModifyCompleteTrigger(
+                        replication_task_arn=self.replication_task_arn,
+                        waiter_delay=self.waiter_delay,
+                        waiter_max_attempts=self.waiter_max_attempts,
+                        aws_conn_id=self.aws_conn_id,
+                    ),
+                    method_name="execute_complete",
+                    kwargs={"result": result},
+                )
+            else:
+                # modify_replication_task is async — poll until the task exits 'modifying'.
+                final_status = self._wait_until_not_modifying()
+                if final_status not in self.MODIFIABLE_STATES:
+                    raise RuntimeError(
+                        f"Replication task {self.replication_task_arn} ended in unexpected state "
+                        f"'{final_status}' after modification."
+                    )
+
+        return result
+
+    def execute_complete(
+        self, context: Context, event: dict | None = None, result: dict | None = None
+    ) -> dict:
+        validated_event = validate_execute_complete_event(event)
+        if validated_event["status"] != "success":
+            raise RuntimeError(f"Error waiting for DMS task modification to complete: {validated_event}")
+        self.log.info("DMS replication task(%s) modification complete.", self.replication_task_arn)
+        return result or {}
+
+    def _wait_until_not_modifying(self) -> str:

Review Comment:
   I would encourage implementing a custom waiter for that. You can find more information about it here: https://github.com/apache/airflow/blob/main/providers/amazon/src/airflow/providers/amazon/aws/waiters/README.md



##########
providers/amazon/src/airflow/providers/amazon/aws/operators/dms.py:
##########
@@ -118,6 +120,192 @@ def execute(self, context: Context):
         return task_arn
 
 
+class DmsModifyTaskOperator(AwsBaseOperator[DmsHook]):
+    """
+    Modifies an existing AWS DMS replication task.
+
+    The task must already be stopped before modification. Use :class:`DmsStopTaskOperator`
+    upstream in the Dag to stop it, and :class:`DmsStartTaskOperator` downstream to restart
+    it afterwards if needed.
+
+    .. seealso::
+        For more information on how to use this operator, take a look at the guide:
+        :ref:`howto/operator:DmsModifyTaskOperator`
+
+    :param replication_task_arn: Replication task ARN
+    :param table_mappings: New table mappings. If not provided, existing mappings are kept.
+    :param migration_type: Migration type ('full-load'|'cdc'|'full-load-and-cdc').
+        If not provided, existing type is kept.
+    :param replication_task_settings: Task settings dict. If not provided, existing settings are kept.
+    :param cdc_start_time: Start time for CDC.
+    :param cdc_start_position: Indicates when to start CDC (checkpoint or LSN/SCN format).
+        Mutually exclusive with cdc_start_time.
+    :param cdc_stop_position: Indicates when to stop CDC.
+    :param wait_for_completion: If True, wait for the modification to finish before returning.
+        In deferrable mode the operator defers rather than blocking. Defaults to True.
+    :param deferrable: Run the operator in deferrable mode. Defaults to False.
+    :param waiter_delay: Seconds between waiter polls (default: 30).
+    :param waiter_max_attempts: Maximum waiter poll attempts (default: 60).
+    :param aws_conn_id: The Airflow connection used for AWS credentials.
+        If this is ``None`` or empty then the default boto3 behaviour is used. If
+        running Airflow in a distributed manner and aws_conn_id is None or
+        empty, then default boto3 configuration would be used (and must be
+        maintained on each worker node).
+    :param region_name: AWS region_name. If not specified then the default boto3 behaviour is used.
+    :param verify: Whether or not to verify SSL certificates. See:
+        https://boto3.amazonaws.com/v1/documentation/api/latest/reference/core/session.html
+    :param botocore_config: Configuration dictionary (key-values) for botocore client. See:
+        https://botocore.amazonaws.com/v1/documentation/api/latest/reference/config.html
+    """
+
+    MODIFIABLE_STATES = DMS_MODIFIABLE_STATES
+
+    aws_hook_class = DmsHook
+    template_fields: Sequence[str] = aws_template_fields(
+        "replication_task_arn",
+        "table_mappings",
+        "migration_type",
+        "replication_task_settings",
+        "cdc_start_time",
+        "cdc_start_position",
+        "cdc_stop_position",
+    )
+    template_fields_renderers: ClassVar[dict] = {
+        "table_mappings": "json",
+        "replication_task_settings": "json",
+    }
+
+    def __init__(
+        self,
+        *,
+        replication_task_arn: str,
+        table_mappings: dict | None = None,
+        migration_type: str | None = None,
+        replication_task_settings: dict | None = None,
+        cdc_start_time: datetime | None = None,
+        cdc_start_position: str | None = None,
+        cdc_stop_position: str | None = None,
+        wait_for_completion: bool = True,
+        deferrable: bool = conf.getboolean("operators", "default_deferrable", fallback=False),
+        waiter_delay: int = 30,
+        waiter_max_attempts: int = 60,
+        aws_conn_id: str | None = "aws_default",
+        **kwargs,
+    ):
+        super().__init__(aws_conn_id=aws_conn_id, **kwargs)
+        if cdc_start_time and cdc_start_position:
+            raise ValueError("Only one of cdc_start_time or cdc_start_position can be provided.")
+        self.replication_task_arn = replication_task_arn
+        self.table_mappings = table_mappings
+        self.migration_type = migration_type
+        self.replication_task_settings = replication_task_settings
+        self.cdc_start_time = cdc_start_time
+        self.cdc_start_position = cdc_start_position
+        self.cdc_stop_position = cdc_stop_position
+        self.wait_for_completion = wait_for_completion
+        self.deferrable = deferrable
+        self.waiter_delay = waiter_delay
+        self.waiter_max_attempts = waiter_max_attempts
+
+    def execute(self, context: Context) -> dict:
+        tasks = self.hook.find_replication_tasks_by_arn(
+            replication_task_arn=self.replication_task_arn, without_settings=True
+        )
+        if not tasks:
+            raise ValueError(f"Replication task {self.replication_task_arn} not found.")
+
+        current_status = tasks[0].get("Status", "").lower()
+        self.log.info(
+            "Current status of replication task(%s) is '%s'.", self.replication_task_arn, current_status
+        )
+
+        if current_status == DmsTaskState.MODIFYING:
+            # boto3 stopped/ready waiters treat 'modifying' as a terminal failure — use poll loop.
+            current_status = self._wait_until_not_modifying()
+
+        if current_status not in self.MODIFIABLE_STATES:
+            raise RuntimeError(
+                f"Replication task {self.replication_task_arn} is in state '{current_status}' "
+                f"and must be in a modifiable state (stopped, ready, or failed) before modification. "
+                f"Use DmsStopTaskOperator to stop it first."
+            )
+
+        result = self.hook.modify_replication_task(
+            replication_task_arn=self.replication_task_arn,
+            table_mappings=self.table_mappings,
+            migration_type=self.migration_type,
+            replication_task_settings=self.replication_task_settings,
+            cdc_start_time=self.cdc_start_time,
+            cdc_start_position=self.cdc_start_position,
+            cdc_stop_position=self.cdc_stop_position,
+        )
+        self.log.info("DMS replication task(%s) has been modified.", self.replication_task_arn)
+
+        if self.wait_for_completion:
+            if self.deferrable:
+                self.defer(
+                    trigger=DmsTaskModifyCompleteTrigger(
+                        replication_task_arn=self.replication_task_arn,
+                        waiter_delay=self.waiter_delay,
+                        waiter_max_attempts=self.waiter_max_attempts,
+                        aws_conn_id=self.aws_conn_id,
+                    ),
+                    method_name="execute_complete",
+                    kwargs={"result": result},
+                )
+            else:
+                # modify_replication_task is async — poll until the task exits 'modifying'.
+                final_status = self._wait_until_not_modifying()
+                if final_status not in self.MODIFIABLE_STATES:
+                    raise RuntimeError(
+                        f"Replication task {self.replication_task_arn} ended in unexpected state "
+                        f"'{final_status}' after modification."
+                    )
+
+        return result
+
+    def execute_complete(
+        self, context: Context, event: dict | None = None, result: dict | None = None
+    ) -> dict:
+        validated_event = validate_execute_complete_event(event)
+        if validated_event["status"] != "success":
+            raise RuntimeError(f"Error waiting for DMS task modification to complete: {validated_event}")
+        self.log.info("DMS replication task(%s) modification complete.", self.replication_task_arn)

Review Comment:
   By using `self.replication_task_arn` in `execute_complete`, you assume both `execute` and `execute_complete` are executer on the same worker/environment. This is not true. Ideally you should use only information coming from the event



##########
providers/amazon/src/airflow/providers/amazon/aws/triggers/dms.py:
##########
@@ -219,3 +222,97 @@ def hook(self) -> AwsGenericHook:
             verify=self.verify,
             config=self.botocore_config,
         )
+
+
+class DmsTaskModifyCompleteTrigger(BaseTrigger):
+    """
+    Trigger that polls until a DMS classic replication task exits the ``modifying`` state.
+
+    The boto3 ``replication_task_stopped`` waiter treats ``modifying`` as a terminal failure,
+    so a custom polling loop is required here.
+
+    :param replication_task_arn: The ARN of the replication task.
+    :param waiter_delay: Seconds between polls.
+    :param waiter_max_attempts: Maximum number of poll attempts before giving up.
+    :param aws_conn_id: The Airflow connection used for AWS credentials.
+    :param verify: Whether or not to verify SSL certificates.
+    :param botocore_config: Configuration dictionary (key-values) for botocore client.
+    """
+
+    def __init__(
+        self,
+        replication_task_arn: str,
+        waiter_delay: int = 30,
+        waiter_max_attempts: int = 60,
+        aws_conn_id: str | None = "aws_default",
+        verify: bool | str | None = None,
+        botocore_config: dict | None = None,
+    ) -> None:
+        super().__init__()
+        self.replication_task_arn = replication_task_arn
+        self.waiter_delay = waiter_delay
+        self.waiter_max_attempts = waiter_max_attempts
+        self.aws_conn_id = aws_conn_id
+        self.verify = verify
+        self.botocore_config = botocore_config
+
+    def serialize(self) -> tuple[str, dict]:
+        return (
+            "airflow.providers.amazon.aws.triggers.dms.DmsTaskModifyCompleteTrigger",
+            {
+                "replication_task_arn": self.replication_task_arn,
+                "waiter_delay": self.waiter_delay,
+                "waiter_max_attempts": self.waiter_max_attempts,
+                "aws_conn_id": self.aws_conn_id,
+                "verify": self.verify,
+                "botocore_config": self.botocore_config,
+            },
+        )
+
+    async def run(self) -> AsyncIterator[TriggerEvent]:
+        hook = DmsHook(aws_conn_id=self.aws_conn_id, verify=self.verify, config=self.botocore_config)
+        try:
+            for _ in range(self.waiter_max_attempts):

Review Comment:
   Same here, I would use a custom waiter



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: commits-unsubscribe@airflow.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] Add DmsModifyTaskOperator [airflow]

Posted by "AlejandroMorgante (via GitHub)" <gi...@apache.org>.
AlejandroMorgante commented on code in PR #67524:
URL: https://github.com/apache/airflow/pull/67524#discussion_r3314647660


##########
providers/amazon/docs/changelog.rst:
##########
@@ -32,6 +32,7 @@ Changelog
 Features
 ~~~~~~~~
 
+* ``Add DmsModifyTaskOperator to modify DMS replication tasks with stop/restart lifecycle (#67524)``

Review Comment:
   Good catch, reverted.
   
   ---
   Drafted-by: Claude Code (claude-sonnet-4-6); reviewed by @AlejandroMorgante before posting



##########
providers/amazon/src/airflow/providers/amazon/aws/operators/dms.py:
##########
@@ -118,6 +121,274 @@ def execute(self, context: Context):
         return task_arn
 
 
+class DmsModifyTaskOperator(AwsBaseOperator[DmsHook]):
+    """
+    Modifies an existing AWS DMS replication task.
+
+    If the task is not already stopped, set ``stop_task_before=True`` to stop it first.
+    To restart the task after modification, set ``restart_task_after=True``.
+
+    .. seealso::
+        For more information on how to use this operator, take a look at the guide:
+        :ref:`howto/operator:DmsModifyTaskOperator`
+
+    :param replication_task_arn: Replication task ARN
+    :param table_mappings: New table mappings. If not provided, existing mappings are kept.
+    :param migration_type: Migration type ('full-load'|'cdc'|'full-load-and-cdc').
+        If not provided, existing type is kept.
+    :param replication_task_settings: Task settings dict. If not provided, existing settings are kept.
+    :param cdc_start_time: Start time for CDC.
+    :param cdc_start_position: Indicates when to start CDC (checkpoint or LSN/SCN format).
+        Mutually exclusive with cdc_start_time.
+    :param cdc_stop_position: Indicates when to stop CDC.
+    :param stop_task_before: If True, stop the task before modifying if it is not already stopped.
+    :param restart_task_after: If True, restart the task after modifying.
+    :param start_replication_task_type: Start type used when restarting the task.
+        One of 'start-replication', 'resume-processing', or 'reload-target'.
+        Defaults to 'resume-processing'. Only used when ``restart_task_after=True``.
+    :param wait_for_completion: Only applies when the task is already in ``modifying`` state
+        when ``execute()`` is called. If True, wait for the modification to finish before
+        proceeding. If False, raises immediately instead of waiting.
+    :param deferrable: Run the operator in deferrable mode.
+    :param waiter_delay: Seconds between waiter polls (default: 30).
+    :param waiter_max_attempts: Maximum waiter poll attempts (default: 60).
+    :param aws_conn_id: The Airflow connection used for AWS credentials.
+        If this is ``None`` or empty then the default boto3 behaviour is used. If
+        running Airflow in a distributed manner and aws_conn_id is None or
+        empty, then default boto3 configuration would be used (and must be
+        maintained on each worker node).
+    :param region_name: AWS region_name. If not specified then the default boto3 behaviour is used.
+    :param verify: Whether or not to verify SSL certificates. See:
+        https://boto3.amazonaws.com/v1/documentation/api/latest/reference/core/session.html
+    :param botocore_config: Configuration dictionary (key-values) for botocore client. See:
+        https://botocore.amazonaws.com/v1/documentation/api/latest/reference/config.html
+    """
+
+    STOPPED_STATES = ("stopped", "ready", "failed", "created")
+    TERMINAL_STATES = frozenset({"failed", "stopped", "ready", "created", "deleting"})
+
+    aws_hook_class = DmsHook
+    template_fields: Sequence[str] = aws_template_fields(
+        "replication_task_arn",
+        "table_mappings",
+        "migration_type",
+        "replication_task_settings",
+        "cdc_start_time",
+        "cdc_start_position",
+        "cdc_stop_position",
+        "start_replication_task_type",
+    )
+    template_fields_renderers: ClassVar[dict] = {
+        "table_mappings": "json",
+        "replication_task_settings": "json",
+    }
+
+    def __init__(
+        self,
+        *,
+        replication_task_arn: str,
+        table_mappings: dict | None = None,
+        migration_type: str | None = None,
+        replication_task_settings: dict | None = None,
+        cdc_start_time: datetime | None = None,
+        cdc_start_position: str | None = None,
+        cdc_stop_position: str | None = None,
+        stop_task_before: bool = False,
+        restart_task_after: bool = False,
+        start_replication_task_type: str = "resume-processing",
+        wait_for_completion: bool = True,
+        deferrable: bool = conf.getboolean("operators", "default_deferrable", fallback=False),
+        waiter_delay: int = 30,
+        waiter_max_attempts: int = 60,
+        **kwargs,
+    ):
+        super().__init__(**kwargs)
+        if cdc_start_time and cdc_start_position:
+            raise ValueError("Only one of cdc_start_time or cdc_start_position can be provided.")
+        self.replication_task_arn = replication_task_arn
+        self.table_mappings = table_mappings
+        self.migration_type = migration_type
+        self.replication_task_settings = replication_task_settings
+        self.cdc_start_time = cdc_start_time
+        self.cdc_start_position = cdc_start_position
+        self.cdc_stop_position = cdc_stop_position
+        self.stop_task_before = stop_task_before
+        self.restart_task_after = restart_task_after
+        self.start_replication_task_type = start_replication_task_type
+        self.wait_for_completion = wait_for_completion
+        self.deferrable = deferrable
+        self.waiter_delay = waiter_delay
+        self.waiter_max_attempts = waiter_max_attempts
+
+    def execute(self, context: Context) -> dict:
+        tasks = self.hook.find_replication_tasks_by_arn(
+            replication_task_arn=self.replication_task_arn, without_settings=True
+        )
+        if not tasks:
+            raise AirflowException(f"Replication task {self.replication_task_arn} not found.")
+
+        current_status = tasks[0].get("Status", "").lower()
+        self.log.info(
+            "Current status of replication task(%s) is '%s'.", self.replication_task_arn, current_status
+        )
+
+        if current_status == "modifying":
+            # boto3 stopped/ready waiters treat 'modifying' as a terminal failure — use poll loop.
+            if not self.wait_for_completion:
+                raise AirflowException(

Review Comment:
   Done — ValueError for not-found, RuntimeError for state errors and timeouts.
   
   ---
   Drafted-by: Claude Code (claude-sonnet-4-6); reviewed by @AlejandroMorgante before posting



##########
providers/amazon/src/airflow/providers/amazon/aws/operators/dms.py:
##########
@@ -118,6 +121,274 @@ def execute(self, context: Context):
         return task_arn
 
 
+class DmsModifyTaskOperator(AwsBaseOperator[DmsHook]):
+    """
+    Modifies an existing AWS DMS replication task.
+
+    If the task is not already stopped, set ``stop_task_before=True`` to stop it first.
+    To restart the task after modification, set ``restart_task_after=True``.
+
+    .. seealso::
+        For more information on how to use this operator, take a look at the guide:
+        :ref:`howto/operator:DmsModifyTaskOperator`
+
+    :param replication_task_arn: Replication task ARN
+    :param table_mappings: New table mappings. If not provided, existing mappings are kept.
+    :param migration_type: Migration type ('full-load'|'cdc'|'full-load-and-cdc').
+        If not provided, existing type is kept.
+    :param replication_task_settings: Task settings dict. If not provided, existing settings are kept.
+    :param cdc_start_time: Start time for CDC.
+    :param cdc_start_position: Indicates when to start CDC (checkpoint or LSN/SCN format).
+        Mutually exclusive with cdc_start_time.
+    :param cdc_stop_position: Indicates when to stop CDC.
+    :param stop_task_before: If True, stop the task before modifying if it is not already stopped.
+    :param restart_task_after: If True, restart the task after modifying.
+    :param start_replication_task_type: Start type used when restarting the task.
+        One of 'start-replication', 'resume-processing', or 'reload-target'.
+        Defaults to 'resume-processing'. Only used when ``restart_task_after=True``.
+    :param wait_for_completion: Only applies when the task is already in ``modifying`` state
+        when ``execute()`` is called. If True, wait for the modification to finish before
+        proceeding. If False, raises immediately instead of waiting.
+    :param deferrable: Run the operator in deferrable mode.
+    :param waiter_delay: Seconds between waiter polls (default: 30).
+    :param waiter_max_attempts: Maximum waiter poll attempts (default: 60).
+    :param aws_conn_id: The Airflow connection used for AWS credentials.
+        If this is ``None`` or empty then the default boto3 behaviour is used. If
+        running Airflow in a distributed manner and aws_conn_id is None or
+        empty, then default boto3 configuration would be used (and must be
+        maintained on each worker node).
+    :param region_name: AWS region_name. If not specified then the default boto3 behaviour is used.
+    :param verify: Whether or not to verify SSL certificates. See:
+        https://boto3.amazonaws.com/v1/documentation/api/latest/reference/core/session.html
+    :param botocore_config: Configuration dictionary (key-values) for botocore client. See:
+        https://botocore.amazonaws.com/v1/documentation/api/latest/reference/config.html
+    """
+
+    STOPPED_STATES = ("stopped", "ready", "failed", "created")
+    TERMINAL_STATES = frozenset({"failed", "stopped", "ready", "created", "deleting"})

Review Comment:
   Added DmsTaskState enum to the hook (modeled after DmsTaskWaiterStatus that was already there) and renamed to MODIFIABLE_STATES.
   
   ---
   Drafted-by: Claude Code (claude-sonnet-4-6); reviewed by @AlejandroMorgante before posting



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: commits-unsubscribe@airflow.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] Add DmsModifyTaskOperator [airflow]

Posted by "AlejandroMorgante (via GitHub)" <gi...@apache.org>.
AlejandroMorgante commented on code in PR #67524:
URL: https://github.com/apache/airflow/pull/67524#discussion_r3314647660


##########
providers/amazon/docs/changelog.rst:
##########
@@ -32,6 +32,7 @@ Changelog
 Features
 ~~~~~~~~
 
+* ``Add DmsModifyTaskOperator to modify DMS replication tasks with stop/restart lifecycle (#67524)``

Review Comment:
   Good catch, reverted.



##########
providers/amazon/src/airflow/providers/amazon/aws/operators/dms.py:
##########
@@ -118,6 +121,274 @@ def execute(self, context: Context):
         return task_arn
 
 
+class DmsModifyTaskOperator(AwsBaseOperator[DmsHook]):
+    """
+    Modifies an existing AWS DMS replication task.
+
+    If the task is not already stopped, set ``stop_task_before=True`` to stop it first.
+    To restart the task after modification, set ``restart_task_after=True``.
+
+    .. seealso::
+        For more information on how to use this operator, take a look at the guide:
+        :ref:`howto/operator:DmsModifyTaskOperator`
+
+    :param replication_task_arn: Replication task ARN
+    :param table_mappings: New table mappings. If not provided, existing mappings are kept.
+    :param migration_type: Migration type ('full-load'|'cdc'|'full-load-and-cdc').
+        If not provided, existing type is kept.
+    :param replication_task_settings: Task settings dict. If not provided, existing settings are kept.
+    :param cdc_start_time: Start time for CDC.
+    :param cdc_start_position: Indicates when to start CDC (checkpoint or LSN/SCN format).
+        Mutually exclusive with cdc_start_time.
+    :param cdc_stop_position: Indicates when to stop CDC.
+    :param stop_task_before: If True, stop the task before modifying if it is not already stopped.
+    :param restart_task_after: If True, restart the task after modifying.
+    :param start_replication_task_type: Start type used when restarting the task.
+        One of 'start-replication', 'resume-processing', or 'reload-target'.
+        Defaults to 'resume-processing'. Only used when ``restart_task_after=True``.
+    :param wait_for_completion: Only applies when the task is already in ``modifying`` state
+        when ``execute()`` is called. If True, wait for the modification to finish before
+        proceeding. If False, raises immediately instead of waiting.
+    :param deferrable: Run the operator in deferrable mode.
+    :param waiter_delay: Seconds between waiter polls (default: 30).
+    :param waiter_max_attempts: Maximum waiter poll attempts (default: 60).
+    :param aws_conn_id: The Airflow connection used for AWS credentials.
+        If this is ``None`` or empty then the default boto3 behaviour is used. If
+        running Airflow in a distributed manner and aws_conn_id is None or
+        empty, then default boto3 configuration would be used (and must be
+        maintained on each worker node).
+    :param region_name: AWS region_name. If not specified then the default boto3 behaviour is used.
+    :param verify: Whether or not to verify SSL certificates. See:
+        https://boto3.amazonaws.com/v1/documentation/api/latest/reference/core/session.html
+    :param botocore_config: Configuration dictionary (key-values) for botocore client. See:
+        https://botocore.amazonaws.com/v1/documentation/api/latest/reference/config.html
+    """
+
+    STOPPED_STATES = ("stopped", "ready", "failed", "created")
+    TERMINAL_STATES = frozenset({"failed", "stopped", "ready", "created", "deleting"})
+
+    aws_hook_class = DmsHook
+    template_fields: Sequence[str] = aws_template_fields(
+        "replication_task_arn",
+        "table_mappings",
+        "migration_type",
+        "replication_task_settings",
+        "cdc_start_time",
+        "cdc_start_position",
+        "cdc_stop_position",
+        "start_replication_task_type",
+    )
+    template_fields_renderers: ClassVar[dict] = {
+        "table_mappings": "json",
+        "replication_task_settings": "json",
+    }
+
+    def __init__(
+        self,
+        *,
+        replication_task_arn: str,
+        table_mappings: dict | None = None,
+        migration_type: str | None = None,
+        replication_task_settings: dict | None = None,
+        cdc_start_time: datetime | None = None,
+        cdc_start_position: str | None = None,
+        cdc_stop_position: str | None = None,
+        stop_task_before: bool = False,
+        restart_task_after: bool = False,
+        start_replication_task_type: str = "resume-processing",
+        wait_for_completion: bool = True,
+        deferrable: bool = conf.getboolean("operators", "default_deferrable", fallback=False),
+        waiter_delay: int = 30,
+        waiter_max_attempts: int = 60,
+        **kwargs,
+    ):
+        super().__init__(**kwargs)
+        if cdc_start_time and cdc_start_position:
+            raise ValueError("Only one of cdc_start_time or cdc_start_position can be provided.")
+        self.replication_task_arn = replication_task_arn
+        self.table_mappings = table_mappings
+        self.migration_type = migration_type
+        self.replication_task_settings = replication_task_settings
+        self.cdc_start_time = cdc_start_time
+        self.cdc_start_position = cdc_start_position
+        self.cdc_stop_position = cdc_stop_position
+        self.stop_task_before = stop_task_before
+        self.restart_task_after = restart_task_after
+        self.start_replication_task_type = start_replication_task_type
+        self.wait_for_completion = wait_for_completion
+        self.deferrable = deferrable
+        self.waiter_delay = waiter_delay
+        self.waiter_max_attempts = waiter_max_attempts
+
+    def execute(self, context: Context) -> dict:
+        tasks = self.hook.find_replication_tasks_by_arn(
+            replication_task_arn=self.replication_task_arn, without_settings=True
+        )
+        if not tasks:
+            raise AirflowException(f"Replication task {self.replication_task_arn} not found.")
+
+        current_status = tasks[0].get("Status", "").lower()
+        self.log.info(
+            "Current status of replication task(%s) is '%s'.", self.replication_task_arn, current_status
+        )
+
+        if current_status == "modifying":
+            # boto3 stopped/ready waiters treat 'modifying' as a terminal failure — use poll loop.
+            if not self.wait_for_completion:
+                raise AirflowException(

Review Comment:
   Done — ValueError for not-found, RuntimeError for state errors and timeouts.



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: commits-unsubscribe@airflow.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] Add `DmsModifyTaskOperator` [airflow]

Posted by "AlejandroMorgante (via GitHub)" <gi...@apache.org>.
AlejandroMorgante commented on code in PR #67524:
URL: https://github.com/apache/airflow/pull/67524#discussion_r3314858522


##########
providers/amazon/src/airflow/providers/amazon/aws/operators/dms.py:
##########
@@ -118,6 +121,274 @@ def execute(self, context: Context):
         return task_arn
 
 
+class DmsModifyTaskOperator(AwsBaseOperator[DmsHook]):
+    """
+    Modifies an existing AWS DMS replication task.
+
+    If the task is not already stopped, set ``stop_task_before=True`` to stop it first.
+    To restart the task after modification, set ``restart_task_after=True``.
+
+    .. seealso::
+        For more information on how to use this operator, take a look at the guide:
+        :ref:`howto/operator:DmsModifyTaskOperator`
+
+    :param replication_task_arn: Replication task ARN
+    :param table_mappings: New table mappings. If not provided, existing mappings are kept.
+    :param migration_type: Migration type ('full-load'|'cdc'|'full-load-and-cdc').
+        If not provided, existing type is kept.
+    :param replication_task_settings: Task settings dict. If not provided, existing settings are kept.
+    :param cdc_start_time: Start time for CDC.
+    :param cdc_start_position: Indicates when to start CDC (checkpoint or LSN/SCN format).
+        Mutually exclusive with cdc_start_time.
+    :param cdc_stop_position: Indicates when to stop CDC.
+    :param stop_task_before: If True, stop the task before modifying if it is not already stopped.
+    :param restart_task_after: If True, restart the task after modifying.
+    :param start_replication_task_type: Start type used when restarting the task.
+        One of 'start-replication', 'resume-processing', or 'reload-target'.
+        Defaults to 'resume-processing'. Only used when ``restart_task_after=True``.
+    :param wait_for_completion: Only applies when the task is already in ``modifying`` state
+        when ``execute()`` is called. If True, wait for the modification to finish before
+        proceeding. If False, raises immediately instead of waiting.
+    :param deferrable: Run the operator in deferrable mode.
+    :param waiter_delay: Seconds between waiter polls (default: 30).
+    :param waiter_max_attempts: Maximum waiter poll attempts (default: 60).
+    :param aws_conn_id: The Airflow connection used for AWS credentials.
+        If this is ``None`` or empty then the default boto3 behaviour is used. If
+        running Airflow in a distributed manner and aws_conn_id is None or
+        empty, then default boto3 configuration would be used (and must be
+        maintained on each worker node).
+    :param region_name: AWS region_name. If not specified then the default boto3 behaviour is used.
+    :param verify: Whether or not to verify SSL certificates. See:
+        https://boto3.amazonaws.com/v1/documentation/api/latest/reference/core/session.html
+    :param botocore_config: Configuration dictionary (key-values) for botocore client. See:
+        https://botocore.amazonaws.com/v1/documentation/api/latest/reference/config.html
+    """
+
+    STOPPED_STATES = ("stopped", "ready", "failed", "created")
+    TERMINAL_STATES = frozenset({"failed", "stopped", "ready", "created", "deleting"})
+
+    aws_hook_class = DmsHook
+    template_fields: Sequence[str] = aws_template_fields(
+        "replication_task_arn",
+        "table_mappings",
+        "migration_type",
+        "replication_task_settings",
+        "cdc_start_time",
+        "cdc_start_position",
+        "cdc_stop_position",
+        "start_replication_task_type",
+    )
+    template_fields_renderers: ClassVar[dict] = {
+        "table_mappings": "json",
+        "replication_task_settings": "json",
+    }
+
+    def __init__(
+        self,
+        *,
+        replication_task_arn: str,
+        table_mappings: dict | None = None,
+        migration_type: str | None = None,
+        replication_task_settings: dict | None = None,
+        cdc_start_time: datetime | None = None,
+        cdc_start_position: str | None = None,
+        cdc_stop_position: str | None = None,
+        stop_task_before: bool = False,
+        restart_task_after: bool = False,
+        start_replication_task_type: str = "resume-processing",
+        wait_for_completion: bool = True,
+        deferrable: bool = conf.getboolean("operators", "default_deferrable", fallback=False),
+        waiter_delay: int = 30,
+        waiter_max_attempts: int = 60,
+        **kwargs,
+    ):
+        super().__init__(**kwargs)
+        if cdc_start_time and cdc_start_position:
+            raise ValueError("Only one of cdc_start_time or cdc_start_position can be provided.")
+        self.replication_task_arn = replication_task_arn
+        self.table_mappings = table_mappings
+        self.migration_type = migration_type
+        self.replication_task_settings = replication_task_settings
+        self.cdc_start_time = cdc_start_time
+        self.cdc_start_position = cdc_start_position
+        self.cdc_stop_position = cdc_stop_position
+        self.stop_task_before = stop_task_before
+        self.restart_task_after = restart_task_after
+        self.start_replication_task_type = start_replication_task_type
+        self.wait_for_completion = wait_for_completion
+        self.deferrable = deferrable
+        self.waiter_delay = waiter_delay
+        self.waiter_max_attempts = waiter_max_attempts
+
+    def execute(self, context: Context) -> dict:
+        tasks = self.hook.find_replication_tasks_by_arn(
+            replication_task_arn=self.replication_task_arn, without_settings=True
+        )
+        if not tasks:
+            raise AirflowException(f"Replication task {self.replication_task_arn} not found.")
+
+        current_status = tasks[0].get("Status", "").lower()
+        self.log.info(
+            "Current status of replication task(%s) is '%s'.", self.replication_task_arn, current_status
+        )
+
+        if current_status == "modifying":
+            # boto3 stopped/ready waiters treat 'modifying' as a terminal failure — use poll loop.
+            if not self.wait_for_completion:
+                raise AirflowException(
+                    f"Replication task {self.replication_task_arn} is already being modified. "
+                    f"Set wait_for_completion=True to wait for it to finish."
+                )
+            self._wait_until_not_modifying()
+        elif current_status not in self.STOPPED_STATES:
+            if not self.stop_task_before:
+                raise AirflowException(
+                    f"Replication task {self.replication_task_arn} is in state '{current_status}' "
+                    f"and must be stopped before modification. Set stop_task_before=True to stop it "
+                    f"automatically, or stop the task first."
+                )
+            if current_status == "starting":
+                # DMS rejects StopReplicationTask while the task is still starting up.
+                self.log.info(
+                    "Replication task(%s) is starting, waiting for it to reach 'running'.",
+                    self.replication_task_arn,
+                )
+                self._wait_for_status("running")
+            self.log.info("Stopping replication task(%s).", self.replication_task_arn)
+            self.hook.stop_replication_task(replication_task_arn=self.replication_task_arn)
+            self.log.info("Waiting for replication task(%s) to stop.", self.replication_task_arn)
+            if self.deferrable:

Review Comment:
   Fair point — the modify phase itself is short (~1-2 min in practice, as we confirmed against real AWS). You're right that stopping a running task is where the wait can get significant, but that's now on DmsStopTaskOperator rather than here.
   
   The deferrable option is kept as opt-in (default is False), so it doesn't change behaviour for anyone not asking for it. Happy to drop it if the preference is to keep the operator minimal.



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: commits-unsubscribe@airflow.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] Add `DmsModifyTaskOperator` [airflow]

Posted by "SameerMesiah97 (via GitHub)" <gi...@apache.org>.
SameerMesiah97 commented on code in PR #67524:
URL: https://github.com/apache/airflow/pull/67524#discussion_r3329198947


##########
providers/amazon/src/airflow/providers/amazon/aws/operators/dms.py:
##########
@@ -118,6 +120,178 @@ def execute(self, context: Context):
         return task_arn
 
 
+class DmsModifyTaskOperator(AwsBaseOperator[DmsHook]):
+    """
+    Modifies an existing AWS DMS replication task.
+
+    The task must already be stopped before modification. Use :class:`DmsStopTaskOperator`
+    upstream in the Dag to stop it, and :class:`DmsStartTaskOperator` downstream to restart
+    it afterwards if needed.
+
+    .. seealso::
+        For more information on how to use this operator, take a look at the guide:
+        :ref:`howto/operator:DmsModifyTaskOperator`
+
+    :param replication_task_arn: Replication task ARN
+    :param table_mappings: New table mappings. If not provided, existing mappings are kept.
+    :param migration_type: Migration type ('full-load'|'cdc'|'full-load-and-cdc').
+        If not provided, existing type is kept.
+    :param replication_task_settings: Task settings dict. If not provided, existing settings are kept.
+    :param cdc_start_time: Start time for CDC.
+    :param cdc_start_position: Indicates when to start CDC (checkpoint or LSN/SCN format).
+        Mutually exclusive with cdc_start_time.
+    :param cdc_stop_position: Indicates when to stop CDC.
+    :param wait_for_completion: If True, wait for the modification to finish before returning.
+        In deferrable mode the operator defers rather than blocking. Defaults to True.
+    :param deferrable: Run the operator in deferrable mode. Defaults to False.
+    :param waiter_delay: Seconds between waiter polls (default: 30).
+    :param waiter_max_attempts: Maximum waiter poll attempts (default: 60).
+    :param aws_conn_id: The Airflow connection used for AWS credentials.
+        If this is ``None`` or empty then the default boto3 behaviour is used. If
+        running Airflow in a distributed manner and aws_conn_id is None or
+        empty, then default boto3 configuration would be used (and must be
+        maintained on each worker node).
+    :param region_name: AWS region_name. If not specified then the default boto3 behaviour is used.
+    :param verify: Whether or not to verify SSL certificates. See:
+        https://boto3.amazonaws.com/v1/documentation/api/latest/reference/core/session.html
+    :param botocore_config: Configuration dictionary (key-values) for botocore client. See:
+        https://botocore.amazonaws.com/v1/documentation/api/latest/reference/config.html
+    """
+
+    MODIFIABLE_STATES = frozenset({DmsTaskState.STOPPED, DmsTaskState.READY, DmsTaskState.FAILED})
+
+    aws_hook_class = DmsHook
+    template_fields: Sequence[str] = aws_template_fields(
+        "replication_task_arn",
+        "table_mappings",
+        "migration_type",
+        "replication_task_settings",
+        "cdc_start_time",
+        "cdc_start_position",
+        "cdc_stop_position",
+    )
+    template_fields_renderers: ClassVar[dict] = {
+        "table_mappings": "json",
+        "replication_task_settings": "json",
+    }
+
+    def __init__(
+        self,
+        *,
+        replication_task_arn: str,
+        table_mappings: dict | None = None,
+        migration_type: str | None = None,
+        replication_task_settings: dict | None = None,
+        cdc_start_time: datetime | None = None,
+        cdc_start_position: str | None = None,
+        cdc_stop_position: str | None = None,
+        wait_for_completion: bool = True,
+        deferrable: bool = conf.getboolean("operators", "default_deferrable", fallback=False),
+        waiter_delay: int = 30,
+        waiter_max_attempts: int = 60,
+        **kwargs,
+    ):
+        super().__init__(**kwargs)
+        if cdc_start_time and cdc_start_position:
+            raise ValueError("Only one of cdc_start_time or cdc_start_position can be provided.")
+        self.replication_task_arn = replication_task_arn
+        self.table_mappings = table_mappings
+        self.migration_type = migration_type
+        self.replication_task_settings = replication_task_settings
+        self.cdc_start_time = cdc_start_time
+        self.cdc_start_position = cdc_start_position
+        self.cdc_stop_position = cdc_stop_position
+        self.wait_for_completion = wait_for_completion
+        self.deferrable = deferrable
+        self.waiter_delay = waiter_delay
+        self.waiter_max_attempts = waiter_max_attempts
+
+    def execute(self, context: Context) -> dict:
+        tasks = self.hook.find_replication_tasks_by_arn(
+            replication_task_arn=self.replication_task_arn, without_settings=True
+        )
+        if not tasks:
+            raise ValueError(f"Replication task {self.replication_task_arn} not found.")
+
+        current_status = tasks[0].get("Status", "").lower()
+        self.log.info(
+            "Current status of replication task(%s) is '%s'.", self.replication_task_arn, current_status
+        )
+
+        if current_status == DmsTaskState.MODIFYING:
+            # boto3 stopped/ready waiters treat 'modifying' as a terminal failure — use poll loop.
+            self._wait_until_not_modifying()
+        elif current_status not in self.MODIFIABLE_STATES:
+            raise RuntimeError(
+                f"Replication task {self.replication_task_arn} is in state '{current_status}' "
+                f"and must be stopped before modification. "
+                f"Use DmsStopTaskOperator to stop it first."

Review Comment:
   Is this error message accurate? `MODIFIABLE_STATES` includes `READY` and `FAILED` in addition to `STOPPED`. 



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: commits-unsubscribe@airflow.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] Add `DmsModifyTaskOperator` [airflow]

Posted by "AlejandroMorgante (via GitHub)" <gi...@apache.org>.
AlejandroMorgante commented on code in PR #67524:
URL: https://github.com/apache/airflow/pull/67524#discussion_r3329301672


##########
providers/amazon/src/airflow/providers/amazon/aws/operators/dms.py:
##########
@@ -118,6 +120,178 @@ def execute(self, context: Context):
         return task_arn
 
 
+class DmsModifyTaskOperator(AwsBaseOperator[DmsHook]):
+    """
+    Modifies an existing AWS DMS replication task.
+
+    The task must already be stopped before modification. Use :class:`DmsStopTaskOperator`
+    upstream in the Dag to stop it, and :class:`DmsStartTaskOperator` downstream to restart
+    it afterwards if needed.
+
+    .. seealso::
+        For more information on how to use this operator, take a look at the guide:
+        :ref:`howto/operator:DmsModifyTaskOperator`
+
+    :param replication_task_arn: Replication task ARN
+    :param table_mappings: New table mappings. If not provided, existing mappings are kept.
+    :param migration_type: Migration type ('full-load'|'cdc'|'full-load-and-cdc').
+        If not provided, existing type is kept.
+    :param replication_task_settings: Task settings dict. If not provided, existing settings are kept.
+    :param cdc_start_time: Start time for CDC.
+    :param cdc_start_position: Indicates when to start CDC (checkpoint or LSN/SCN format).
+        Mutually exclusive with cdc_start_time.
+    :param cdc_stop_position: Indicates when to stop CDC.
+    :param wait_for_completion: If True, wait for the modification to finish before returning.
+        In deferrable mode the operator defers rather than blocking. Defaults to True.
+    :param deferrable: Run the operator in deferrable mode. Defaults to False.
+    :param waiter_delay: Seconds between waiter polls (default: 30).
+    :param waiter_max_attempts: Maximum waiter poll attempts (default: 60).
+    :param aws_conn_id: The Airflow connection used for AWS credentials.
+        If this is ``None`` or empty then the default boto3 behaviour is used. If
+        running Airflow in a distributed manner and aws_conn_id is None or
+        empty, then default boto3 configuration would be used (and must be
+        maintained on each worker node).
+    :param region_name: AWS region_name. If not specified then the default boto3 behaviour is used.
+    :param verify: Whether or not to verify SSL certificates. See:
+        https://boto3.amazonaws.com/v1/documentation/api/latest/reference/core/session.html
+    :param botocore_config: Configuration dictionary (key-values) for botocore client. See:
+        https://botocore.amazonaws.com/v1/documentation/api/latest/reference/config.html
+    """
+
+    MODIFIABLE_STATES = frozenset({DmsTaskState.STOPPED, DmsTaskState.READY, DmsTaskState.FAILED})
+
+    aws_hook_class = DmsHook
+    template_fields: Sequence[str] = aws_template_fields(
+        "replication_task_arn",
+        "table_mappings",
+        "migration_type",
+        "replication_task_settings",
+        "cdc_start_time",
+        "cdc_start_position",
+        "cdc_stop_position",
+    )
+    template_fields_renderers: ClassVar[dict] = {
+        "table_mappings": "json",
+        "replication_task_settings": "json",
+    }
+
+    def __init__(
+        self,
+        *,
+        replication_task_arn: str,
+        table_mappings: dict | None = None,
+        migration_type: str | None = None,
+        replication_task_settings: dict | None = None,
+        cdc_start_time: datetime | None = None,
+        cdc_start_position: str | None = None,
+        cdc_stop_position: str | None = None,
+        wait_for_completion: bool = True,
+        deferrable: bool = conf.getboolean("operators", "default_deferrable", fallback=False),
+        waiter_delay: int = 30,
+        waiter_max_attempts: int = 60,
+        **kwargs,
+    ):
+        super().__init__(**kwargs)
+        if cdc_start_time and cdc_start_position:
+            raise ValueError("Only one of cdc_start_time or cdc_start_position can be provided.")
+        self.replication_task_arn = replication_task_arn
+        self.table_mappings = table_mappings
+        self.migration_type = migration_type
+        self.replication_task_settings = replication_task_settings
+        self.cdc_start_time = cdc_start_time
+        self.cdc_start_position = cdc_start_position
+        self.cdc_stop_position = cdc_stop_position
+        self.wait_for_completion = wait_for_completion
+        self.deferrable = deferrable
+        self.waiter_delay = waiter_delay
+        self.waiter_max_attempts = waiter_max_attempts
+
+    def execute(self, context: Context) -> dict:
+        tasks = self.hook.find_replication_tasks_by_arn(
+            replication_task_arn=self.replication_task_arn, without_settings=True
+        )
+        if not tasks:
+            raise ValueError(f"Replication task {self.replication_task_arn} not found.")
+
+        current_status = tasks[0].get("Status", "").lower()
+        self.log.info(
+            "Current status of replication task(%s) is '%s'.", self.replication_task_arn, current_status
+        )
+
+        if current_status == DmsTaskState.MODIFYING:
+            # boto3 stopped/ready waiters treat 'modifying' as a terminal failure — use poll loop.
+            self._wait_until_not_modifying()
+        elif current_status not in self.MODIFIABLE_STATES:
+            raise RuntimeError(
+                f"Replication task {self.replication_task_arn} is in state '{current_status}' "
+                f"and must be stopped before modification. "
+                f"Use DmsStopTaskOperator to stop it first."
+            )
+
+        result = self.hook.modify_replication_task(
+            replication_task_arn=self.replication_task_arn,
+            table_mappings=self.table_mappings,
+            migration_type=self.migration_type,
+            replication_task_settings=self.replication_task_settings,
+            cdc_start_time=self.cdc_start_time,
+            cdc_start_position=self.cdc_start_position,
+            cdc_stop_position=self.cdc_stop_position,
+        )
+        self.log.info("DMS replication task(%s) has been modified.", self.replication_task_arn)
+
+        if self.wait_for_completion:
+            if self.deferrable:
+                self.defer(
+                    trigger=DmsTaskModifyCompleteTrigger(
+                        replication_task_arn=self.replication_task_arn,
+                        waiter_delay=self.waiter_delay,
+                        waiter_max_attempts=self.waiter_max_attempts,
+                        aws_conn_id=self.aws_conn_id,
+                    ),
+                    method_name="execute_complete",
+                )
+            # modify_replication_task is async — poll until the task exits 'modifying'.
+            self._wait_until_not_modifying()
+
+        return result
+
+    def execute_complete(self, context: Context, event: dict | None = None) -> None:
+        validated_event = validate_execute_complete_event(event)
+        if validated_event["status"] != "success":
+            raise RuntimeError(f"Error waiting for DMS task modification to complete: {validated_event}")
+        self.log.info("DMS replication task(%s) modification complete.", self.replication_task_arn)
+
+    def _wait_until_not_modifying(self) -> None:
+        """
+        Poll until the task leaves the 'modifying' state.
+
+        boto3 waiters for replication_task_stopped and replication_task_ready both
+        treat 'modifying' as a terminal failure, so a polling loop is necessary.
+        """
+        for _ in range(self.waiter_max_attempts):
+            tasks = self.hook.find_replication_tasks_by_arn(
+                replication_task_arn=self.replication_task_arn, without_settings=True
+            )

Review Comment:
   Added — `_wait_until_not_modifying()` now raises `ValueError` if the task is not found during polling, consistent with the check in `execute()`.



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: commits-unsubscribe@airflow.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] Add `DmsModifyTaskOperator` [airflow]

Posted by "SameerMesiah97 (via GitHub)" <gi...@apache.org>.
SameerMesiah97 commented on code in PR #67524:
URL: https://github.com/apache/airflow/pull/67524#discussion_r3329203987


##########
providers/amazon/tests/system/amazon/aws/example_dms.py:
##########
@@ -374,6 +375,24 @@ def delete_security_group(security_group_id: str, security_group_name: str):
     )
     # [END howto_operator_dms_stop_task]
 
+    # [START howto_operator_dms_modify_task]
+    modify_task = DmsModifyTaskOperator(
+        task_id="modify_task",
+        replication_task_arn=task_arn,
+        table_mappings={
+            "rules": [
+                {
+                    "rule-type": "selection",
+                    "rule-id": "1",
+                    "rule-name": "1",
+                    "object-locator": {"schema-name": "%", "table-name": "%"},
+                    "rule-action": "include",
+                }
+            ]
+        },
+    )
+    # [END howto_operator_dms_modify_task]

Review Comment:
   I think it would be better to move this new task after `await_task_stop`. The operator requires the task to be in a modifiable state (`STOPPED` is one of them) before it is executed



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: commits-unsubscribe@airflow.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] Add `DmsModifyTaskOperator` [airflow]

Posted by "SameerMesiah97 (via GitHub)" <gi...@apache.org>.
SameerMesiah97 commented on code in PR #67524:
URL: https://github.com/apache/airflow/pull/67524#discussion_r3329218398


##########
providers/amazon/tests/unit/amazon/aws/operators/test_dms.py:
##########
@@ -180,6 +181,214 @@ def test_default_conn_passed_to_hook(self):
         assert op.hook.aws_conn_id == DEFAULT_CONN
 
 
+class TestDmsModifyTaskOperator:
+    TASK_ARN = "arn:aws:dms:us-east-1:123456789012:task:EXAMPLE"
+    TABLE_MAPPINGS = {
+        "rules": [
+            {
+                "rule-type": "selection",
+                "rule-id": "1",
+                "rule-name": "1",
+                "object-locator": {"schema-name": "myschema", "table-name": "mytable"},
+                "rule-action": "include",
+            }
+        ]
+    }
+
+    def _stopped_task(self):
+        return [{"ReplicationTaskArn": self.TASK_ARN, "Status": "stopped"}]
+
+    def _running_task(self):
+        return [{"ReplicationTaskArn": self.TASK_ARN, "Status": "running"}]
+
+    def _modifying_task(self):
+        return [{"ReplicationTaskArn": self.TASK_ARN, "Status": "modifying"}]
+
+    def test_init(self):
+        op = DmsModifyTaskOperator(
+            task_id="modify_task",
+            replication_task_arn=self.TASK_ARN,
+            table_mappings=self.TABLE_MAPPINGS,
+            migration_type="cdc",
+            aws_conn_id="fake-conn-id",
+            region_name="us-east-1",
+        )
+        assert op.replication_task_arn == self.TASK_ARN
+        assert op.table_mappings == self.TABLE_MAPPINGS
+        assert op.migration_type == "cdc"
+        assert op.wait_for_completion is True
+        assert op.deferrable is False
+        assert op.hook.aws_conn_id == "fake-conn-id"
+        assert op.hook._region_name == "us-east-1"
+
+    def test_init_defaults(self):
+        op = DmsModifyTaskOperator(task_id="modify_task", replication_task_arn=self.TASK_ARN)
+        assert op.table_mappings is None
+        assert op.migration_type is None
+        assert op.replication_task_settings is None
+        assert op.cdc_start_time is None
+        assert op.cdc_start_position is None
+        assert op.cdc_stop_position is None
+        assert op.wait_for_completion is True
+        assert op.deferrable is False
+
+    def test_init_raises_if_both_cdc_start_params_provided(self):
+        from datetime import datetime
+
+        with pytest.raises(ValueError, match="Only one of"):
+            DmsModifyTaskOperator(
+                task_id="modify_task",
+                replication_task_arn=self.TASK_ARN,
+                cdc_start_time=datetime(2024, 1, 1),
+                cdc_start_position="mysql-bin.000001:4",
+            )
+
+    @mock.patch.object(DmsHook, "find_replication_tasks_by_arn")
+    @mock.patch.object(DmsHook, "get_conn")
+    def test_modify_task_already_stopped(self, mock_conn, mock_find):
+        mock_find.return_value = self._stopped_task()
+        expected = {"ReplicationTaskArn": self.TASK_ARN}
+        with mock.patch.object(DmsHook, "modify_replication_task", return_value=expected) as mock_modify:
+            op = DmsModifyTaskOperator(
+                task_id="modify_task",
+                replication_task_arn=self.TASK_ARN,
+                table_mappings=self.TABLE_MAPPINGS,
+                wait_for_completion=False,
+            )
+            result = op.execute(None)
+
+            mock_modify.assert_called_once_with(
+                replication_task_arn=self.TASK_ARN,
+                table_mappings=self.TABLE_MAPPINGS,
+                migration_type=None,
+                replication_task_settings=None,
+                cdc_start_time=None,
+                cdc_start_position=None,
+                cdc_stop_position=None,
+            )
+            assert result == expected
+
+    @mock.patch.object(DmsHook, "find_replication_tasks_by_arn")
+    @mock.patch.object(DmsHook, "get_conn")
+    def test_modify_task_raises_if_running(self, mock_conn, mock_find):
+        mock_find.return_value = self._running_task()
+        op = DmsModifyTaskOperator(
+            task_id="modify_task",
+            replication_task_arn=self.TASK_ARN,
+        )
+        with pytest.raises(RuntimeError, match="must be stopped"):
+            op.execute(None)
+
+    @mock.patch.object(DmsHook, "find_replication_tasks_by_arn")
+    @mock.patch.object(DmsHook, "get_conn")
+    def test_modify_task_raises_if_not_found(self, mock_conn, mock_find):
+        mock_find.return_value = []
+        op = DmsModifyTaskOperator(task_id="modify_task", replication_task_arn=self.TASK_ARN)
+        with pytest.raises(ValueError, match="not found"):
+            op.execute(None)
+
+    @mock.patch.object(DmsHook, "find_replication_tasks_by_arn")
+    @mock.patch.object(DmsHook, "get_conn")
+    def test_modify_task_defers_for_completion(self, mock_conn, mock_find):
+        from airflow.exceptions import TaskDeferred
+        from airflow.providers.amazon.aws.triggers.dms import DmsTaskModifyCompleteTrigger
+
+        mock_find.return_value = self._stopped_task()
+        expected = {"ReplicationTaskArn": self.TASK_ARN}
+        with mock.patch.object(DmsHook, "modify_replication_task", return_value=expected):
+            op = DmsModifyTaskOperator(
+                task_id="modify_task",
+                replication_task_arn=self.TASK_ARN,
+                deferrable=True,
+                wait_for_completion=True,
+            )
+            with pytest.raises(TaskDeferred) as exc_info:
+                op.execute(None)
+
+        assert isinstance(exc_info.value.trigger, DmsTaskModifyCompleteTrigger)
+        assert exc_info.value.method_name == "execute_complete"
+
+    @mock.patch.object(DmsHook, "find_replication_tasks_by_arn")
+    @mock.patch.object(DmsHook, "get_conn")
+    def test_modify_task_with_all_params(self, mock_conn, mock_find):
+        from datetime import datetime

Review Comment:
   This too. Top of the file.



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: commits-unsubscribe@airflow.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] Add `DmsModifyTaskOperator` [airflow]

Posted by "AlejandroMorgante (via GitHub)" <gi...@apache.org>.
AlejandroMorgante commented on PR #67524:
URL: https://github.com/apache/airflow/pull/67524#issuecomment-4584546786

   Added `TestDmsTaskModifyCompleteTrigger` in `tests/unit/amazon/aws/triggers/test_dms.py` with tests for serialization, success, task not found (None), timeout, unexpected post-modify state, and exception. Also addressed the other inline comments in the latest push.


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: commits-unsubscribe@airflow.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] Add `DmsModifyTaskOperator` [airflow]

Posted by "AlejandroMorgante (via GitHub)" <gi...@apache.org>.
AlejandroMorgante commented on code in PR #67524:
URL: https://github.com/apache/airflow/pull/67524#discussion_r3329272005


##########
providers/amazon/src/airflow/providers/amazon/aws/operators/dms.py:
##########
@@ -118,6 +120,178 @@ def execute(self, context: Context):
         return task_arn
 
 
+class DmsModifyTaskOperator(AwsBaseOperator[DmsHook]):
+    """
+    Modifies an existing AWS DMS replication task.
+
+    The task must already be stopped before modification. Use :class:`DmsStopTaskOperator`
+    upstream in the Dag to stop it, and :class:`DmsStartTaskOperator` downstream to restart
+    it afterwards if needed.
+
+    .. seealso::
+        For more information on how to use this operator, take a look at the guide:
+        :ref:`howto/operator:DmsModifyTaskOperator`
+
+    :param replication_task_arn: Replication task ARN
+    :param table_mappings: New table mappings. If not provided, existing mappings are kept.
+    :param migration_type: Migration type ('full-load'|'cdc'|'full-load-and-cdc').
+        If not provided, existing type is kept.
+    :param replication_task_settings: Task settings dict. If not provided, existing settings are kept.
+    :param cdc_start_time: Start time for CDC.
+    :param cdc_start_position: Indicates when to start CDC (checkpoint or LSN/SCN format).
+        Mutually exclusive with cdc_start_time.
+    :param cdc_stop_position: Indicates when to stop CDC.
+    :param wait_for_completion: If True, wait for the modification to finish before returning.
+        In deferrable mode the operator defers rather than blocking. Defaults to True.
+    :param deferrable: Run the operator in deferrable mode. Defaults to False.
+    :param waiter_delay: Seconds between waiter polls (default: 30).
+    :param waiter_max_attempts: Maximum waiter poll attempts (default: 60).
+    :param aws_conn_id: The Airflow connection used for AWS credentials.
+        If this is ``None`` or empty then the default boto3 behaviour is used. If
+        running Airflow in a distributed manner and aws_conn_id is None or
+        empty, then default boto3 configuration would be used (and must be
+        maintained on each worker node).
+    :param region_name: AWS region_name. If not specified then the default boto3 behaviour is used.
+    :param verify: Whether or not to verify SSL certificates. See:
+        https://boto3.amazonaws.com/v1/documentation/api/latest/reference/core/session.html
+    :param botocore_config: Configuration dictionary (key-values) for botocore client. See:
+        https://botocore.amazonaws.com/v1/documentation/api/latest/reference/config.html
+    """
+
+    MODIFIABLE_STATES = frozenset({DmsTaskState.STOPPED, DmsTaskState.READY, DmsTaskState.FAILED})
+
+    aws_hook_class = DmsHook
+    template_fields: Sequence[str] = aws_template_fields(
+        "replication_task_arn",
+        "table_mappings",
+        "migration_type",
+        "replication_task_settings",
+        "cdc_start_time",
+        "cdc_start_position",
+        "cdc_stop_position",
+    )
+    template_fields_renderers: ClassVar[dict] = {
+        "table_mappings": "json",
+        "replication_task_settings": "json",
+    }
+
+    def __init__(
+        self,
+        *,
+        replication_task_arn: str,
+        table_mappings: dict | None = None,
+        migration_type: str | None = None,
+        replication_task_settings: dict | None = None,
+        cdc_start_time: datetime | None = None,
+        cdc_start_position: str | None = None,
+        cdc_stop_position: str | None = None,
+        wait_for_completion: bool = True,
+        deferrable: bool = conf.getboolean("operators", "default_deferrable", fallback=False),
+        waiter_delay: int = 30,
+        waiter_max_attempts: int = 60,
+        **kwargs,
+    ):
+        super().__init__(**kwargs)
+        if cdc_start_time and cdc_start_position:
+            raise ValueError("Only one of cdc_start_time or cdc_start_position can be provided.")
+        self.replication_task_arn = replication_task_arn
+        self.table_mappings = table_mappings
+        self.migration_type = migration_type
+        self.replication_task_settings = replication_task_settings
+        self.cdc_start_time = cdc_start_time
+        self.cdc_start_position = cdc_start_position
+        self.cdc_stop_position = cdc_stop_position
+        self.wait_for_completion = wait_for_completion
+        self.deferrable = deferrable
+        self.waiter_delay = waiter_delay
+        self.waiter_max_attempts = waiter_max_attempts
+
+    def execute(self, context: Context) -> dict:
+        tasks = self.hook.find_replication_tasks_by_arn(
+            replication_task_arn=self.replication_task_arn, without_settings=True
+        )
+        if not tasks:
+            raise ValueError(f"Replication task {self.replication_task_arn} not found.")
+
+        current_status = tasks[0].get("Status", "").lower()
+        self.log.info(
+            "Current status of replication task(%s) is '%s'.", self.replication_task_arn, current_status
+        )
+
+        if current_status == DmsTaskState.MODIFYING:
+            # boto3 stopped/ready waiters treat 'modifying' as a terminal failure — use poll loop.
+            self._wait_until_not_modifying()
+        elif current_status not in self.MODIFIABLE_STATES:
+            raise RuntimeError(
+                f"Replication task {self.replication_task_arn} is in state '{current_status}' "
+                f"and must be stopped before modification. "
+                f"Use DmsStopTaskOperator to stop it first."
+            )
+
+        result = self.hook.modify_replication_task(
+            replication_task_arn=self.replication_task_arn,
+            table_mappings=self.table_mappings,
+            migration_type=self.migration_type,
+            replication_task_settings=self.replication_task_settings,
+            cdc_start_time=self.cdc_start_time,
+            cdc_start_position=self.cdc_start_position,
+            cdc_stop_position=self.cdc_stop_position,
+        )
+        self.log.info("DMS replication task(%s) has been modified.", self.replication_task_arn)
+
+        if self.wait_for_completion:
+            if self.deferrable:
+                self.defer(
+                    trigger=DmsTaskModifyCompleteTrigger(
+                        replication_task_arn=self.replication_task_arn,
+                        waiter_delay=self.waiter_delay,
+                        waiter_max_attempts=self.waiter_max_attempts,
+                        aws_conn_id=self.aws_conn_id,
+                    ),
+                    method_name="execute_complete",
+                )

Review Comment:
   Done.



##########
providers/amazon/src/airflow/providers/amazon/aws/operators/dms.py:
##########
@@ -118,6 +120,178 @@ def execute(self, context: Context):
         return task_arn
 
 
+class DmsModifyTaskOperator(AwsBaseOperator[DmsHook]):
+    """
+    Modifies an existing AWS DMS replication task.
+
+    The task must already be stopped before modification. Use :class:`DmsStopTaskOperator`
+    upstream in the Dag to stop it, and :class:`DmsStartTaskOperator` downstream to restart
+    it afterwards if needed.
+
+    .. seealso::
+        For more information on how to use this operator, take a look at the guide:
+        :ref:`howto/operator:DmsModifyTaskOperator`
+
+    :param replication_task_arn: Replication task ARN
+    :param table_mappings: New table mappings. If not provided, existing mappings are kept.
+    :param migration_type: Migration type ('full-load'|'cdc'|'full-load-and-cdc').
+        If not provided, existing type is kept.
+    :param replication_task_settings: Task settings dict. If not provided, existing settings are kept.
+    :param cdc_start_time: Start time for CDC.
+    :param cdc_start_position: Indicates when to start CDC (checkpoint or LSN/SCN format).
+        Mutually exclusive with cdc_start_time.
+    :param cdc_stop_position: Indicates when to stop CDC.
+    :param wait_for_completion: If True, wait for the modification to finish before returning.
+        In deferrable mode the operator defers rather than blocking. Defaults to True.
+    :param deferrable: Run the operator in deferrable mode. Defaults to False.
+    :param waiter_delay: Seconds between waiter polls (default: 30).
+    :param waiter_max_attempts: Maximum waiter poll attempts (default: 60).
+    :param aws_conn_id: The Airflow connection used for AWS credentials.
+        If this is ``None`` or empty then the default boto3 behaviour is used. If
+        running Airflow in a distributed manner and aws_conn_id is None or
+        empty, then default boto3 configuration would be used (and must be
+        maintained on each worker node).
+    :param region_name: AWS region_name. If not specified then the default boto3 behaviour is used.
+    :param verify: Whether or not to verify SSL certificates. See:
+        https://boto3.amazonaws.com/v1/documentation/api/latest/reference/core/session.html
+    :param botocore_config: Configuration dictionary (key-values) for botocore client. See:
+        https://botocore.amazonaws.com/v1/documentation/api/latest/reference/config.html
+    """
+
+    MODIFIABLE_STATES = frozenset({DmsTaskState.STOPPED, DmsTaskState.READY, DmsTaskState.FAILED})
+
+    aws_hook_class = DmsHook
+    template_fields: Sequence[str] = aws_template_fields(
+        "replication_task_arn",
+        "table_mappings",
+        "migration_type",
+        "replication_task_settings",
+        "cdc_start_time",
+        "cdc_start_position",
+        "cdc_stop_position",
+    )
+    template_fields_renderers: ClassVar[dict] = {
+        "table_mappings": "json",
+        "replication_task_settings": "json",
+    }
+
+    def __init__(
+        self,
+        *,
+        replication_task_arn: str,
+        table_mappings: dict | None = None,
+        migration_type: str | None = None,
+        replication_task_settings: dict | None = None,
+        cdc_start_time: datetime | None = None,
+        cdc_start_position: str | None = None,
+        cdc_stop_position: str | None = None,
+        wait_for_completion: bool = True,
+        deferrable: bool = conf.getboolean("operators", "default_deferrable", fallback=False),
+        waiter_delay: int = 30,
+        waiter_max_attempts: int = 60,
+        **kwargs,
+    ):
+        super().__init__(**kwargs)
+        if cdc_start_time and cdc_start_position:
+            raise ValueError("Only one of cdc_start_time or cdc_start_position can be provided.")
+        self.replication_task_arn = replication_task_arn
+        self.table_mappings = table_mappings
+        self.migration_type = migration_type
+        self.replication_task_settings = replication_task_settings
+        self.cdc_start_time = cdc_start_time
+        self.cdc_start_position = cdc_start_position
+        self.cdc_stop_position = cdc_stop_position
+        self.wait_for_completion = wait_for_completion
+        self.deferrable = deferrable
+        self.waiter_delay = waiter_delay
+        self.waiter_max_attempts = waiter_max_attempts
+
+    def execute(self, context: Context) -> dict:
+        tasks = self.hook.find_replication_tasks_by_arn(
+            replication_task_arn=self.replication_task_arn, without_settings=True
+        )
+        if not tasks:
+            raise ValueError(f"Replication task {self.replication_task_arn} not found.")
+
+        current_status = tasks[0].get("Status", "").lower()
+        self.log.info(
+            "Current status of replication task(%s) is '%s'.", self.replication_task_arn, current_status
+        )
+
+        if current_status == DmsTaskState.MODIFYING:
+            # boto3 stopped/ready waiters treat 'modifying' as a terminal failure — use poll loop.
+            self._wait_until_not_modifying()
+        elif current_status not in self.MODIFIABLE_STATES:
+            raise RuntimeError(
+                f"Replication task {self.replication_task_arn} is in state '{current_status}' "
+                f"and must be stopped before modification. "
+                f"Use DmsStopTaskOperator to stop it first."
+            )
+
+        result = self.hook.modify_replication_task(
+            replication_task_arn=self.replication_task_arn,
+            table_mappings=self.table_mappings,
+            migration_type=self.migration_type,
+            replication_task_settings=self.replication_task_settings,
+            cdc_start_time=self.cdc_start_time,
+            cdc_start_position=self.cdc_start_position,
+            cdc_stop_position=self.cdc_stop_position,
+        )
+        self.log.info("DMS replication task(%s) has been modified.", self.replication_task_arn)
+
+        if self.wait_for_completion:
+            if self.deferrable:
+                self.defer(
+                    trigger=DmsTaskModifyCompleteTrigger(
+                        replication_task_arn=self.replication_task_arn,
+                        waiter_delay=self.waiter_delay,
+                        waiter_max_attempts=self.waiter_max_attempts,
+                        aws_conn_id=self.aws_conn_id,
+                    ),
+                    method_name="execute_complete",
+                )
+            # modify_replication_task is async — poll until the task exits 'modifying'.
+            self._wait_until_not_modifying()
+
+        return result
+
+    def execute_complete(self, context: Context, event: dict | None = None) -> None:
+        validated_event = validate_execute_complete_event(event)
+        if validated_event["status"] != "success":
+            raise RuntimeError(f"Error waiting for DMS task modification to complete: {validated_event}")
+        self.log.info("DMS replication task(%s) modification complete.", self.replication_task_arn)

Review Comment:
   Fixed — `result` from `modify_replication_task` is now passed via `defer(kwargs={"result": result})` so `execute_complete()` returns the same object as the sync path.



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: commits-unsubscribe@airflow.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] Add `DmsModifyTaskOperator` [airflow]

Posted by "AlejandroMorgante (via GitHub)" <gi...@apache.org>.
AlejandroMorgante commented on code in PR #67524:
URL: https://github.com/apache/airflow/pull/67524#discussion_r3329424530


##########
providers/amazon/src/airflow/providers/amazon/aws/triggers/dms.py:
##########
@@ -219,3 +222,79 @@ def hook(self) -> AwsGenericHook:
             verify=self.verify,
             config=self.botocore_config,
         )
+
+
+class DmsTaskModifyCompleteTrigger(BaseTrigger):
+    """
+    Trigger that polls until a DMS classic replication task exits the ``modifying`` state.
+
+    The boto3 ``replication_task_stopped`` waiter treats ``modifying`` as a terminal failure,
+    so a custom polling loop is required here.
+
+    :param replication_task_arn: The ARN of the replication task.
+    :param waiter_delay: Seconds between polls.
+    :param waiter_max_attempts: Maximum number of poll attempts before giving up.
+    :param aws_conn_id: The Airflow connection used for AWS credentials.
+    :param verify: Whether or not to verify SSL certificates.
+    :param botocore_config: Configuration dictionary (key-values) for botocore client.
+    """
+
+    def __init__(
+        self,
+        replication_task_arn: str,
+        waiter_delay: int = 30,
+        waiter_max_attempts: int = 60,
+        aws_conn_id: str | None = "aws_default",
+        verify: bool | str | None = None,
+        botocore_config: dict | None = None,
+    ) -> None:
+        super().__init__()
+        self.replication_task_arn = replication_task_arn
+        self.waiter_delay = waiter_delay
+        self.waiter_max_attempts = waiter_max_attempts
+        self.aws_conn_id = aws_conn_id
+        self.verify = verify
+        self.botocore_config = botocore_config
+
+    def serialize(self) -> tuple[str, dict]:
+        return (
+            "airflow.providers.amazon.aws.triggers.dms.DmsTaskModifyCompleteTrigger",
+            {
+                "replication_task_arn": self.replication_task_arn,
+                "waiter_delay": self.waiter_delay,
+                "waiter_max_attempts": self.waiter_max_attempts,
+                "aws_conn_id": self.aws_conn_id,
+                "verify": self.verify,
+                "botocore_config": self.botocore_config,
+            },
+        )
+
+    async def run(self) -> AsyncIterator[TriggerEvent]:
+        hook = DmsHook(aws_conn_id=self.aws_conn_id, verify=self.verify, config=self.botocore_config)
+        try:
+            for _ in range(self.waiter_max_attempts):
+                status = await hook.get_task_status_async(self.replication_task_arn)
+                if status != "modifying":

Review Comment:
   Done — using `DmsTaskState.MODIFYING` now.
   
   On the state handling: the trigger checks `status is None` (task not found → error), then validates the final state against `DMS_MODIFIABLE_STATES` (stopped, ready, failed → success; anything else → error with the unexpected state in the message). Timeout and exceptions each yield their own error events.



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: commits-unsubscribe@airflow.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] Add `DmsModifyTaskOperator` [airflow]

Posted by "SameerMesiah97 (via GitHub)" <gi...@apache.org>.
SameerMesiah97 commented on code in PR #67524:
URL: https://github.com/apache/airflow/pull/67524#discussion_r3329136328


##########
providers/amazon/src/airflow/providers/amazon/aws/operators/dms.py:
##########
@@ -118,6 +121,274 @@ def execute(self, context: Context):
         return task_arn
 
 
+class DmsModifyTaskOperator(AwsBaseOperator[DmsHook]):
+    """
+    Modifies an existing AWS DMS replication task.
+
+    If the task is not already stopped, set ``stop_task_before=True`` to stop it first.
+    To restart the task after modification, set ``restart_task_after=True``.
+
+    .. seealso::
+        For more information on how to use this operator, take a look at the guide:
+        :ref:`howto/operator:DmsModifyTaskOperator`
+
+    :param replication_task_arn: Replication task ARN
+    :param table_mappings: New table mappings. If not provided, existing mappings are kept.
+    :param migration_type: Migration type ('full-load'|'cdc'|'full-load-and-cdc').
+        If not provided, existing type is kept.
+    :param replication_task_settings: Task settings dict. If not provided, existing settings are kept.
+    :param cdc_start_time: Start time for CDC.
+    :param cdc_start_position: Indicates when to start CDC (checkpoint or LSN/SCN format).
+        Mutually exclusive with cdc_start_time.
+    :param cdc_stop_position: Indicates when to stop CDC.
+    :param stop_task_before: If True, stop the task before modifying if it is not already stopped.
+    :param restart_task_after: If True, restart the task after modifying.
+    :param start_replication_task_type: Start type used when restarting the task.
+        One of 'start-replication', 'resume-processing', or 'reload-target'.
+        Defaults to 'resume-processing'. Only used when ``restart_task_after=True``.
+    :param wait_for_completion: Only applies when the task is already in ``modifying`` state
+        when ``execute()`` is called. If True, wait for the modification to finish before
+        proceeding. If False, raises immediately instead of waiting.
+    :param deferrable: Run the operator in deferrable mode.
+    :param waiter_delay: Seconds between waiter polls (default: 30).
+    :param waiter_max_attempts: Maximum waiter poll attempts (default: 60).
+    :param aws_conn_id: The Airflow connection used for AWS credentials.
+        If this is ``None`` or empty then the default boto3 behaviour is used. If
+        running Airflow in a distributed manner and aws_conn_id is None or
+        empty, then default boto3 configuration would be used (and must be
+        maintained on each worker node).
+    :param region_name: AWS region_name. If not specified then the default boto3 behaviour is used.
+    :param verify: Whether or not to verify SSL certificates. See:
+        https://boto3.amazonaws.com/v1/documentation/api/latest/reference/core/session.html
+    :param botocore_config: Configuration dictionary (key-values) for botocore client. See:
+        https://botocore.amazonaws.com/v1/documentation/api/latest/reference/config.html
+    """
+
+    STOPPED_STATES = ("stopped", "ready", "failed", "created")
+    TERMINAL_STATES = frozenset({"failed", "stopped", "ready", "created", "deleting"})
+
+    aws_hook_class = DmsHook
+    template_fields: Sequence[str] = aws_template_fields(
+        "replication_task_arn",
+        "table_mappings",
+        "migration_type",
+        "replication_task_settings",
+        "cdc_start_time",
+        "cdc_start_position",
+        "cdc_stop_position",
+        "start_replication_task_type",
+    )
+    template_fields_renderers: ClassVar[dict] = {
+        "table_mappings": "json",
+        "replication_task_settings": "json",
+    }
+
+    def __init__(
+        self,
+        *,
+        replication_task_arn: str,
+        table_mappings: dict | None = None,
+        migration_type: str | None = None,
+        replication_task_settings: dict | None = None,
+        cdc_start_time: datetime | None = None,
+        cdc_start_position: str | None = None,
+        cdc_stop_position: str | None = None,
+        stop_task_before: bool = False,
+        restart_task_after: bool = False,
+        start_replication_task_type: str = "resume-processing",
+        wait_for_completion: bool = True,
+        deferrable: bool = conf.getboolean("operators", "default_deferrable", fallback=False),
+        waiter_delay: int = 30,
+        waiter_max_attempts: int = 60,
+        **kwargs,
+    ):
+        super().__init__(**kwargs)
+        if cdc_start_time and cdc_start_position:
+            raise ValueError("Only one of cdc_start_time or cdc_start_position can be provided.")
+        self.replication_task_arn = replication_task_arn
+        self.table_mappings = table_mappings
+        self.migration_type = migration_type
+        self.replication_task_settings = replication_task_settings
+        self.cdc_start_time = cdc_start_time
+        self.cdc_start_position = cdc_start_position
+        self.cdc_stop_position = cdc_stop_position
+        self.stop_task_before = stop_task_before
+        self.restart_task_after = restart_task_after
+        self.start_replication_task_type = start_replication_task_type
+        self.wait_for_completion = wait_for_completion
+        self.deferrable = deferrable
+        self.waiter_delay = waiter_delay
+        self.waiter_max_attempts = waiter_max_attempts
+
+    def execute(self, context: Context) -> dict:
+        tasks = self.hook.find_replication_tasks_by_arn(
+            replication_task_arn=self.replication_task_arn, without_settings=True
+        )
+        if not tasks:
+            raise AirflowException(f"Replication task {self.replication_task_arn} not found.")
+
+        current_status = tasks[0].get("Status", "").lower()
+        self.log.info(
+            "Current status of replication task(%s) is '%s'.", self.replication_task_arn, current_status
+        )
+
+        if current_status == "modifying":
+            # boto3 stopped/ready waiters treat 'modifying' as a terminal failure — use poll loop.
+            if not self.wait_for_completion:
+                raise AirflowException(
+                    f"Replication task {self.replication_task_arn} is already being modified. "
+                    f"Set wait_for_completion=True to wait for it to finish."
+                )
+            self._wait_until_not_modifying()
+        elif current_status not in self.STOPPED_STATES:
+            if not self.stop_task_before:
+                raise AirflowException(
+                    f"Replication task {self.replication_task_arn} is in state '{current_status}' "
+                    f"and must be stopped before modification. Set stop_task_before=True to stop it "
+                    f"automatically, or stop the task first."
+                )
+            if current_status == "starting":
+                # DMS rejects StopReplicationTask while the task is still starting up.
+                self.log.info(
+                    "Replication task(%s) is starting, waiting for it to reach 'running'.",
+                    self.replication_task_arn,
+                )
+                self._wait_for_status("running")
+            self.log.info("Stopping replication task(%s).", self.replication_task_arn)
+            self.hook.stop_replication_task(replication_task_arn=self.replication_task_arn)
+            self.log.info("Waiting for replication task(%s) to stop.", self.replication_task_arn)
+            if self.deferrable:

Review Comment:
   > Yes, the modify phase itself is short (~1-2 min in practice, as we confirmed against real AWS). You're right that stopping a running task is where the wait can get significant, but that's now on DmsStopTaskOperator rather than here.
   > 
   > The deferrable option is kept as opt-in (default is False), so it doesn't change behaviour for anyone not asking for it. Happy to drop it if the preference is to keep the operator minimal.
   
   After looking at the new streamlined operator, I think deferrable mode is more defensible. I would not strictly classify it as a long-running task but the value-to-maintainability ratio is now favourable enough and it is opt-in as you said so I must concede to you. Thanks for pushing back. 



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: commits-unsubscribe@airflow.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] Add `DmsModifyTaskOperator` [airflow]

Posted by "boring-cyborg[bot] (via GitHub)" <gi...@apache.org>.
boring-cyborg[bot] commented on PR #67524:
URL: https://github.com/apache/airflow/pull/67524#issuecomment-4614768939

   Awesome work, congrats on your first merged pull request! You are invited to check our [Issue Tracker](https://github.com/apache/airflow/issues) for additional contributions.
   


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: commits-unsubscribe@airflow.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] Add DmsModifyTaskOperator [airflow]

Posted by "AlejandroMorgante (via GitHub)" <gi...@apache.org>.
AlejandroMorgante commented on PR #67524:
URL: https://github.com/apache/airflow/pull/67524#issuecomment-4559822153

   @SameerMesiah97 you're right, and I appreciate the clear feedback. Simplified the operator significantly — removed `stop_task_before`, `restart_task_after`, `start_replication_task_type`, the multi-stage deferral chain, and `_wait_for_status`. It now just calls `ModifyReplicationTask` and optionally waits for the task to exit `modifying`. Stop/restart is the caller's responsibility via the existing operators.
   
   Addressed your other inline comments in the same pass.
   
   ---
   Drafted-by: Claude Code (claude-sonnet-4-6); reviewed by @AlejandroMorgante before posting


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: commits-unsubscribe@airflow.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] Add `DmsModifyTaskOperator` [airflow]

Posted by "AlejandroMorgante (via GitHub)" <gi...@apache.org>.
AlejandroMorgante commented on code in PR #67524:
URL: https://github.com/apache/airflow/pull/67524#discussion_r3345124708


##########
providers/amazon/src/airflow/providers/amazon/aws/operators/dms.py:
##########
@@ -118,6 +120,192 @@ def execute(self, context: Context):
         return task_arn
 
 
+class DmsModifyTaskOperator(AwsBaseOperator[DmsHook]):
+    """
+    Modifies an existing AWS DMS replication task.
+
+    The task must already be stopped before modification. Use :class:`DmsStopTaskOperator`
+    upstream in the Dag to stop it, and :class:`DmsStartTaskOperator` downstream to restart
+    it afterwards if needed.
+
+    .. seealso::
+        For more information on how to use this operator, take a look at the guide:
+        :ref:`howto/operator:DmsModifyTaskOperator`
+
+    :param replication_task_arn: Replication task ARN
+    :param table_mappings: New table mappings. If not provided, existing mappings are kept.
+    :param migration_type: Migration type ('full-load'|'cdc'|'full-load-and-cdc').
+        If not provided, existing type is kept.
+    :param replication_task_settings: Task settings dict. If not provided, existing settings are kept.
+    :param cdc_start_time: Start time for CDC.
+    :param cdc_start_position: Indicates when to start CDC (checkpoint or LSN/SCN format).
+        Mutually exclusive with cdc_start_time.
+    :param cdc_stop_position: Indicates when to stop CDC.
+    :param wait_for_completion: If True, wait for the modification to finish before returning.
+        In deferrable mode the operator defers rather than blocking. Defaults to True.
+    :param deferrable: Run the operator in deferrable mode. Defaults to False.
+    :param waiter_delay: Seconds between waiter polls (default: 30).
+    :param waiter_max_attempts: Maximum waiter poll attempts (default: 60).
+    :param aws_conn_id: The Airflow connection used for AWS credentials.
+        If this is ``None`` or empty then the default boto3 behaviour is used. If
+        running Airflow in a distributed manner and aws_conn_id is None or
+        empty, then default boto3 configuration would be used (and must be
+        maintained on each worker node).
+    :param region_name: AWS region_name. If not specified then the default boto3 behaviour is used.
+    :param verify: Whether or not to verify SSL certificates. See:
+        https://boto3.amazonaws.com/v1/documentation/api/latest/reference/core/session.html
+    :param botocore_config: Configuration dictionary (key-values) for botocore client. See:
+        https://botocore.amazonaws.com/v1/documentation/api/latest/reference/config.html
+    """
+
+    MODIFIABLE_STATES = DMS_MODIFIABLE_STATES
+
+    aws_hook_class = DmsHook
+    template_fields: Sequence[str] = aws_template_fields(
+        "replication_task_arn",
+        "table_mappings",
+        "migration_type",
+        "replication_task_settings",
+        "cdc_start_time",
+        "cdc_start_position",
+        "cdc_stop_position",
+    )
+    template_fields_renderers: ClassVar[dict] = {
+        "table_mappings": "json",
+        "replication_task_settings": "json",
+    }
+
+    def __init__(
+        self,
+        *,
+        replication_task_arn: str,
+        table_mappings: dict | None = None,
+        migration_type: str | None = None,
+        replication_task_settings: dict | None = None,
+        cdc_start_time: datetime | None = None,
+        cdc_start_position: str | None = None,
+        cdc_stop_position: str | None = None,
+        wait_for_completion: bool = True,
+        deferrable: bool = conf.getboolean("operators", "default_deferrable", fallback=False),
+        waiter_delay: int = 30,
+        waiter_max_attempts: int = 60,
+        aws_conn_id: str | None = "aws_default",
+        **kwargs,
+    ):
+        super().__init__(aws_conn_id=aws_conn_id, **kwargs)
+        if cdc_start_time and cdc_start_position:
+            raise ValueError("Only one of cdc_start_time or cdc_start_position can be provided.")
+        self.replication_task_arn = replication_task_arn
+        self.table_mappings = table_mappings
+        self.migration_type = migration_type
+        self.replication_task_settings = replication_task_settings
+        self.cdc_start_time = cdc_start_time
+        self.cdc_start_position = cdc_start_position
+        self.cdc_stop_position = cdc_stop_position
+        self.wait_for_completion = wait_for_completion
+        self.deferrable = deferrable
+        self.waiter_delay = waiter_delay
+        self.waiter_max_attempts = waiter_max_attempts
+
+    def execute(self, context: Context) -> dict:
+        tasks = self.hook.find_replication_tasks_by_arn(
+            replication_task_arn=self.replication_task_arn, without_settings=True
+        )
+        if not tasks:
+            raise ValueError(f"Replication task {self.replication_task_arn} not found.")
+
+        current_status = tasks[0].get("Status", "").lower()
+        self.log.info(
+            "Current status of replication task(%s) is '%s'.", self.replication_task_arn, current_status
+        )
+
+        if current_status == DmsTaskState.MODIFYING:
+            # boto3 stopped/ready waiters treat 'modifying' as a terminal failure — use poll loop.
+            current_status = self._wait_until_not_modifying()
+
+        if current_status not in self.MODIFIABLE_STATES:
+            raise RuntimeError(
+                f"Replication task {self.replication_task_arn} is in state '{current_status}' "
+                f"and must be in a modifiable state (stopped, ready, or failed) before modification. "
+                f"Use DmsStopTaskOperator to stop it first."
+            )
+
+        result = self.hook.modify_replication_task(
+            replication_task_arn=self.replication_task_arn,
+            table_mappings=self.table_mappings,
+            migration_type=self.migration_type,
+            replication_task_settings=self.replication_task_settings,
+            cdc_start_time=self.cdc_start_time,
+            cdc_start_position=self.cdc_start_position,
+            cdc_stop_position=self.cdc_stop_position,
+        )
+        self.log.info("DMS replication task(%s) has been modified.", self.replication_task_arn)
+
+        if self.wait_for_completion:
+            if self.deferrable:
+                self.defer(
+                    trigger=DmsTaskModifyCompleteTrigger(
+                        replication_task_arn=self.replication_task_arn,
+                        waiter_delay=self.waiter_delay,
+                        waiter_max_attempts=self.waiter_max_attempts,
+                        aws_conn_id=self.aws_conn_id,
+                    ),
+                    method_name="execute_complete",
+                    kwargs={"result": result},
+                )
+            else:
+                # modify_replication_task is async — poll until the task exits 'modifying'.
+                final_status = self._wait_until_not_modifying()
+                if final_status not in self.MODIFIABLE_STATES:
+                    raise RuntimeError(
+                        f"Replication task {self.replication_task_arn} ended in unexpected state "
+                        f"'{final_status}' after modification."
+                    )
+
+        return result
+
+    def execute_complete(
+        self, context: Context, event: dict | None = None, result: dict | None = None
+    ) -> dict:
+        validated_event = validate_execute_complete_event(event)
+        if validated_event["status"] != "success":
+            raise RuntimeError(f"Error waiting for DMS task modification to complete: {validated_event}")
+        self.log.info("DMS replication task(%s) modification complete.", self.replication_task_arn)
+        return result or {}
+
+    def _wait_until_not_modifying(self) -> str:

Review Comment:
   Thanks, I updated this in the latest revision by adding a custom `replication_task_modified` waiter under `providers/amazon/src/airflow/providers/amazon/aws/waiters/dms.json`, and the operator/trigger now use it through `AwsBaseWaiterTrigger` and `get_waiter(...)`.
   
   This avoids the built-in DMS waiter behavior that treats `modifying` as terminal failure, while keeping the flow on the standard waiter path



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: commits-unsubscribe@airflow.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] Add `DmsModifyTaskOperator` [airflow]

Posted by "AlejandroMorgante (via GitHub)" <gi...@apache.org>.
AlejandroMorgante commented on code in PR #67524:
URL: https://github.com/apache/airflow/pull/67524#discussion_r3329300925


##########
providers/amazon/tests/unit/amazon/aws/operators/test_dms.py:
##########
@@ -180,6 +181,214 @@ def test_default_conn_passed_to_hook(self):
         assert op.hook.aws_conn_id == DEFAULT_CONN
 
 
+class TestDmsModifyTaskOperator:
+    TASK_ARN = "arn:aws:dms:us-east-1:123456789012:task:EXAMPLE"
+    TABLE_MAPPINGS = {
+        "rules": [
+            {
+                "rule-type": "selection",
+                "rule-id": "1",
+                "rule-name": "1",
+                "object-locator": {"schema-name": "myschema", "table-name": "mytable"},
+                "rule-action": "include",
+            }
+        ]
+    }
+
+    def _stopped_task(self):
+        return [{"ReplicationTaskArn": self.TASK_ARN, "Status": "stopped"}]
+
+    def _running_task(self):
+        return [{"ReplicationTaskArn": self.TASK_ARN, "Status": "running"}]
+
+    def _modifying_task(self):
+        return [{"ReplicationTaskArn": self.TASK_ARN, "Status": "modifying"}]
+
+    def test_init(self):
+        op = DmsModifyTaskOperator(
+            task_id="modify_task",
+            replication_task_arn=self.TASK_ARN,
+            table_mappings=self.TABLE_MAPPINGS,
+            migration_type="cdc",
+            aws_conn_id="fake-conn-id",
+            region_name="us-east-1",
+        )
+        assert op.replication_task_arn == self.TASK_ARN
+        assert op.table_mappings == self.TABLE_MAPPINGS
+        assert op.migration_type == "cdc"
+        assert op.wait_for_completion is True
+        assert op.deferrable is False
+        assert op.hook.aws_conn_id == "fake-conn-id"
+        assert op.hook._region_name == "us-east-1"
+
+    def test_init_defaults(self):
+        op = DmsModifyTaskOperator(task_id="modify_task", replication_task_arn=self.TASK_ARN)
+        assert op.table_mappings is None
+        assert op.migration_type is None
+        assert op.replication_task_settings is None
+        assert op.cdc_start_time is None
+        assert op.cdc_start_position is None
+        assert op.cdc_stop_position is None
+        assert op.wait_for_completion is True
+        assert op.deferrable is False
+
+    def test_init_raises_if_both_cdc_start_params_provided(self):
+        from datetime import datetime
+
+        with pytest.raises(ValueError, match="Only one of"):
+            DmsModifyTaskOperator(
+                task_id="modify_task",
+                replication_task_arn=self.TASK_ARN,
+                cdc_start_time=datetime(2024, 1, 1),
+                cdc_start_position="mysql-bin.000001:4",
+            )
+
+    @mock.patch.object(DmsHook, "find_replication_tasks_by_arn")
+    @mock.patch.object(DmsHook, "get_conn")
+    def test_modify_task_already_stopped(self, mock_conn, mock_find):
+        mock_find.return_value = self._stopped_task()
+        expected = {"ReplicationTaskArn": self.TASK_ARN}
+        with mock.patch.object(DmsHook, "modify_replication_task", return_value=expected) as mock_modify:
+            op = DmsModifyTaskOperator(
+                task_id="modify_task",
+                replication_task_arn=self.TASK_ARN,
+                table_mappings=self.TABLE_MAPPINGS,
+                wait_for_completion=False,
+            )
+            result = op.execute(None)
+
+            mock_modify.assert_called_once_with(
+                replication_task_arn=self.TASK_ARN,
+                table_mappings=self.TABLE_MAPPINGS,
+                migration_type=None,
+                replication_task_settings=None,
+                cdc_start_time=None,
+                cdc_start_position=None,
+                cdc_stop_position=None,
+            )
+            assert result == expected
+
+    @mock.patch.object(DmsHook, "find_replication_tasks_by_arn")
+    @mock.patch.object(DmsHook, "get_conn")
+    def test_modify_task_raises_if_running(self, mock_conn, mock_find):
+        mock_find.return_value = self._running_task()
+        op = DmsModifyTaskOperator(
+            task_id="modify_task",
+            replication_task_arn=self.TASK_ARN,
+        )
+        with pytest.raises(RuntimeError, match="must be stopped"):
+            op.execute(None)
+
+    @mock.patch.object(DmsHook, "find_replication_tasks_by_arn")
+    @mock.patch.object(DmsHook, "get_conn")
+    def test_modify_task_raises_if_not_found(self, mock_conn, mock_find):
+        mock_find.return_value = []
+        op = DmsModifyTaskOperator(task_id="modify_task", replication_task_arn=self.TASK_ARN)
+        with pytest.raises(ValueError, match="not found"):
+            op.execute(None)
+
+    @mock.patch.object(DmsHook, "find_replication_tasks_by_arn")
+    @mock.patch.object(DmsHook, "get_conn")
+    def test_modify_task_defers_for_completion(self, mock_conn, mock_find):
+        from airflow.exceptions import TaskDeferred
+        from airflow.providers.amazon.aws.triggers.dms import DmsTaskModifyCompleteTrigger
+
+        mock_find.return_value = self._stopped_task()
+        expected = {"ReplicationTaskArn": self.TASK_ARN}
+        with mock.patch.object(DmsHook, "modify_replication_task", return_value=expected):
+            op = DmsModifyTaskOperator(
+                task_id="modify_task",
+                replication_task_arn=self.TASK_ARN,
+                deferrable=True,
+                wait_for_completion=True,
+            )
+            with pytest.raises(TaskDeferred) as exc_info:
+                op.execute(None)
+
+        assert isinstance(exc_info.value.trigger, DmsTaskModifyCompleteTrigger)
+        assert exc_info.value.method_name == "execute_complete"
+
+    @mock.patch.object(DmsHook, "find_replication_tasks_by_arn")
+    @mock.patch.object(DmsHook, "get_conn")
+    def test_modify_task_with_all_params(self, mock_conn, mock_find):
+        from datetime import datetime
+
+        mock_find.return_value = self._stopped_task()
+        cdc_start = datetime(2024, 1, 1)
+        expected = {"ReplicationTaskArn": self.TASK_ARN}
+        with mock.patch.object(DmsHook, "modify_replication_task", return_value=expected) as mock_modify:
+            op = DmsModifyTaskOperator(
+                task_id="modify_task",
+                replication_task_arn=self.TASK_ARN,
+                table_mappings=self.TABLE_MAPPINGS,
+                migration_type="full-load-and-cdc",
+                replication_task_settings={"TargetMetadata": {}},
+                cdc_start_time=cdc_start,
+                cdc_stop_position="2024-01-31:00:00:00",
+            )
+            op.execute(None)
+
+            mock_modify.assert_called_once_with(
+                replication_task_arn=self.TASK_ARN,
+                table_mappings=self.TABLE_MAPPINGS,
+                migration_type="full-load-and-cdc",
+                replication_task_settings={"TargetMetadata": {}},
+                cdc_start_time=cdc_start,
+                cdc_start_position=None,
+                cdc_stop_position="2024-01-31:00:00:00",
+            )
+
+    @mock.patch.object(DmsHook, "find_replication_tasks_by_arn")
+    @mock.patch.object(DmsHook, "get_conn")
+    def test_modify_task_waits_if_modifying(self, mock_conn, mock_find):
+        stopped_task = self._stopped_task()
+        expected = {"ReplicationTaskArn": self.TASK_ARN}
+        # execute() sees 'modifying' → _wait_until_not_modifying polls once → 'stopped';
+        # modify is called; wait_for_completion=True → _wait_until_not_modifying polls once → 'stopped'.
+        mock_find.side_effect = [
+            self._modifying_task(),
+            stopped_task,
+            stopped_task,
+        ]
+        with mock.patch.object(DmsHook, "modify_replication_task", return_value=expected) as mock_modify:
+            op = DmsModifyTaskOperator(
+                task_id="modify_task",
+                replication_task_arn=self.TASK_ARN,
+                table_mappings=self.TABLE_MAPPINGS,
+                wait_for_completion=True,
+                waiter_delay=0,
+            )
+            op.execute(None)
+
+            mock_modify.assert_called_once()
+
+    def test_execute_complete_success(self):
+        op = DmsModifyTaskOperator(
+            task_id="modify_task",
+            replication_task_arn=self.TASK_ARN,
+        )
+        success_event = {"status": "success", "replication_task_arn": self.TASK_ARN}
+        result = op.execute_complete({}, success_event)
+        assert result is None
+
+    def test_execute_complete_error(self):
+        op = DmsModifyTaskOperator(
+            task_id="modify_task",
+            replication_task_arn=self.TASK_ARN,
+        )
+        error_event = {"status": "error", "message": "Timeout", "replication_task_arn": self.TASK_ARN}
+        with pytest.raises(RuntimeError, match="Error waiting for DMS task modification to complete"):
+            op.execute_complete({}, error_event)
+
+    def test_template_fields(self):
+        op = DmsModifyTaskOperator(
+            task_id="modify_task",
+            replication_task_arn=self.TASK_ARN,
+            table_mappings=self.TABLE_MAPPINGS,
+        )
+        validate_template_fields(op)

Review Comment:
   Added `test_modify_task_raises_if_waiter_exceeded` (sync timeout) and `test_modify_task_raises_if_task_disappears_during_wait` (task not found mid-poll). `wait_for_completion=False` is covered by the parametrized `test_modify_task_modifiable_states`.



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: commits-unsubscribe@airflow.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] Add `DmsModifyTaskOperator` [airflow]

Posted by "AlejandroMorgante (via GitHub)" <gi...@apache.org>.
AlejandroMorgante commented on code in PR #67524:
URL: https://github.com/apache/airflow/pull/67524#discussion_r3329288696


##########
providers/amazon/src/airflow/providers/amazon/aws/triggers/dms.py:
##########
@@ -219,3 +222,79 @@ def hook(self) -> AwsGenericHook:
             verify=self.verify,
             config=self.botocore_config,
         )
+
+
+class DmsTaskModifyCompleteTrigger(BaseTrigger):

Review Comment:
   `AwsBaseWaiterTrigger` relies on boto3 waiters, but both the `ReplicationTaskReady` and `ReplicationTaskStopped` boto3 waiters explicitly treat `modifying` as a terminal `failure` state — they'd error out the moment the task enters modification. There's no boto3 waiter that waits for a task to *exit* `modifying`, so a custom polling loop with `BaseTrigger` is necessary here.



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: commits-unsubscribe@airflow.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] Add `DmsModifyTaskOperator` [airflow]

Posted by "SameerMesiah97 (via GitHub)" <gi...@apache.org>.
SameerMesiah97 commented on code in PR #67524:
URL: https://github.com/apache/airflow/pull/67524#discussion_r3329167919


##########
providers/amazon/src/airflow/providers/amazon/aws/triggers/dms.py:
##########
@@ -219,3 +222,79 @@ def hook(self) -> AwsGenericHook:
             verify=self.verify,
             config=self.botocore_config,
         )
+
+
+class DmsTaskModifyCompleteTrigger(BaseTrigger):
+    """
+    Trigger that polls until a DMS classic replication task exits the ``modifying`` state.
+
+    The boto3 ``replication_task_stopped`` waiter treats ``modifying`` as a terminal failure,
+    so a custom polling loop is required here.
+
+    :param replication_task_arn: The ARN of the replication task.
+    :param waiter_delay: Seconds between polls.
+    :param waiter_max_attempts: Maximum number of poll attempts before giving up.
+    :param aws_conn_id: The Airflow connection used for AWS credentials.
+    :param verify: Whether or not to verify SSL certificates.
+    :param botocore_config: Configuration dictionary (key-values) for botocore client.
+    """
+
+    def __init__(
+        self,
+        replication_task_arn: str,
+        waiter_delay: int = 30,
+        waiter_max_attempts: int = 60,
+        aws_conn_id: str | None = "aws_default",
+        verify: bool | str | None = None,
+        botocore_config: dict | None = None,
+    ) -> None:
+        super().__init__()
+        self.replication_task_arn = replication_task_arn
+        self.waiter_delay = waiter_delay
+        self.waiter_max_attempts = waiter_max_attempts
+        self.aws_conn_id = aws_conn_id
+        self.verify = verify
+        self.botocore_config = botocore_config
+
+    def serialize(self) -> tuple[str, dict]:
+        return (
+            "airflow.providers.amazon.aws.triggers.dms.DmsTaskModifyCompleteTrigger",
+            {
+                "replication_task_arn": self.replication_task_arn,
+                "waiter_delay": self.waiter_delay,
+                "waiter_max_attempts": self.waiter_max_attempts,
+                "aws_conn_id": self.aws_conn_id,
+                "verify": self.verify,
+                "botocore_config": self.botocore_config,
+            },
+        )
+
+    async def run(self) -> AsyncIterator[TriggerEvent]:
+        hook = DmsHook(aws_conn_id=self.aws_conn_id, verify=self.verify, config=self.botocore_config)
+        try:
+            for _ in range(self.waiter_max_attempts):
+                status = await hook.get_task_status_async(self.replication_task_arn)
+                if status != "modifying":

Review Comment:
   I would use the `ENUM` for the task state instead of raw strings to be consistent with the operator. If you follow my suggestion in the other comment, this line will become:
   
   `if status != DmsTaskWaiterStatus.MODIFYING`



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: commits-unsubscribe@airflow.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] Add `DmsModifyTaskOperator` [airflow]

Posted by "AlejandroMorgante (via GitHub)" <gi...@apache.org>.
AlejandroMorgante commented on code in PR #67524:
URL: https://github.com/apache/airflow/pull/67524#discussion_r3329271854


##########
providers/amazon/tests/unit/amazon/aws/operators/test_dms.py:
##########
@@ -180,6 +181,214 @@ def test_default_conn_passed_to_hook(self):
         assert op.hook.aws_conn_id == DEFAULT_CONN
 
 
+class TestDmsModifyTaskOperator:
+    TASK_ARN = "arn:aws:dms:us-east-1:123456789012:task:EXAMPLE"
+    TABLE_MAPPINGS = {
+        "rules": [
+            {
+                "rule-type": "selection",
+                "rule-id": "1",
+                "rule-name": "1",
+                "object-locator": {"schema-name": "myschema", "table-name": "mytable"},
+                "rule-action": "include",
+            }
+        ]
+    }
+
+    def _stopped_task(self):
+        return [{"ReplicationTaskArn": self.TASK_ARN, "Status": "stopped"}]
+
+    def _running_task(self):
+        return [{"ReplicationTaskArn": self.TASK_ARN, "Status": "running"}]
+
+    def _modifying_task(self):
+        return [{"ReplicationTaskArn": self.TASK_ARN, "Status": "modifying"}]
+
+    def test_init(self):
+        op = DmsModifyTaskOperator(
+            task_id="modify_task",
+            replication_task_arn=self.TASK_ARN,
+            table_mappings=self.TABLE_MAPPINGS,
+            migration_type="cdc",
+            aws_conn_id="fake-conn-id",
+            region_name="us-east-1",
+        )
+        assert op.replication_task_arn == self.TASK_ARN
+        assert op.table_mappings == self.TABLE_MAPPINGS
+        assert op.migration_type == "cdc"
+        assert op.wait_for_completion is True
+        assert op.deferrable is False
+        assert op.hook.aws_conn_id == "fake-conn-id"
+        assert op.hook._region_name == "us-east-1"
+
+    def test_init_defaults(self):
+        op = DmsModifyTaskOperator(task_id="modify_task", replication_task_arn=self.TASK_ARN)
+        assert op.table_mappings is None
+        assert op.migration_type is None
+        assert op.replication_task_settings is None
+        assert op.cdc_start_time is None
+        assert op.cdc_start_position is None
+        assert op.cdc_stop_position is None
+        assert op.wait_for_completion is True
+        assert op.deferrable is False
+
+    def test_init_raises_if_both_cdc_start_params_provided(self):
+        from datetime import datetime
+
+        with pytest.raises(ValueError, match="Only one of"):
+            DmsModifyTaskOperator(
+                task_id="modify_task",
+                replication_task_arn=self.TASK_ARN,
+                cdc_start_time=datetime(2024, 1, 1),
+                cdc_start_position="mysql-bin.000001:4",
+            )
+
+    @mock.patch.object(DmsHook, "find_replication_tasks_by_arn")
+    @mock.patch.object(DmsHook, "get_conn")
+    def test_modify_task_already_stopped(self, mock_conn, mock_find):
+        mock_find.return_value = self._stopped_task()
+        expected = {"ReplicationTaskArn": self.TASK_ARN}
+        with mock.patch.object(DmsHook, "modify_replication_task", return_value=expected) as mock_modify:
+            op = DmsModifyTaskOperator(
+                task_id="modify_task",
+                replication_task_arn=self.TASK_ARN,
+                table_mappings=self.TABLE_MAPPINGS,
+                wait_for_completion=False,
+            )
+            result = op.execute(None)
+
+            mock_modify.assert_called_once_with(
+                replication_task_arn=self.TASK_ARN,
+                table_mappings=self.TABLE_MAPPINGS,
+                migration_type=None,
+                replication_task_settings=None,
+                cdc_start_time=None,
+                cdc_start_position=None,
+                cdc_stop_position=None,
+            )
+            assert result == expected
+
+    @mock.patch.object(DmsHook, "find_replication_tasks_by_arn")
+    @mock.patch.object(DmsHook, "get_conn")
+    def test_modify_task_raises_if_running(self, mock_conn, mock_find):
+        mock_find.return_value = self._running_task()
+        op = DmsModifyTaskOperator(
+            task_id="modify_task",
+            replication_task_arn=self.TASK_ARN,
+        )
+        with pytest.raises(RuntimeError, match="must be stopped"):
+            op.execute(None)
+
+    @mock.patch.object(DmsHook, "find_replication_tasks_by_arn")
+    @mock.patch.object(DmsHook, "get_conn")
+    def test_modify_task_raises_if_not_found(self, mock_conn, mock_find):
+        mock_find.return_value = []
+        op = DmsModifyTaskOperator(task_id="modify_task", replication_task_arn=self.TASK_ARN)
+        with pytest.raises(ValueError, match="not found"):
+            op.execute(None)
+
+    @mock.patch.object(DmsHook, "find_replication_tasks_by_arn")
+    @mock.patch.object(DmsHook, "get_conn")
+    def test_modify_task_defers_for_completion(self, mock_conn, mock_find):
+        from airflow.exceptions import TaskDeferred

Review Comment:
   Removed the local import, using the `TaskDeferred` already imported at the top of the file.



##########
providers/amazon/tests/unit/amazon/aws/operators/test_dms.py:
##########
@@ -180,6 +181,214 @@ def test_default_conn_passed_to_hook(self):
         assert op.hook.aws_conn_id == DEFAULT_CONN
 
 
+class TestDmsModifyTaskOperator:
+    TASK_ARN = "arn:aws:dms:us-east-1:123456789012:task:EXAMPLE"
+    TABLE_MAPPINGS = {
+        "rules": [
+            {
+                "rule-type": "selection",
+                "rule-id": "1",
+                "rule-name": "1",
+                "object-locator": {"schema-name": "myschema", "table-name": "mytable"},
+                "rule-action": "include",
+            }
+        ]
+    }
+
+    def _stopped_task(self):
+        return [{"ReplicationTaskArn": self.TASK_ARN, "Status": "stopped"}]
+
+    def _running_task(self):
+        return [{"ReplicationTaskArn": self.TASK_ARN, "Status": "running"}]
+
+    def _modifying_task(self):
+        return [{"ReplicationTaskArn": self.TASK_ARN, "Status": "modifying"}]
+
+    def test_init(self):
+        op = DmsModifyTaskOperator(
+            task_id="modify_task",
+            replication_task_arn=self.TASK_ARN,
+            table_mappings=self.TABLE_MAPPINGS,
+            migration_type="cdc",
+            aws_conn_id="fake-conn-id",
+            region_name="us-east-1",
+        )
+        assert op.replication_task_arn == self.TASK_ARN
+        assert op.table_mappings == self.TABLE_MAPPINGS
+        assert op.migration_type == "cdc"
+        assert op.wait_for_completion is True
+        assert op.deferrable is False
+        assert op.hook.aws_conn_id == "fake-conn-id"
+        assert op.hook._region_name == "us-east-1"
+
+    def test_init_defaults(self):
+        op = DmsModifyTaskOperator(task_id="modify_task", replication_task_arn=self.TASK_ARN)
+        assert op.table_mappings is None
+        assert op.migration_type is None
+        assert op.replication_task_settings is None
+        assert op.cdc_start_time is None
+        assert op.cdc_start_position is None
+        assert op.cdc_stop_position is None
+        assert op.wait_for_completion is True
+        assert op.deferrable is False
+
+    def test_init_raises_if_both_cdc_start_params_provided(self):
+        from datetime import datetime
+
+        with pytest.raises(ValueError, match="Only one of"):
+            DmsModifyTaskOperator(
+                task_id="modify_task",
+                replication_task_arn=self.TASK_ARN,
+                cdc_start_time=datetime(2024, 1, 1),
+                cdc_start_position="mysql-bin.000001:4",
+            )
+
+    @mock.patch.object(DmsHook, "find_replication_tasks_by_arn")
+    @mock.patch.object(DmsHook, "get_conn")
+    def test_modify_task_already_stopped(self, mock_conn, mock_find):
+        mock_find.return_value = self._stopped_task()
+        expected = {"ReplicationTaskArn": self.TASK_ARN}
+        with mock.patch.object(DmsHook, "modify_replication_task", return_value=expected) as mock_modify:
+            op = DmsModifyTaskOperator(
+                task_id="modify_task",
+                replication_task_arn=self.TASK_ARN,
+                table_mappings=self.TABLE_MAPPINGS,
+                wait_for_completion=False,
+            )
+            result = op.execute(None)
+
+            mock_modify.assert_called_once_with(
+                replication_task_arn=self.TASK_ARN,
+                table_mappings=self.TABLE_MAPPINGS,
+                migration_type=None,
+                replication_task_settings=None,
+                cdc_start_time=None,
+                cdc_start_position=None,
+                cdc_stop_position=None,
+            )
+            assert result == expected
+
+    @mock.patch.object(DmsHook, "find_replication_tasks_by_arn")
+    @mock.patch.object(DmsHook, "get_conn")
+    def test_modify_task_raises_if_running(self, mock_conn, mock_find):
+        mock_find.return_value = self._running_task()
+        op = DmsModifyTaskOperator(
+            task_id="modify_task",
+            replication_task_arn=self.TASK_ARN,
+        )
+        with pytest.raises(RuntimeError, match="must be stopped"):
+            op.execute(None)
+
+    @mock.patch.object(DmsHook, "find_replication_tasks_by_arn")
+    @mock.patch.object(DmsHook, "get_conn")
+    def test_modify_task_raises_if_not_found(self, mock_conn, mock_find):
+        mock_find.return_value = []
+        op = DmsModifyTaskOperator(task_id="modify_task", replication_task_arn=self.TASK_ARN)
+        with pytest.raises(ValueError, match="not found"):
+            op.execute(None)
+
+    @mock.patch.object(DmsHook, "find_replication_tasks_by_arn")
+    @mock.patch.object(DmsHook, "get_conn")
+    def test_modify_task_defers_for_completion(self, mock_conn, mock_find):
+        from airflow.exceptions import TaskDeferred
+        from airflow.providers.amazon.aws.triggers.dms import DmsTaskModifyCompleteTrigger

Review Comment:
   Moved `DmsTaskModifyCompleteTrigger` to the top-level imports block alongside the other trigger imports.



##########
providers/amazon/tests/unit/amazon/aws/operators/test_dms.py:
##########
@@ -180,6 +181,214 @@ def test_default_conn_passed_to_hook(self):
         assert op.hook.aws_conn_id == DEFAULT_CONN
 
 
+class TestDmsModifyTaskOperator:
+    TASK_ARN = "arn:aws:dms:us-east-1:123456789012:task:EXAMPLE"
+    TABLE_MAPPINGS = {
+        "rules": [
+            {
+                "rule-type": "selection",
+                "rule-id": "1",
+                "rule-name": "1",
+                "object-locator": {"schema-name": "myschema", "table-name": "mytable"},
+                "rule-action": "include",
+            }
+        ]
+    }
+
+    def _stopped_task(self):
+        return [{"ReplicationTaskArn": self.TASK_ARN, "Status": "stopped"}]
+
+    def _running_task(self):
+        return [{"ReplicationTaskArn": self.TASK_ARN, "Status": "running"}]
+
+    def _modifying_task(self):
+        return [{"ReplicationTaskArn": self.TASK_ARN, "Status": "modifying"}]
+
+    def test_init(self):
+        op = DmsModifyTaskOperator(
+            task_id="modify_task",
+            replication_task_arn=self.TASK_ARN,
+            table_mappings=self.TABLE_MAPPINGS,
+            migration_type="cdc",
+            aws_conn_id="fake-conn-id",
+            region_name="us-east-1",
+        )
+        assert op.replication_task_arn == self.TASK_ARN
+        assert op.table_mappings == self.TABLE_MAPPINGS
+        assert op.migration_type == "cdc"
+        assert op.wait_for_completion is True
+        assert op.deferrable is False
+        assert op.hook.aws_conn_id == "fake-conn-id"
+        assert op.hook._region_name == "us-east-1"
+
+    def test_init_defaults(self):
+        op = DmsModifyTaskOperator(task_id="modify_task", replication_task_arn=self.TASK_ARN)
+        assert op.table_mappings is None
+        assert op.migration_type is None
+        assert op.replication_task_settings is None
+        assert op.cdc_start_time is None
+        assert op.cdc_start_position is None
+        assert op.cdc_stop_position is None
+        assert op.wait_for_completion is True
+        assert op.deferrable is False
+
+    def test_init_raises_if_both_cdc_start_params_provided(self):
+        from datetime import datetime
+
+        with pytest.raises(ValueError, match="Only one of"):
+            DmsModifyTaskOperator(
+                task_id="modify_task",
+                replication_task_arn=self.TASK_ARN,
+                cdc_start_time=datetime(2024, 1, 1),
+                cdc_start_position="mysql-bin.000001:4",
+            )
+
+    @mock.patch.object(DmsHook, "find_replication_tasks_by_arn")
+    @mock.patch.object(DmsHook, "get_conn")
+    def test_modify_task_already_stopped(self, mock_conn, mock_find):
+        mock_find.return_value = self._stopped_task()
+        expected = {"ReplicationTaskArn": self.TASK_ARN}
+        with mock.patch.object(DmsHook, "modify_replication_task", return_value=expected) as mock_modify:
+            op = DmsModifyTaskOperator(
+                task_id="modify_task",
+                replication_task_arn=self.TASK_ARN,
+                table_mappings=self.TABLE_MAPPINGS,
+                wait_for_completion=False,
+            )
+            result = op.execute(None)
+
+            mock_modify.assert_called_once_with(
+                replication_task_arn=self.TASK_ARN,
+                table_mappings=self.TABLE_MAPPINGS,
+                migration_type=None,
+                replication_task_settings=None,
+                cdc_start_time=None,
+                cdc_start_position=None,
+                cdc_stop_position=None,
+            )
+            assert result == expected
+
+    @mock.patch.object(DmsHook, "find_replication_tasks_by_arn")
+    @mock.patch.object(DmsHook, "get_conn")
+    def test_modify_task_raises_if_running(self, mock_conn, mock_find):
+        mock_find.return_value = self._running_task()
+        op = DmsModifyTaskOperator(
+            task_id="modify_task",
+            replication_task_arn=self.TASK_ARN,
+        )
+        with pytest.raises(RuntimeError, match="must be stopped"):
+            op.execute(None)
+
+    @mock.patch.object(DmsHook, "find_replication_tasks_by_arn")
+    @mock.patch.object(DmsHook, "get_conn")
+    def test_modify_task_raises_if_not_found(self, mock_conn, mock_find):
+        mock_find.return_value = []
+        op = DmsModifyTaskOperator(task_id="modify_task", replication_task_arn=self.TASK_ARN)
+        with pytest.raises(ValueError, match="not found"):
+            op.execute(None)
+
+    @mock.patch.object(DmsHook, "find_replication_tasks_by_arn")
+    @mock.patch.object(DmsHook, "get_conn")
+    def test_modify_task_defers_for_completion(self, mock_conn, mock_find):
+        from airflow.exceptions import TaskDeferred
+        from airflow.providers.amazon.aws.triggers.dms import DmsTaskModifyCompleteTrigger
+
+        mock_find.return_value = self._stopped_task()
+        expected = {"ReplicationTaskArn": self.TASK_ARN}
+        with mock.patch.object(DmsHook, "modify_replication_task", return_value=expected):
+            op = DmsModifyTaskOperator(
+                task_id="modify_task",
+                replication_task_arn=self.TASK_ARN,
+                deferrable=True,
+                wait_for_completion=True,
+            )
+            with pytest.raises(TaskDeferred) as exc_info:
+                op.execute(None)
+
+        assert isinstance(exc_info.value.trigger, DmsTaskModifyCompleteTrigger)
+        assert exc_info.value.method_name == "execute_complete"
+
+    @mock.patch.object(DmsHook, "find_replication_tasks_by_arn")
+    @mock.patch.object(DmsHook, "get_conn")
+    def test_modify_task_with_all_params(self, mock_conn, mock_find):
+        from datetime import datetime

Review Comment:
   Moved `datetime` to the top of the file.



##########
providers/amazon/tests/unit/amazon/aws/operators/test_dms.py:
##########
@@ -180,6 +181,214 @@ def test_default_conn_passed_to_hook(self):
         assert op.hook.aws_conn_id == DEFAULT_CONN
 
 
+class TestDmsModifyTaskOperator:
+    TASK_ARN = "arn:aws:dms:us-east-1:123456789012:task:EXAMPLE"
+    TABLE_MAPPINGS = {
+        "rules": [
+            {
+                "rule-type": "selection",
+                "rule-id": "1",
+                "rule-name": "1",
+                "object-locator": {"schema-name": "myschema", "table-name": "mytable"},
+                "rule-action": "include",
+            }
+        ]
+    }
+
+    def _stopped_task(self):
+        return [{"ReplicationTaskArn": self.TASK_ARN, "Status": "stopped"}]
+
+    def _running_task(self):
+        return [{"ReplicationTaskArn": self.TASK_ARN, "Status": "running"}]
+
+    def _modifying_task(self):
+        return [{"ReplicationTaskArn": self.TASK_ARN, "Status": "modifying"}]
+
+    def test_init(self):
+        op = DmsModifyTaskOperator(
+            task_id="modify_task",
+            replication_task_arn=self.TASK_ARN,
+            table_mappings=self.TABLE_MAPPINGS,
+            migration_type="cdc",
+            aws_conn_id="fake-conn-id",
+            region_name="us-east-1",
+        )
+        assert op.replication_task_arn == self.TASK_ARN
+        assert op.table_mappings == self.TABLE_MAPPINGS
+        assert op.migration_type == "cdc"
+        assert op.wait_for_completion is True
+        assert op.deferrable is False
+        assert op.hook.aws_conn_id == "fake-conn-id"
+        assert op.hook._region_name == "us-east-1"
+
+    def test_init_defaults(self):
+        op = DmsModifyTaskOperator(task_id="modify_task", replication_task_arn=self.TASK_ARN)
+        assert op.table_mappings is None
+        assert op.migration_type is None
+        assert op.replication_task_settings is None
+        assert op.cdc_start_time is None
+        assert op.cdc_start_position is None
+        assert op.cdc_stop_position is None
+        assert op.wait_for_completion is True
+        assert op.deferrable is False
+
+    def test_init_raises_if_both_cdc_start_params_provided(self):
+        from datetime import datetime

Review Comment:
   Moved `datetime` to the top of the file.



##########
providers/amazon/src/airflow/providers/amazon/aws/operators/dms.py:
##########
@@ -118,6 +120,178 @@ def execute(self, context: Context):
         return task_arn
 
 
+class DmsModifyTaskOperator(AwsBaseOperator[DmsHook]):
+    """
+    Modifies an existing AWS DMS replication task.
+
+    The task must already be stopped before modification. Use :class:`DmsStopTaskOperator`
+    upstream in the Dag to stop it, and :class:`DmsStartTaskOperator` downstream to restart
+    it afterwards if needed.
+
+    .. seealso::
+        For more information on how to use this operator, take a look at the guide:
+        :ref:`howto/operator:DmsModifyTaskOperator`
+
+    :param replication_task_arn: Replication task ARN
+    :param table_mappings: New table mappings. If not provided, existing mappings are kept.
+    :param migration_type: Migration type ('full-load'|'cdc'|'full-load-and-cdc').
+        If not provided, existing type is kept.
+    :param replication_task_settings: Task settings dict. If not provided, existing settings are kept.
+    :param cdc_start_time: Start time for CDC.
+    :param cdc_start_position: Indicates when to start CDC (checkpoint or LSN/SCN format).
+        Mutually exclusive with cdc_start_time.
+    :param cdc_stop_position: Indicates when to stop CDC.
+    :param wait_for_completion: If True, wait for the modification to finish before returning.
+        In deferrable mode the operator defers rather than blocking. Defaults to True.
+    :param deferrable: Run the operator in deferrable mode. Defaults to False.
+    :param waiter_delay: Seconds between waiter polls (default: 30).
+    :param waiter_max_attempts: Maximum waiter poll attempts (default: 60).
+    :param aws_conn_id: The Airflow connection used for AWS credentials.
+        If this is ``None`` or empty then the default boto3 behaviour is used. If
+        running Airflow in a distributed manner and aws_conn_id is None or
+        empty, then default boto3 configuration would be used (and must be
+        maintained on each worker node).
+    :param region_name: AWS region_name. If not specified then the default boto3 behaviour is used.
+    :param verify: Whether or not to verify SSL certificates. See:
+        https://boto3.amazonaws.com/v1/documentation/api/latest/reference/core/session.html
+    :param botocore_config: Configuration dictionary (key-values) for botocore client. See:
+        https://botocore.amazonaws.com/v1/documentation/api/latest/reference/config.html
+    """
+
+    MODIFIABLE_STATES = frozenset({DmsTaskState.STOPPED, DmsTaskState.READY, DmsTaskState.FAILED})
+
+    aws_hook_class = DmsHook
+    template_fields: Sequence[str] = aws_template_fields(
+        "replication_task_arn",
+        "table_mappings",
+        "migration_type",
+        "replication_task_settings",
+        "cdc_start_time",
+        "cdc_start_position",
+        "cdc_stop_position",
+    )
+    template_fields_renderers: ClassVar[dict] = {
+        "table_mappings": "json",
+        "replication_task_settings": "json",
+    }
+
+    def __init__(
+        self,
+        *,
+        replication_task_arn: str,
+        table_mappings: dict | None = None,
+        migration_type: str | None = None,
+        replication_task_settings: dict | None = None,
+        cdc_start_time: datetime | None = None,
+        cdc_start_position: str | None = None,
+        cdc_stop_position: str | None = None,
+        wait_for_completion: bool = True,
+        deferrable: bool = conf.getboolean("operators", "default_deferrable", fallback=False),
+        waiter_delay: int = 30,
+        waiter_max_attempts: int = 60,
+        **kwargs,
+    ):
+        super().__init__(**kwargs)
+        if cdc_start_time and cdc_start_position:
+            raise ValueError("Only one of cdc_start_time or cdc_start_position can be provided.")
+        self.replication_task_arn = replication_task_arn
+        self.table_mappings = table_mappings
+        self.migration_type = migration_type
+        self.replication_task_settings = replication_task_settings
+        self.cdc_start_time = cdc_start_time
+        self.cdc_start_position = cdc_start_position
+        self.cdc_stop_position = cdc_stop_position
+        self.wait_for_completion = wait_for_completion
+        self.deferrable = deferrable
+        self.waiter_delay = waiter_delay
+        self.waiter_max_attempts = waiter_max_attempts
+
+    def execute(self, context: Context) -> dict:
+        tasks = self.hook.find_replication_tasks_by_arn(
+            replication_task_arn=self.replication_task_arn, without_settings=True
+        )
+        if not tasks:
+            raise ValueError(f"Replication task {self.replication_task_arn} not found.")
+
+        current_status = tasks[0].get("Status", "").lower()
+        self.log.info(
+            "Current status of replication task(%s) is '%s'.", self.replication_task_arn, current_status
+        )
+
+        if current_status == DmsTaskState.MODIFYING:
+            # boto3 stopped/ready waiters treat 'modifying' as a terminal failure — use poll loop.
+            self._wait_until_not_modifying()
+        elif current_status not in self.MODIFIABLE_STATES:
+            raise RuntimeError(
+                f"Replication task {self.replication_task_arn} is in state '{current_status}' "
+                f"and must be stopped before modification. "
+                f"Use DmsStopTaskOperator to stop it first."
+            )
+
+        result = self.hook.modify_replication_task(
+            replication_task_arn=self.replication_task_arn,
+            table_mappings=self.table_mappings,
+            migration_type=self.migration_type,
+            replication_task_settings=self.replication_task_settings,
+            cdc_start_time=self.cdc_start_time,
+            cdc_start_position=self.cdc_start_position,
+            cdc_stop_position=self.cdc_stop_position,
+        )
+        self.log.info("DMS replication task(%s) has been modified.", self.replication_task_arn)
+
+        if self.wait_for_completion:
+            if self.deferrable:
+                self.defer(
+                    trigger=DmsTaskModifyCompleteTrigger(
+                        replication_task_arn=self.replication_task_arn,
+                        waiter_delay=self.waiter_delay,
+                        waiter_max_attempts=self.waiter_max_attempts,
+                        aws_conn_id=self.aws_conn_id,
+                    ),
+                    method_name="execute_complete",
+                )

Review Comment:
   Added the `else` so `_wait_until_not_modifying()` only runs on the non-deferrable path.



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: commits-unsubscribe@airflow.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] Add `DmsModifyTaskOperator` [airflow]

Posted by "SameerMesiah97 (via GitHub)" <gi...@apache.org>.
SameerMesiah97 commented on code in PR #67524:
URL: https://github.com/apache/airflow/pull/67524#discussion_r3329245887


##########
providers/amazon/tests/unit/amazon/aws/operators/test_dms.py:
##########
@@ -180,6 +181,214 @@ def test_default_conn_passed_to_hook(self):
         assert op.hook.aws_conn_id == DEFAULT_CONN
 
 
+class TestDmsModifyTaskOperator:
+    TASK_ARN = "arn:aws:dms:us-east-1:123456789012:task:EXAMPLE"
+    TABLE_MAPPINGS = {
+        "rules": [
+            {
+                "rule-type": "selection",
+                "rule-id": "1",
+                "rule-name": "1",
+                "object-locator": {"schema-name": "myschema", "table-name": "mytable"},
+                "rule-action": "include",
+            }
+        ]
+    }
+
+    def _stopped_task(self):
+        return [{"ReplicationTaskArn": self.TASK_ARN, "Status": "stopped"}]
+
+    def _running_task(self):
+        return [{"ReplicationTaskArn": self.TASK_ARN, "Status": "running"}]
+
+    def _modifying_task(self):
+        return [{"ReplicationTaskArn": self.TASK_ARN, "Status": "modifying"}]
+
+    def test_init(self):
+        op = DmsModifyTaskOperator(
+            task_id="modify_task",
+            replication_task_arn=self.TASK_ARN,
+            table_mappings=self.TABLE_MAPPINGS,
+            migration_type="cdc",
+            aws_conn_id="fake-conn-id",
+            region_name="us-east-1",
+        )
+        assert op.replication_task_arn == self.TASK_ARN
+        assert op.table_mappings == self.TABLE_MAPPINGS
+        assert op.migration_type == "cdc"
+        assert op.wait_for_completion is True
+        assert op.deferrable is False
+        assert op.hook.aws_conn_id == "fake-conn-id"
+        assert op.hook._region_name == "us-east-1"
+
+    def test_init_defaults(self):
+        op = DmsModifyTaskOperator(task_id="modify_task", replication_task_arn=self.TASK_ARN)
+        assert op.table_mappings is None
+        assert op.migration_type is None
+        assert op.replication_task_settings is None
+        assert op.cdc_start_time is None
+        assert op.cdc_start_position is None
+        assert op.cdc_stop_position is None
+        assert op.wait_for_completion is True
+        assert op.deferrable is False
+
+    def test_init_raises_if_both_cdc_start_params_provided(self):
+        from datetime import datetime
+
+        with pytest.raises(ValueError, match="Only one of"):
+            DmsModifyTaskOperator(
+                task_id="modify_task",
+                replication_task_arn=self.TASK_ARN,
+                cdc_start_time=datetime(2024, 1, 1),
+                cdc_start_position="mysql-bin.000001:4",
+            )
+
+    @mock.patch.object(DmsHook, "find_replication_tasks_by_arn")
+    @mock.patch.object(DmsHook, "get_conn")
+    def test_modify_task_already_stopped(self, mock_conn, mock_find):
+        mock_find.return_value = self._stopped_task()
+        expected = {"ReplicationTaskArn": self.TASK_ARN}
+        with mock.patch.object(DmsHook, "modify_replication_task", return_value=expected) as mock_modify:
+            op = DmsModifyTaskOperator(
+                task_id="modify_task",
+                replication_task_arn=self.TASK_ARN,
+                table_mappings=self.TABLE_MAPPINGS,
+                wait_for_completion=False,
+            )
+            result = op.execute(None)
+
+            mock_modify.assert_called_once_with(
+                replication_task_arn=self.TASK_ARN,
+                table_mappings=self.TABLE_MAPPINGS,
+                migration_type=None,
+                replication_task_settings=None,
+                cdc_start_time=None,
+                cdc_start_position=None,
+                cdc_stop_position=None,
+            )
+            assert result == expected
+
+    @mock.patch.object(DmsHook, "find_replication_tasks_by_arn")
+    @mock.patch.object(DmsHook, "get_conn")
+    def test_modify_task_raises_if_running(self, mock_conn, mock_find):
+        mock_find.return_value = self._running_task()
+        op = DmsModifyTaskOperator(
+            task_id="modify_task",
+            replication_task_arn=self.TASK_ARN,
+        )
+        with pytest.raises(RuntimeError, match="must be stopped"):
+            op.execute(None)
+
+    @mock.patch.object(DmsHook, "find_replication_tasks_by_arn")
+    @mock.patch.object(DmsHook, "get_conn")
+    def test_modify_task_raises_if_not_found(self, mock_conn, mock_find):
+        mock_find.return_value = []
+        op = DmsModifyTaskOperator(task_id="modify_task", replication_task_arn=self.TASK_ARN)
+        with pytest.raises(ValueError, match="not found"):
+            op.execute(None)
+
+    @mock.patch.object(DmsHook, "find_replication_tasks_by_arn")
+    @mock.patch.object(DmsHook, "get_conn")
+    def test_modify_task_defers_for_completion(self, mock_conn, mock_find):
+        from airflow.exceptions import TaskDeferred
+        from airflow.providers.amazon.aws.triggers.dms import DmsTaskModifyCompleteTrigger
+
+        mock_find.return_value = self._stopped_task()
+        expected = {"ReplicationTaskArn": self.TASK_ARN}
+        with mock.patch.object(DmsHook, "modify_replication_task", return_value=expected):
+            op = DmsModifyTaskOperator(
+                task_id="modify_task",
+                replication_task_arn=self.TASK_ARN,
+                deferrable=True,
+                wait_for_completion=True,
+            )
+            with pytest.raises(TaskDeferred) as exc_info:
+                op.execute(None)
+
+        assert isinstance(exc_info.value.trigger, DmsTaskModifyCompleteTrigger)
+        assert exc_info.value.method_name == "execute_complete"
+
+    @mock.patch.object(DmsHook, "find_replication_tasks_by_arn")
+    @mock.patch.object(DmsHook, "get_conn")
+    def test_modify_task_with_all_params(self, mock_conn, mock_find):
+        from datetime import datetime
+
+        mock_find.return_value = self._stopped_task()
+        cdc_start = datetime(2024, 1, 1)
+        expected = {"ReplicationTaskArn": self.TASK_ARN}
+        with mock.patch.object(DmsHook, "modify_replication_task", return_value=expected) as mock_modify:
+            op = DmsModifyTaskOperator(
+                task_id="modify_task",
+                replication_task_arn=self.TASK_ARN,
+                table_mappings=self.TABLE_MAPPINGS,
+                migration_type="full-load-and-cdc",
+                replication_task_settings={"TargetMetadata": {}},
+                cdc_start_time=cdc_start,
+                cdc_stop_position="2024-01-31:00:00:00",
+            )
+            op.execute(None)
+
+            mock_modify.assert_called_once_with(
+                replication_task_arn=self.TASK_ARN,
+                table_mappings=self.TABLE_MAPPINGS,
+                migration_type="full-load-and-cdc",
+                replication_task_settings={"TargetMetadata": {}},
+                cdc_start_time=cdc_start,
+                cdc_start_position=None,
+                cdc_stop_position="2024-01-31:00:00:00",
+            )
+
+    @mock.patch.object(DmsHook, "find_replication_tasks_by_arn")
+    @mock.patch.object(DmsHook, "get_conn")
+    def test_modify_task_waits_if_modifying(self, mock_conn, mock_find):
+        stopped_task = self._stopped_task()
+        expected = {"ReplicationTaskArn": self.TASK_ARN}
+        # execute() sees 'modifying' → _wait_until_not_modifying polls once → 'stopped';
+        # modify is called; wait_for_completion=True → _wait_until_not_modifying polls once → 'stopped'.
+        mock_find.side_effect = [
+            self._modifying_task(),
+            stopped_task,
+            stopped_task,
+        ]
+        with mock.patch.object(DmsHook, "modify_replication_task", return_value=expected) as mock_modify:
+            op = DmsModifyTaskOperator(
+                task_id="modify_task",
+                replication_task_arn=self.TASK_ARN,
+                table_mappings=self.TABLE_MAPPINGS,
+                wait_for_completion=True,
+                waiter_delay=0,
+            )
+            op.execute(None)
+
+            mock_modify.assert_called_once()
+
+    def test_execute_complete_success(self):
+        op = DmsModifyTaskOperator(
+            task_id="modify_task",
+            replication_task_arn=self.TASK_ARN,
+        )
+        success_event = {"status": "success", "replication_task_arn": self.TASK_ARN}
+        result = op.execute_complete({}, success_event)
+        assert result is None
+
+    def test_execute_complete_error(self):
+        op = DmsModifyTaskOperator(
+            task_id="modify_task",
+            replication_task_arn=self.TASK_ARN,
+        )
+        error_event = {"status": "error", "message": "Timeout", "replication_task_arn": self.TASK_ARN}
+        with pytest.raises(RuntimeError, match="Error waiting for DMS task modification to complete"):
+            op.execute_complete({}, error_event)
+
+    def test_template_fields(self):
+        op = DmsModifyTaskOperator(
+            task_id="modify_task",
+            replication_task_arn=self.TASK_ARN,
+            table_mappings=self.TABLE_MAPPINGS,
+        )
+        validate_template_fields(op)

Review Comment:
   I think you should add tests for the following:
   
   1) `waiter_max_attempts` exceeded in sychronous path.
   2)` wait_for_completion=False`
   3) tasks not during `_wait_until_not_modifying`



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: commits-unsubscribe@airflow.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] Add `DmsModifyTaskOperator` [airflow]

Posted by "SameerMesiah97 (via GitHub)" <gi...@apache.org>.
SameerMesiah97 commented on code in PR #67524:
URL: https://github.com/apache/airflow/pull/67524#discussion_r3329251710


##########
providers/amazon/src/airflow/providers/amazon/aws/operators/dms.py:
##########
@@ -118,6 +120,178 @@ def execute(self, context: Context):
         return task_arn
 
 
+class DmsModifyTaskOperator(AwsBaseOperator[DmsHook]):
+    """
+    Modifies an existing AWS DMS replication task.
+
+    The task must already be stopped before modification. Use :class:`DmsStopTaskOperator`
+    upstream in the Dag to stop it, and :class:`DmsStartTaskOperator` downstream to restart
+    it afterwards if needed.
+
+    .. seealso::
+        For more information on how to use this operator, take a look at the guide:
+        :ref:`howto/operator:DmsModifyTaskOperator`
+
+    :param replication_task_arn: Replication task ARN
+    :param table_mappings: New table mappings. If not provided, existing mappings are kept.
+    :param migration_type: Migration type ('full-load'|'cdc'|'full-load-and-cdc').
+        If not provided, existing type is kept.
+    :param replication_task_settings: Task settings dict. If not provided, existing settings are kept.
+    :param cdc_start_time: Start time for CDC.
+    :param cdc_start_position: Indicates when to start CDC (checkpoint or LSN/SCN format).
+        Mutually exclusive with cdc_start_time.
+    :param cdc_stop_position: Indicates when to stop CDC.
+    :param wait_for_completion: If True, wait for the modification to finish before returning.
+        In deferrable mode the operator defers rather than blocking. Defaults to True.
+    :param deferrable: Run the operator in deferrable mode. Defaults to False.
+    :param waiter_delay: Seconds between waiter polls (default: 30).
+    :param waiter_max_attempts: Maximum waiter poll attempts (default: 60).
+    :param aws_conn_id: The Airflow connection used for AWS credentials.
+        If this is ``None`` or empty then the default boto3 behaviour is used. If
+        running Airflow in a distributed manner and aws_conn_id is None or
+        empty, then default boto3 configuration would be used (and must be
+        maintained on each worker node).
+    :param region_name: AWS region_name. If not specified then the default boto3 behaviour is used.
+    :param verify: Whether or not to verify SSL certificates. See:
+        https://boto3.amazonaws.com/v1/documentation/api/latest/reference/core/session.html
+    :param botocore_config: Configuration dictionary (key-values) for botocore client. See:
+        https://botocore.amazonaws.com/v1/documentation/api/latest/reference/config.html
+    """

Review Comment:
   Are these last 3 docstring entries needed? The other DMS operators don't appear to have them.



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: commits-unsubscribe@airflow.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] Add `DmsModifyTaskOperator` [airflow]

Posted by "SameerMesiah97 (via GitHub)" <gi...@apache.org>.
SameerMesiah97 commented on code in PR #67524:
URL: https://github.com/apache/airflow/pull/67524#discussion_r3329265289


##########
providers/amazon/src/airflow/providers/amazon/aws/triggers/dms.py:
##########
@@ -219,3 +222,79 @@ def hook(self) -> AwsGenericHook:
             verify=self.verify,
             config=self.botocore_config,
         )
+
+
+class DmsTaskModifyCompleteTrigger(BaseTrigger):

Review Comment:
   Just curious here. Why are you inheriting from `BaseTrigger` instead of `AwsBaseWaiterTrigger`? Could this trigger still inherit from `AwsBaseWaiterTrigger` and override the polling/state-machine behavior i.e. the `run `method? It seems like most of the AWS-specific plumbing is still applicable, and only the waiter lifecycle handling differs. You may override anything else you need to get this to work.



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: commits-unsubscribe@airflow.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] Add `DmsModifyTaskOperator` [airflow]

Posted by "AlejandroMorgante (via GitHub)" <gi...@apache.org>.
AlejandroMorgante commented on code in PR #67524:
URL: https://github.com/apache/airflow/pull/67524#discussion_r3349559024


##########
providers/amazon/src/airflow/providers/amazon/aws/waiters/dms.json:
##########
@@ -95,6 +95,85 @@
                     "state": "success"
                 }
             ]
+        },
+        "replication_task_modified": {
+            "operation": "DescribeReplicationTasks",
+            "delay": 30,
+            "maxAttempts": 60,
+            "acceptors": [
+                {
+                    "matcher": "path",
+                    "argument": "ReplicationTasks[0].Status",
+                    "expected": "modifying",
+                    "state": "retry"
+                },
+                {
+                    "matcher": "path",
+                    "argument": "ReplicationTasks[0].Status",
+                    "expected": "stopped",
+                    "state": "success"
+                },
+                {
+                    "matcher": "path",
+                    "argument": "ReplicationTasks[0].Status",
+                    "expected": "ready",
+                    "state": "success"
+                },
+                {
+                    "matcher": "path",
+                    "argument": "ReplicationTasks[0].Status",
+                    "expected": "failed",
+                    "state": "success"

Review Comment:
   Yes, in this waiter `success` means the async modification phase has completed, not that the replication task is healthy/runnable.
   
   DMS does not expose a separate `modify-failed` task state. If the `ModifyReplicationTask` API call itself fails, boto3 raises an error immediately before the waiter starts. Once the API call is accepted, the task enters `modifying`, and this waiter only waits for it to leave that state. 
   
   `stopped`, `ready`, and `failed` are all terminal states for that wait. `failed` is included because users may modify a failed task to fix its configuration, and the task can remain in `failed` until they explicitly start/retry it afterwards.
   
     So `failed` here means "the modification wait is complete", not "replication succeeded".



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: commits-unsubscribe@airflow.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] Add DmsModifyTaskOperator [airflow]

Posted by "AlejandroMorgante (via GitHub)" <gi...@apache.org>.
AlejandroMorgante commented on code in PR #67524:
URL: https://github.com/apache/airflow/pull/67524#discussion_r3314648179


##########
providers/amazon/src/airflow/providers/amazon/aws/operators/dms.py:
##########
@@ -118,6 +121,274 @@ def execute(self, context: Context):
         return task_arn
 
 
+class DmsModifyTaskOperator(AwsBaseOperator[DmsHook]):
+    """
+    Modifies an existing AWS DMS replication task.
+
+    If the task is not already stopped, set ``stop_task_before=True`` to stop it first.
+    To restart the task after modification, set ``restart_task_after=True``.
+
+    .. seealso::
+        For more information on how to use this operator, take a look at the guide:
+        :ref:`howto/operator:DmsModifyTaskOperator`
+
+    :param replication_task_arn: Replication task ARN
+    :param table_mappings: New table mappings. If not provided, existing mappings are kept.
+    :param migration_type: Migration type ('full-load'|'cdc'|'full-load-and-cdc').
+        If not provided, existing type is kept.
+    :param replication_task_settings: Task settings dict. If not provided, existing settings are kept.
+    :param cdc_start_time: Start time for CDC.
+    :param cdc_start_position: Indicates when to start CDC (checkpoint or LSN/SCN format).
+        Mutually exclusive with cdc_start_time.
+    :param cdc_stop_position: Indicates when to stop CDC.
+    :param stop_task_before: If True, stop the task before modifying if it is not already stopped.
+    :param restart_task_after: If True, restart the task after modifying.
+    :param start_replication_task_type: Start type used when restarting the task.
+        One of 'start-replication', 'resume-processing', or 'reload-target'.
+        Defaults to 'resume-processing'. Only used when ``restart_task_after=True``.
+    :param wait_for_completion: Only applies when the task is already in ``modifying`` state
+        when ``execute()`` is called. If True, wait for the modification to finish before
+        proceeding. If False, raises immediately instead of waiting.
+    :param deferrable: Run the operator in deferrable mode.
+    :param waiter_delay: Seconds between waiter polls (default: 30).
+    :param waiter_max_attempts: Maximum waiter poll attempts (default: 60).
+    :param aws_conn_id: The Airflow connection used for AWS credentials.
+        If this is ``None`` or empty then the default boto3 behaviour is used. If
+        running Airflow in a distributed manner and aws_conn_id is None or
+        empty, then default boto3 configuration would be used (and must be
+        maintained on each worker node).
+    :param region_name: AWS region_name. If not specified then the default boto3 behaviour is used.
+    :param verify: Whether or not to verify SSL certificates. See:
+        https://boto3.amazonaws.com/v1/documentation/api/latest/reference/core/session.html
+    :param botocore_config: Configuration dictionary (key-values) for botocore client. See:
+        https://botocore.amazonaws.com/v1/documentation/api/latest/reference/config.html
+    """
+
+    STOPPED_STATES = ("stopped", "ready", "failed", "created")
+    TERMINAL_STATES = frozenset({"failed", "stopped", "ready", "created", "deleting"})
+
+    aws_hook_class = DmsHook
+    template_fields: Sequence[str] = aws_template_fields(
+        "replication_task_arn",
+        "table_mappings",
+        "migration_type",
+        "replication_task_settings",
+        "cdc_start_time",
+        "cdc_start_position",
+        "cdc_stop_position",
+        "start_replication_task_type",
+    )
+    template_fields_renderers: ClassVar[dict] = {
+        "table_mappings": "json",
+        "replication_task_settings": "json",
+    }
+
+    def __init__(
+        self,
+        *,
+        replication_task_arn: str,
+        table_mappings: dict | None = None,
+        migration_type: str | None = None,
+        replication_task_settings: dict | None = None,
+        cdc_start_time: datetime | None = None,
+        cdc_start_position: str | None = None,
+        cdc_stop_position: str | None = None,
+        stop_task_before: bool = False,
+        restart_task_after: bool = False,
+        start_replication_task_type: str = "resume-processing",
+        wait_for_completion: bool = True,
+        deferrable: bool = conf.getboolean("operators", "default_deferrable", fallback=False),
+        waiter_delay: int = 30,
+        waiter_max_attempts: int = 60,
+        **kwargs,
+    ):
+        super().__init__(**kwargs)
+        if cdc_start_time and cdc_start_position:
+            raise ValueError("Only one of cdc_start_time or cdc_start_position can be provided.")
+        self.replication_task_arn = replication_task_arn
+        self.table_mappings = table_mappings
+        self.migration_type = migration_type
+        self.replication_task_settings = replication_task_settings
+        self.cdc_start_time = cdc_start_time
+        self.cdc_start_position = cdc_start_position
+        self.cdc_stop_position = cdc_stop_position
+        self.stop_task_before = stop_task_before
+        self.restart_task_after = restart_task_after
+        self.start_replication_task_type = start_replication_task_type
+        self.wait_for_completion = wait_for_completion
+        self.deferrable = deferrable
+        self.waiter_delay = waiter_delay
+        self.waiter_max_attempts = waiter_max_attempts
+
+    def execute(self, context: Context) -> dict:
+        tasks = self.hook.find_replication_tasks_by_arn(
+            replication_task_arn=self.replication_task_arn, without_settings=True
+        )
+        if not tasks:
+            raise AirflowException(f"Replication task {self.replication_task_arn} not found.")
+
+        current_status = tasks[0].get("Status", "").lower()
+        self.log.info(
+            "Current status of replication task(%s) is '%s'.", self.replication_task_arn, current_status
+        )
+
+        if current_status == "modifying":
+            # boto3 stopped/ready waiters treat 'modifying' as a terminal failure — use poll loop.
+            if not self.wait_for_completion:
+                raise AirflowException(
+                    f"Replication task {self.replication_task_arn} is already being modified. "
+                    f"Set wait_for_completion=True to wait for it to finish."
+                )
+            self._wait_until_not_modifying()
+        elif current_status not in self.STOPPED_STATES:
+            if not self.stop_task_before:
+                raise AirflowException(
+                    f"Replication task {self.replication_task_arn} is in state '{current_status}' "
+                    f"and must be stopped before modification. Set stop_task_before=True to stop it "
+                    f"automatically, or stop the task first."
+                )
+            if current_status == "starting":
+                # DMS rejects StopReplicationTask while the task is still starting up.
+                self.log.info(
+                    "Replication task(%s) is starting, waiting for it to reach 'running'.",
+                    self.replication_task_arn,
+                )
+                self._wait_for_status("running")
+            self.log.info("Stopping replication task(%s).", self.replication_task_arn)
+            self.hook.stop_replication_task(replication_task_arn=self.replication_task_arn)
+            self.log.info("Waiting for replication task(%s) to stop.", self.replication_task_arn)
+            if self.deferrable:

Review Comment:
   Fair point. The modify API is async — DMS puts the task in modifying for ~1 min regardless — so the deferrable path does save a worker slot during that wait. Happy to drop it if the preference is to keep things simpler.
   
   ---
   Drafted-by: Claude Code (claude-sonnet-4-6); reviewed by @AlejandroMorgante before posting



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: commits-unsubscribe@airflow.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] Add DmsModifyTaskOperator [airflow]

Posted by "AlejandroMorgante (via GitHub)" <gi...@apache.org>.
AlejandroMorgante commented on code in PR #67524:
URL: https://github.com/apache/airflow/pull/67524#discussion_r3314648138


##########
providers/amazon/src/airflow/providers/amazon/aws/operators/dms.py:
##########
@@ -118,6 +121,274 @@ def execute(self, context: Context):
         return task_arn
 
 
+class DmsModifyTaskOperator(AwsBaseOperator[DmsHook]):
+    """
+    Modifies an existing AWS DMS replication task.
+
+    If the task is not already stopped, set ``stop_task_before=True`` to stop it first.
+    To restart the task after modification, set ``restart_task_after=True``.
+
+    .. seealso::
+        For more information on how to use this operator, take a look at the guide:
+        :ref:`howto/operator:DmsModifyTaskOperator`
+
+    :param replication_task_arn: Replication task ARN
+    :param table_mappings: New table mappings. If not provided, existing mappings are kept.
+    :param migration_type: Migration type ('full-load'|'cdc'|'full-load-and-cdc').
+        If not provided, existing type is kept.
+    :param replication_task_settings: Task settings dict. If not provided, existing settings are kept.
+    :param cdc_start_time: Start time for CDC.
+    :param cdc_start_position: Indicates when to start CDC (checkpoint or LSN/SCN format).
+        Mutually exclusive with cdc_start_time.
+    :param cdc_stop_position: Indicates when to stop CDC.
+    :param stop_task_before: If True, stop the task before modifying if it is not already stopped.
+    :param restart_task_after: If True, restart the task after modifying.
+    :param start_replication_task_type: Start type used when restarting the task.
+        One of 'start-replication', 'resume-processing', or 'reload-target'.
+        Defaults to 'resume-processing'. Only used when ``restart_task_after=True``.
+    :param wait_for_completion: Only applies when the task is already in ``modifying`` state
+        when ``execute()`` is called. If True, wait for the modification to finish before
+        proceeding. If False, raises immediately instead of waiting.
+    :param deferrable: Run the operator in deferrable mode.
+    :param waiter_delay: Seconds between waiter polls (default: 30).
+    :param waiter_max_attempts: Maximum waiter poll attempts (default: 60).
+    :param aws_conn_id: The Airflow connection used for AWS credentials.
+        If this is ``None`` or empty then the default boto3 behaviour is used. If
+        running Airflow in a distributed manner and aws_conn_id is None or
+        empty, then default boto3 configuration would be used (and must be
+        maintained on each worker node).
+    :param region_name: AWS region_name. If not specified then the default boto3 behaviour is used.
+    :param verify: Whether or not to verify SSL certificates. See:
+        https://boto3.amazonaws.com/v1/documentation/api/latest/reference/core/session.html
+    :param botocore_config: Configuration dictionary (key-values) for botocore client. See:
+        https://botocore.amazonaws.com/v1/documentation/api/latest/reference/config.html
+    """
+
+    STOPPED_STATES = ("stopped", "ready", "failed", "created")
+    TERMINAL_STATES = frozenset({"failed", "stopped", "ready", "created", "deleting"})

Review Comment:
   Added DmsTaskState enum to the hook (modeled after DmsTaskWaiterStatus that was already there) and renamed to MODIFIABLE_STATES.



##########
providers/amazon/src/airflow/providers/amazon/aws/operators/dms.py:
##########
@@ -118,6 +121,274 @@ def execute(self, context: Context):
         return task_arn
 
 
+class DmsModifyTaskOperator(AwsBaseOperator[DmsHook]):
+    """
+    Modifies an existing AWS DMS replication task.
+
+    If the task is not already stopped, set ``stop_task_before=True`` to stop it first.
+    To restart the task after modification, set ``restart_task_after=True``.
+
+    .. seealso::
+        For more information on how to use this operator, take a look at the guide:
+        :ref:`howto/operator:DmsModifyTaskOperator`
+
+    :param replication_task_arn: Replication task ARN
+    :param table_mappings: New table mappings. If not provided, existing mappings are kept.
+    :param migration_type: Migration type ('full-load'|'cdc'|'full-load-and-cdc').
+        If not provided, existing type is kept.
+    :param replication_task_settings: Task settings dict. If not provided, existing settings are kept.
+    :param cdc_start_time: Start time for CDC.
+    :param cdc_start_position: Indicates when to start CDC (checkpoint or LSN/SCN format).
+        Mutually exclusive with cdc_start_time.
+    :param cdc_stop_position: Indicates when to stop CDC.
+    :param stop_task_before: If True, stop the task before modifying if it is not already stopped.
+    :param restart_task_after: If True, restart the task after modifying.
+    :param start_replication_task_type: Start type used when restarting the task.
+        One of 'start-replication', 'resume-processing', or 'reload-target'.
+        Defaults to 'resume-processing'. Only used when ``restart_task_after=True``.
+    :param wait_for_completion: Only applies when the task is already in ``modifying`` state
+        when ``execute()`` is called. If True, wait for the modification to finish before
+        proceeding. If False, raises immediately instead of waiting.
+    :param deferrable: Run the operator in deferrable mode.
+    :param waiter_delay: Seconds between waiter polls (default: 30).
+    :param waiter_max_attempts: Maximum waiter poll attempts (default: 60).
+    :param aws_conn_id: The Airflow connection used for AWS credentials.
+        If this is ``None`` or empty then the default boto3 behaviour is used. If
+        running Airflow in a distributed manner and aws_conn_id is None or
+        empty, then default boto3 configuration would be used (and must be
+        maintained on each worker node).
+    :param region_name: AWS region_name. If not specified then the default boto3 behaviour is used.
+    :param verify: Whether or not to verify SSL certificates. See:
+        https://boto3.amazonaws.com/v1/documentation/api/latest/reference/core/session.html
+    :param botocore_config: Configuration dictionary (key-values) for botocore client. See:
+        https://botocore.amazonaws.com/v1/documentation/api/latest/reference/config.html
+    """
+
+    STOPPED_STATES = ("stopped", "ready", "failed", "created")
+    TERMINAL_STATES = frozenset({"failed", "stopped", "ready", "created", "deleting"})
+
+    aws_hook_class = DmsHook
+    template_fields: Sequence[str] = aws_template_fields(
+        "replication_task_arn",
+        "table_mappings",
+        "migration_type",
+        "replication_task_settings",
+        "cdc_start_time",
+        "cdc_start_position",
+        "cdc_stop_position",
+        "start_replication_task_type",
+    )
+    template_fields_renderers: ClassVar[dict] = {
+        "table_mappings": "json",
+        "replication_task_settings": "json",
+    }
+
+    def __init__(
+        self,
+        *,
+        replication_task_arn: str,
+        table_mappings: dict | None = None,
+        migration_type: str | None = None,
+        replication_task_settings: dict | None = None,
+        cdc_start_time: datetime | None = None,
+        cdc_start_position: str | None = None,
+        cdc_stop_position: str | None = None,
+        stop_task_before: bool = False,
+        restart_task_after: bool = False,
+        start_replication_task_type: str = "resume-processing",
+        wait_for_completion: bool = True,
+        deferrable: bool = conf.getboolean("operators", "default_deferrable", fallback=False),
+        waiter_delay: int = 30,
+        waiter_max_attempts: int = 60,
+        **kwargs,
+    ):
+        super().__init__(**kwargs)
+        if cdc_start_time and cdc_start_position:
+            raise ValueError("Only one of cdc_start_time or cdc_start_position can be provided.")
+        self.replication_task_arn = replication_task_arn
+        self.table_mappings = table_mappings
+        self.migration_type = migration_type
+        self.replication_task_settings = replication_task_settings
+        self.cdc_start_time = cdc_start_time
+        self.cdc_start_position = cdc_start_position
+        self.cdc_stop_position = cdc_stop_position
+        self.stop_task_before = stop_task_before
+        self.restart_task_after = restart_task_after
+        self.start_replication_task_type = start_replication_task_type
+        self.wait_for_completion = wait_for_completion
+        self.deferrable = deferrable
+        self.waiter_delay = waiter_delay
+        self.waiter_max_attempts = waiter_max_attempts
+
+    def execute(self, context: Context) -> dict:
+        tasks = self.hook.find_replication_tasks_by_arn(
+            replication_task_arn=self.replication_task_arn, without_settings=True
+        )
+        if not tasks:
+            raise AirflowException(f"Replication task {self.replication_task_arn} not found.")
+
+        current_status = tasks[0].get("Status", "").lower()
+        self.log.info(
+            "Current status of replication task(%s) is '%s'.", self.replication_task_arn, current_status
+        )
+
+        if current_status == "modifying":
+            # boto3 stopped/ready waiters treat 'modifying' as a terminal failure — use poll loop.
+            if not self.wait_for_completion:
+                raise AirflowException(
+                    f"Replication task {self.replication_task_arn} is already being modified. "
+                    f"Set wait_for_completion=True to wait for it to finish."
+                )
+            self._wait_until_not_modifying()
+        elif current_status not in self.STOPPED_STATES:
+            if not self.stop_task_before:
+                raise AirflowException(
+                    f"Replication task {self.replication_task_arn} is in state '{current_status}' "
+                    f"and must be stopped before modification. Set stop_task_before=True to stop it "
+                    f"automatically, or stop the task first."
+                )
+            if current_status == "starting":
+                # DMS rejects StopReplicationTask while the task is still starting up.
+                self.log.info(
+                    "Replication task(%s) is starting, waiting for it to reach 'running'.",
+                    self.replication_task_arn,
+                )
+                self._wait_for_status("running")
+            self.log.info("Stopping replication task(%s).", self.replication_task_arn)
+            self.hook.stop_replication_task(replication_task_arn=self.replication_task_arn)
+            self.log.info("Waiting for replication task(%s) to stop.", self.replication_task_arn)
+            if self.deferrable:

Review Comment:
   Fair point. The modify API is async — DMS puts the task in modifying for ~1 min regardless — so the deferrable path does save a worker slot during that wait. Happy to drop it if the preference is to keep things simpler.



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: commits-unsubscribe@airflow.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org