Skip to content

feat(websocket): generic task push transport — per-principal chart-data + guest face pile - #43434

Merged
villebro merged 5 commits into
gaq-to-gtffrom
villebro/gtf-websocket-wiring
Aug 23, 2026
Merged

villebro merged 5 commits into
gaq-to-gtffrom
villebro/gtf-websocket-wiring

Conversation

@villebro

Copy link
Copy Markdown
Member

SUMMARY

Wires up the realtime WebSocket transport end-to-end (epic step 6b) on top of the 6a backend foundation (#43431), and in doing so generalizes superset-websocket into a feature-agnostic Task push transport: the Node server now routes purely by Redis channel name and never interprets a message's contents, so any async task (chart data today; thumbnails / reports / exports later) can ride the same mechanism with its specifics carried in the payload.

Targets the gaq-to-gtf feature branch (part of the GAQ→GTF epic).

Two-tier channel model (both lossy Redis Pub/Sub; the status_changes interval poll from step 4 remains the correctness backstop):

  • Tier 1 — public entity-change nudges (entity-changes:<type>): broadcast to every socket, opaque {entity_type, id} only. (Shipped in 6a; consumed here.)
  • Tier 2 — per-principal messages (realtime:<channel_id>): delivered only to the JWT-bound principal's sockets, may carry task-specific detail ({task_id, status}). New in this PR.

The browser receives a generic {channel, payload} envelope and routes on channel exactly as the server does.

Slice C — per-principal (tier-2) publish (backend)

  • superset/websocket/channel.py: extract channel_id_for(user_id, guest_key) as the single source of truth for the principal-channel format (user:<id> / guest-<hmac>), shared by cookie minting and the task layer.
  • TaskDAO.get_subscriber_channels(task_id): map a task's subscribers (users + guests) to their per-principal channels.
  • TaskManager.publish_task_status(task_uuid, status): best-effort fan-out of {task_id, status} to realtime:<channel_id> for each subscriber channel, called from publish_completion. A chart-data client learns each terminal transition over the socket instead of re-polling REST.

Slice D — superset-websocket rewrite (generic transport)

  • Replace the async-events Redis Streams firehose + result_url / per-job-channel model with Redis Pub/Sub. Route by channel name only: entity-changes:* broadcast, realtime:<channel_id> per-principal by JWT channel claim.
  • Drop stream reconnection / last_id replay (Pub/Sub is lossy; poll is the backstop). New config entityChangesChannelPrefix / perPrincipalChannelPrefix; cookie default superset-ws-token. README rewritten.

Slice E — frontend WS client (asyncEvent.ts)

  • Connect to WEBSOCKET_URL (JWT channel cookie rides the handshake) when WEBSOCKET_ENABLED; on a tier-2 message for an awaited task_id, apply the status immediately (accelerates completion). Reconnect on close; the interval poll stays the backstop.

Guest subscribers in the Task List face pile

  • get_subscribers now returns embedded guests as anonymized is_guest entries with stable G1/G2… labels (ordered by subscription time) instead of nameless blanks; the face pile renders them as G1/G2 avatars.

Also folded in (CI fixes for pre-existing failures on the gaq-to-gtf branch, per maintainer request):

  • tsc: declare the per-dashboard async_mode override (step 5) on DashboardInfo.metadata.
  • mypy: widen the chart-data orchestrator's depends_on to the list[CoreTask | UUID | str] | None union TaskOptions accepts.
  • UPDATING.md: document the GAQ→GTF cutover + websocket flow for 7.0, and drop the now-stale GLOBAL_ASYNC_QUERIES_CACHE_BACKEND deprecation bullet (the key is fully removed this cycle).

TESTING INSTRUCTIONS

Automated (all green locally):

  • Backend: pytest tests/unit_tests/tasks/ tests/unit_tests/daos/test_tasks.py tests/unit_tests/websocket/ — 394 passed. New coverage: publish_task_status fan-out, get_subscriber_channels, channel_id_for, guest schema serialization.
  • Node: cd superset-websocket && npm test — 46 passed. New coverage: pub/sub routing (broadcast + per-principal + malformed/unknown channel).
  • Frontend: jest src/middleware/asyncEvent.test.ts src/pages/TaskList/TaskList.test.tsx — 15 passed. New coverage: WS tier-2 acceleration (settle/reject/ignore-non-realtime).
  • mypy / ruff / pylint / tsc / eslint clean on changed files.

Manual (with GLOBAL_ASYNC_QUERIES on, DISTRIBUTED_COORDINATION_CONFIG + WEBSOCKET_ENABLED set, superset-websocket running on the same host):

  1. Load a dashboard with async charts → confirm completion arrives over the socket (faster than the poll interval) and charts render.
  2. Kill the websocket server → confirm charts still complete via the interval poll.
  3. Open an embedded/guest dashboard that schedules a shared task → confirm it appears in the Task List subscriber face pile as G1.

ADDITIONAL INFORMATION

  • Has associated issue:
  • Required feature flags: GLOBAL_ASYNC_QUERIES (async chart data); WEBSOCKET_ENABLED (realtime transport, optional)
  • 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

Two type errors surfaced on the gaq-to-gtf feature branch's CI (tsc and
mypy) that predate the 6b work; fold the fixes in here.

