codeant-ai-for-open-source[bot] commented on code in PR #43627:
URL: https://github.com/apache/superset/pull/43627#discussion_r3876986065


##########
superset/commands/tasks/reap.py:
##########
@@ -0,0 +1,135 @@
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements.  See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership.  The ASF licenses this file
+# to you under the Apache License, Version 2.0 (the
+# "License"); you may not use this file except in compliance
+# with the License.  You may obtain a copy of the License at
+#
+#   http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing,
+# software distributed under the License is distributed on an
+# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+# KIND, either express or implied.  See the License for the
+# specific language governing permissions and limitations
+# under the License.
+"""Reap GTF tasks abandoned by a dead worker or wedged in ABORTING."""
+
+import logging
+from typing import cast
+
+from flask import current_app
+from superset_core.tasks.types import TaskProperties, TaskStatus
+
+from superset import db
+from superset.commands.base import BaseCommand
+from superset.daos.tasks import OrphanCandidate, TaskDAO
+from superset.extensions import celery_app
+from superset.stats_logger import BaseStatsLogger
+from superset.tasks.constants import ACTIVE_STATES
+from superset.tasks.utils import parse_properties
+
+logger = logging.getLogger(__name__)
+
+ORPHAN_ERROR_MESSAGE = "Task orphaned: worker heartbeat timed out"
+
+
+class ReapOrphanedTasksCommand(BaseCommand):
+    """Detect and clean up tasks abandoned by a dead or wedged worker.
+
+    Run from the prune cron before row deletion. Candidates come from
+    ``TaskDAO.find_orphaned``:
+
+    - **Orphans** (dead worker, stale heartbeat): revoke any lingering Celery
+      job, then force the row to FAILURE and publish completion so waiters
+      (sync joiners, DAG dependents, chart-data pollers) unblock — the worker 
is
+      gone and cannot finalize itself.
+    - **Wedged aborts** (live worker still ABORTING past the grace window): 
only
+      escalate with a forced revoke, letting the worker's own ``finally`` block
+      finalize the status once ``SoftTimeLimitExceeded`` is raised.
+
+    All Celery/DB operations are best-effort accelerators; the atomic
+    compare-and-swap transition is authoritative, so a worker that revives and
+    commits its own terminal status simply makes the reaper's CAS a no-op.
+    """
+
+    def run(self) -> int:
+        stats_logger: BaseStatsLogger = current_app.config["STATS_LOGGER"]
+        # A single threshold governs both "no heartbeat for this long → 
orphaned"
+        # and "ABORTING for this long despite a live heartbeat → escalate".
+        timeout = current_app.config["GTF_ORPHAN_TASK_TIMEOUT"]
+
+        candidates = TaskDAO.find_orphaned(timeout, timeout)
+        reaped = sum(self._process(candidate, stats_logger) for candidate in 
candidates)

Review Comment:
   **Suggestion:** The per-candidate processing is executed directly inside 
