Skip to content

feat(gtf): per-tab task subscriptions for cross-tab cancel + async/ws follow-ups - #43685

Merged
villebro merged 2 commits into
apache:gaq-to-gtffrom
villebro:villebro/gtf-review-followups
Aug 29, 2026
Merged

villebro merged 2 commits into
apache:gaq-to-gtffrom
villebro:villebro/gtf-review-followups

Conversation

@villebro

@villebro villebro commented Aug 29, 2026 •

Copy link
Copy Markdown
Member

SUMMARY

Server-side fix for cross-tab cancellation of shared async chart-data tasks,
plus the async/ws review follow-ups from @sadpandajoe on the umbrella PR
(#43407).

Root cause. Chart-data tasks are SHARED and deduplicated by
query_cache_key, so one user viewing the same chart in two browser tabs is
a single principal with a single task_subscribers row. Any tab's cancel (an
explicit cancel, or the navigate-away teardown that cancels unwaited tasks) hit
subscriber_count <= 1 and aborted the shared task, killing the other tab's
still-pending query. The earlier client-side guard only covered the intra-tab
case; it cannot see sibling tabs.

1. Per-tab task subscriptions (task-type subscription policy)

The framework's subscriber model stays principal-grain — task_subscribers,
subscriber_count, TaskFilter, and raise_for_access are untouched. A task
type may now register a TaskSubscriptionPolicy on its @task decorator to
refine cancellation to a finer per-client (browser tab) grain:

  • on_subscribe(task, *, principal, client_ref) / on_unsubscribe(...) -> bool,
    both invoked in the web request under the existing task_lock that serializes
    submit/cancel (so their read-modify-write on task state is race-free).
  • CancelTaskCommand._do_cancel consults the policy as a pre-gate: if it
    reports the caller's principal still has other clients, the cancel is a
    detach (task keeps running); otherwise it falls through to the unchanged
    principal-grain abort/unsubscribe rule. An admin force-abort bypasses the
    policy.
  • The chart-data policy (ChartQueryConsumerPolicy) ref-counts
    "<principal>:<tab_id>" entries in the task-owned, debug-gated
    private["task"] namespace (the framework never inspects it). A task with no
    policy, or a request with no tab_id, keeps today's principal-grain behavior.
  • tab_id is an opaque per-tab id, not an authorization token: the caller's
    principal is authorized before the policy runs, and the policy only ever
    records/removes entries scoped to that principal.

Frontend: getTabId() is extracted from useTabId (and its BroadcastChannel
made lazy so importing the module has no side effect); the async chart-data POST
and the cancel POST now carry tab_id.

superset-core (extension API): adds the TaskSubscriptionPolicy interface, the
subscription_policy= arg on @task, and Task.properties_dict /
Task.update_task_private. Documented in extensions/tasks.md.

2. Fully-anonymous chart-data runs synchronously

A fully-anonymous request (public dashboard viewed directly, no login and no
guest token) has no subscription, so it could neither poll nor cancel its task —
a 202 that never resolved. _should_run_async now also requires a
subscribe-able identity (user or guest key); anonymous falls back to the
synchronous 200 path. Embedded guest dashboards keep async delivery via
their token-derived key.

3. Shared-task cancellation deferral (client guard)

cancelUnwaitedTasks() only cancels a task id when no local waiter still awaits
it (checked after unregistering the aborting waiter, or before registering on an
already-aborted signal), so aborting one chart no longer cancels a shared task
another local chart still needs. This is the intra-tab complement to the
server-side per-tab fix above.

4. Websocket Pub/Sub channel docs

UPDATING.md and the websocket README listed realtime:<channel_id> — the
browser-delivery channel — as a channel the server consumes. The server
actually subscribes to entity-changes:* and task-status and republishes
to browsers on realtime:* after fanout. Corrected so a Redis ACL following the
guidance allows task-status.

Not included here (from the same review, handled separately):

  • The 202 poll cursor microsecond-vs-seconds miss was already fixed on
    gaq-to-gtf (floored via the shared floored_status_cursor() helper).
  • The Helm GLOBAL_ASYNC_QUERIES_* → WEBSOCKET_* migration is intentionally
    not done: the Helm chart is being deprecated (7.0), and first-class support
    for this feature will land in the official Superset Kubernetes operator.