- dashboard/types.ts: declare the per-dashboard `async_mode` override
  (step 5) on `DashboardInfo.metadata` so FilterValue/FiltersConfigForm's
  `state.dashboardInfo?.metadata?.async_mode` reads type-check.
- tasks/async_queries.py: widen the chart-data orchestrator's
  `depends_on` param/local to the `list[CoreTask | UUID | str] | None`
  union that `TaskOptions.depends_on` accepts (list invariance: a
  `list[Task]` is not assignable to the declared element union).
…ta + guest face pile

Wire up the realtime transport end to end (6b) on top of the 6a backend
foundation, and generalize superset-websocket into a feature-agnostic Task
push transport: the Node server routes purely by Redis channel name and never
interprets a message's contents, so any async task (chart data today;
thumbnails / reports / exports later) rides the same mechanism with its
specifics carried in the payload.

Slice C — per-principal (tier-2) publish:
- superset/websocket/channel.py: extract channel_id_for(user_id, guest_key) as
  the single source of truth for the principal-channel format (user:<id> /
  guest-<hmac>), shared by cookie minting and the task layer.
- TaskDAO.get_subscriber_channels(task_id): map a task's subscribers (users and
  guests) to their per-principal channels.
- TaskManager.publish_task_status(task_uuid, status): best-effort fan-out of
  {task_id, status} to realtime:<channel_id> for each subscriber channel;
  called from publish_completion alongside the tier-1 nudge. A chart-data
  client learns each terminal transition over the socket instead of re-polling.

Slice D — superset-websocket rewrite (generic transport):
- Replace the async-events Redis Streams firehose + result_url/per-job-channel
  model with Redis Pub/Sub. Route by channel name only: entity-changes:*
  (tier-1) broadcast to all sockets; realtime:<channel_id> (tier-2) delivered
  to the JWT-bound principal. Forward a generic {channel, payload} envelope.
- Drop stream reconnection/last_id replay (Pub/Sub is lossy; the browser's
  interval poll is the backstop). New config: entityChangesChannelPrefix /
  perPrincipalChannelPrefix; cookie default superset-ws-token. README rewritten.

Slice E — frontend WS client (asyncEvent.ts):
- Connect to WEBSOCKET_URL (JWT channel cookie rides the handshake) when
  WEBSOCKET_ENABLED; on a tier-2 message for an awaited task_id, apply the
  status immediately (accelerates completion). Reconnect on close; the existing
  status_changes interval poll stays the correctness backstop.

Guest subscribers in the Task List face pile:
- get_subscribers now returns embedded guests as anonymized is_guest entries
  with stable G1/G2… labels (ordered by subscription time) instead of
  nameless blanks; the face pile renders them as G1/G2 avatars.

Tests: TaskManager tier-2 publish, DAO get_subscriber_channels, channel_id_for,
schema guest serialization, Node pub/sub routing (broadcast + per-principal +
malformed), and asyncEvent WS acceleration. All green; mypy/ruff/pylint/tsc/
eslint clean on changed files.
Add a 7.0 (## Next) breaking-change entry for the Global Async Queries
re-platform onto GTF: the removed async_event API / AsyncQueryManager /
qc-<hash> replay + config keys, how to enable async chart data in the new flow
(GLOBAL_ASYNC_QUERIES flag + DISTRIBUTED_COORDINATION_CONFIG, per-request
async_mode opt-in), and how to enable the realtime websocket transport
(WEBSOCKET_* + the same-host superset-websocket server on Redis pub/sub).

Also drop the now-stale 'GLOBAL_ASYNC_QUERIES_CACHE_BACKEND is deprecated,
removed in 8.0' bullet: the key is fully removed this cycle (7.0), so the
deprecation-window narrative no longer applies.
@dosubot dosubot Bot added change:backend Requires changing the backend change:frontend Requires changing the frontend global:async-query Related to Async Queries feature labels Aug 23, 2026
@bito-code-review

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

@villebro

Copy link
Copy Markdown
Member Author

/review

@netlify

netlify Bot commented Aug 23, 2026

Copy link
Copy Markdown

✅ Deploy Preview for superset-docs-preview ready!

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

CI's superset-websocket format-check (oxfmt against the package's own
.oxfmtrc.json, which wraps narrower than the frontend config) flagged
src/index.ts. Apply the formatting, and add an oxfmt-websocket pre-commit hook
mirroring oxfmt-frontend but scoped to superset-websocket/ so this is caught
locally next time (the frontend hook only covers superset-frontend/).
Comment on lines +595 to +596
// start receiving realtime messages from Redis Pub/Sub
subscribeToChannels();

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 asynchronous subscription is started without awaiting it or attaching a local failure handler. If Redis connection setup or psubscribe rejects, the HTTP/WebSocket server continues running but receives no realtime messages, leaving the transport silently unavailable. Start the subscription before accepting traffic and handle failure explicitly, such as by aborting startup or retrying with an observable error state. [possible bug]

