Repository navigation
feat(gtf): heartbeat orphan reaping + cancellable chart-data queries - #43627
Conversation
Add a worker-liveness heartbeat and fold orphan reaping into the existing prune_tasks cron so tasks abandoned by a dead worker are revoked and marked FAILURE, and make async chart-data query tasks cancellable at the engine level with a restored per-query timeout.
|
Bito Automatic Review Skipped - Branch Excluded |
✅ Deploy Preview for superset-docs-preview ready!
To edit notification comments on pull requests, go to your Netlify project configuration. |
| refreshed = SimpleNamespace( | ||
| status=( | ||
| TaskStatus.TIMED_OUT.value | ||
| if timeout_triggered | ||
| else TaskStatus.ABORTED.value | ||
| ) | ||
| ) |
There was a problem hiding this 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]
Severity Level: Minor 🧹
- ⚠️ Timeout regression test can pass without finalizing tasks.
- ⚠️ Abort regression test has the same unverified transition.
- ⚠️ CI may miss tasks stuck in ABORTING.Prompt for AI Agent 🤖
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|
The flagged issue is correct. The current regression tests in To resolve this, you should assert that the transition mock was called with the expected terminal status ( 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 |
| candidates = TaskDAO.find_orphaned(timeout, timeout) | ||
| reaped = sum(self._process(candidate, stats_logger) for candidate in candidates) |
There was a problem hiding this 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]
Severity Level: Major ⚠️
- ⚠️ 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.Prompt for AI Agent 🤖
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| properties = cast(TaskProperties, dict(parse_properties(candidate.properties))) | ||
| self._revoke(properties.get("celery_task_id"), stats_logger) |
There was a problem hiding this 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]
Severity Level: Major ⚠️
- ⚠️ Orphaned task progress metadata can be lost.
- ⚠️ Runtime abortability and diagnostic properties can be overwritten.
- ⚠️ Reaper retains stale Celery metadata after concurrent updates.Prompt for AI Agent 🤖
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| 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) |
There was a problem hiding this 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]
Severity Level: Major ⚠️
- ❌ Ocient query cancellation fails on every registered cancellable query.
- ❌ Impala cancellation cannot access required database metadata.
- ⚠️ Aborted tasks can leave warehouse queries consuming resources.Prompt for AI Agent 🤖
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| 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] |
There was a problem hiding this 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]
Severity Level: Major ⚠️
- ❌ OAuth2 chart-query cancellation can fail.
- ⚠️ Original warehouse queries continue after task aborts.
- ⚠️ Per-user database authentication is absent on cancellation.Prompt for AI Agent 🤖
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
Codecov Report❌ Patch coverage is Additional details and impacted files@@ Coverage Diff @@
## gaq-to-gtf #43627 +/- ##
==============================================
+ Coverage 79.25% 79.27% +0.01%
==============================================
Files 2887 2890 +3
Lines 166194 166398 +204
Branches 38448 38454 +6
==============================================
+ Hits 131724 131913 +189
- Misses 31992 32006 +14
- Partials 2478 2479 +1
Flags with carried forward coverage won't be shown. Click here to find out more. ☔ View full report in Codecov by Harness. 🚀 New features to boost your workflow:
|
- reaper: isolate per-candidate failures (one DB error no longer aborts the loop or skips the retention prune pass) and re-read fresh properties before the status CAS to avoid clobbering concurrent runtime state - query cancel: pass a minimal Query stand-in instead of None so engines that dereference query.id/query.database (Ocient, Impala) degrade gracefully - strengthen the executor abort/timeout regression test to assert the terminal transition is actually issued - fix MySQL-only test failure: compare changed_on at DB (seconds) precision - docs: document orphan reaping in the GTF task docs
|
Thanks for the review — addressed in
CI: the |
Remove the wedged-ABORTING escalation and drop terminate=True from the reaper's Celery revoke. Layering forced Celery termination on top of the cooperative on_abort path was redundant and risky: heartbeat starvation on a healthy but CPU-bound task could trigger a false-positive orphan, and terminate=True would then kill live work. The reaper now only recovers tasks with no live worker (stale heartbeat) — mark FAILURE, release waiters, and revoke (without terminate) so a redelivered job will not run. Cooperative cancellation of live workers is unchanged.
|
Follow-up (
Also rewrote the PR description to be objective (dropped the "zombie" framing — a worker that ends mid-task simply leaves the row unresolved). |
| # ``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( |
There was a problem hiding this 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?
There was a problem hiding this 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.
The dedupe detail wrapped its content directly in Flex, which is not a forwardRef component, so the antd Tooltip had no DOM node to anchor to and the hover never triggered (the sibling tooltips wrap a span). Wrap it in a span to match. Also pluralize the copy correctly via tn and shorten it, and inline the redundant hasDedupe boolean.
Drop the redundant `=== 0` in the early-return guard (plain boolean context).
Keep the explicit `> 0` in the JSX render — a bare `{dedupeCount && …}` would
render a literal 0 when the count is 0.
Hovering the Task List 'Depends on' chain icon now tints the rows of the prerequisite tasks that are visible on the current page, so it is easy to see what a task is waiting on. Adds an optional isRowHighlighted predicate to ListView/TableCollection (additive; generalizes the existing highlightRowId), reusing the existing table-row-highlighted background. The popover reports its open/close via onOpenChange so the list highlights the dependency uuids.
…ange Setting state inside the antd Popover's onOpenChange wedged the hover popover (content never rendered and the close event never fired, so the row highlight never cleared). Keep the popover pristine and drive the highlight from onMouseEnter/onMouseLeave on the chain icon instead: the popover shows again (needed since some prerequisites may be on another page) and the highlight clears on mouse-leave.
A dependent task's list row shows its prerequisites' statuses (the 'depends on' detail and the 'waiting on N' indicator), but the realtime entity-change nudge only refetched the row whose own status changed, so dependents showed stale prerequisite state. On a task's status transition (start/terminal, incl. cancel and orphan reap) also nudge the tasks that depend on it, via a reverse-dependency lookup (TaskDAO.get_dependent_uuids) and TaskManager.publish_dependents_changed. Best-effort and a no-op when the task has no dependents.
…ectional Add a symmetric `dependents` relationship on the Task entity (reverse of `dependencies`, same viewonly selectin), exposed via the API schema, so both DAG directions are available directly on the entity/API without a separate query. Task List: the dependency detail now uses a branching icon (PartitionOutlined) and its popover shows both 'Depends on' (upstream) and 'Required by' (downstream) sections; hovering highlights the visible rows in both directions.
…ocally The popover was uncontrolled, so when hovering updated the row-highlight state the parent list re-rendered and reset antd's internal open state, so the popover never appeared. Control open with local state (matching the other Task List popovers) and report open/close to the parent for highlighting — the parent re-render no longer affects the popover's visibility.
Rename the task DAG relationships/fields to the clearer, self-documenting pair 'A depends_on B' <=> 'B required_by A', consistently across the Task model relationships, the API response schema, and the frontend Task type/component. The prior dependencies/dependents pair differed by only a couple of characters and split from the API's existing depends_on. TaskOptions.depends_on (submit) already matched. Cheap to change now (pre-merge), hard after.
The `components` prop was an inline object recreated on every render, with fresh inner cell/row function identities. antd treats those as new component types and remounts every row and cell on each re-render. That tore down an open hover popover inside a cell whenever the table re-rendered — e.g. when the Task List updates row highlighting on hover, which made the dependency popover never show and its close event never fire (so the highlight stuck). Memoize the components object so re-renders (row highlighting, etc.) update in place instead of remounting. General perf win for every ListView too.
The /status_changes poll returns a server-clock watermark and re-queries with changed_on >= cursor. changed_on is stored at the metastore column's precision: MySQL DATETIME truncates to whole seconds, so a sub-second cursor could sit after a change that landed in the same second and miss it (the row's stored changed_on < the sub-second cursor). Floor the returned cursor to whole seconds so >= stays inclusive on every backend; re-delivering an earlier same-second change is harmless (idempotent for the client). Fixes the flaky MySQL test_status_changes_narrows_by_task_type.
SUMMARY
Part of the GAQ→GTF epic (targets
gaq-to-gtf, notmaster). It closes two resilience gaps in the Global Task Framework once async chart data runs on it:SIGKILL, or a lost broker message), theTaskrow stays in an active state (IN_PROGRESS/ABORTING) and is never transitioned to a terminal state. Anything waiting on it — sync join-and-wait callers, DAG dependents, and the chart-data status poll — waits indefinitely.prune_tasksonly deletes old terminal rows, so it does not help; the only existing signal is the client-sideGLOBAL_ASYNC_QUERIES_POLLING_STALE_TIMEOUT, which stops the browser from waiting but leaves the server-side row and any warehouse query in place.execute_chart_querysets no timeout and registers no abort handler, because the chart-data execution path (Database.get_df→db_engine_spec.execute) captures no engine cancel id, unlike SQL Lab. A cancel/timeout therefore only changes the task row; the warehouse query continues to run.This PR adds a worker liveness heartbeat and folds orphan recovery into the existing
prune_taskscron, and makes chart-data query tasks cancellable via the framework's existingon_abortmechanism, with an opt-in per-query timeout.GAQ vs. GTF vs. this PR
FAILUREand releases waitersrevoke(terminate=True)revoke(noterminate)on_aborthandlerson_aborthandlers (unchanged)on_aborthandler calls the engine'scancel_query(engines that support it)GLOBAL_ASYNC_QUERIES_QUERY_TIMEOUTHow it works
superset/tasks/heartbeat.py): while a worker holds a task it refreshestasks.last_heartbeaton a daemon thread everyGTF_TASK_HEARTBEAT_INTERVAL(default 15s). The write is a rawUPDATEof that one column so it does not touchchanged_on— otherwise every heartbeat would resurface the task in thestatus_changespoll and reset client backoff.execute_taskis split into a thin wrapper (records the Celery job id, runs the body under the heartbeat) and_execute_task_body; the heartbeat starts before the DAG gate so a task blocked on prerequisites is still covered.ReapOrphanedTasksCommand, run fromprune_tasksbefore deletion): for each active task whose heartbeat is older thanGTF_ORPHAN_TASK_TIMEOUT(default 60s), it transitions the row toFAILURE(an atomic compare-and-swap, so a worker that revives and commits its own terminal status simply makes it a no-op), publishes completion so waiters unblock, and revokes the Celery job. Each task is handled independently so one failure neither aborts the pass nor skips the subsequent retention prune.terminate=True, and there is no path that force-terminates a live worker. Orphan detection is heartbeat-based, and a healthy but CPU-bound task can briefly starve its own heartbeat thread; forcingSoftTimeLimitExceededinto it on a false positive would kill good work. The reaper acts only on tasks that already have no live worker; a task still being worked on keeps a fresh heartbeat and is left entirely to its own cooperative abort/cleanup.revokewithoutterminateonly marks the job id revoked, which matters whentask_acks_lateis enabled and the broker redelivers.superset/tasks/query_cancel.py) reuses the framework's existing cooperation model rather than adding a parallel one: a contextvar seam (invoked fromget_dfbefore the blocking execute) lets the task capture an engine cancel id viadb_engine_spec.get_cancel_query_id, andexecute_chart_queryregisters anon_aborthandler that runsdb_engine_spec.cancel_queryover a fresh connection. Cancellation auto-enables per engine — Postgres/MySQL/Snowflake/Redshift are cancellable; engines that expose no cancel id register no handler and behave exactly as before. A cancel/timeout that makes the running query raise is finalized asABORTED/TIMED_OUT(notFAILURE).gtf.task.heartbeat,gtf.task.heartbeat_failure,gtf.task.orphan_reaped,gtf.task.revoke,gtf.task.revoke_failure,gtf.task.reap_error,gtf.query.cancel,gtf.query.cancel_failed.Also included
A few Task List / realtime improvements surfaced while building and demoing the above:
Flex, which is not aforwardRefcomponent, so the antdTooltiphad no DOM node to anchor to and never showed on hover (the sibling tooltips wrap aspan). Wrapped it in aspan, and tightened/pluralized the copy viatn.depends_on(upstream) and a symmetricrequired_by(downstream) relationship (A depends_on B⟺B required_by A). In the list, the dependency detail uses a branching icon whose popover shows both "Depends on" and "Required by" sections; hovering highlights the related rows (both directions) visible on the current page — via an additiveisRowHighlightedpredicate onListView/TableCollection, reusing the existingtable-row-highlightedbackground.Out of scope
Cancelling the warehouse query of an already-orphaned task (from the reaper) is not included: it would require persisting the engine cancel handle on the row, which can race the task's own property writes. The reaper still transitions the row and releases waiters; an abandoned query is bounded by the warehouse's own timeouts. Live user-abort/timeout cancellation is fully implemented.
TESTING INSTRUCTIONS
pytest tests/unit_tests/tasks/ tests/integration_tests/tasks/commands/test_reap.py. Coverage includes the heartbeat lifecycle/failure,find_orphanedselection (stale vs. fresh vs. null-heartbeat vs. terminal), the reaper (revoke +FAILURECAS + publish, CAS no-op race, missing-id skip, per-task error isolation),touch_heartbeatleavingchanged_onunchanged, the executor finalizing a cancel-induced exception asTIMED_OUT/ABORTED, and the cancel seam (capture/notify/cancel success/decline/exception). Frontend:npm run test -- src/pages/TaskList.DISTRIBUTED_COORDINATION_CONFIG+ a Celery worker +celery beatrunningprune_taskson a short interval): submit an async chart query,kill -9the worker mid-query → withinGTF_ORPHAN_TASK_TIMEOUTthe row becomesFAILUREand waiters unblock. On a supported engine, setGLOBAL_ASYNC_QUERIES_QUERY_TIMEOUTor cancel a long query from the UI and confirm the warehouse query is cancelled (e.g.pg_stat_activity) and the task endsABORTED/TIMED_OUT.ADDITIONAL INFORMATION
GLOBAL_TASK_FRAMEWORK(async chart data also needsGLOBAL_ASYNC_QUERIES)The
tasks.last_heartbeatcolumn (nullable, indexed, reversible) is folded into the branch's existing task-schema migration7e2c9a4f1b83rather than a new revision, matching howguest_keywas folded — so there is no new migration file.