Follow-up (not in this PR): per-tab websocket channels — scope the ws JWT to
a channel namespace (keeping sub for identity) so each tab can bind
realtime:user:<id>:<tab_id> under the shared per-browser cookie. Not required
for cross-tab cancel (fixed server-side here); sibling-tab status messages are
harmless today since the client filters by task_id.

TESTING INSTRUCTIONS

  • Backend unit: pytest tests/unit_tests/tasks/test_async_queries.py tests/unit_tests/tasks/test_decorators.py tests/unit_tests/charts/test_chart_data_api.py
    (policy behavior, decorator/registry wiring, anonymous-sync gate).
  • Backend integration: pytest tests/integration_tests/tasks/commands/test_cancel.py
    (two-tab detach keeps the task alive; last-tab cancel aborts; cross-user;
    admin force).
  • Frontend: npm run test -- asyncEvent chartActions useTabId.
  • Manual: open the same chart in two tabs backed by one async query; cancel/close
    one tab and confirm the other still resolves; close the last tab and confirm
    the task aborts. Confirm a fully-anonymous public dashboard loads charts
    synchronously.

ADDITIONAL INFORMATION

  • Has associated issue:
  • Required feature flags: GLOBAL_ASYNC_QUERIES / GLOBAL_TASK_FRAMEWORK
  • Changes UI
  • Includes DB Migration
  • Introduces new feature or API
  • Removes existing feature or API

… docs

Addresses review feedback on the umbrella PR:

- asyncEvent: aborting one chart cancelled the shared GTF task even when another
  chart for the same principal still awaited it (they dedupe to one backend
  subscriber), aborting work the surviving chart needed. Cancellation is now
  deferred via cancelUnwaitedTasks(): a task id is only cancelled when no local
  waiter still awaits it (checked after unregistering the aborting waiter, or
  before registering on a pre-aborted signal). Regression test added.
- Docs: UPDATING.md and the websocket README wrongly listed realtime:<channel_id>
  (the browser-delivery channel) as a channel the server consumes. The server
  subscribes to entity-changes:* and task-status and republishes to browsers on
  realtime:*; correct the ACL guidance so operators don't omit task-status (which
  would silently drop task updates).
@dosubot dosubot Bot added change:frontend Requires changing the frontend global:async-query Related to Async Queries feature labels Aug 29, 2026
@bito-code-review

bito-code-review Bot commented Aug 29, 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].

@netlify

netlify Bot commented Aug 29, 2026 •

Copy link
Copy Markdown

✅ Deploy Preview for superset-docs-preview ready!

Name Link
🔨 Latest commit 344c232
🔍 Latest deploy log https://app.netlify.com/projects/superset-docs-preview/deploys/6a930d6bead2e80008a1a869
😎 Deploy Preview https://deploy-preview-43685--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.

