Skip to content

feat(gtf): heartbeat orphan reaping + cancellable chart-data queries - #43627

Merged
villebro merged 13 commits into
gaq-to-gtffrom
villebro/gtf-heartbeat-cancellation
Aug 28, 2026
Merged

villebro merged 13 commits into
gaq-to-gtffrom
villebro/gtf-heartbeat-cancellation

Conversation

@villebro

@villebro villebro commented Aug 28, 2026 •

Copy link
Copy Markdown
Member

SUMMARY

Part of the GAQ→GTF epic (targets gaq-to-gtf, not master). It closes two resilience gaps in the Global Task Framework once async chart data runs on it:

  1. A worker that stops running a task leaves the task unresolved. If a worker process ends mid-execution (crash, OOM kill, SIGKILL, or a lost broker message), the Task row 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_tasks only deletes old terminal rows, so it does not help; the only existing signal is the client-side GLOBAL_ASYNC_QUERIES_POLLING_STALE_TIMEOUT, which stops the browser from waiting but leaves the server-side row and any warehouse query in place.
  2. Async chart-data query tasks are not cancellable. execute_chart_query sets 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_tasks cron, and makes chart-data query tasks cancellable via the framework's existing on_abort mechanism, with an opt-in per-query timeout.

GAQ vs. GTF vs. this PR

Capability Legacy GAQ GTF (before this PR) After this PR
Recover a task whose worker stopped running it No No Heartbeat + reaper transitions the row to FAILURE and releases waiters
Prevent a redelivered Celery job from re-running revoke(terminate=True) No revoke (no terminate)
Cooperative user/timeout cancellation Redis flag polled by the worker on_abort handlers on_abort handlers (unchanged)
Cancel the underlying warehouse query SQL Lab path only Not for chart data on_abort handler calls the engine's cancel_query (engines that support it)
Per-query timeout for async chart data No No (removed pending cancellation) Opt-in GLOBAL_ASYNC_QUERIES_QUERY_TIMEOUT

How it works

  • Heartbeat (superset/tasks/heartbeat.py): while a worker holds a task it refreshes tasks.last_heartbeat on a daemon thread every GTF_TASK_HEARTBEAT_INTERVAL (default 15s). The write is a raw UPDATE of that one column so it does not touch 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, 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.
  • Reaper (ReapOrphanedTasksCommand, run from prune_tasks before deletion): for each active task whose heartbeat is older than GTF_ORPHAN_TASK_TIMEOUT (default 60s), it transitions the row to FAILURE (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.
  • Deliberately no forced termination. The reaper revokes without 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; forcing SoftTimeLimitExceeded into 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. revoke without terminate only marks the job id revoked, which matters when task_acks_late is enabled and the broker redelivers.
  • Query cancellation (superset/tasks/query_cancel.py) reuses the framework's existing cooperation model rather than adding a parallel one: a contextvar seam (invoked from get_df before the blocking execute) lets the task capture an engine cancel id via db_engine_spec.get_cancel_query_id, and execute_chart_query registers an on_abort handler that runs db_engine_spec.cancel_query over 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 as ABORTED/TIMED_OUT (not FAILURE).
  • Metrics: 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:

  • Dedupe-count tooltip fix. It wrapped its content directly in Flex, which is not a forwardRef component, so the antd Tooltip had no DOM node to anchor to and never showed on hover (the sibling tooltips wrap a span). Wrapped it in a span, and tightened/pluralized the copy via tn.
  • Bidirectional dependency hover. The Task entity/API exposes both DAG directions as a self-documenting pair — depends_on (upstream) and a symmetric required_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 additive isRowHighlighted predicate on ListView/TableCollection, reusing the existing table-row-highlighted background.
  • Keep dependents' rows fresh. A dependent's row shows its prerequisites' statuses, so a task's status change now also nudges the tasks that depend on it — otherwise those rows showed stale prerequisite state.

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

  • Unit + integration: pytest tests/unit_tests/tasks/ tests/integration_tests/tasks/commands/test_reap.py. Coverage includes the heartbeat lifecycle/failure, find_orphaned selection (stale vs. fresh vs. null-heartbeat vs. terminal), the reaper (revoke + FAILURE CAS + publish, CAS no-op race, missing-id skip, per-task error isolation), touch_heartbeat leaving changed_on unchanged, the executor finalizing a cancel-induced exception as TIMED_OUT/ABORTED, and the cancel seam (capture/notify/cancel success/decline/exception). Frontend: npm run test -- src/pages/TaskList.
  • 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 row becomes FAILURE and waiters unblock. On a supported engine, set GLOBAL_ASYNC_QUERIES_QUERY_TIMEOUT or cancel a long query from the UI and confirm the warehouse query is cancelled (e.g. pg_stat_activity) and the task ends ABORTED/TIMED_OUT.

ADDITIONAL INFORMATION

  • Has associated issue:
  • Required feature flags: GLOBAL_TASK_FRAMEWORK (async chart data also needs GLOBAL_ASYNC_QUERIES)
  • Changes UI
  • Includes DB Migration (follow approval process in SIP-59)
    • Migration is atomic, supports rollback & is backwards-compatible
    • Confirm DB migration upgrade and downgrade tested
    • Runtime estimates and downtime expectations provided
  • Introduces new feature or API
  • Removes existing feature or API

The tasks.last_heartbeat column (nullable, indexed, reversible) is folded into the branch's existing task-schema migration 7e2c9a4f1b83 rather than a new revision, matching how guest_key was folded — so there is no new migration file.

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.
@dosubot dosubot Bot added the global:async-query Related to Async Queries feature label Aug 28, 2026
@bito-code-review

bito-code-review Bot commented Aug 28, 2026 •

Copy link
Copy Markdown
Contributor

Bito Automatic Review Skipped - Branch Excluded

Bito didn't auto-review because the source or target branch is excluded from automatic reviews.
No action is needed if you didn't intend for the agent to review it. Otherwise, to manually trigger a review, type /review in a comment and save.
You can change the branch exclusion settings here, or contact your Bito workspace admin at [email protected].

@github-actions github-actions Bot added the risk:db-migration PRs that require a DB migration label Aug 28, 2026
@netlify

netlify Bot commented Aug 28, 2026 •

Copy link
Copy Markdown

✅ Deploy Preview for superset-docs-preview ready!

Name Link
🔨 Latest commit 7ce5c3f
🔍 Latest deploy log https://app.netlify.com/projects/superset-docs-preview/deploys/6a910a4c45b3b8000866b70f
😎 Deploy Preview https://deploy-preview-43627--superset-docs-preview.netlify.app
📱 Preview on mobile
Toggle QR Code...

QR Code

Use your smartphone camera to open QR code link.
🤖 Make changes Run an agent on this branch

To edit notification comments on pull requests, go to your Netlify project configuration.

Comment on lines +39 to +45
refreshed = SimpleNamespace(
status=(
TaskStatus.TIMED_OUT.value
if timeout_triggered
else TaskStatus.ABORTED.value
)
)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

Use CodeAnt Skill Fix in Cursor Fix in VSCode Claude

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
👍 | 👎

@bito-code-review

Copy link
Copy Markdown
Contributor

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()

Comment thread superset/commands/tasks/reap.py Outdated
Comment on lines +63 to +64
candidates = TaskDAO.find_orphaned(timeout, timeout)
reaped = sum(self._process(candidate, stats_logger) for candidate in candidates)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

Use CodeAnt Skill Fix in Cursor Fix in VSCode Claude

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
👍 | 👎

Comment thread superset/commands/tasks/reap.py Outdated
Comment on lines +77 to +78
properties = cast(TaskProperties, dict(parse_properties(candidate.properties)))
self._revoke(properties.get("celery_task_id"), stats_logger)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

Use CodeAnt Skill Fix in Cursor Fix in VSCode Claude

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
👍 | 👎

Comment thread superset/tasks/async_queries.py Outdated
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)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