`sum`, and database failures from `conditional_status_update` or 
`db.session.commit()` are not converted to `CommandException` or isolated to 
the affected task. The scheduler catches only `CommandException`, so one 
transient database error aborts the reaper and prevents the retention pruning 
pass from running for that cron invocation. Handle failures at the command 
boundary and/or continue processing remaining candidates after recording the 
failure. [possible bug]
   
   <details>
   <summary><b>Severity Level:</b> Major ⚠️</summary>
   
   ```mdx
   - ⚠️ One database failure can stop the entire reaper loop.
   - ⚠️ Remaining orphan candidates wait for the next cron run.
   - ⚠️ Retention pruning is skipped for that invocation.
   ```
   </details>
   
   [![Use CodeAnt 
Skill](https://new-codeant-butcket.s3.us-west-1.amazonaws.com/badges/use-codeant-skill-flat-v2.svg)](https://docs.codeant.ai/cli/resolve-pr-comments-skill)
 [![Fix in 
Cursor](https://new-codeant-butcket.s3.us-west-1.amazonaws.com/badges/fix-in-cursor-flat.svg)](https://app.codeant.ai/fix-in-ide?tool=cursor&prompt_id=cca91dc76228462892f9ff7f24e48840&service=github&base_url=https%3A%2F%2Fgithub.com&org=apache&repo=apache%2Fsuperset)
 [![Fix in VSCode 
Claude](https://new-codeant-butcket.s3.us-west-1.amazonaws.com/badges/fix-in-vscode-claude-flat.svg)](https://app.codeant.ai/fix-in-ide?tool=vscode-claude&prompt_id=cca91dc76228462892f9ff7f24e48840&service=github&base_url=https%3A%2F%2Fgithub.com&org=apache&repo=apache%2Fsuperset)
   <details>
   <summary><b>Prompt for AI Agent 🤖 </b></summary>
   
   ```mdx
   This is a comment left during a code review.
   
   **Path:** superset/commands/tasks/reap.py
   **Line:** 63:64
   **Comment:**
        *Possible Bug: The per-candidate processing is executed directly inside 
`sum`, and database failures from `conditional_status_update` or 
`db.session.commit()` are not converted to `CommandException` or isolated to 
the affected task. The scheduler catches only `CommandException`, so one 
transient database error aborts the reaper and prevents the retention pruning 
pass from running for that cron invocation. Handle failures at the command 
boundary and/or continue processing remaining candidates after recording the 
failure.
   
   Validate the correctness of the flagged issue. If correct, How can I resolve 
this? If you propose a fix, implement it and please make it concise.
   Once fix is implemented, also check other comments on the same PR, and ask 
user if the user wants to fix the rest of the comments as well. if said yes, 
then fetch all the comments validate the correctness and implement a minimal fix
   ```
   </details>
   <a 
href='https://app.codeant.ai/feedback?pr_url=https%3A%2F%2Fgithub.com%2Fapache%2Fsuperset%2Fpull%2F43627&comment_hash=b7398befc8896ce25a4e060e43ee1b5632f8ff88e57af2128ebb041645f19f1d&reaction=like'>👍</a>
 | <a 
href='https://app.codeant.ai/feedback?pr_url=https%3A%2F%2Fgithub.com%2Fapache%2Fsuperset%2Fpull%2F43627&comment_hash=b7398befc8896ce25a4e060e43ee1b5632f8ff88e57af2128ebb041645f19f1d&reaction=dislike'>👎</a>



##########
superset/commands/tasks/reap.py:
##########
@@ -0,0 +1,135 @@
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements.  See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership.  The ASF licenses this file
+# to you under the Apache License, Version 2.0 (the
+# "License"); you may not use this file except in compliance
+# with the License.  You may obtain a copy of the License at
+#
+#   http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing,
+# software distributed under the License is distributed on an
+# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+# KIND, either express or implied.  See the License for the
+# specific language governing permissions and limitations
+# under the License.
+"""Reap GTF tasks abandoned by a dead worker or wedged in ABORTING."""
+
+import logging
+from typing import cast
+
+from flask import current_app
+from superset_core.tasks.types import TaskProperties, TaskStatus
+
+from superset import db
+from superset.commands.base import BaseCommand
+from superset.daos.tasks import OrphanCandidate, TaskDAO
+from superset.extensions import celery_app
+from superset.stats_logger import BaseStatsLogger
+from superset.tasks.constants import ACTIVE_STATES
+from superset.tasks.utils import parse_properties
+
+logger = logging.getLogger(__name__)
+
+ORPHAN_ERROR_MESSAGE = "Task orphaned: worker heartbeat timed out"
+
+
+class ReapOrphanedTasksCommand(BaseCommand):
+    """Detect and clean up tasks abandoned by a dead or wedged worker.
+
+    Run from the prune cron before row deletion. Candidates come from
+    ``TaskDAO.find_orphaned``:
+
+    - **Orphans** (dead worker, stale heartbeat): revoke any lingering Celery
+      job, then force the row to FAILURE and publish completion so waiters
+      (sync joiners, DAG dependents, chart-data pollers) unblock — the worker 
is
+      gone and cannot finalize itself.
+    - **Wedged aborts** (live worker still ABORTING past the grace window): 
only
+      escalate with a forced revoke, letting the worker's own ``finally`` block
+      finalize the status once ``SoftTimeLimitExceeded`` is raised.
+
+    All Celery/DB operations are best-effort accelerators; the atomic
+    compare-and-swap transition is authoritative, so a worker that revives and
+    commits its own terminal status simply makes the reaper's CAS a no-op.
+    """
+
+    def run(self) -> int:
+        stats_logger: BaseStatsLogger = current_app.config["STATS_LOGGER"]
+        # A single threshold governs both "no heartbeat for this long → 
orphaned"
+        # and "ABORTING for this long despite a live heartbeat → escalate".
+        timeout = current_app.config["GTF_ORPHAN_TASK_TIMEOUT"]
+
+        candidates = TaskDAO.find_orphaned(timeout, timeout)
+        reaped = sum(self._process(candidate, stats_logger) for candidate in 
candidates)
+        if candidates:
+            logger.info(
+                "Orphan reaper processed %d task(s), reaped %d", 
len(candidates), reaped
+            )
+        return reaped
+
+    def _process(
+        self, candidate: OrphanCandidate, stats_logger: BaseStatsLogger
+    ) -> bool:
+        """Handle one candidate; return True if it was reaped to FAILURE."""
+        # Preserve existing runtime state (is_abortable, timeout, 
celery_task_id,
+        # ...); conditional_status_update replaces the whole properties column.
+        properties = cast(TaskProperties, 
dict(parse_properties(candidate.properties)))
+        self._revoke(properties.get("celery_task_id"), stats_logger)

Review Comment:
   **Suggestion:** The reaper builds a complete properties dictionary from a 
stale candidate snapshot and writes it back atomically with only a status 
predicate. If the worker updates progress, abortability, or another runtime 
property after `find_orphaned` reads the row but before this update executes, 
the successful status transition replaces those newer properties and loses 
state. Update only the orphan error fields, or include a version/snapshot 
predicate in the compare-and-swap. [race condition]
   
   <details>
   <summary><b>Severity Level:</b> Major ⚠️</summary>
   
   ```mdx
   - ⚠️ Orphaned task progress metadata can be lost.
   - ⚠️ Runtime abortability and diagnostic properties can be overwritten.
   - ⚠️ Reaper retains stale Celery metadata after concurrent updates.
   ```
   </details>
   
   [![Use CodeAnt 
Skill](https://new-codeant-butcket.s3.us-west-1.amazonaws.com/badges/use-codeant-skill-flat-v2.svg)](https://docs.codeant.ai/cli/resolve-pr-comments-skill)
 [![Fix in 
Cursor](https://new-codeant-butcket.s3.us-west-1.amazonaws.com/badges/fix-in-cursor-flat.svg)](https://app.codeant.ai/fix-in-ide?tool=cursor&prompt_id=e4289209f4a34b83a8de4929b0a3e224&service=github&base_url=https%3A%2F%2Fgithub.com&org=apache&repo=apache%2Fsuperset)
 [![Fix in VSCode 
Claude](https://new-codeant-butcket.s3.us-west-1.amazonaws.com/badges/fix-in-vscode-claude-flat.svg)](https://app.codeant.ai/fix-in-ide?tool=vscode-claude&prompt_id=e4289209f4a34b83a8de4929b0a3e224&service=github&base_url=https%3A%2F%2Fgithub.com&org=apache&repo=apache%2Fsuperset)
   <details>
   <summary><b>Prompt for AI Agent 🤖 </b></summary>
   
   ```mdx
   This is a comment left during a code review.
   
   **Path:** superset/commands/tasks/reap.py
   **Line:** 77:78
   **Comment:**
        *Race Condition: The reaper builds a complete properties dictionary 
from a stale candidate snapshot and writes it back atomically with only a 
status predicate. If the worker updates progress, abortability, or another 
runtime property after `find_orphaned` reads the row but before this update 
executes, the successful status transition replaces those newer properties and 
loses state. Update only the orphan error fields, or include a version/snapshot 
predicate in the compare-and-swap.
   
   Validate the correctness of the flagged issue. If correct, How can I resolve 
this? If you propose a fix, implement it and please make it concise.
   Once fix is implemented, also check other comments on the same PR, and ask 
user if the user wants to fix the rest of the comments as well. if said yes, 
then fetch all the comments validate the correctness and implement a minimal fix
   ```
   </details>
   <a 
href='https://app.codeant.ai/feedback?pr_url=https%3A%2F%2Fgithub.com%2Fapache%2Fsuperset%2Fpull%2F43627&comment_hash=1d8a4095c15634b5e130f0fa3ebc040338992954c1ad72b4ddc45bb878e7fa2f&reaction=like'>👍</a>
 | <a 
href='https://app.codeant.ai/feedback?pr_url=https%3A%2F%2Fgithub.com%2Fapache%2Fsuperset%2Fpull%2F43627&comment_hash=1d8a4095c15634b5e130f0fa3ebc040338992954c1ad72b4ddc45bb878e7fa2f&reaction=dislike'>👎</a>



-- 
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]


---------------------------------------------------------------------
To unsubscribe, e-mail: [email protected]
For additional commands, e-mail: [email protected]

Reply via email to