// so a task id still present in the registry means another waiter depends on it.
const cancelUnwaitedTasks = (taskIds: string[]) => {
taskIds.forEach(taskId => {
if (!waitersByTaskId.has(taskId)) cancelTask(taskId);

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 waiter registry is scoped to this JavaScript module instance, so it cannot observe charts waiting in another browser tab or window. When the last local waiter aborts, this condition sends /cancel even if another tab for the same principal still depends on the shared task; the backend can then unsubscribe the principal and abort work needed by that other chart. Coordinate cancellation across browser contexts or make cancellation depend on the backend's principal-level subscriber state rather than only this local map. [race condition]

Severity Level: Major ⚠️
- ❌ One tab can abort work required by another tab.
- ❌ The surviving chart receives a failed async result.
- ⚠️ Trigger requires identical shared requests across browser contexts.

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-frontend/src/middleware/asyncEvent.ts
**Line:** 163:163
**Comment:**
	*Race Condition: The waiter registry is scoped to this JavaScript module instance, so it cannot observe charts waiting in another browser tab or window. When the last local waiter aborts, this condition sends `/cancel` even if another tab for the same principal still depends on the shared task; the backend can then unsubscribe the principal and abort work needed by that other chart. Coordinate cancellation across browser contexts or make cancellation depend on the backend's principal-level subscriber state rather than only this local map.

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 original implementation sent a /cancel request immediately upon any abort, which could prematurely terminate a shared task still needed by other charts in the same browser session. The provided diff already implements a fix by introducing cancelUnwaitedTasks, which checks if any other local waiters still depend on the task before sending the cancellation request. This ensures that shared tasks are only cancelled when no local waiters remain. No further action is required for this specific issue.

superset-frontend/src/middleware/asyncEvent.ts

const cancelUnwaitedTasks = (taskIds: string[]) => {
  taskIds.forEach(taskId => {
    if (!waitersByTaskId.has(taskId)) cancelTask(taskId);
  });
};

…chart-data runs sync

Chart-data tasks are SHARED and deduped by query_cache_key, so one user in
two browser tabs is a single principal subscriber. Any tab's cancel or
navigate-away teardown hit subscriber_count<=1 and aborted the shared task,
killing the other tab's still-pending query.

Add a task-type subscription policy: the framework's subscriber model stays
principal-grain (task_subscribers/TaskFilter untouched); a task type may
register a TaskSubscriptionPolicy on @task that refines cancel to a finer
per-client (browser tab) grain. Submit/cancel consult it under the existing
task lock. The chart-data policy ref-counts "<principal>:<tab_id>" entries in
the task-owned private.task namespace; a tab cancel detaches only that tab and
the task aborts only once the principal's last tab leaves. Admin force-abort
bypasses the policy.

Also gate async on a subscribe-able identity: a fully-anonymous chart-data
request (no login, no guest token) can neither poll nor cancel its task, so it
now runs synchronously. Embedded guests keep async via their guest key.

- superset-core: TaskSubscriptionPolicy interface + @task(subscription_policy=)
  + Task.properties_dict/update_task_private
- host: subscription.py (policy re-export, principal_channel, get_request_tab_id);
  registry stores/looks up policies; channel_id_for delegates to principal_channel
- frontend: getTabId() extracted from useTabId (lazy BroadcastChannel); tab_id
  sent on the async chart POST and the cancel POST
- docs: extensions/tasks.md Per-client subscriptions section
@github-actions github-actions Bot added api Related to the REST API doc Namespace | Anything related to documentation labels Aug 29, 2026
@codecov

codecov Bot commented Aug 29, 2026 •

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 67.70833% with 31 lines in your changes missing coverage. Please review.
✅ Project coverage is 75.08%. Comparing base (d2e10e3) to head (344c232).
⚠️ Report is 1 commits behind head on gaq-to-gtf.

Files with missing lines Patch % Lines
superset/commands/tasks/cancel.py 21.42% 11 Missing ⚠️
superset/tasks/subscription.py 61.90% 7 Missing and 1 partial ⚠️
superset/commands/tasks/submit.py 60.00% 5 Missing and 1 partial ⚠️
superset/tasks/api.py 0.00% 4 Missing ⚠️
superset/tasks/async_queries.py 96.15% 0 Missing and 1 partial ⚠️
superset/tasks/registry.py 88.88% 1 Missing ⚠️
Additional details and impacted files
@@              Coverage Diff               @@
##           gaq-to-gtf   #43685      +/-   ##
==============================================
+ Coverage       75.02%   75.08%   +0.06%     
==============================================
  Files            2891     2897       +6     
  Lines          166485   167169     +684     
  Branches        38463    38473      +10     
==============================================
+ Hits           124901   125520     +619     
- Misses          39041    39103      +62     
- Partials         2543     2546       +3     
Flag Coverage Δ
hive 37.93% <33.33%> (-0.01%) ⬇️
presto 39.83% <33.33%> (-0.01%) ⬇️
python 75.32% <67.70%> (-0.01%) ⬇️
superset-extensions-cli 90.57% <ø> (?)
unit 74.29% <67.70%> (-0.01%) ⬇️

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.

@villebro villebro changed the title fix(gtf): defer shared-task cancel to last waiter + correct ws channel docs feat(gtf): per-tab task subscriptions for cross-tab cancel + async/ws follow-ups Aug 29, 2026
@villebro
villebro merged commit e2dbca8 into apache:gaq-to-gtf Aug 29, 2026
52 of 55 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

api Related to the REST API change:frontend Requires changing the frontend doc Namespace | Anything related to documentation global:async-query Related to Async Queries feature size/XXL

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant