amoghrajesh commented on code in PR #76106:
URL: https://github.com/apache/airflow/pull/76106#discussion_r4664641437


##########
providers/snowflake/src/airflow/providers/snowflake/operators/snowpark_containers.py:
##########
@@ -147,13 +181,17 @@ def __init__(
         self.poll_interval = poll_interval
         self.snowflake_conn_id = snowflake_conn_id
         self.deferrable = deferrable
+        self.cancel_on_kill = cancel_on_kill
         self.timeout = timeout
         self.database = database
         self.schema = schema
         self.role = role
         self.warehouse = warehouse
         # Set after the job is submitted, parsed from the job submission 
response.
         self.job_name: str | None = None
+        # On a fresh submit the mixin runs both poll_until_complete and 
get_job_result.

Review Comment:
   The "finalize only once" reason is explained three times (lines 192-193, 
296-297, and the docstring at 306). That is 13 added comments and docstrings 
across the operator file, and 2 are trimmable. Keep it once, at the source.



##########
providers/snowflake/src/airflow/providers/snowflake/operators/snowpark_containers.py:
##########
@@ -94,6 +120,8 @@ class SnowparkContainerJobOperator(BaseOperator):
         own SQL commands, not for the container's queries
     """
 
+    external_id_key = "snowpark_container_job_name"
+    _job_status_key = "snowpark_container_job_status"

Review Comment:
   `_job_status_key` reads as "the job's status". It only ever stores a 
`{job_name: "DONE"}` marker. Rename to `_job_done_marker_key`.



##########
providers/snowflake/src/airflow/providers/snowflake/operators/snowpark_containers.py:
##########
@@ -187,18 +225,54 @@ def _build_sql(self) -> str:
             sql += f" FROM {self.spec_stage} SPEC = '{self.spec}'"
         return sql
 
-    def _run_one(self, sql: str, return_dictionaries: bool = False) -> Any:
+    def _run_one(
+        self, sql: str, return_dictionaries: bool = False, parameters: 
dict[str, Any] | None = None
+    ) -> Any:
         """Run a single statement that returns one row via 
fetch_one_handler."""
-        return self._hook.run(sql, handler=fetch_one_handler, 
return_dictionaries=return_dictionaries)
+        return self._hook.run(
+            sql, parameters=parameters, handler=fetch_one_handler, 
return_dictionaries=return_dictionaries
+        )
+
+    def _describe_status(self, external_id: JsonValue) -> str:
+        """Describe the job's current status."""
+        response = self._run_one(f"DESCRIBE SERVICE {external_id}", 
return_dictionaries=True)
+        return response.get("status")
 
-    def _submit_job(self) -> str:
+    def submit_job(self, context: Context) -> str:
         """Submit the job and return the name."""
         response = self._run_one(self._build_sql())
-        job_name = response[0].split("'")[1]
-        return job_name
+        self.job_name = response[0].split("'")[1]
+        if not self.job_name:
+            raise RuntimeError("Job name was not returned")
+        return self.job_name
+
+    def get_job_status(self, external_id: JsonValue, context: Context) -> str:
+        """Return DONE if a prior try stored it, NOT_FOUND if the service is 
gone, else the current status."""
+        job_name = _validate_job_name(external_id)

Review Comment:
   `_validate_job_name` rejects qualified or quoted names that `name` (line 
213) accepts. If Snowflake echoes `DB.SCHEMA.JOB` back, the first try works but 
every retry raises `ValueError` before it can submit. Bind the name with 
`IDENTIFIER(%(job_name)s)` in `DESCRIBE SERVICE` and `DROP SERVICE`, and keep 
only the `isinstance(str)` check.



##########
providers/snowflake/tests/unit/snowflake/operators/test_snowpark_containers.py:
##########
@@ -449,3 +495,249 @@ def 
test_execute_complete_timeout_skips_drop_when_disabled(self, mock_log, mock_
             )
         mock_log.assert_called_once_with("timeout")
         mock_hook.run.assert_not_called()
+
+
[email protected](
+    not AIRFLOW_V_3_3_PLUS, reason="task_state_store (durable execution) 
requires Airflow 3.3+"
+)
+class TestSnowparkContainerJobOperatorDurable:
+    @mock.patch.object(SnowparkContainerJobOperator, "_handle_final_status")
+    @mock.patch.object(SnowparkContainerJobOperator, "submit_job", 
return_value=JOB_NAME)
+    @mock.patch(MOCK_HOOK_PATH)
+    def test_job_name_persists_to_task_state_store_on_fresh_submit(
+        self, mock_hook_cls, mock_submit_job, mock_handle
+    ):
+        mock_hook = mock_hook_cls.return_value
+        mock_hook.run.return_value = {"status": "DONE"}
+
+        op = _make_operator(poll_interval=0)
+        task_store = mock.MagicMock(spec_set=["get", "set"])
+        task_store.get.return_value = None
+
+        op.execute(context=_context(task_store=task_store))
+
+        task_store.get.assert_called_once_with(op.external_id_key)
+        assert task_store.set.call_args_list == [
+            mock.call(op.external_id_key, JOB_NAME),
+            mock.call(op._job_status_key, {JOB_NAME: "DONE"}),
+        ]
+        mock_handle.assert_called_once_with(status="DONE")
+
+    @mock.patch("time.sleep")
+    @mock.patch.object(SnowparkContainerJobOperator, "_handle_final_status")
+    @mock.patch.object(SnowparkContainerJobOperator, "submit_job")
+    @mock.patch(MOCK_HOOK_PATH)
+    def test_reconnects_to_running_job_without_resubmitting(
+        self, mock_hook_cls, mock_submit_job, mock_handle, mock_sleep
+    ):
+        mock_hook = mock_hook_cls.return_value
+        mock_hook.run.side_effect = [
+            {"status": "RUNNING"},
+            {"status": "DONE"},
+        ]
+
+        op = _make_operator(poll_interval=5)
+        task_store = mock.MagicMock(spec_set=["get", "set"])
+        task_store.get.return_value = JOB_NAME
+
+        result = op.execute(context=_context(task_store=task_store))
+
+        assert task_store.get.call_args_list == 
[mock.call(op.external_id_key), mock.call(op._job_status_key)]
+        task_store.set.assert_called_once_with(op._job_status_key, {JOB_NAME: 
"DONE"})
+        mock_submit_job.assert_not_called()
+        mock_handle.assert_called_once_with(status="DONE")
+        assert result == JOB_NAME
+
+    @mock.patch.object(SnowparkContainerJobOperator, "_handle_final_status")
+    @mock.patch.object(SnowparkContainerJobOperator, "poll_until_complete")
+    @mock.patch.object(SnowparkContainerJobOperator, "submit_job")
+    @mock.patch(MOCK_HOOK_PATH)
+    def test_already_succeeded_completes_without_polling(
+        self, mock_hook_cls, mock_submit_job, mock_poll_until_complete, 
mock_handle
+    ):
+        mock_hook = mock_hook_cls.return_value
+        mock_hook.run.side_effect = [{"status": "DONE"}]
+
+        op = _make_operator(poll_interval=5)
+        task_store = mock.MagicMock(spec_set=["get", "set"])
+        task_store.get.return_value = JOB_NAME
+
+        op.execute(context=_context(task_store=task_store))
+
+        assert task_store.get.call_args_list == 
[mock.call(op.external_id_key), mock.call(op._job_status_key)]
+        mock_submit_job.assert_not_called()
+        mock_poll_until_complete.assert_not_called()
+        mock_handle.assert_called_once_with(status="DONE")
+
+    @mock.patch.object(SnowparkContainerJobOperator, "_handle_final_status")
+    @mock.patch.object(SnowparkContainerJobOperator, "poll_until_complete")
+    @mock.patch.object(SnowparkContainerJobOperator, "get_job_status")
+    @mock.patch.object(SnowparkContainerJobOperator, "submit_job")
+    @mock.patch(MOCK_HOOK_PATH)
+    def test_resubmits_when_stored_job_in_terminal_error(

Review Comment:
   This test never checks that the new job is polled, so half of the resubmit 
path is unchecked. Add 
`mock_poll_until_complete.assert_called_once_with(f"{JOB_NAME}_2", mock.ANY)`.
   



-- 
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: [email protected]

For queries about this service, please contact Infrastructure at:
[email protected]

Reply via email to