Use CodeAnt Skill Fix in Cursor Fix in VSCode Claude

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
👍 | 👎

Comment thread superset/tasks/query_cancel.py Outdated
Comment on lines +107 to +112
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]

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

Use CodeAnt Skill Fix in Cursor Fix in VSCode Claude

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

codecov Bot commented Aug 28, 2026 •

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 89.87342% with 24 lines in your changes missing coverage. Please review.
✅ Project coverage is 79.27%. Comparing base (26d556c) to head (a51dd3b).

Files with missing lines Patch % Lines
superset/commands/tasks/reap.py 84.48% 8 Missing and 1 partial ⚠️
superset/tasks/scheduler.py 66.66% 8 Missing and 1 partial ⚠️
superset/daos/tasks.py 84.21% 3 Missing ⚠️
superset/tasks/manager.py 81.81% 2 Missing ⚠️
superset/tasks/async_queries.py 96.29% 1 Missing ⚠️
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     
Flag Coverage Δ
hive 37.99% <32.48%> (-0.02%) ⬇️
mysql 57.62% <59.91%> (+<0.01%) ⬆️
postgres 57.65% <59.91%> (+<0.01%) ⬆️
presto 39.90% <34.17%> (-0.02%) ⬇️
python 83.85% <89.87%> (+0.02%) ⬆️
sqlite 57.34% <59.91%> (+<0.01%) ⬆️
unit 74.26% <84.81%> (+0.05%) ⬆️

Flags with carried forward coverage won't be shown. Click here to find out more.

☔ View full report in Codecov by Harness.
📢 Have feedback on the report? Share it here.

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.
  • 📦 JS Bundle Analysis: Save yourself from yourself by tracking and limiting bundle sizes in JS merges.

- 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
@github-actions github-actions Bot added the doc Namespace | Anything related to documentation label Aug 28, 2026
@villebro

Copy link
Copy Markdown
Member Author

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.

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.
@villebro

Copy link
Copy Markdown
Member Author

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).

# ``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(

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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?

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.
@villebro
villebro merged commit e8a1a84 into gaq-to-gtf Aug 28, 2026
69 of 70 checks passed
@villebro
villebro deleted the villebro/gtf-heartbeat-cancellation branch August 28, 2026 20:51
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

doc Namespace | Anything related to documentation global:async-query Related to Async Queries feature packages risk:db-migration PRs that require a DB migration size/XXL

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants