You are viewing a plain text version of this content. The canonical link for it is here.
Posted to notifications@superset.apache.org by "villebro (via GitHub)" <gi...@apache.org> on 2026/08/28 00:41:43 UTC

[PR] feat(gtf): heartbeat orphan reaping + cancellable chart-data queries [superset]

villebro opened a new pull request, #43627:
URL: https://github.com/apache/superset/pull/43627

   ### SUMMARY
   
   Part of the GAQ→GTF epic (targets `gaq-to-gtf`, not `master`). Two resilience gaps remained in the Global Task Framework once async chart data moved onto it, both called out in the code itself:
   
   1. **Orphaned tasks** — a worker killed mid-execution (OOM, SIGKILL, crash, lost broker message) left the `Task` row stuck `IN_PROGRESS` forever and its Celery job a zombie. `prune_tasks` only deleted *old terminal* rows; the only backstop was client-side (`GLOBAL_ASYNC_QUERIES_POLLING_STALE_TIMEOUT`), which just makes the browser give up while the task + Celery job + warehouse query keep running.
   2. **Non-cancellable queries** — `execute_chart_query` deliberately set no timeout and no abort handler, because the chart-data path (`Database.get_df` → `db_engine_spec.execute`) has none of SQL Lab's cancellation plumbing, so a GTF abort/timeout only flipped the row terminal while the warehouse kept churning.
   
   This PR adds a worker **heartbeat + orphan reaper** (folded into the existing `prune_tasks` cron) and makes chart-data query tasks **cancellable** on engines that support it, then restores an (opt-in) per-query timeout.
   
   #### What GAQ had, what GTF has today, and what this adds
   
   | Capability | Legacy GAQ | GTF (today, pre-PR) | After this PR |
   |---|---|---|---|
   | Detect a worker that died mid-task | ❌ none | ❌ none (task stuck `IN_PROGRESS` forever) | ✅ liveness heartbeat + reaper marks it `FAILURE` |
   | Kill the Celery job | ✅ `revoke(terminate, SIGUSR1)` | ❌ cooperative DB abort only | ✅ tiered: cooperative first, forced `revoke` as escalation/reaper |
   | Reclaim a wedged worker slot | ✅ (blunt `revoke`) | ❌ (task must cooperate) | ✅ reaper force-`revoke`s a task wedged in `ABORTING` |
   | Graceful cleanup on cancel | ⚠️ can interrupt mid-cleanup | ✅ `on_abort` / `on_cleanup` run | ✅ preserved (cooperative path runs first) |
   | Cancel the actual warehouse query | ⚠️ SQL-Lab STOPPED flag only, not chart data | ❌ none for chart data | ✅ engine `cancel_query` over a fresh connection (supported engines) |
   | Per-query timeout for async chart data | ❌ | ❌ (removed pending cancellation) | ✅ opt-in `GLOBAL_ASYNC_QUERIES_QUERY_TIMEOUT` |
   | Terminal state after a cancelled query | ⚠️ marked failed/cancelled ad hoc | n/a | ✅ `ABORTED` / `TIMED_OUT` (not `FAILURE`) |
   | Source of truth | Redis job registry / flags | DB `Task` row (CAS) | DB `Task` row (CAS); `revoke`/`cancel` are best-effort accelerators |
   
   #### Design notes
   
   - **Heartbeat** (`superset/tasks/heartbeat.py`): while a worker holds a task it bumps `tasks.last_heartbeat` on a daemon thread every `GTF_TASK_HEARTBEAT_INTERVAL` (default 15s). The write is a raw `text()` UPDATE so it **never advances `changed_on`** — otherwise every heartbeat would resurface the task in the `status_changes` poll and reset client backoff. `execute_task` is split into a thin wrapper (records the Celery job id, wraps the body in the heartbeat) + `_execute_task_body`; the heartbeat starts **before** the DAG gate so a task blocked on prerequisites still counts as alive.
   - **Reaper** (`ReapOrphanedTasksCommand`, run from `prune_tasks` before deletion): a dead-worker orphan (stale heartbeat) is `revoke`d + CAS-transitioned to `FAILURE` + `publish_completion` (so waiters/DAG dependents/pollers unblock); a live worker wedged in `ABORTING` past the grace window is force-`revoke`d only, letting its own `finally` finalize. The CAS is authoritative, so a revived worker that already committed a terminal status just no-ops the reaper.
   - **Query cancellation** (`superset/tasks/query_cancel.py`): a contextvar cursor-capture seam (hooked into `Database._execute_sql_with_mutation_and_logging` before the blocking execute) lets the task capture an engine cancel id via `db_engine_spec.get_cancel_query_id`; the abort handler then kills the backend over a fresh connection (`cancel_chart_query`, mirroring `sql_lab.cancel_query`). Cancellation auto-enables **per engine** — Postgres/MySQL/Snowflake/Redshift are cancellable; engines without cancel support stay non-abortable and behave exactly as before.
   - **Metrics** on every op: `gtf.task.heartbeat`, `gtf.task.heartbeat_failure`, `gtf.task.orphan_reaped`, `gtf.task.revoke`, `gtf.task.revoke_failure`, `gtf.task.abort_escalated`, `gtf.query.cancel`, `gtf.query.cancel_failed`.
   
   #### Known follow-up (intentionally out of scope)
   
   Out-of-band cancellation of an **orphan's** warehouse query (from the reaper) is deferred — it needs the cancel handle persisted on the task, which races the wholesale `properties` writes. The reaper still revokes + fails the orphaned task; its abandoned query relies on warehouse-side timeouts until then. **Live** user-abort/timeout cancellation is fully implemented.
   
   ### TESTING INSTRUCTIONS
   
   - Unit + integration: `pytest tests/unit_tests/tasks/ tests/integration_tests/tasks/commands/test_reap.py` — 408 unit tests pass. New coverage: heartbeat lifecycle/failure, `find_orphaned` orphan + wedged-abort selection (DB-backed), all reaper branches (orphan / wedged / CAS-race / no-celery-id), the executor except-guard (a cancel-induced exception ends `TIMED_OUT`/`ABORTED`, not `FAILURE`), `touch_heartbeat` not advancing `changed_on`, and the full cancel seam (capture / notify / cancel success / decline / exception).
   - Manual (needs `DISTRIBUTED_COORDINATION_CONFIG` + a Celery worker + `celery beat` running `prune_tasks` on a short interval): submit an async chart query, `kill -9` the worker mid-query → within `GTF_ORPHAN_TASK_TIMEOUT` the task flips to `FAILURE` and its Celery job is revoked. Then, on a supported engine, abort a long-running query from the UI (or set `GLOBAL_ASYNC_QUERIES_QUERY_TIMEOUT`) and confirm the warehouse query is gone (e.g. `pg_stat_activity`) and the task ends `ABORTED`/`TIMED_OUT`.
   
   ### ADDITIONAL INFORMATION
   
   - [ ] Has associated issue:
   - [x] Required feature flags: `GLOBAL_TASK_FRAMEWORK` (async chart data also needs `GLOBAL_ASYNC_QUERIES`)
   - [ ] Changes UI
   - [x] Includes DB Migration (follow approval process in [SIP-59](https://github.com/apache/superset/issues/13351))
     - [x] Migration is atomic, supports rollback & is backwards-compatible
     - [ ] Confirm DB migration upgrade and downgrade tested
     - [ ] Runtime estimates and downtime expectations provided
   - [x] Introduces new feature or API
   - [ ] Removes existing feature or API
   
   <sub>Note: the `tasks.last_heartbeat` column is folded into the branch's existing task-schema migration `7e2c9a4f1b83` (nullable add + index, reversible) rather than a new revision, matching how `guest_key` was folded — so there is no new migration file.</sub>
   


-- 
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: notifications-unsubscribe@superset.apache.org

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


---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org


Re: [PR] feat(gtf): heartbeat orphan reaping + cancellable chart-data queries [superset]

Posted by "codeant-ai-for-open-source[bot] (via GitHub)" <gi...@apache.org>.
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: notifications-unsubscribe@superset.apache.org

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


---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org


Re: [PR] feat(gtf): heartbeat orphan reaping + cancellable chart-data queries [superset]

Posted by "codecov[bot] (via GitHub)" <gi...@apache.org>.
codecov[bot] commented on PR #43627:
URL: https://github.com/apache/superset/pull/43627#issuecomment-5447053497

   ## [Codecov](https://app.codecov.io/gh/apache/superset/pull/43627?dropdown=coverage&src=pr&el=h1&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache) Report
   :x: Patch coverage is `61.57635%` with `78 lines` in your changes missing coverage. Please review.
   :white_check_mark: Project coverage is 66.18%. Comparing base ([`26d556c`](https://app.codecov.io/gh/apache/superset/commit/26d556c73dc9e3d97b596c6f25c2ca1826871a0d?dropdown=coverage&el=desc&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache)) to head ([`48a97c9`](https://app.codecov.io/gh/apache/superset/commit/48a97c9da1b24fa34e085f68a740b41b59dea0f4?dropdown=coverage&el=desc&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache)).
   
   | [Files with missing lines](https://app.codecov.io/gh/apache/superset/pull/43627?dropdown=coverage&src=pr&el=tree&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache) | Patch % | Lines |
   |---|---|---|
   | [superset/tasks/query\_cancel.py](https://app.codecov.io/gh/apache/superset/pull/43627?src=pr&el=tree&filepath=superset%2Ftasks%2Fquery_cancel.py&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache#diff-c3VwZXJzZXQvdGFza3MvcXVlcnlfY2FuY2VsLnB5) | 35.00% | [25 Missing and 1 partial :warning: ](https://app.codecov.io/gh/apache/superset/pull/43627?src=pr&el=tree&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache) |
   | [superset/tasks/async\_queries.py](https://app.codecov.io/gh/apache/superset/pull/43627?src=pr&el=tree&filepath=superset%2Ftasks%2Fasync_queries.py&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache#diff-c3VwZXJzZXQvdGFza3MvYXN5bmNfcXVlcmllcy5weQ==) | 22.22% | [21 Missing :warning: ](https://app.codecov.io/gh/apache/superset/pull/43627?src=pr&el=tree&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache) |
   | [superset/commands/tasks/reap.py](https://app.codecov.io/gh/apache/superset/pull/43627?src=pr&el=tree&filepath=superset%2Fcommands%2Ftasks%2Freap.py&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache#diff-c3VwZXJzZXQvY29tbWFuZHMvdGFza3MvcmVhcC5weQ==) | 74.50% | [9 Missing and 4 partials :warning: ](https://app.codecov.io/gh/apache/superset/pull/43627?src=pr&el=tree&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache) |
   | [superset/tasks/scheduler.py](https://app.codecov.io/gh/apache/superset/pull/43627?src=pr&el=tree&filepath=superset%2Ftasks%2Fscheduler.py&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache#diff-c3VwZXJzZXQvdGFza3Mvc2NoZWR1bGVyLnB5) | 53.84% | [11 Missing and 1 partial :warning: ](https://app.codecov.io/gh/apache/superset/pull/43627?src=pr&el=tree&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache) |
   | [superset/tasks/heartbeat.py](https://app.codecov.io/gh/apache/superset/pull/43627?src=pr&el=tree&filepath=superset%2Ftasks%2Fheartbeat.py&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache#diff-c3VwZXJzZXQvdGFza3MvaGVhcnRiZWF0LnB5) | 80.00% | [5 Missing and 1 partial :warning: ](https://app.codecov.io/gh/apache/superset/pull/43627?src=pr&el=tree&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache) |
   > :exclamation:  There is a different number of reports uploaded between BASE (26d556c) and HEAD (48a97c9). Click for more details.
   > 
   > <details><summary>HEAD has 3 uploads less than BASE</summary>
   >
   >| Flag | BASE (26d556c) | HEAD (48a97c9) |
   >|------|------|------|
   >|python|6|3|
   ></details>
   
   <details><summary>Additional details and impacted files</summary>
   
   
   
   ```diff
   @@               Coverage Diff               @@
   ##           gaq-to-gtf   #43627       +/-   ##
   ===============================================
   - Coverage       79.25%   66.18%   -13.08%     
   ===============================================
     Files            2887     2890        +3     
     Lines          166194   166385      +191     
     Branches        38448    38461       +13     
   ===============================================
   - Hits           131724   110114    -21610     
   - Misses          31992    54035    +22043     
   + Partials         2478     2236      -242     
   ```
   
   | [Flag](https://app.codecov.io/gh/apache/superset/pull/43627/flags?src=pr&el=flags&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache) | Coverage Δ | |
   |---|---|---|
   | [hive](https://app.codecov.io/gh/apache/superset/pull/43627/flags?src=pr&el=flag&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache) | `37.99% <33.99%> (-0.02%)` | :arrow_down: |
   | [mysql](https://app.codecov.io/gh/apache/superset/pull/43627/flags?src=pr&el=flag&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache) | `?` | |
   | [postgres](https://app.codecov.io/gh/apache/superset/pull/43627/flags?src=pr&el=flag&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache) | `?` | |
   | [presto](https://app.codecov.io/gh/apache/superset/pull/43627/flags?src=pr&el=flag&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache) | `39.91% <35.96%> (-0.02%)` | :arrow_down: |
   | [python](https://app.codecov.io/gh/apache/superset/pull/43627/flags?src=pr&el=flag&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache) | `57.48% <61.57%> (-26.35%)` | :arrow_down: |
   | [sqlite](https://app.codecov.io/gh/apache/superset/pull/43627/flags?src=pr&el=flag&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache) | `57.35% <61.57%> (+0.01%)` | :arrow_up: |
   | [unit](https://app.codecov.io/gh/apache/superset/pull/43627/flags?src=pr&el=flag&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache) | `?` | |
   
   Flags with carried forward coverage won't be shown. [Click here](https://docs.codecov.io/docs/carryforward-flags?utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache#carryforward-flags-in-the-pull-request-comment) to find out more.
   </details>
   
   [:umbrella: View full report in Codecov by Harness](https://app.codecov.io/gh/apache/superset/pull/43627?dropdown=coverage&src=pr&el=continue&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache).   
   :loudspeaker: Have feedback on the report? [Share it here](https://about.codecov.io/codecov-pr-comment-feedback/?utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache).
   <details><summary> :rocket: New features to boost your workflow: </summary>
   
   - :snowflake: [Test Analytics](https://docs.codecov.com/docs/test-analytics): Detect flaky tests, report on failures, and find test suite problems.
   - :package: [JS Bundle Analysis](https://docs.codecov.com/docs/javascript-bundle-analysis): Save yourself from yourself by tracking and limiting bundle sizes in JS merges.
   </details>


-- 
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: notifications-unsubscribe@superset.apache.org

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


---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org


Re: [PR] feat(gtf): heartbeat orphan reaping + cancellable chart-data queries [superset]

Posted by "netlify[bot] (via GitHub)" <gi...@apache.org>.
netlify[bot] commented on PR #43627:
URL: https://github.com/apache/superset/pull/43627#issuecomment-5446947177

   ### <span aria-hidden="true">✅</span> Deploy Preview for *superset-docs-preview* ready!
   
   
   |  Name | Link |
   |:-:|------------------------|
   |<span aria-hidden="true">🔨</span> Latest commit | 48a97c9da1b24fa34e085f68a740b41b59dea0f4 |
   |<span aria-hidden="true">🔍</span> Latest deploy log | https://app.netlify.com/projects/superset-docs-preview/deploys/6a90d94700aa240008342b07 |
   |<span aria-hidden="true">😎</span> Deploy Preview | [https://deploy-preview-43627--superset-docs-preview.netlify.app](https://deploy-preview-43627--superset-docs-preview.netlify.app) |
   |<span aria-hidden="true">📱</span> Preview on mobile | <details><summary> Toggle QR Code... </summary><br /><br />![QR Code](https://app.netlify.com/qr-code/eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1cmwiOiJodHRwczovL2RlcGxveS1wcmV2aWV3LTQzNjI3LS1zdXBlcnNldC1kb2NzLXByZXZpZXcubmV0bGlmeS5hcHAifQ.tDujgBtFe71RindsVxoHpCp3cEK6Rzj06qASos1sNeI)<br /><br />_Use your smartphone camera to open QR code link._</details> |
   |<span aria-hidden="true">🤖</span> Make changes | [Run an agent on this branch](https://app.netlify.com/projects/superset-docs-preview/agent-runs#DYvbCYAwDAB3ybdi0GKtGzhGauMDYltKEETc3f4d3N0LuaQrK8wADfhCcT0q36cI-5K6Xbf2YCrqmbRdq2YR0jPFmgfOkp4l1GEkh8EZi0jUG0ScBtN7tPD9) |
   ---
   <!-- [superset-docs-preview Preview](https://deploy-preview-43627--superset-docs-preview.netlify.app) -->
   _To edit notification comments on pull requests, go to your [Netlify project configuration](https://app.netlify.com/projects/superset-docs-preview/configuration/notifications#deploy-notifications)._


-- 
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: notifications-unsubscribe@superset.apache.org

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


---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org


Re: [PR] feat(gtf): heartbeat orphan reaping + cancellable chart-data queries [superset]

Posted by "villebro (via GitHub)" <gi...@apache.org>.
villebro commented on PR #43627:
URL: https://github.com/apache/superset/pull/43627#issuecomment-5448302747

   Follow-up (`7ce5c3f9e3`) — tightened the design after a self-review of the cancellation logic:
   
   - **Removed the "wedged-ABORTING" escalation and dropped `terminate=True` from the reaper's revoke.** Layering forced Celery termination on top of the cooperative `on_abort` path was redundant and risky: orphan detection is heartbeat-based, and a healthy but CPU-bound task can briefly starve its own heartbeat thread, so `terminate=True` could fire `SoftTimeLimitExceeded` into live, healthy work on a false positive. It also duplicated a mechanism the cooperative path already owns.
   - The reaper now recovers **only** tasks with no live worker (stale heartbeat): transition to `FAILURE`, release waiters, and `revoke` **without** `terminate` (prevents a redelivered job from re-running under `task_acks_late`; never signals a running process). Cooperative cancellation of live workers is unchanged, and query cancellation stays entirely within the existing `on_abort` mechanism — no parallel/conflicting cancellation path.
   
   Also rewrote the PR description to be objective (dropped the "zombie" framing — a worker that ends mid-task simply leaves the row unresolved).
   


-- 
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: notifications-unsubscribe@superset.apache.org

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


---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org


Re: [PR] feat(gtf): heartbeat orphan reaping + cancellable chart-data queries [superset]

Posted by "sadpandajoe (via GitHub)" <gi...@apache.org>.
sadpandajoe commented on code in PR #43627:
URL: https://github.com/apache/superset/pull/43627#discussion_r3879575782


##########
superset/migrations/versions/2026-08-21_12-00_7e2c9a4f1b83_create_task_dependencies_table.py:
##########
@@ -148,9 +148,22 @@ def upgrade():
             "uq_task_subscribers_task_guest", ["task_id", "guest_key"]
         )
 
+    # Liveness marker for orphan detection: the executing worker bumps
+    # ``tasks.last_heartbeat`` on a background thread, and the prune cron reaps
+    # ACTIVE tasks whose heartbeat has gone stale (a dead/orphaned worker). The
+    # index backs the reaper's ``last_heartbeat < now - timeout`` scan.
+    add_columns(

Review Comment:
   Upgrades that already ran this revision will never execute these added DDL statements, so their `tasks` table lacks `last_heartbeat` and the new heartbeat/reaper paths fail at runtime. Could this column and index be added in a new migration revision instead?



-- 
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: notifications-unsubscribe@superset.apache.org

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


---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org


Re: [PR] feat(gtf): heartbeat orphan reaping + cancellable chart-data queries [superset]

Posted by "villebro (via GitHub)" <gi...@apache.org>.
villebro commented on code in PR #43627:
URL: https://github.com/apache/superset/pull/43627#discussion_r3881858355


##########
superset/migrations/versions/2026-08-21_12-00_7e2c9a4f1b83_create_task_dependencies_table.py:
##########
@@ -148,9 +148,22 @@ def upgrade():
             "uq_task_subscribers_task_guest", ["task_id", "guest_key"]
         )
 
+    # Liveness marker for orphan detection: the executing worker bumps
+    # ``tasks.last_heartbeat`` on a background thread, and the prune cron reaps
+    # ACTIVE tasks whose heartbeat has gone stale (a dead/orphaned worker). The
+    # index backs the reaper's ``last_heartbeat < now - timeout`` scan.
+    add_columns(

Review Comment:
   This is intentional - this is against a feature branch, so no point in adding multiple separate migrations as the final PR will be squashed to a single commit when merged to master.



-- 
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: notifications-unsubscribe@superset.apache.org

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


---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org


Re: [PR] feat(gtf): heartbeat orphan reaping + cancellable chart-data queries [superset]

Posted by "bito-code-review[bot] (via GitHub)" <gi...@apache.org>.
bito-code-review[bot] commented on PR #43627:
URL: https://github.com/apache/superset/pull/43627#issuecomment-5446937098

   AI Code Review is in progress (usually takes 3 to 15 minutes unless it's a very large PR).


-- 
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: notifications-unsubscribe@superset.apache.org

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


---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org


Re: [PR] feat(gtf): heartbeat orphan reaping + cancellable chart-data queries [superset]

Posted by "villebro (via GitHub)" <gi...@apache.org>.
villebro commented on PR #43627:
URL: https://github.com/apache/superset/pull/43627#issuecomment-5447541799

   Thanks for the review — addressed in `58893a8a54`, plus a fix for the MySQL CI failure:
   
   - **Reaper aborts on one DB error (Major):** each candidate is now processed in its own `try/except` that rolls back and continues on failure (metric `gtf.task.reap_error`), so a transient error can neither abort the loop nor escape as a non-`CommandException` and skip the retention prune pass.
   - **Reaper stale-snapshot clobber (Major):** the FAILURE transition now re-reads the task's current `properties` immediately before the CAS (instead of reusing the possibly batch-stale `find_orphaned` snapshot), so a concurrently-written runtime property isn't overwritten. The status CAS remains the authority; for a genuine orphan the worker is dead and cannot race it.
   - **`None` query arg breaks Ocient/Impala (Major):** replaced `None` with a minimal `_CancellationQuery` stand-in exposing `database`, `id=None`, and the `extra` accessors. Impala/Ocient no longer `AttributeError`; an engine that cancels by query id sees `id=None` and declines gracefully via `validate_cancel_query_id` rather than raising.
   - **Regression test can pass without finalizing (Minor):** the executor abort/timeout tests now assert the `ABORTING → TIMED_OUT`/`ABORTED` transition was actually issued (correct `new_status` + `expected_status=ABORTING`), not just that the result echoes the fixture.
   
   **CI:** the `test-mysql` failure was `test_touch_heartbeat_does_not_advance_changed_on` comparing an in-memory `changed_on` (microseconds) against a post-`refresh()` value, which MySQL `DATETIME` truncates to whole seconds (Postgres/SQLite keep microseconds, so they passed). Fixed by reading the baseline back at column precision first.
   


-- 
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: notifications-unsubscribe@superset.apache.org

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


---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org


Re: [PR] feat(gtf): heartbeat orphan reaping + cancellable chart-data queries [superset]

Posted by "codeant-ai-for-open-source[bot] (via GitHub)" <gi...@apache.org>.
codeant-ai-for-open-source[bot] commented on code in PR #43627:
URL: https://github.com/apache/superset/pull/43627#discussion_r3876989389


##########
superset/tasks/query_cancel.py:
##########
@@ -0,0 +1,131 @@
+# 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.
+"""Engine-level cancellation for GTF chart-data query tasks.
+
+The chart-data execution path (``Database.get_df``) has none of SQL Lab's
+cancel plumbing, so a GTF abort/timeout could only mark the task terminal while
+the warehouse query kept running. This module adds the missing seam:
+
+- ``capture_cancel_id`` registers a cursor sink for the duration of a task's
+  query; ``notify_cursor`` (called from ``get_df`` before the blocking execute)
+  hands the live cursor to that sink so the task can capture an engine cancel id
+  via ``db_engine_spec.get_cancel_query_id`` — the same contract SQL Lab uses.
+- ``cancel_chart_query`` kills the backend session over a *fresh* connection
+  (``db_engine_spec.cancel_query``), which unblocks the task's blocked ``get_df``.
+
+Only engines that return a cancel id before execution participate; others
+capture nothing and are simply not cancellable (the abort still frees the task).
+"""
+
+from __future__ import annotations
+
+import logging
+from contextlib import closing, contextmanager
+from contextvars import ContextVar
+from typing import Any, Callable, Iterator, TYPE_CHECKING
+
+from superset.stats_logger import BaseStatsLogger
+
+if TYPE_CHECKING:
+    from flask import Flask
+
+    from superset.models.core import Database
+
+logger = logging.getLogger(__name__)
+
+# Set by a chart-data task for the span of its query. When present,
+# Database._execute_sql_with_mutation_and_logging hands the sink the live cursor
+# before the blocking execute so the task can capture an engine cancel id.
+# Absent (None) for every other get_df caller, so this is a no-op elsewhere.
+_cancel_id_sink: ContextVar["Callable[[Any], None] | None"] = ContextVar(
+    "gtf_cancel_id_sink", default=None
+)
+
+
+@contextmanager
+def capture_cancel_id(sink: "Callable[[Any], None]") -> Iterator[None]:
+    """Register a cursor sink for the duration of a chart-data query execution."""
+    token = _cancel_id_sink.set(sink)
+    try:
+        yield
+    finally:
+        _cancel_id_sink.reset(token)
+
+
+def notify_cursor(cursor: Any) -> None:
+    """Hand the live cursor to the active sink, if any.
+
+    Called from ``get_df`` before the query executes. Best-effort: a capture
+    failure must never break query execution — it only forfeits cancellability.
+    """
+    sink = _cancel_id_sink.get()
+    if sink is None:
+        return
+    try:
+        sink(cursor)
+    except Exception:  # noqa: BLE001 pylint: disable=broad-except
+        logger.warning("Cancel-id capture failed", exc_info=True)
+
+
+def cancel_chart_query(
+    database: "Database", cancel_query_id: str, app: "Flask | None" = None
+) -> bool:
+    """Cancel a running chart-data warehouse query over a fresh connection.
+
+    Runs ``db_engine_spec.cancel_query`` against a new connection to the same
+    database, terminating the backend session that the task's blocked ``get_df``
+    is waiting on. Invoked from the task's abort handler (on the abort-listener
+    thread), so it opens its own connection rather than touching the busy one.
+    Best-effort and fully logged; the task's terminal transition is authoritative.
+
+    :param database: the database the query is running against
+    :param cancel_query_id: engine cancel handle captured at query start
+    :param app: Flask app for config/DB access from the background thread
+    :returns: True if the engine reported the query cancelled
+    """
+    from flask import current_app
+
+    stats_logger: BaseStatsLogger = (app or current_app).config.get(
+        "STATS_LOGGER", BaseStatsLogger()
+    )
+    spec = database.db_engine_spec
+    try:
+        with database.get_sqla_engine() as engine:
+            with closing(engine.raw_connection()) as conn:
+                with closing(conn.cursor()) as cursor:
+                    # query is unused by the explicit-id specs (they cancel by
+                    # the captured id alone); the chart path has no Query model.
+                    cancelled = spec.cancel_query(cursor, None, cancel_query_id)  # type: ignore[arg-type]

Review Comment:
   **Suggestion:** The abort callback runs on a background thread with only the Flask application context, not the `override_user` context used by the executing task. Calling `database.get_sqla_engine()` therefore constructs a fresh OAuth2 connection without the task user's token, causing cancellation to fail for OAuth2-enabled databases and leaving the original warehouse query running. Preserve the task user context or pass the required OAuth2 credentials into the cancellation operation. [security]
   
   <details>
   <summary><b>Severity Level:</b> Major ⚠️</summary>
   
   ```mdx
   - ❌ OAuth2 chart-query cancellation can fail.
   - ⚠️ Original warehouse queries continue after task aborts.
   - ⚠️ Per-user database authentication is absent on cancellation.
   ```
   </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=52118ca2453f49fb85959c1f310cd50f&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=52118ca2453f49fb85959c1f310cd50f&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/tasks/query_cancel.py
   **Line:** 107:112
   **Comment:**
   	*Security: The abort callback runs on a background thread with only the Flask application context, not the `override_user` context used by the executing task. Calling `database.get_sqla_engine()` therefore constructs a fresh OAuth2 connection without the task user's token, causing cancellation to fail for OAuth2-enabled databases and leaving the original warehouse query running. Preserve the task user context or pass the required OAuth2 credentials into the cancellation operation.
   
   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=89164201e8c2c050d9edd128ce0cd73a8d0929e91124440b4756501e60fcccf9&reaction=like'>👍</a> | <a href='https://app.codeant.ai/feedback?pr_url=https%3A%2F%2Fgithub.com%2Fapache%2Fsuperset%2Fpull%2F43627&comment_hash=89164201e8c2c050d9edd128ce0cd73a8d0929e91124440b4756501e60fcccf9&reaction=dislike'>👎</a>



##########
superset/tasks/async_queries.py:
##########
@@ -120,10 +123,47 @@ def _get_dependency_cache_key() -> str:
     raise SupersetException("Prerequisite task did not publish a cache key")
 
 
-# No timeout is set on these tasks yet: GTF enforces a timeout by aborting the
-# task, but chart-data queries have no abort handler to cancel the underlying
-# warehouse query, so a timeout would only mark the task failed while the query
-# kept running. Restore a timeout once query cancellation is implemented.
+@contextmanager
+def _capture_query_cancellation(query_context: "QueryContext") -> Iterator[None]:
+    """Enable engine-level cancellation of this task's warehouse query.
+
+    Captures the engine cancel id off the live cursor (for engines that expose
+    one before execution) and registers an abort handler that kills the backend
+    session over a fresh connection, unblocking the task's ``get_df``. Engines
+    without cancel support capture nothing and the task stays non-abortable, so
+    an abort/timeout simply frees the task without killing the (uncancellable)
+    query — matching the pre-cancellation behavior for those engines.
+    """
+    database = getattr(query_context.datasource, "database", None)
+    if database is None:
+        yield
+        return
+
+    ctx = get_context()
+    app = current_app._get_current_object()  # noqa: SLF001
+    captured = False
+
+    def _sink(cursor: Any) -> None:
+        nonlocal captured
+        if captured:
+            return
+        # query is unused by the explicit-id specs; the chart path has no Query.
+        cancel_id = database.db_engine_spec.get_cancel_query_id(cursor, None)

Review Comment:
   **Suggestion:** The engine-spec cancellation contract requires a real SQL Lab `Query`, but this passes `None`. Engines such as Ocient dereference `query.id` during `cancel_query`, and engines such as Impala access `query.database`; the resulting exception is swallowed by the cancellation path, so the task is marked aborted while the warehouse query continues running. Provide the actual query object or restrict this path to engines whose cancellation methods do not require it. [api mismatch]
   
   <details>
   <summary><b>Severity Level:</b> Major ⚠️</summary>
   
   ```mdx
   - ❌ Ocient query cancellation fails on every registered cancellable query.
   - ❌ Impala cancellation cannot access required database metadata.
   - ⚠️ Aborted tasks can leave warehouse queries consuming resources.
   ```
   </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=4a03511e37aa42c3b63f1a9b739f93ef&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=4a03511e37aa42c3b63f1a9b739f93ef&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/tasks/async_queries.py
   **Line:** 151:151
   **Comment:**
   	*Api Mismatch: The engine-spec cancellation contract requires a real SQL Lab `Query`, but this passes `None`. Engines such as Ocient dereference `query.id` during `cancel_query`, and engines such as Impala access `query.database`; the resulting exception is swallowed by the cancellation path, so the task is marked aborted while the warehouse query continues running. Provide the actual query object or restrict this path to engines whose cancellation methods do not require it.
   
   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=0551a5d09dd1b79a50eb782dc2c99eda82f8b1d020da675d39a5712abfc0c8c2&reaction=like'>👍</a> | <a href='https://app.codeant.ai/feedback?pr_url=https%3A%2F%2Fgithub.com%2Fapache%2Fsuperset%2Fpull%2F43627&comment_hash=0551a5d09dd1b79a50eb782dc2c99eda82f8b1d020da675d39a5712abfc0c8c2&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: notifications-unsubscribe@superset.apache.org

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


---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org


Re: [PR] feat(gtf): heartbeat orphan reaping + cancellable chart-data queries [superset]

Posted by "codeant-ai-for-open-source[bot] (via GitHub)" <gi...@apache.org>.
codeant-ai-for-open-source[bot] commented on code in PR #43627:
URL: https://github.com/apache/superset/pull/43627#discussion_r3876981919


##########
tests/unit_tests/tasks/test_scheduler_executor.py:
##########
@@ -0,0 +1,137 @@
+# 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.
+"""Unit tests for the GTF executor body (scheduler._execute_task_body)."""
+
+from types import SimpleNamespace
+from unittest.mock import MagicMock, patch
+from uuid import uuid4
+
+from superset_core.tasks.types import TaskStatus
+
+
+def _run_body_with_raising_executor(*, timeout_triggered: bool, abort_detected: bool):
+    """Drive _execute_task_body where the task body raises mid-abort/timeout.
+
+    Returns ``(result, transition_mock, task_manager_mock, stats_logger_mock)`` for
+    the caller to assert on the terminal handling.
+    """
+    native = uuid4()
+    task = SimpleNamespace(
+        uuid=native,
+        status=TaskStatus.PENDING.value,
+        properties_dict={},  # no "timeout" key -> no timeout timer started
+    )
+    # What the finally block's terminal transition commits, read back at the end.
+    refreshed = SimpleNamespace(
+        status=(
+            TaskStatus.TIMED_OUT.value
+            if timeout_triggered
+            else TaskStatus.ABORTED.value
+        )
+    )

Review Comment:
   **Suggestion:** The refreshed ORM stub is initialized with the expected terminal status before `_execute_task_body` runs, so the result assertion can pass even if the implementation never issues the required `TIMED_OUT`/`ABORTED` transition. Assert that the transition mock was called with the corresponding terminal status (and expected state) to make this regression test verify finalization rather than merely echoing the fixture. [incomplete implementation]
   
   <details>
   <summary><b>Severity Level:</b> Minor 🧹</summary>
   
   ```mdx
   - ⚠️ Timeout regression test can pass without finalizing tasks.
   - ⚠️ Abort regression test has the same unverified transition.
   - ⚠️ CI may miss tasks stuck in ABORTING.
   ```
   </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=be87468fc66e4c6e94505b3f89ae60a5&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=be87468fc66e4c6e94505b3f89ae60a5&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:** tests/unit_tests/tasks/test_scheduler_executor.py
   **Line:** 39:45
   **Comment:**
   	*Incomplete Implementation: The refreshed ORM stub is initialized with the expected terminal status before `_execute_task_body` runs, so the result assertion can pass even if the implementation never issues the required `TIMED_OUT`/`ABORTED` transition. Assert that the transition mock was called with the corresponding terminal status (and expected state) to make this regression test verify finalization rather than merely echoing the fixture.
   
   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=0dff2a2def45b0481c0752b447b65fc6ee84d650f1a5001ef18746b168e7f906&reaction=like'>👍</a> | <a href='https://app.codeant.ai/feedback?pr_url=https%3A%2F%2Fgithub.com%2Fapache%2Fsuperset%2Fpull%2F43627&comment_hash=0dff2a2def45b0481c0752b447b65fc6ee84d650f1a5001ef18746b168e7f906&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: notifications-unsubscribe@superset.apache.org

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


---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org


Re: [PR] feat(gtf): heartbeat orphan reaping + cancellable chart-data queries [superset]

Posted by "bito-code-review[bot] (via GitHub)" <gi...@apache.org>.
bito-code-review[bot] commented on PR #43627:
URL: https://github.com/apache/superset/pull/43627#issuecomment-5446971105

   <!-- Bito Reply -->
   The flagged issue is correct. The current regression tests in `tests/unit_tests/tasks/test_scheduler_executor.py` verify the final status of the task but do not confirm that the `InternalStatusTransitionCommand` was actually invoked to perform the transition. This means the test could pass even if the task status was set incorrectly or if the transition logic was bypassed.
   
   To resolve this, you should assert that the transition mock was called with the expected terminal status (`TIMED_OUT` or `ABORTED`) and the correct state. You can achieve this by inspecting the `transition` mock's call arguments in your test cases, similar to how `_requested_statuses` is used in the existing test file.
   
   Would you like me to implement this fix for the flagged tests and check the rest of the PR comments for similar issues?
   
   **tests/unit_tests/tasks/test_scheduler_executor.py**
   ```
   def test_exception_during_timeout_finalizes_timed_out_not_failure() -> None:
       result, transition, task_manager, stats_logger = _run_body_with_raising_executor(
           timeout_triggered=True, abort_detected=False
       )
   
       assert TaskStatus.FAILURE not in _requested_statuses(transition)
       assert result["status"] == TaskStatus.TIMED_OUT.value
       # Add assertion for transition call:
       transition.assert_called_with(new_status=TaskStatus.TIMED_OUT, ...)
       task_manager.publish_completion.assert_called_once()
   ```


-- 
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: notifications-unsubscribe@superset.apache.org

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


---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org


Re: [PR] feat(gtf): heartbeat orphan reaping + cancellable chart-data queries [superset]

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


-- 
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: notifications-unsubscribe@superset.apache.org

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


---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org