Severity Level: Major ⚠️
- ❌ Realtime task notifications can be missed after Redis startup failure.
- ⚠️ Health checks report ready before Pub/Sub readiness.
- ⚠️ Entity-change delivery remains unavailable until subscription recovery.

Use CodeAnt Skill

Prompt for AI Agent 🤖
This is a comment left during a code review.

**Path:** superset-websocket/src/index.ts
**Line:** 595:596
**Comment:**
	*Possible Bug: The asynchronous subscription is started without awaiting it or attaching a local failure handler. If Redis connection setup or `psubscribe` rejects, the HTTP/WebSocket server continues running but receives no realtime messages, leaving the transport silently unavailable. Start the subscription before accepting traffic and handle failure explicitly, such as by aborting startup or retrying with an observable error state.

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

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.

Fixed in a2ab075. subscribeToChannels now logs the failure and retries (and binds the pmessage router only once so retries can't stack duplicate listeners); ioredis also auto-resubscribes across reconnects. Delivery stays best-effort by design — the browser's status_changes interval poll is the correctness backstop, so startup is not aborted for an optional acceleration transport.

@bito-code-review

Copy link
Copy Markdown
Contributor

The flagged issue is correct. Starting an asynchronous subscription without awaiting its initialization or handling potential connection failures can lead to a silent failure where the WebSocket server remains active but unable to deliver realtime messages. To resolve this, you should wrap the subscription logic in an initialization function that is awaited before the server begins accepting traffic, and implement a robust error handler that prevents startup or triggers a retry mechanism if the Redis connection or subscription fails.

superset-websocket/src/index.ts

async function startServer() {
  try {
    await initializeRedisSubscription();
    await startHttpServer();
  } catch (error) {
    console.error('Failed to start server:', error);
    process.exit(1);
  }
}

Comment thread superset-websocket/src/config.ts Outdated
Comment on lines +147 to +150
ENTITY_CHANGES_CHANNEL_PREFIX: val =>
(config.entityChangesChannelPrefix = val),
PER_PRINCIPAL_CHANNEL_PREFIX: val =>
(config.perPrincipalChannelPrefix = val),

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 new environment overrides let the WebSocket service subscribe to custom Redis prefixes, but the Superset producer still publishes to hard-coded entity-changes: and realtime: prefixes and exposes no corresponding application configuration. Setting either override therefore makes the WebSocket service subscribe to channels that producers never publish to, silently disabling realtime delivery. Remove these independent overrides or wire the same values through the Flask configuration and producer. [api mismatch]

Severity Level: Major ⚠️
- ❌ Custom entity-change prefixes receive no producer messages.
- ❌ Custom per-principal prefixes break task-status delivery.
- ⚠️ Chart updates fall back to interval polling.
- ⚠️ Docker defaults mask the mismatch unless overridden.

Use CodeAnt Skill

Prompt for AI Agent 🤖
This is a comment left during a code review.

**Path:** superset-websocket/src/config.ts
**Line:** 147:150
**Comment:**
	*Api Mismatch: The new environment overrides let the WebSocket service subscribe to custom Redis prefixes, but the Superset producer still publishes to hard-coded `entity-changes:` and `realtime:` prefixes and exposes no corresponding application configuration. Setting either override therefore makes the WebSocket service subscribe to channels that producers never publish to, silently disabling realtime delivery. Remove these independent overrides or wire the same values through the Flask configuration and producer.

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

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.

Good catch — fixed in a2ab075 by removing the independent overrides. The prefixes (entity-changes: / realtime:) are a wire-protocol contract with the Python producer (TaskManager.ENTITY_CHANGES_CHANNEL_PREFIX / REALTIME_CHANNEL_PREFIX), not a deployment knob, so they're now fixed constants in the Node server (config keys, env overrides, and example/README references dropped) that must stay in lockstep with the producer.

…d channel prefixes

Two PR review findings (codeant/bito):

- The Redis Pub/Sub subscription was started fire-and-forget: if the initial
  psubscribe rejected (e.g. Redis unreachable at startup) it was an unhandled
  rejection and the transport was silently dead. subscribeToChannels now logs
  the failure and retries (and binds the pmessage router exactly once so retries
  can't stack duplicate listeners); ioredis also auto-resubscribes across
  reconnects. Delivery stays best-effort — the browser interval poll is the
  correctness backstop.
- The channel prefixes were exposed as independent Node-side config
  (entityChangesChannelPrefix / perPrincipalChannelPrefix env + config keys) with
  no matching producer-side setting, so overriding either would silently
  subscribe to channels nothing publishes to. They are a wire-protocol contract
  with the Python producer (TaskManager.ENTITY_CHANGES_CHANNEL_PREFIX /
  REALTIME_CHANNEL_PREFIX), so hardcode them as constants that must stay in
  lockstep; drop the config keys, env overrides, and example/README references.
@villebro

Copy link
Copy Markdown
Member Author

Thanks for the reviews — both findings were valid and are addressed in a2ab075:

  1. Fire-and-forget subscription (flagged by both bito and CodeAnt): subscribeToChannels no longer starts unawaited without error handling. It now logs the failure and retries (binding the pmessage router exactly once so retries can't stack duplicate listeners), and ioredis auto-resubscribes across reconnects. I deliberately did not abort startup on failure: the WebSocket transport is a best-effort acceleration layer, and the browser's status_changes interval poll (shipped earlier in this epic) is the correctness backstop — so a transient Redis hiccup degrades to polling rather than taking the server down.

  2. Configurable channel prefixes with no producer counterpart (CodeAnt): removed the independent Node-side entityChangesChannelPrefix/perPrincipalChannelPrefix config + env overrides. They are a wire-protocol contract with the Python producer (TaskManager.ENTITY_CHANGES_CHANNEL_PREFIX / REALTIME_CHANNEL_PREFIX), not a deployment knob, so they're now fixed constants that must stay in lockstep with the producer (example config + README updated to match).

tsc / eslint / oxfmt / all 46 Node tests green after the fix.

Comment thread .pre-commit-config.yaml
Comment on lines +71 to +76
- id: oxfmt-websocket
name: oxfmt (websocket)
entry: bash -c 'cd superset-websocket && files=(); for f in "$@"; do files+=("${f#superset-websocket/}"); done; npx oxfmt --write --no-error-on-unmatched-pattern -- "${files[@]}"' --
language: system
pass_filenames: true
files: ^superset-websocket/.*\.(js|ts|json)$

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.

bycatch - websocket codebase wasn't being reformatted automatically

@villebro
villebro merged commit fe47a2d into gaq-to-gtf Aug 23, 2026
58 of 59 checks passed
@villebro
villebro deleted the villebro/gtf-websocket-wiring branch August 23, 2026 17:56
@codecov

codecov Bot commented Aug 23, 2026 •

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 79.00000% with 21 lines in your changes missing coverage. Please review.
✅ Project coverage is 78.83%. Comparing base (5719f04) to head (a2ab075).
⚠️ Report is 2 commits behind head on gaq-to-gtf.

Files with missing lines Patch % Lines
superset-frontend/src/middleware/asyncEvent.ts 56.09% 18 Missing ⚠️
superset-frontend/src/pages/TaskList/index.tsx 66.66% 2 Missing ⚠️
superset/daos/tasks.py 90.00% 0 Missing and 1 partial ⚠️
Additional details and impacted files
@@              Coverage Diff               @@
##           gaq-to-gtf   #43434      +/-   ##
==============================================
- Coverage       78.84%   78.83%   -0.01%     
==============================================
  Files            2880     2882       +2     
  Lines          164425   164665     +240     
  Branches        37995    38064      +69     
==============================================
+ Hits           129636   129817     +181     
- Misses          32346    32403      +57     
- Partials         2443     2445       +2     
Flag Coverage Δ
hive 38.13% <13.20%> (-0.02%) ⬇️
mysql 57.68% <24.52%> (-0.03%) ⬇️
postgres 57.72% <24.52%> (-0.03%) ⬇️
presto 40.07% <13.20%> (-0.02%) ⬇️
python 83.52% <98.11%> (+<0.01%) ⬆️
sqlite 57.41% <24.52%> (-0.03%) ⬇️
unit 73.61% <98.11%> (+<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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

change:backend Requires changing the backend change:frontend Requires changing the frontend 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