You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@superset.apache.org by vi...@apache.org on 2026/08/30 20:30:11 UTC

(superset) branch villebro/gtf-external-review-fixes created (now 06cd5c8832c)

This is an automated email from the ASF dual-hosted git repository.

villebro pushed a change to branch villebro/gtf-external-review-fixes
in repository https://gitbox.apache.org/repos/asf/superset.git


      at 06cd5c8832c fix(gtf): harden realtime transport per external review

This branch includes the following new commits:

     new 06cd5c8832c fix(gtf): harden realtime transport per external review

The 1 revisions listed above as "new" are entirely new to this
repository and will be described in separate emails.  The revisions
listed as "add" were already present in the repository and have only
been added to this reference.



(superset) 01/01: fix(gtf): harden realtime transport per external review

Posted by vi...@apache.org.
This is an automated email from the ASF dual-hosted git repository.

villebro pushed a commit to branch villebro/gtf-external-review-fixes
in repository https://gitbox.apache.org/repos/asf/superset.git

commit 06cd5c8832c90fc673730c2828940350b907984e
Author: Ville Brofeldt <vi...@gmail.com>
AuthorDate: Sun Aug 30 13:29:21 2026 -0700

    fix(gtf): harden realtime transport per external review
    
    Addresses an external review of the realtime/websocket work:
    
    - Split the browser envelope's semantic topic from its recipient route:
      one 'realtime' pub/sub channel carrying {topic, scope, routes, payload};
      the browser now dispatches on topic and never sees routing keys.
    - StatefulChart sends tab_id on async chart-data (per-tab cancel/detach).
    - Cancel uses the tab id captured at submit, not one read fresh later.
    - Validate the client-supplied tab id at both ingress points (Flask + Node).
    - Validate policy-returned routing keys against the task's own principals.
    - Sliding-window channel-cookie re-mint + client keepalive so a realtime
      surface stays connected past the JWT lifetime.
    - Docs: broadcast is authenticated-global (not public); task.status is
      terminal-only.
---
 SECURITY.md                                        |   2 +-
 .../src/chart/components/StatefulChart.test.tsx    |  31 ++-
 .../src/chart/components/StatefulChart.tsx         |   9 +-
 .../src/chart/models/ChartProps.ts                 |   7 +
 .../src/components/Chart/ChartRenderer.tsx         |  10 +-
 .../src/middleware/asyncEvent.test.ts              |  67 ++++--
 superset-frontend/src/middleware/asyncEvent.ts     |  60 ++---
 superset-frontend/src/middleware/realtime.test.ts  |  96 ++++++--
 superset-frontend/src/middleware/realtime.ts       | 148 ++++++++----
 superset-frontend/src/views/CRUD/hooks.test.tsx    |  10 +-
 superset-frontend/src/views/CRUD/hooks.ts          |  38 +--
 superset-websocket/README.md                       | 111 +++++----
 superset-websocket/spec/index.test.ts              | 202 +++++++++-------
 superset-websocket/src/index.ts                    | 258 +++++++++++----------
 superset/config.py                                 |  29 +--
 superset/tasks/manager.py                          | 179 +++++++++-----
 superset/tasks/subscription.py                     |  21 +-
 superset/views/base.py                             |   1 +
 superset/websocket/channel.py                      |  51 ++--
 tests/unit_tests/tasks/test_manager.py             |  93 ++++++--
 tests/unit_tests/tasks/test_subscription.py        |  68 ++++++
 tests/unit_tests/websocket/test_channel.py         |  56 +++++
 22 files changed, 1046 insertions(+), 501 deletions(-)

diff --git a/SECURITY.md b/SECURITY.md
index 294b0f6b625..d327d741759 100644
--- a/SECURITY.md
+++ b/SECURITY.md
@@ -90,7 +90,7 @@ Asynchronous execution paths do not create a separate data-access capability. A
 
 Task metadata is itself a request-scoped resource. Non-admin users and embedded guests may read or cancel only tasks they are subscribed to or that otherwise represent work they are entitled to observe; Admin may observe and manage tasks as part of the trusted operational boundary. A bug that lets a principal create, read, join, cancel, or receive task state for work outside the role and capability matrix is in scope.
 
-Realtime transports, including WebSocket delivery backed by Redis or Valkey Pub/Sub, are notification mechanisms rather than authorization sources. WebSocket notification access is controlled by `can_read` on the `Realtime` resource. Broadcast Pub/Sub messages, such as list-view entity-change events, must be context-free nudges; sensitive or authoritative state must not be published on broadcast channels. Targeted Pub/Sub messages may carry task state only when the producer names routing [...]
+Realtime transports, including WebSocket delivery backed by Redis or Valkey Pub/Sub, are notification mechanisms rather than authorization sources. WebSocket notification access is controlled by `can_read` on the `Realtime` resource. The broadcast scope is authenticated-global, not public: it reaches every authenticated realtime socket, and an anonymous request receives no realtime principal, no JWT cookie, and therefore no socket, so it never receives these messages (true anonymous/Publ [...]
 
 The realtime notification permission is distinct from the permission to read the underlying object. It controls whether a principal receives push notifications, not whether they may read the object once they call the protected REST API. Existing websocket connections are authorized by the JWT accepted at upgrade time; permission revocation after token minting is bounded by `WEBSOCKET_JWT_EXPIRATION_SECONDS` plus the websocket server's socket-check interval. Redis Streams are internal ser [...]
 
diff --git a/superset-frontend/packages/superset-ui-core/src/chart/components/StatefulChart.test.tsx b/superset-frontend/packages/superset-ui-core/src/chart/components/StatefulChart.test.tsx
index ab50ab45165..e4dbbcdc45a 100644
--- a/superset-frontend/packages/superset-ui-core/src/chart/components/StatefulChart.test.tsx
+++ b/superset-frontend/packages/superset-ui-core/src/chart/components/StatefulChart.test.tsx
@@ -750,7 +750,35 @@ test('resolves async (202) responses via the injected handleAsyncChartData hook'
   });
 });
 
-test('requests async_mode when resolveAsyncMode opts in and 202 is handled', async () => {
+test('requests async_mode and the tab id when opting in and 202 is handled', async () => {
+  mockChartClient.client.post.mockResolvedValue({
+    response: { status: 200 } as Response,
+    json: [{ data: 'sync-from-cache' }],
+  });
+  const handleAsyncChartData = jest.fn().mockResolvedValue([{ data: 'x' }]);
+
+  render(
+    <StatefulChart
+      formData={mockFormData}
+      chartType="test_chart"
+      hooks={{
+        handleAsyncChartData,
+        resolveAsyncMode: () => true,
+        getTabId: () => 'tab-7',
+      }}
+    />,
+  );
+
+  await waitFor(() => {
+    expect(mockChartClient.client.post).toHaveBeenCalledTimes(1);
+  });
+  const { jsonPayload } = mockChartClient.client.post.mock.calls[0][0];
+  expect(jsonPayload.async_mode).toBe(true);
+  // The tab id lets the backend ref-count this tab (per-tab cancel/detach).
+  expect(jsonPayload.tab_id).toBe('tab-7');
+});
+
+test('omits the tab id when no getTabId hook is wired', async () => {
   mockChartClient.client.post.mockResolvedValue({
     response: { status: 200 } as Response,
     json: [{ data: 'sync-from-cache' }],
@@ -770,6 +798,7 @@ test('requests async_mode when resolveAsyncMode opts in and 202 is handled', asy
   });
   const { jsonPayload } = mockChartClient.client.post.mock.calls[0][0];
   expect(jsonPayload.async_mode).toBe(true);
+  expect(jsonPayload.tab_id).toBeUndefined();
 });
 
 test('omits async_mode when resolveAsyncMode opts out', async () => {
diff --git a/superset-frontend/packages/superset-ui-core/src/chart/components/StatefulChart.tsx b/superset-frontend/packages/superset-ui-core/src/chart/components/StatefulChart.tsx
index 6c5bc09e90e..f68c352e546 100644
--- a/superset-frontend/packages/superset-ui-core/src/chart/components/StatefulChart.tsx
+++ b/superset-frontend/packages/superset-ui-core/src/chart/components/StatefulChart.tsx
@@ -315,9 +315,14 @@ export default function StatefulChart(props: StatefulChartProps) {
           ...(force && { force: true }),
           // Opt into async execution per the injected policy (feature flag +
           // deployment default + dashboard override). We handle the 202 below via
-          // handleAsyncChartData; without the hook we stay synchronous.
+          // handleAsyncChartData; without the hook we stay synchronous. Send the
+          // tab id (when the app injected getTabId) so the backend ref-counts
+          // this tab as a consumer of the shared task, matching the Redux path.
           ...(hooks?.handleAsyncChartData && hooks?.resolveAsyncMode?.()
-            ? { async_mode: true }
+            ? {
+                async_mode: true,
+                ...(hooks?.getTabId ? { tab_id: hooks.getTabId() } : {}),
+              }
             : {}),
         },
       };
diff --git a/superset-frontend/packages/superset-ui-core/src/chart/models/ChartProps.ts b/superset-frontend/packages/superset-ui-core/src/chart/models/ChartProps.ts
index ce2362b59ae..515d0bfb087 100644
--- a/superset-frontend/packages/superset-ui-core/src/chart/models/ChartProps.ts
+++ b/superset-frontend/packages/superset-ui-core/src/chart/models/ChartProps.ts
@@ -84,6 +84,13 @@ export type Hooks = {
    * execution, per the app's resolved async policy.
    */
   resolveAsyncMode?: () => boolean;
+  /**
+   * The app's stable per-tab id, sent with an async chart-data request so the
+   * backend ref-counts this tab as a consumer of the (shared) task — a later
+   * cancel/navigate-away then detaches only this tab. Injected from the app (the
+   * package cannot import the app-level tab-id hook).
+   */
+  getTabId?: () => string;
 } & PlainObject;
 
 /**
diff --git a/superset-frontend/src/components/Chart/ChartRenderer.tsx b/superset-frontend/src/components/Chart/ChartRenderer.tsx
index 7ecf941db3c..312ded42245 100644
--- a/superset-frontend/src/components/Chart/ChartRenderer.tsx
+++ b/superset-frontend/src/components/Chart/ChartRenderer.tsx
@@ -59,6 +59,7 @@ import ChartContextMenu, {
 } from './ChartContextMenu/ChartContextMenu';
 import { handleChartDataResponse } from './chartAction';
 import { resolveAsyncMode } from 'src/utils/asyncMode';
+import { getTabId } from 'src/hooks/useTabId';
 
 // Types for filter values
 type FilterValue = string | number | boolean | null | undefined;
@@ -147,7 +148,10 @@ export interface ChartRendererProps {
 // Async resolution is injected for self-contained chart components in
 // superset-ui-core (e.g. StatefulChart), which read these off `Hooks` and cannot
 // import app-level async-event middleware themselves.
-type AsyncChartHooks = Pick<Hooks, 'handleAsyncChartData' | 'resolveAsyncMode'>;
+type AsyncChartHooks = Pick<
+  Hooks,
+  'handleAsyncChartData' | 'resolveAsyncMode' | 'getTabId'
+>;
 
 // Hooks interface
 interface ChartHooks extends AsyncChartHooks {
@@ -400,6 +404,10 @@ function ChartRendererComponent({
       // Shares the async opt-in policy (feature flag + deployment default) with
       // those self-contained producers so they don't always run synchronously.
       resolveAsyncMode: () => resolveAsyncMode(),
+      // Lets those producers send this tab's id on an async request so the
+      // backend ref-counts the tab (per-tab cancel/detach), matching the Redux
+      // chart path (see chartAction.ts).
+      getTabId: () => getTabId(),
     }),
     [
       handleAddFilter,
diff --git a/superset-frontend/src/middleware/asyncEvent.test.ts b/superset-frontend/src/middleware/asyncEvent.test.ts
index 0fae24145aa..282ea376fb9 100644
--- a/superset-frontend/src/middleware/asyncEvent.test.ts
+++ b/superset-frontend/src/middleware/asyncEvent.test.ts
@@ -25,6 +25,19 @@ jest.mock('@superset-ui/core', () => ({
   isFeatureEnabled: jest.fn(),
 }));
 
+// Mutable tab-id mock (overrides the global shim) so a test can change the tab id
+// between submit and cancel. `var` + lazy init sidesteps jest.mock hoisting/TDZ.
+/* eslint-disable no-var, vars-on-top */
+var mockTabId: string;
+/* eslint-enable no-var, vars-on-top */
+jest.mock('src/hooks/useTabId', () => {
+  mockTabId = 'test-tab-id';
+  return {
+    getTabId: () => mockTabId,
+    subscribeTabIdChange: () => () => {},
+  };
+});
+
 const mockedIsFeatureEnabled = isFeatureEnabled as jest.Mock;
 
 const STATUS_CHANGES_ENDPOINT = 'glob:*/api/v1/task/status_changes*';
@@ -63,6 +76,7 @@ afterEach(() => {
   jest.useRealTimers();
   fetchMock.clearHistory().removeRoutes();
   mockedIsFeatureEnabled.mockRestore();
+  mockTabId = 'test-tab-id';
 });
 
 test('re-issues the request once every query task succeeds', async () => {
@@ -185,6 +199,32 @@ test('aborting one chart does not cancel a shared task another chart still await
   expect(fetchMock.callHistory.calls(CANCEL_ENDPOINT)).toHaveLength(1);
 });
 
+test('cancel uses the tab id captured at submit, not a reassigned one', async () => {
+  // A duplicate-tab collision can reassign this tab's id after submit. Cancel
+  // must carry the id used at submit so the backend detaches the right per-tab
+  // subscription (reading getTabId() fresh at cancel would send the new id and
+  // orphan the original subscription).
+  queueStatuses(); // task never resolves on its own
+  asyncEvent.init(config);
+
+  mockTabId = 'tab-A';
+  const controller = new AbortController();
+  const promise = asyncEvent.waitForAsyncData(
+    { task_ids: ['task-1'] },
+    jest.fn(),
+    controller.signal,
+  );
+
+  mockTabId = 'tab-B'; // reassigned after submit
+  controller.abort();
+
+  await expect(promise).rejects.toThrow('Aborted');
+  const cancelCalls = fetchMock.callHistory.calls(CANCEL_ENDPOINT);
+  expect(cancelCalls).toHaveLength(1);
+  const body = JSON.parse(String(cancelCalls[0].options.body));
+  expect(body.tab_id).toBe('tab-A');
+});
+
 test('settles every request awaiting a deduplicated shared task', async () => {
   // Two concurrent chart requests share the same (deduplicated) task uuid; both
   // must resolve when it completes — the later waiter must not overwrite the first.
@@ -334,9 +374,12 @@ test('backs off while awaited tasks stay quiet, then polls eagerly again on prog
   await expect(promise).resolves.toEqual([]);
 });
 
-const realtime = (taskId: string, status: string) => ({
-  channel: `realtime:user:1`,
-  payload: { task_id: taskId, status },
+// The shared realtime client passes a `task.status` message's payload straight to
+// the handler (the topic already matched), so tests call the handler with just
+// the payload.
+const taskStatusPayload = (taskId: string, status: string) => ({
+  task_id: taskId,
+  status,
 });
 
 test('a realtime message settles a waiting chart without a poll', async () => {
@@ -355,7 +398,7 @@ test('a realtime message settles a waiting chart without a poll', async () => {
   // registers its waiter synchronously (before any await), so a fast task
   // whose event arrives immediately after the 202 is never missed. (Regression
   // guard: registration must not sit behind an awaited baseline fetch.)
-  asyncEvent.handleRealtimeMessage(realtime('task-1', 'success'));
+  asyncEvent.handleTaskStatus(taskStatusPayload('task-1', 'success'));
 
   expect(await promise).toEqual([{ rows: 1 }]);
   expect(refetch).toHaveBeenCalledTimes(1);
@@ -371,13 +414,13 @@ test('a realtime failure message rejects the waiting chart', async () => {
     refetch,
   );
 
-  asyncEvent.handleRealtimeMessage(realtime('task-1', 'failure'));
+  asyncEvent.handleTaskStatus(taskStatusPayload('task-1', 'failure'));
 
   await expect(promise).rejects.toThrow();
   expect(refetch).not.toHaveBeenCalled();
 });
 
-test('ignores non-realtime channels', async () => {
+test('ignores a payload without task_id/status', async () => {
   queueStatuses();
   asyncEvent.init(config);
 
@@ -387,15 +430,13 @@ test('ignores non-realtime channels', async () => {
     refetch,
   );
 
-  // A public entity-change nudge carries no status and must not settle a chart.
-  asyncEvent.handleRealtimeMessage({
-    channel: 'entity-changes:task',
-    payload: { entity_type: 'task', id: 'task-1' },
-  });
+  // A non-task-status payload (e.g. an entity-change nudge shape) must not
+  // settle a chart.
+  asyncEvent.handleTaskStatus({ entity_type: 'task', id: 'task-1' });
   expect(refetch).not.toHaveBeenCalled();
 
   // The task is still pending; complete it so the test doesn't leak a waiter.
-  asyncEvent.handleRealtimeMessage(realtime('task-1', 'success'));
+  asyncEvent.handleTaskStatus(taskStatusPayload('task-1', 'success'));
   await promise;
 });
 
@@ -407,6 +448,6 @@ test('a realtime message is a no-op when async queries are disabled', () => {
   asyncEvent.init(config);
 
   expect(() =>
-    asyncEvent.handleRealtimeMessage(realtime('task-1', 'success')),
+    asyncEvent.handleTaskStatus(taskStatusPayload('task-1', 'success')),
   ).not.toThrow();
 });
diff --git a/superset-frontend/src/middleware/asyncEvent.ts b/superset-frontend/src/middleware/asyncEvent.ts
index 8e47e2bfc4b..5db906ca6ed 100644
--- a/superset-frontend/src/middleware/asyncEvent.ts
+++ b/superset-frontend/src/middleware/asyncEvent.ts
@@ -35,11 +35,7 @@ import {
 import { logging } from '@apache-superset/core/utils';
 import getBootstrapData from 'src/utils/getBootstrapData';
 import { getTabId } from 'src/hooks/useTabId';
-import {
-  connectRealtime,
-  subscribeRealtime,
-  type RealtimeMessage,
-} from 'src/middleware/realtime';
+import { connectRealtime, subscribeRealtime } from 'src/middleware/realtime';
 
 // The GTF task type chart-data queries run under (see
 // superset/tasks/async_queries.py CHART_QUERY_TASK). Polling is filtered to this
@@ -128,11 +124,11 @@ const stopIfStale = (generation: number): boolean => {
   return true;
 };
 
-// Browser channel prefix for per-principal messages emitted by
-// superset-websocket after it fans out backend task-status events. The browser
-// socket is JWT-bound to its own principal routing key, so it only ever receives
-// its own realtime messages.
-const REALTIME_CHANNEL_PREFIX = 'realtime:';
+// GTF task-status topic emitted by superset-websocket after it fans out backend
+// task-status events (see superset/tasks/manager.py TOPIC_TASK_STATUS). Delivery
+// is scoped server-side to this principal's (or tab's) routing key, so a message
+// that reaches this browser is always its own.
+const TASK_STATUS_TOPIC = 'task.status';
 
 const fetchStatusChanges = makeApi<
   { cursor?: string | null; task_type: string },
@@ -142,18 +138,20 @@ const fetchStatusChanges = makeApi<
   endpoint: STATUS_CHANGES_URL,
 });
 
-const cancelTask = (taskId: string) => {
+const cancelTask = (taskId: string, tabId: string) => {
   // Best-effort task abort/unsubscribe. This can prevent pending work from
   // starting, but chart tasks do not cancel an underlying warehouse query after
   // execution starts. Failures are non-fatal: the client has stopped waiting.
   //
-  // Send this tab's id so the backend detaches only this tab from a shared task:
-  // if another tab of the same user is still watching it, the task keeps running
-  // and only aborts once its last tab leaves.
+  // Send the tab id captured at submit time (not read fresh here) so the backend
+  // detaches exactly the tab that subscribed: if another tab of the same user is
+  // still watching the shared task, it keeps running and only aborts once its
+  // last tab leaves. Reading getTabId() at cancel time could send a reassigned id
+  // (a duplicate-tab collision) and orphan the original per-tab subscription.
   SupersetClient.post({
     endpoint: `/api/v1/task/${taskId}/cancel`,
     headers: { 'Content-Type': 'application/json' },
-    body: JSON.stringify({ tab_id: getTabId() }),
+    body: JSON.stringify({ tab_id: tabId }),
   }).catch(error => {
     logging.warn('Failed to cancel task', taskId, error);
   });
@@ -165,9 +163,10 @@ const cancelTask = (taskId: string) => {
 // would tell the server the last subscriber left and abort work the other chart
 // needs. Call *after* removing the aborting waiter (or before registering it),
 // so a task id still present in the registry means another waiter depends on it.
-const cancelUnwaitedTasks = (taskIds: string[]) => {
+// `tabId` is the id captured when the aborting request was submitted.
+const cancelUnwaitedTasks = (taskIds: string[], tabId: string) => {
   taskIds.forEach(taskId => {
-    if (!waitersByTaskId.has(taskId)) cancelTask(taskId);
+    if (!waitersByTaskId.has(taskId)) cancelTask(taskId, tabId);
   });
 };
 
@@ -286,17 +285,14 @@ const ensurePolling = () => {
 };
 
 /**
- * Handle a realtime message from the shared client.
+ * Handle a `task.status` message from the shared realtime client.
  *
- * A per-principal chart-data payload is ``{task_id, status}``; because delivery
- * is scoped to this principal's own JWT-bound channel the status is
- * authoritative enough to settle the waiter immediately (the ensuing ``refetch``
- * reads the authorized per-query cache anyway). Other channels (e.g. the
- * ``entity-changes:*`` list-view nudges) are not chart-data's concern.
+ * The payload is ``{task_id, status}``; because delivery is scoped server-side to
+ * this principal's (or tab's) own routing key, the status is authoritative enough
+ * to settle the waiter immediately (the ensuing ``refetch`` reads the authorized
+ * per-query cache anyway).
  */
-export const handleRealtimeMessage = (message: RealtimeMessage) => {
-  const { channel, payload } = message;
-  if (!channel.startsWith(REALTIME_CHANNEL_PREFIX)) return;
+export const handleTaskStatus = (payload: unknown) => {
   if (!payload || typeof payload !== 'object') return;
   const { task_id: taskId, status } = payload as {
     task_id?: unknown;
@@ -309,7 +305,7 @@ export const handleRealtimeMessage = (message: RealtimeMessage) => {
 
 // The handler reads the live waiter registry, so it stays correct across init()
 // generations.
-subscribeRealtime(handleRealtimeMessage);
+subscribeRealtime(TASK_STATUS_TOPIC, handleTaskStatus);
 
 /**
  * Await completion of an async chart-data job's query tasks, then re-issue the
@@ -327,12 +323,18 @@ export const waitForAsyncData = async <T = unknown[]>(
 ): Promise<T> => {
   const taskIds = asyncJob.task_ids ?? [];
 
+  // Capture the tab id once, in the same tick the 202 was received, and reuse it
+  // for any later cancel/detach of these tasks. Reading it fresh at cancel time
+  // could send a different id if the tab id was reassigned meanwhile (a
+  // duplicate-tab collision), orphaning the original per-tab subscription.
+  const submitTabId = getTabId();
+
   // Register the waiter synchronously, in the same tick the 202 was received —
   // NOT after an await — so a completion socket event can't arrive before the
   // waiter exists and be dropped.
   await new Promise<void>((resolve, reject) => {
     if (signal?.aborted) {
-      cancelUnwaitedTasks(taskIds);
+      cancelUnwaitedTasks(taskIds, submitTabId);
       reject(new DOMException('Aborted', 'AbortError'));
       return;
     }
@@ -347,7 +349,7 @@ export const waitForAsyncData = async <T = unknown[]>(
     if (signal) {
       waiter.onAbort = () => {
         unregister(waiter);
-        cancelUnwaitedTasks(taskIds);
+        cancelUnwaitedTasks(taskIds, submitTabId);
         reject(new DOMException('Aborted', 'AbortError'));
       };
       signal.addEventListener('abort', waiter.onAbort, { once: true });
diff --git a/superset-frontend/src/middleware/realtime.test.ts b/superset-frontend/src/middleware/realtime.test.ts
index 165ba3fdfb7..ae6449c7fa9 100644
--- a/superset-frontend/src/middleware/realtime.test.ts
+++ b/superset-frontend/src/middleware/realtime.test.ts
@@ -16,12 +16,12 @@
  * specific language governing permissions and limitations
  * under the License.
  */
+import { SupersetClient } from '@superset-ui/core';
 import {
   connectRealtime,
   dispatchRealtimeMessage,
   resetRealtimeForTests,
   subscribeRealtime,
-  type RealtimeMessage,
 } from 'src/middleware/realtime';
 
 // Controllable useTabId mock (overrides the global shim for this file) so we can
@@ -91,42 +91,52 @@ const ENABLED = {
   WEBSOCKET_URL: 'ws://localhost:8080/',
 };
 
-test('dispatches a parsed envelope to every subscribed handler', () => {
+test('dispatches a parsed envelope to every handler of its topic', () => {
   const a = jest.fn();
   const b = jest.fn();
-  subscribeRealtime(a);
-  subscribeRealtime(b);
+  subscribeRealtime('entity.changed', a);
+  subscribeRealtime('entity.changed', b);
 
   dispatchRealtimeMessage(
-    JSON.stringify({ channel: 'entity-changes:task', payload: { id: '7' } }),
+    JSON.stringify({ topic: 'entity.changed', payload: { id: '7' } }),
   );
 
-  const expected: RealtimeMessage = {
-    channel: 'entity-changes:task',
-    payload: { id: '7' },
-  };
-  expect(a).toHaveBeenCalledWith(expected);
-  expect(b).toHaveBeenCalledWith(expected);
+  expect(a).toHaveBeenCalledWith({ id: '7' });
+  expect(b).toHaveBeenCalledWith({ id: '7' });
+});
+
+test('dispatches only to handlers subscribed to the message topic', () => {
+  const taskStatus = jest.fn();
+  const entityChanged = jest.fn();
+  subscribeRealtime('task.status', taskStatus);
+  subscribeRealtime('entity.changed', entityChanged);
+
+  dispatchRealtimeMessage(
+    JSON.stringify({ topic: 'task.status', payload: { task_id: 'a' } }),
+  );
+
+  expect(taskStatus).toHaveBeenCalledWith({ task_id: 'a' });
+  expect(entityChanged).not.toHaveBeenCalled();
 });
 
 test('unsubscribe stops a handler from receiving further messages', () => {
   const handler = jest.fn();
-  const unsubscribe = subscribeRealtime(handler);
+  const unsubscribe = subscribeRealtime('entity.changed', handler);
 
   unsubscribe();
   dispatchRealtimeMessage(
-    JSON.stringify({ channel: 'entity-changes:task', payload: {} }),
+    JSON.stringify({ topic: 'entity.changed', payload: {} }),
   );
 
   expect(handler).not.toHaveBeenCalled();
 });
 
-test('ignores malformed data and messages without a channel', () => {
+test('ignores malformed data and messages without a topic', () => {
   const handler = jest.fn();
-  subscribeRealtime(handler);
+  subscribeRealtime('entity.changed', handler);
 
   expect(() => dispatchRealtimeMessage('not json')).not.toThrow();
-  dispatchRealtimeMessage(JSON.stringify({ payload: { id: '7' } })); // no channel
+  dispatchRealtimeMessage(JSON.stringify({ payload: { id: '7' } })); // no topic
 
   expect(handler).not.toHaveBeenCalled();
 });
@@ -136,12 +146,12 @@ test('a throwing handler does not break other handlers', () => {
     throw new Error('boom');
   });
   const good = jest.fn();
-  subscribeRealtime(bad);
-  subscribeRealtime(good);
+  subscribeRealtime('entity.changed', bad);
+  subscribeRealtime('entity.changed', good);
 
   expect(() =>
     dispatchRealtimeMessage(
-      JSON.stringify({ channel: 'entity-changes:task', payload: {} }),
+      JSON.stringify({ topic: 'entity.changed', payload: {} }),
     ),
   ).not.toThrow();
   expect(good).toHaveBeenCalledTimes(1);
@@ -154,7 +164,7 @@ test('does not open a socket when disabled', () => {
 
 test('opens a socket when enabled and routes its messages to handlers', () => {
   const handler = jest.fn();
-  subscribeRealtime(handler);
+  subscribeRealtime('task.status', handler);
   connectRealtime(ENABLED);
 
   expect(FakeWebSocket.instances).toHaveLength(1);
@@ -168,13 +178,10 @@ test('opens a socket when enabled and routes its messages to handlers', () => {
   expect(wsUrl.searchParams.get('tab_id')).toBe('test-tab-id');
 
   ws.onmessage?.({
-    data: JSON.stringify({ channel: 'realtime:user:1', payload: { ok: true } }),
+    data: JSON.stringify({ topic: 'task.status', payload: { ok: true } }),
   });
 
-  expect(handler).toHaveBeenCalledWith({
-    channel: 'realtime:user:1',
-    payload: { ok: true },
-  });
+  expect(handler).toHaveBeenCalledWith({ ok: true });
 });
 
 test('resolves a root-relative ws url against the page and adds tab_id', () => {
@@ -243,3 +250,42 @@ test('disconnect closes the socket and stops reconnecting', () => {
   expect(FakeWebSocket.instances).toHaveLength(1); // no new socket
   jest.useRealTimers();
 });
+
+test('refreshes the cookie and reconnects before the token expires', async () => {
+  jest.useFakeTimers();
+  const getSpy = jest
+    .spyOn(SupersetClient, 'get')
+    .mockResolvedValue({} as never);
+  try {
+    // A 900s token → the keepalive fires at half its life (450s), issuing the
+    // authed cookie-refresh GET, then reconnecting so the new handshake rides a
+    // freshly minted token before the server terminates the socket at expiry.
+    connectRealtime({ ...ENABLED, WEBSOCKET_JWT_EXPIRATION_SECONDS: 900 });
+    expect(FakeWebSocket.instances).toHaveLength(1);
+
+    jest.advanceTimersByTime(450_000);
+    expect(getSpy).toHaveBeenCalledWith({ endpoint: '/api/v1/me/' });
+
+    // Flush the refresh promise chain so the .finally reconnect runs.
+    await Promise.resolve();
+    await Promise.resolve();
+    expect(FakeWebSocket.instances).toHaveLength(2);
+  } finally {
+    getSpy.mockRestore();
+    jest.useRealTimers();
+  }
+});
+
+test('does not schedule a keepalive without a configured token lifetime', () => {
+  jest.useFakeTimers();
+  const getSpy = jest.spyOn(SupersetClient, 'get');
+  try {
+    connectRealtime(ENABLED); // no WEBSOCKET_JWT_EXPIRATION_SECONDS
+    jest.advanceTimersByTime(60 * 60 * 1000);
+    expect(getSpy).not.toHaveBeenCalled();
+    expect(FakeWebSocket.instances).toHaveLength(1);
+  } finally {
+    getSpy.mockRestore();
+    jest.useRealTimers();
+  }
+});
diff --git a/superset-frontend/src/middleware/realtime.ts b/superset-frontend/src/middleware/realtime.ts
index 694f616526f..6a8fc26442b 100644
--- a/superset-frontend/src/middleware/realtime.ts
+++ b/superset-frontend/src/middleware/realtime.ts
@@ -20,34 +20,37 @@
 /**
  * Shared client for the realtime WebSocket transport (`superset-websocket`).
  *
- * Owns the single browser socket and fans every message out to registered
- * handlers, so multiple features share one connection: async chart-data
- * completion (per-principal `realtime:*` messages, see `asyncEvent.ts`) and
- * realtime list views (authenticated `entity-changes:*` nudges, see
- * `useListViewResource`). The server forwards a generic `{channel, payload}`
- * envelope and this client is deliberately payload-agnostic — each handler
- * routes on `channel` and interprets `payload` for its own feature.
+ * Owns the single browser socket and fans every message out to handlers
+ * registered for its topic, so multiple features share one connection: async
+ * chart-data completion (`task.status`, see `asyncEvent.ts`) and realtime list
+ * views (`entity.changed` nudges, see `useListViewResource`). The server forwards
+ * a generic `{topic, payload}` envelope — the semantic topic separated from the
+ * route it arrived by — and this client dispatches purely on `topic`; each
+ * handler interprets `payload` for its own feature.
  *
  * The transport is strictly best-effort: it is only an acceleration layer over
  * each feature's own authorized fetch/poll, so a socket outage costs latency,
  * not correctness. Connection auth is the `superset-ws-token` JWT cookie, which
  * rides the handshake automatically (same-host requirement).
  */
+import { SupersetClient } from '@superset-ui/core';
 import { logging } from '@apache-superset/core/utils';
 import getBootstrapData from 'src/utils/getBootstrapData';
 import { getTabId, subscribeTabIdChange } from 'src/hooks/useTabId';
 
 /** The generic envelope the server forwards to the browser. */
 export interface RealtimeMessage {
-  channel: string;
+  topic: string;
   payload: unknown;
 }
 
-type RealtimeHandler = (message: RealtimeMessage) => void;
+/** A topic handler receives the message payload; the topic already matched. */
+type RealtimeHandler = (payload: unknown) => void;
 
 type RealtimeConfig = {
   WEBSOCKET_ENABLE?: boolean;
   WEBSOCKET_URL?: string;
+  WEBSOCKET_JWT_EXPIRATION_SECONDS?: number;
 };
 
 // Backoff before reconnecting after the socket closes (mirrors the Node
@@ -57,39 +60,55 @@ const RECONNECT_DELAY_MS = 5000;
 const WS_CONNECTING = 0;
 const WS_OPEN = 1;
 
+// Fraction of the token lifetime after which the client proactively refreshes the
+// channel cookie and reconnects, so the socket rides a fresh token before the
+// server terminates it at expiry (see Finding 6 / superset/websocket/channel.py's
+// sliding-window re-mint). Half the lifetime lands inside that server window.
+const KEEPALIVE_FRACTION = 0.5;
+// An authed, same-origin GET whose response passes through the Flask
+// `after_request` hook that (re)mints the ws cookie. Any authed endpoint works;
+// `me` is the cheapest stable one.
+const COOKIE_REFRESH_ENDPOINT = '/api/v1/me/';
+
 let socket: WebSocket | undefined;
 let reconnectTimeoutId: number;
+let keepaliveTimeoutId: number;
+// Token lifetime (ms) from bootstrap config; 0 disables the proactive keepalive.
+let tokenLifetimeMs = 0;
 let enabled = false;
 let url: string | undefined;
 let started = false;
 // Bumped on every (re)configuration so an in-flight reconnect scheduled against
 // a superseded socket detects it is stale and stops.
 let generation = 0;
-const handlers = new Set<RealtimeHandler>();
+const handlersByTopic = new Map<string, Set<RealtimeHandler>>();
 
 /**
- * Parse a raw socket message and dispatch the `{channel, payload}` envelope to
- * every handler. Exported for tests. Strictly best-effort: malformed data and a
- * throwing handler are logged and swallowed, never propagated.
+ * Parse a raw socket message and dispatch the `{topic, payload}` envelope to the
+ * handlers registered for its topic. Exported for tests. Strictly best-effort:
+ * malformed data and a throwing handler are logged and swallowed, never
+ * propagated.
  */
 export const dispatchRealtimeMessage = (rawData: string): void => {
   let message: RealtimeMessage;
   try {
     const parsed: unknown = JSON.parse(rawData) ?? {};
     if (!parsed || typeof parsed !== 'object') return;
-    const { channel, payload } = parsed as {
-      channel?: unknown;
+    const { topic, payload } = parsed as {
+      topic?: unknown;
       payload?: unknown;
     };
-    if (typeof channel !== 'string') return;
-    message = { channel, payload };
+    if (typeof topic !== 'string') return;
+    message = { topic, payload };
   } catch (err) {
     logging.warn('Failed to parse realtime message', err);
     return;
   }
-  handlers.forEach(handler => {
+  const topicHandlers = handlersByTopic.get(message.topic);
+  if (!topicHandlers) return;
+  topicHandlers.forEach(handler => {
     try {
-      handler(message);
+      handler(message.payload);
     } catch (err) {
       logging.warn('Realtime handler error', err);
     }
@@ -119,6 +138,27 @@ const buildConnectUrl = (baseUrl: string): string => {
   }
 };
 
+const hasActiveSocket = (): boolean =>
+  socket?.readyState === WS_CONNECTING || socket?.readyState === WS_OPEN;
+
+const teardownSocket = (): void => {
+  if (reconnectTimeoutId) clearTimeout(reconnectTimeoutId);
+  if (keepaliveTimeoutId) clearTimeout(keepaliveTimeoutId);
+  if (socket) {
+    // Detach handlers first so the closing socket can't schedule a reconnect
+    // against the superseded generation.
+    socket.onmessage = null;
+    socket.onclose = null;
+    socket.onerror = null;
+    try {
+      socket.close();
+    } catch {
+      // ignore: closing an already-closed/broken socket is harmless
+    }
+    socket = undefined;
+  }
+};
+
 const openSocket = (thisGeneration: number): void => {
   if (thisGeneration !== generation) return;
   if (!enabled || !url || typeof WebSocket === 'undefined') return;
@@ -131,6 +171,28 @@ const openSocket = (thisGeneration: number): void => {
     return;
   }
   socket = ws;
+
+  // Proactively refresh the channel cookie and reconnect before this
+  // connection's token expires, so an idle realtime surface (one making no other
+  // HTTP requests, e.g. a quiet list view) does not silently lose the socket at
+  // JWT expiry. The GET re-mints the httponly cookie via the Flask after_request
+  // hook (inside its sliding window); the reconnect then rides the fresh token.
+  // Best-effort: reconnect regardless of the GET's outcome (a stale cookie just
+  // fails the handshake, and onclose retries).
+  if (enabled && tokenLifetimeMs > 0) {
+    keepaliveTimeoutId = window.setTimeout(() => {
+      if (thisGeneration !== generation || !hasActiveSocket()) return;
+      SupersetClient.get({ endpoint: COOKIE_REFRESH_ENDPOINT })
+        .catch(() => {})
+        .finally(() => {
+          if (thisGeneration !== generation) return;
+          generation += 1;
+          teardownSocket();
+          openSocket(generation);
+        });
+    }, tokenLifetimeMs * KEEPALIVE_FRACTION);
+  }
+
   ws.onmessage = (event: MessageEvent) => {
     if (thisGeneration === generation)
       dispatchRealtimeMessage(String(event.data));
@@ -147,26 +209,6 @@ const openSocket = (thisGeneration: number): void => {
   ws.onerror = () => {};
 };
 
-const hasActiveSocket = (): boolean =>
-  socket?.readyState === WS_CONNECTING || socket?.readyState === WS_OPEN;
-
-const teardownSocket = (): void => {
-  if (reconnectTimeoutId) clearTimeout(reconnectTimeoutId);
-  if (socket) {
-    // Detach handlers first so the closing socket can't schedule a reconnect
-    // against the superseded generation.
-    socket.onmessage = null;
-    socket.onclose = null;
-    socket.onerror = null;
-    try {
-      socket.close();
-    } catch {
-      // ignore: closing an already-closed/broken socket is harmless
-    }
-    socket = undefined;
-  }
-};
-
 /**
  * (Re)configure and (re)connect the shared socket. Idempotent and safe to call
  * repeatedly (e.g. from app bootstrap): it supersedes any prior socket. Reads
@@ -192,6 +234,7 @@ export const connectRealtime = (config?: RealtimeConfig): void => {
   started = true;
   enabled = nextEnabled;
   url = nextUrl;
+  tokenLifetimeMs = (conf?.WEBSOCKET_JWT_EXPIRATION_SECONDS ?? 0) * 1000;
   openSocket(generation);
 };
 
@@ -202,16 +245,27 @@ export const disconnectRealtime = (): void => {
 };
 
 /**
- * Register a handler for every realtime message; returns an unsubscribe
- * function. On the first subscription this lazily connects the socket from
- * bootstrap config (unless `connectRealtime` was already called), so a feature
- * can opt into realtime purely by subscribing.
+ * Register a handler for a realtime `topic`; returns an unsubscribe function. On
+ * the first subscription this lazily connects the socket from bootstrap config
+ * (unless `connectRealtime` was already called), so a feature can opt into
+ * realtime purely by subscribing.
  */
-export const subscribeRealtime = (handler: RealtimeHandler): (() => void) => {
-  handlers.add(handler);
+export const subscribeRealtime = (
+  topic: string,
+  handler: RealtimeHandler,
+): (() => void) => {
+  let topicHandlers = handlersByTopic.get(topic);
+  if (!topicHandlers) {
+    topicHandlers = new Set();
+    handlersByTopic.set(topic, topicHandlers);
+  }
+  topicHandlers.add(handler);
   if (!started) connectRealtime();
   return () => {
-    handlers.delete(handler);
+    const current = handlersByTopic.get(topic);
+    if (!current) return;
+    current.delete(handler);
+    if (current.size === 0) handlersByTopic.delete(topic);
   };
 };
 
@@ -230,7 +284,7 @@ subscribeTabIdChange(() => {
 // Test-only: reset module state between cases.
 export const resetRealtimeForTests = (): void => {
   disconnectRealtime();
-  handlers.clear();
+  handlersByTopic.clear();
   started = false;
   enabled = false;
   url = undefined;
diff --git a/superset-frontend/src/views/CRUD/hooks.test.tsx b/superset-frontend/src/views/CRUD/hooks.test.tsx
index d7e3e1f21b4..54b90f1f48e 100644
--- a/superset-frontend/src/views/CRUD/hooks.test.tsx
+++ b/superset-frontend/src/views/CRUD/hooks.test.tsx
@@ -607,7 +607,10 @@ test('useListViewResource: realtime nudge live-patches a displayed row in place'
   // and the fetched row is merged in place; the untouched row is unchanged.
   act(() => {
     dispatchRealtimeMessage(
-      JSON.stringify({ channel: 'entity-changes:chart', payload: { id: 1 } }),
+      JSON.stringify({
+        topic: 'entity.changed',
+        payload: { entity_type: 'chart', id: 1 },
+      }),
     );
   });
 
@@ -656,7 +659,10 @@ test('useListViewResource: realtime ignores nudges for rows not on screen', asyn
   const callsBefore = getSpy.mock.calls.length;
   act(() => {
     dispatchRealtimeMessage(
-      JSON.stringify({ channel: 'entity-changes:chart', payload: { id: 999 } }),
+      JSON.stringify({
+        topic: 'entity.changed',
+        payload: { entity_type: 'chart', id: 999 },
+      }),
     );
   });
 
diff --git a/superset-frontend/src/views/CRUD/hooks.ts b/superset-frontend/src/views/CRUD/hooks.ts
index 28f1503c939..34a19b1cad7 100644
--- a/superset-frontend/src/views/CRUD/hooks.ts
+++ b/superset-frontend/src/views/CRUD/hooks.ts
@@ -45,10 +45,7 @@ import copyTextToClipboard from 'src/utils/copy';
 import { getShareableUrl } from 'src/utils/navigationUtils';
 import SupersetText from 'src/utils/textUtils';
 import { DatabaseObject } from 'src/features/databases/types';
-import {
-  subscribeRealtime,
-  type RealtimeMessage,
-} from 'src/middleware/realtime';
+import { subscribeRealtime } from 'src/middleware/realtime';
 import {
   FavoriteStatus,
   FileEncryptedExtraFields,
@@ -273,7 +270,6 @@ export function useListViewResource<D extends object = any>(
   useEffect(() => {
     if (!enableRealtime) return undefined;
 
-    const channel = `entity-changes:${resource}`;
     const pendingIds = new Set<string>();
     let debounceId: ReturnType<typeof setTimeout> | undefined;
 
@@ -317,19 +313,25 @@ export function useListViewResource<D extends object = any>(
         });
     };
 
-    const unsubscribe = subscribeRealtime((message: RealtimeMessage) => {
-      if (message.channel !== channel) return;
-      const { payload } = message;
-      if (!payload || typeof payload !== 'object') return;
-      const { id } = payload as { id?: unknown };
-      if (id == null) return;
-      const idStr = String(id);
-      if (!isDisplayed(idStr)) return;
-      pendingIds.add(idStr);
-      if (debounceId === undefined) {
-        debounceId = setTimeout(flush, REALTIME_REFETCH_DEBOUNCE_MS);
-      }
-    });
+    // `entity.changed` nudges are broadcast for every entity type; filter to this
+    // list's resource by the payload's entity_type before matching rows.
+    const unsubscribe = subscribeRealtime(
+      'entity.changed',
+      (payload: unknown) => {
+        if (!payload || typeof payload !== 'object') return;
+        const { entity_type: entityType, id } = payload as {
+          entity_type?: unknown;
+          id?: unknown;
+        };
+        if (entityType !== resource || id == null) return;
+        const idStr = String(id);
+        if (!isDisplayed(idStr)) return;
+        pendingIds.add(idStr);
+        if (debounceId === undefined) {
+          debounceId = setTimeout(flush, REALTIME_REFETCH_DEBOUNCE_MS);
+        }
+      },
+    );
 
     return () => {
       unsubscribe();
diff --git a/superset-websocket/README.md b/superset-websocket/README.md
index 57f3519395b..e9f05cc8ab2 100644
--- a/superset-websocket/README.md
+++ b/superset-websocket/README.md
@@ -37,41 +37,62 @@ same browser-visible host.
 
 ## Architecture
 
-### Redis Pub/Sub channels and the two tiers
-
-Realtime events are published to Redis **Pub/Sub** by the Superset Flask app
-(`superset/tasks/manager.py`). Pub/Sub is intentionally lossy (fire-and-forget):
-a missed message must be reconciled by a frontend poll or REST refetch.
-Broadcast messages therefore carry only nudges; targeted task-status messages
-carry a server-side `channels` routing field naming the browser channels to
-deliver to.
-
-The server tails two Pub/Sub channels/patterns:
-
-1. **Tier 1 - authenticated entity-change nudges** (`entity-changes:<type>`,
-   e.g. `entity-changes:task`). Broadcast to every connected realtime socket.
-   The payload carries only opaque ids (`{entity_type, id}`) - no status or
-   sensitive data - so a list view can learn "an entity of this type changed"
-   and re-fetch just the affected rows through the authorized API. Each client
-   filters to the ids it renders.
-2. **Tier 2 - targeted task-status fanout** (`task-status`). Published once per
-   task status transition with `{task_id, status, channels}`. `channels` is a
-   list of server-computed routing keys; the websocket server strips it and
-   forwards `{task_id, status}` to each `realtime:<key>` browser channel. Keys
-   are principal-grain by default — `user:<id>` or `guest:<hmac>`, reaching all
-   of a principal's tabs — but a task type may narrow them to a **per-tab**
-   channel (`user:<id>:<tabId>`) so only the tab watching a task is notified
-   (async chart-data does this). A socket is bound to its per-tab channel only
-   when the browser advertises a `tab_id` on the connect URL (see Connection);
-   it is always also reachable on its principal channel.
-
-The server forwards each browser message as `{channel, payload}`. Entity-change
-messages preserve the Redis channel (`entity-changes:task`). Task-status
-messages use the server-computed browser channel (`realtime:user:42`,
-`realtime:guest:<hmac>`, or `realtime:user:42:<tabId>`) and do not expose the
-routing list to the browser. The websocket server treats each routing key as
-opaque; correctness of the keys is the producer's responsibility (Superset
-builds every key from an authorized identity).
+### The `realtime` Pub/Sub channel and the message envelope
+
+Realtime events are published to a single Redis **Pub/Sub** channel, `realtime`,
+by the Superset Flask app (`superset/tasks/manager.py`). Pub/Sub is intentionally
+lossy (fire-and-forget): a missed message must be reconciled by a frontend poll or
+REST refetch.
+
+Each Redis message is a self-describing envelope that separates **what** a message
+is from **who** receives it:
+
+```
+{ topic, scope, routes?, payload }
+```
+
+- **`topic`** — the semantic stream the browser dispatches on: `task.status`,
+  `entity.changed`, and future topics (`notification.*`, `report.progress`, …). A
+  new surface adds a topic without inventing channel names or overloading payload
+  shapes.
+- **`scope`** — the delivery breadth the server routes by:
+  - `authenticated_global` — broadcast to **every authenticated** realtime socket.
+    This is authenticated-global, **not** public: anonymous users get no realtime
+    principal, no JWT cookie, and therefore no socket, so they never receive these
+    messages. (True anonymous/Public-role realtime would need a separate,
+    restricted model and is out of scope.)
+  - `principal` / `tab` — targeted to the routing keys in `routes`. The server
+    treats the two the same way (deliver to `routes`); the distinction is only
+    descriptive.
+- **`routes`** — server-computed routing keys for a targeted scope: principal-grain
+  `user:<id>` / `guest:<hmac>` (all of a principal's tabs), or per-tab
+  `user:<id>:<tabId>` (one tab). Omitted for a broadcast. **Never forwarded to the
+  browser.**
+- **`payload`** — the feature-defined body forwarded verbatim to the browser.
+
+The two topics in use:
+
+1. **`entity.changed`** (`scope: authenticated_global`). A lossy "an entity
+   changed" broadcast whose payload carries only opaque ids
+   (`{entity_type, id}`) — no status or sensitive data — so a list view can learn
+   that an entity of a type it renders changed and re-fetch just the affected rows
+   through the authorized API. Each client filters by `entity_type` and id.
+2. **`task.status`** (`scope: principal` or `tab`). A targeted `{task_id, status}`
+   message. It is published on a task's **terminal** completion (SUCCESS, FAILURE,
+   ABORTED, TIMED_OUT), not on every intermediate transition — the chart-data
+   client only needs to learn a task finished; intermediate progress for list
+   views rides the `entity.changed` broadcast instead. Keys are principal-grain by
+   default (reaching all of a principal's tabs) but a task type may narrow them to
+   a per-tab channel (async chart-data does this), so only the tab watching a task
+   is notified. A socket is bound to its per-tab channel only when the browser
+   advertises a `tab_id` on the connect URL (see Connection); it is always also
+   reachable on its principal channel.
+
+The server forwards each browser message as `{topic, payload}` — the browser
+dispatches on `topic` and never sees the route it arrived by. The server treats
+each routing key as opaque; the producer is responsible for their correctness and
+validates every policy-supplied key against the task's own subscriber principals
+before publishing, so a key can never target another principal.
 
 ### Connection
 
@@ -97,7 +118,12 @@ per-tab channel (`<channel>:<tab_id>`, derived from the authorized principal
 channel so it can never cross principals), letting the producer target one tab.
 Because permission is checked when Superset mints the JWT and when the websocket
 server accepts the upgrade, revocation after minting is bounded by the token
-lifetime; the Superset default is 15 minutes.
+lifetime; the Superset default is 15 minutes. To keep a long-lived surface
+connected without waiting for a hard disconnect at expiry, Superset re-mints the
+cookie inside a sliding window (any request in the second half of the token's
+life gets a fresh cookie), and the browser client proactively refreshes the
+cookie and reconnects before expiry — so an active or idle-but-open realtime
+surface stays connected while revocation remains bounded by the same lifetime.
 
 During websocket JWT secret rotation, the websocket service can accept both the
 current key (`jwtSecret` / `JWT_SECRET`) and one previous verify-only key
@@ -108,7 +134,7 @@ previous key configured on the websocket service until old cookies and open
 sockets have aged out, then remove it.
 
 The service is stateless apart from process-local live socket handles. Each
-replica subscribes to the same Redis Pub/Sub channels, receives the same lossy
+replica subscribes to the same Redis Pub/Sub channel, receives the same lossy
 events, and forwards only to matching sockets connected to that replica. Sticky
 sessions are not required; reconnecting to another replica reuses the JWT cookie
 and binds the socket to the same principal channel. Short websocket JWT
@@ -212,12 +238,11 @@ this server's `config.json` (or its environment-variable overrides):
 | Cookie name                 | `WEBSOCKET_JWT_COOKIE_NAME` | `jwtCookieName` / `JWT_COOKIE_NAME`         |
 
 The Redis connection (`redis` / `REDIS_*`) must point at the same Redis instance
-Superset publishes to (`DISTRIBUTED_COORDINATION_CONFIG`). The channels the server
-**subscribes** to (`entity-changes:*` and `task-status`) are a fixed wire-protocol
-contract with the backend producer and are not configurable; the server
-republishes to browsers on the derived `realtime:<channel_id>` channel. A Redis
-ACL for this server must therefore allow subscribing to `entity-changes:*` and
-`task-status`.
+Superset publishes to (`DISTRIBUTED_COORDINATION_CONFIG`). The channel the server
+**subscribes** to (`realtime`) is a fixed wire-protocol contract with the backend
+producer and is not configurable; the server forwards each envelope to browsers as
+`{topic, payload}`. A Redis ACL for this server must therefore allow subscribing to
+`realtime`.
 
 ## StatsD monitoring
 
diff --git a/superset-websocket/spec/index.test.ts b/superset-websocket/spec/index.test.ts
index 6c5cc30c953..7b68cce8d7b 100644
--- a/superset-websocket/spec/index.test.ts
+++ b/superset-websocket/spec/index.test.ts
@@ -34,15 +34,15 @@ import { WebSocket } from 'ws';
 import * as server from '../src/index';
 import { statsd } from '../src/index';
 
-const { mockPsubscribe, mockOn } = vi.hoisted(() => {
-  return { mockPsubscribe: vi.fn(), mockOn: vi.fn() };
+const { mockSubscribe, mockOn } = vi.hoisted(() => {
+  return { mockSubscribe: vi.fn(), mockOn: vi.fn() };
 });
 
 vi.mock('ws');
 vi.mock('ioredis', () => {
   return {
     Redis: vi.fn().mockImplementation(function () {
-      return { psubscribe: mockPsubscribe, on: mockOn };
+      return { subscribe: mockSubscribe, on: mockOn };
     }),
   };
 });
@@ -250,69 +250,69 @@ describe('server', () => {
   });
 
   describe('subscribeToChannels', () => {
-    const pmessageHandlers = () =>
-      mockOn.mock.calls.filter(([event]) => event === 'pmessage');
+    const messageHandlers = () =>
+      mockOn.mock.calls.filter(([event]) => event === 'message');
 
     beforeEach(() => {
-      mockPsubscribe.mockReset();
+      mockSubscribe.mockReset();
       mockOn.mockClear();
     });
 
-    test('subscribes to the entity-change pattern and the task-status channel', async () => {
-      mockPsubscribe.mockResolvedValue(2);
+    test('subscribes to the single realtime channel', async () => {
+      mockSubscribe.mockResolvedValue(1);
 
       await server.subscribeToChannels();
 
-      expect(mockPsubscribe).toHaveBeenCalledTimes(1);
-      expect(mockPsubscribe).toHaveBeenCalledWith(
-        'entity-changes:*',
-        'task-status',
-      );
-      expect(pmessageHandlers()).toHaveLength(1);
+      expect(mockSubscribe).toHaveBeenCalledTimes(1);
+      expect(mockSubscribe).toHaveBeenCalledWith('realtime');
+      expect(messageHandlers()).toHaveLength(1);
     });
 
     test('retries a rejected subscription without stacking a second router', async () => {
       vi.useFakeTimers();
       try {
-        mockPsubscribe
+        mockSubscribe
           .mockRejectedValueOnce(new Error('redis unreachable'))
-          .mockResolvedValueOnce(2);
+          .mockResolvedValueOnce(1);
 
         await server.subscribeToChannels();
-        expect(mockPsubscribe).toHaveBeenCalledTimes(1);
+        expect(mockSubscribe).toHaveBeenCalledTimes(1);
 
         await vi.advanceTimersByTimeAsync(5000);
 
-        expect(mockPsubscribe).toHaveBeenCalledTimes(2);
-        // A retry must leave exactly one `pmessage` listener: a second one
+        expect(mockSubscribe).toHaveBeenCalledTimes(2);
+        // A retry must leave exactly one `message` listener: a second one
         // would route every message twice.
-        expect(pmessageHandlers()).toHaveLength(1);
+        expect(messageHandlers()).toHaveLength(1);
       } finally {
         vi.useRealTimers();
       }
     });
 
-    test('the registered pmessage handler routes to the matching socket', async () => {
-      mockPsubscribe.mockResolvedValue(2);
+    test('the registered message handler routes to the matching socket', async () => {
+      mockSubscribe.mockResolvedValue(1);
       await server.subscribeToChannels();
 
       const ws = new wsMock('localhost');
       const send = vi.spyOn(ws, 'send');
       trackSocket(channelId, ws);
 
-      const [, handler] = pmessageHandlers()[0] as [
+      const [, handler] = messageHandlers()[0] as [
         string,
-        (pattern: string, channel: string, message: string) => void,
+        (channel: string, message: string) => void,
       ];
       handler(
-        'entity-changes:*',
-        'entity-changes:task',
-        JSON.stringify({ entity_type: 'task', id: 'abc' }),
+        'realtime',
+        JSON.stringify({
+          topic: 'entity.changed',
+          scope: 'authenticated_global',
+          payload: { entity_type: 'task', id: 'abc' },
+        }),
       );
 
       expect(send).toHaveBeenCalledWith(
         JSON.stringify({
-          channel: 'entity-changes:task',
+          topic: 'entity.changed',
           payload: { entity_type: 'task', id: 'abc' },
         }),
       );
@@ -401,7 +401,15 @@ describe('server', () => {
   });
 
   describe('routeRedisMessage', () => {
-    test('fans a task-status message out to the named channels only', () => {
+    const taskStatus = (routes: string[], scope = 'tab') =>
+      JSON.stringify({
+        topic: 'task.status',
+        scope,
+        routes,
+        payload: { task_id: 'abc', status: 'success' },
+      });
+
+    test('fans a task-status message out to the named routes only', () => {
       // Two principals connected; a task-status message targeting user:5 reaches
       // only user:5 and is forwarded as a per-principal browser message.
       const wsA = new wsMock('localhost');
@@ -412,17 +420,12 @@ describe('server', () => {
       const sendB = vi.spyOn(wsB, 'send');
       trackSocket('user:9', wsB);
 
-      const payload = {
-        task_id: 'abc',
-        status: 'success',
-        channels: ['user:5'],
-      };
-      server.routeRedisMessage('task-status', JSON.stringify(payload));
+      server.routeRedisMessage('realtime', taskStatus(['user:5'], 'principal'));
 
       expect(sendA).toHaveBeenCalledTimes(1);
       expect(sendA).toHaveBeenCalledWith(
         JSON.stringify({
-          channel: 'realtime:user:5',
+          topic: 'task.status',
           payload: { task_id: 'abc', status: 'success' },
         }),
       );
@@ -434,16 +437,19 @@ describe('server', () => {
       const send = vi.spyOn(ws, 'send');
       trackSocket('guest:abc', ws);
 
-      const payload = {
-        task_id: 'xyz',
-        status: 'failure',
-        channels: ['guest:abc'],
-      };
-      server.routeRedisMessage('task-status', JSON.stringify(payload));
+      server.routeRedisMessage(
+        'realtime',
+        JSON.stringify({
+          topic: 'task.status',
+          scope: 'principal',
+          routes: ['guest:abc'],
+          payload: { task_id: 'xyz', status: 'failure' },
+        }),
+      );
 
       expect(send).toHaveBeenCalledWith(
         JSON.stringify({
-          channel: 'realtime:guest:abc',
+          topic: 'task.status',
           payload: { task_id: 'xyz', status: 'failure' },
         }),
       );
@@ -460,55 +466,34 @@ describe('server', () => {
       const sendB = vi.spyOn(wsB, 'send');
       server.wsConnection(wsB, makeIdentity('user:5'), 'tabB');
 
-      server.routeRedisMessage(
-        'task-status',
-        JSON.stringify({
-          task_id: 'abc',
-          status: 'success',
-          channels: ['user:5:tabA'],
-        }),
-      );
+      server.routeRedisMessage('realtime', taskStatus(['user:5:tabA']));
 
       expect(sendA).toHaveBeenCalledTimes(1);
       expect(sendA).toHaveBeenCalledWith(
         JSON.stringify({
-          channel: 'realtime:user:5:tabA',
+          topic: 'task.status',
           payload: { task_id: 'abc', status: 'success' },
         }),
       );
       expect(sendB).not.toHaveBeenCalled();
     });
 
-    test('drops an empty-string channel key', () => {
+    test('drops an envelope with an empty-string routing key', () => {
       const ws = new wsMock('localhost');
       const send = vi.spyOn(ws, 'send');
       trackSocket('user:5', ws);
 
-      server.routeRedisMessage(
-        'task-status',
-        JSON.stringify({
-          task_id: 'abc',
-          status: 'success',
-          channels: [''],
-        }),
-      );
+      server.routeRedisMessage('realtime', taskStatus(['']));
 
       expect(send).not.toHaveBeenCalled();
     });
 
-    test('deduplicates repeated channel keys within a task-status message', () => {
+    test('deduplicates repeated routing keys within a targeted message', () => {
       const ws = new wsMock('localhost');
       const send = vi.spyOn(ws, 'send');
       trackSocket('user:5', ws);
 
-      server.routeRedisMessage(
-        'task-status',
-        JSON.stringify({
-          task_id: 'abc',
-          status: 'success',
-          channels: ['user:5', 'user:5'],
-        }),
-      );
+      server.routeRedisMessage('realtime', taskStatus(['user:5', 'user:5']));
 
       expect(send).toHaveBeenCalledTimes(1);
     });
@@ -523,12 +508,16 @@ describe('server', () => {
       trackSocket('guest:abc', wsB);
 
       const payload = { entity_type: 'task', id: 'abc' };
-      server.routeRedisMessage('entity-changes:task', JSON.stringify(payload));
+      server.routeRedisMessage(
+        'realtime',
+        JSON.stringify({
+          topic: 'entity.changed',
+          scope: 'authenticated_global',
+          payload,
+        }),
+      );
 
-      const expected = JSON.stringify({
-        channel: 'entity-changes:task',
-        payload,
-      });
+      const expected = JSON.stringify({ topic: 'entity.changed', payload });
       expect(sendA).toHaveBeenCalledWith(expected);
       expect(sendB).toHaveBeenCalledWith(expected);
     });
@@ -541,43 +530,54 @@ describe('server', () => {
       server.wsConnection(ws, makeIdentity('user:5'), 'tabA');
 
       server.routeRedisMessage(
-        'entity-changes:task',
-        JSON.stringify({ entity_type: 'task', id: 'abc' }),
+        'realtime',
+        JSON.stringify({
+          topic: 'entity.changed',
+          scope: 'authenticated_global',
+          payload: { entity_type: 'task', id: 'abc' },
+        }),
       );
 
       expect(send).toHaveBeenCalledTimes(1);
     });
 
-    test('ignores a message on an unrecognized channel', () => {
+    test('swallows a malformed (non-JSON) message', () => {
       const ws = new wsMock('localhost');
       const send = vi.spyOn(ws, 'send');
       trackSocket(channelId, ws);
 
-      server.routeRedisMessage('some-other:channel', JSON.stringify({ a: 1 }));
-
+      // Must not throw; simply drops the unparseable message.
+      expect(() =>
+        server.routeRedisMessage('realtime', 'not json'),
+      ).not.toThrow();
       expect(send).not.toHaveBeenCalled();
     });
 
-    test('swallows a malformed (non-JSON) message', () => {
+    test('drops a malformed envelope (missing topic)', () => {
       const ws = new wsMock('localhost');
       const send = vi.spyOn(ws, 'send');
       trackSocket(channelId, ws);
 
-      // Must not throw; simply drops the unparseable message.
-      expect(() =>
-        server.routeRedisMessage('task-status', 'not json'),
-      ).not.toThrow();
+      server.routeRedisMessage(
+        'realtime',
+        JSON.stringify({ scope: 'authenticated_global', payload: { id: 1 } }),
+      );
+
       expect(send).not.toHaveBeenCalled();
     });
 
-    test('drops a malformed task-status message', () => {
+    test('a targeted envelope with no routes delivers nowhere', () => {
       const ws = new wsMock('localhost');
       const send = vi.spyOn(ws, 'send');
-      trackSocket(channelId, ws);
+      trackSocket('user:5', ws);
 
       server.routeRedisMessage(
-        'task-status',
-        JSON.stringify({ task_id: 'abc', status: 'success' }),
+        'realtime',
+        JSON.stringify({
+          topic: 'task.status',
+          scope: 'principal',
+          payload: { task_id: 'abc', status: 'success' },
+        }),
       );
 
       expect(send).not.toHaveBeenCalled();
@@ -586,7 +586,7 @@ describe('server', () => {
 
   describe('backpressure', () => {
     const message: server.OutboundMessage = {
-      channel: 'realtime:user:5',
+      topic: 'task.status',
       payload: { task_id: 'abc', status: 'success' },
     };
 
@@ -972,6 +972,28 @@ describe('server', () => {
       );
     });
 
+    test('an accepted upgrade ignores an invalid ?tab_id', async () => {
+      // A tab id outside the allowed length/charset must not become a channel
+      // key; the socket falls back to principal-grain (no per-tab channel).
+      const token = signRealtimeToken();
+      const ws = new wsMock('localhost');
+      const badTabId = 'a'.repeat(65);
+      const request = makeRequest({
+        token,
+        url: `http://localhost/?tab_id=${badTabId}`,
+      });
+      wssUpgradeSpy.mockImplementation(
+        (_request, _socket, _head, callback: (ws: WebSocket) => void) => {
+          callback(ws);
+        },
+      );
+
+      server.httpUpgrade(request, socket, Buffer.alloc(5));
+
+      expect(server.channels[channelId].sockets).toHaveLength(1);
+      expect(server.channels[`${channelId}:${badTabId}`]).toBeUndefined();
+    });
+
     describe('origin validation', () => {
       afterEach(() => {
         server.opts.allowedOrigins = [];
diff --git a/superset-websocket/src/index.ts b/superset-websocket/src/index.ts
index 158c0b8e265..a74659935f3 100644
--- a/superset-websocket/src/index.ts
+++ b/superset-websocket/src/index.ts
@@ -54,29 +54,32 @@ interface RealtimeJwtPayload extends JsonWebTokenPayload {
 }
 
 /**
- * The generic message the server forwards to browsers. Every connected socket
- * has a valid realtime JWT; a browser client routes on `channel`:
- *   - `entity-changes:<type>` - a lossy "an entity of this type changed"
- *     nudge, broadcast to every authenticated socket; `payload` carries opaque
- *     ids only (`{entity_type, id}`).
- *   - `realtime:<routingKey>` - a targeted task/status browser message,
- *     delivered only to sockets bound to that routing key. The producer chooses
- *     the key: a principal channel (`user:<id>` / `guest:<hmac>`) reaches all of
- *     a principal's tabs, while a per-tab key (`user:<id>:<tabId>`) reaches only
- *     the one tab. `payload` is feature-defined (e.g. `{task_id, status}`).
+ * The generic envelope the server forwards to browsers. Every connected socket
+ * has a valid realtime JWT. A browser client dispatches on `topic` (the semantic
+ * stream), never on the route it arrived by:
+ *   - `entity.changed` - a lossy "an entity changed" nudge broadcast to every
+ *     authenticated socket; `payload` carries opaque ids only (`{entity_type, id}`).
+ *   - `task.status` - a targeted task/status message delivered only to the sockets
+ *     the producer routed to; `payload` is feature-defined (e.g. `{task_id, status}`).
+ * The server-side routing keys never reach the browser.
  */
 export interface OutboundMessage {
-  channel: string;
+  topic: string;
   payload: unknown;
 }
 
-interface TaskStatusRedisPayload {
-  task_id: string;
-  status: string;
-  // Realtime routing keys to deliver to, produced by Superset (each is delivered
-  // on `realtime:<key>`). Principal-grain (`user:<id>`) by default; a task type
-  // may narrow to per-tab keys (`user:<id>:<tabId>`) via its subscription policy.
-  channels: string[];
+/**
+ * A Redis message from the Superset producer. Self-describing: `topic` is the
+ * semantic stream forwarded to the browser, `scope` is the delivery breadth the
+ * server routes by (`authenticated_global` => broadcast; otherwise targeted to
+ * `routes`), `routes` are the server-side routing keys (present for a targeted
+ * scope, absent/ignored for a broadcast), and `payload` is forwarded verbatim.
+ */
+interface RealtimeEnvelope {
+  topic: string;
+  scope: string;
+  routes?: string[];
+  payload: unknown;
 }
 
 export interface SocketIdentity {
@@ -189,16 +192,24 @@ export const wss = new WebSocketServer({
 
 const SOCKET_ACTIVE_STATES: number[] = [WebSocket.OPEN, WebSocket.CONNECTING];
 
-// The Pub/Sub channel prefixes the server tails. These are a wire-protocol
-// contract with the Superset producer (superset/tasks/manager.py:
-// ENTITY_CHANGES_CHANNEL_PREFIX / TASK_STATUS_CHANNEL), NOT a deployment
-// knob - an independent override on this side with no matching producer config
-// would silently subscribe to channels nothing publishes to, so they are fixed
-// constants that must stay in lockstep with the producer.
-const ENTITY_CHANGES_CHANNEL_PREFIX = 'entity-changes:';
-const TASK_STATUS_CHANNEL = 'task-status';
-const REALTIME_BROWSER_CHANNEL_PREFIX = 'realtime:';
-const ENTITY_CHANGES_PATTERN = `${ENTITY_CHANGES_CHANNEL_PREFIX}*`;
+// The single Pub/Sub channel the server tails. This is a wire-protocol contract
+// with the Superset producer (superset/tasks/manager.py: REALTIME_CHANNEL), NOT a
+// deployment knob - an independent override on this side with no matching producer
+// config would silently subscribe to a channel nothing publishes to, so it is a
+// fixed constant that must stay in lockstep with the producer.
+const REALTIME_CHANNEL = 'realtime';
+
+// Envelope scopes (delivery breadth), mirrored from the producer. A message is
+// broadcast to every authenticated socket when its scope is `authenticated_global`,
+// and otherwise targeted to the routing keys it names.
+const SCOPE_AUTHENTICATED_GLOBAL = 'authenticated_global';
+
+// Bound on a client-supplied tab id before it is concatenated into a channel key
+// (`<channel>:<tabId>`). The principal prefix is server-derived, but the tab
+// suffix is client-controlled, so cap its length and restrict its charset. Kept
+// in lockstep with the Flask ingress guard (superset/tasks/subscription.py).
+const TAB_ID_PATTERN = /^[A-Za-z0-9_-]{1,64}$/;
+const isValidTabId = (value: string): boolean => TAB_ID_PATTERN.test(value);
 
 // Backoff before retrying an initial Pub/Sub subscription that failed (e.g.
 // Redis unreachable at startup); see subscribeToChannels.
@@ -359,17 +370,17 @@ export const sendToChannel = (
     if (sendToSocket(socketId, strData, channel)) sentCount += 1;
   });
   logger.debug(
-    `Forwarded message ${message.channel} to ${sentCount} socket(s) on channel ${channel}`,
+    `Forwarded ${message.topic} to ${sentCount} socket(s) on channel ${channel}`,
   );
 };
 
 /**
- * Sends a message to every connected socket, regardless of channel. Used for
- * the lossy entity-change nudges (`entity-changes:*`), which carry only opaque
- * ids and are broadcast to authenticated sockets - each client filters to the
- * ids it renders. Iterates the unique socket registry (not per channel) so a
- * socket registered under both its principal and its per-tab channel still
- * receives each broadcast exactly once.
+ * Sends a message to every connected socket, regardless of channel. Used for the
+ * `authenticated_global` broadcast scope (e.g. lossy `entity.changed` nudges),
+ * which carries only opaque ids - each client filters to the ids it renders.
+ * Iterates the unique socket registry (not per channel) so a socket registered
+ * under both its principal and its per-tab channel still receives each broadcast
+ * exactly once.
  */
 export const broadcastToAll = (message: OutboundMessage): void => {
   const strData = JSON.stringify(message);
@@ -378,25 +389,43 @@ export const broadcastToAll = (message: OutboundMessage): void => {
   });
 };
 
-function isTaskStatusRedisPayload(
-  payload: unknown,
-): payload is TaskStatusRedisPayload {
-  if (!payload || typeof payload !== 'object') {
-    return false;
-  }
+/**
+ * Validate and narrow a parsed Redis message to a RealtimeEnvelope, or return
+ * null (logging) when it is malformed. A targeted (non-broadcast) envelope must
+ * carry a non-empty `routes` array of non-empty strings; a broadcast may omit it.
+ */
+function parseRealtimeEnvelope(payload: unknown): RealtimeEnvelope | null {
+  if (!payload || typeof payload !== 'object') return null;
   const candidate = payload as {
-    task_id?: unknown;
-    status?: unknown;
-    channels?: unknown;
+    topic?: unknown;
+    scope?: unknown;
+    routes?: unknown;
+    payload?: unknown;
+  };
+  if (typeof candidate.topic !== 'string' || candidate.topic.length === 0) {
+    return null;
+  }
+  if (typeof candidate.scope !== 'string' || candidate.scope.length === 0) {
+    return null;
+  }
+  let routes: string[] | undefined;
+  if (candidate.routes !== undefined) {
+    if (
+      !Array.isArray(candidate.routes) ||
+      !candidate.routes.every(
+        route => typeof route === 'string' && route.length > 0,
+      )
+    ) {
+      return null;
+    }
+    routes = candidate.routes as string[];
+  }
+  return {
+    topic: candidate.topic,
+    scope: candidate.scope,
+    routes,
+    payload: candidate.payload,
   };
-  return (
-    typeof candidate.task_id === 'string' &&
-    typeof candidate.status === 'string' &&
-    Array.isArray(candidate.channels) &&
-    candidate.channels.every(
-      channel => typeof channel === 'string' && channel.length > 0,
-    )
-  );
 }
 
 /**
@@ -420,103 +449,80 @@ export const principalChannel = (
 };
 
 /**
- * Fan out one task-status Redis message to every routing key in the payload.
- * `channels` is a server-side routing field produced by Superset (principal
- * channels by default, or per-tab channels for task types that opt in); each key
- * is delivered on `realtime:<key>` and the routing field is stripped from the
- * browser payload. The keys are opaque here - the server does not re-derive or
- * validate them (Superset builds every key from an authorized identity).
- */
-export const sendTaskStatusToSubscribers = (payload: unknown): void => {
-  if (!isTaskStatusRedisPayload(payload)) {
-    logger.error(`Invalid task status message on ${TASK_STATUS_CHANNEL}`);
-    return;
-  }
-
-  const outboundPayload = {
-    task_id: payload.task_id,
-    status: payload.status,
-  };
-  const sent = new Set<string>();
-  payload.channels.forEach(channel => {
-    if (sent.has(channel)) return;
-    sent.add(channel);
-    sendToChannel(channel, {
-      channel: `${REALTIME_BROWSER_CHANNEL_PREFIX}${channel}`,
-      payload: outboundPayload,
-    });
-  });
-};
-
-/**
- * Routes a raw Redis Pub/Sub message to the appropriate sockets.
- *
- * Task-status messages (`task-status`) include subscriber principals and are
- * fanned out to sockets whose JWT bound a matching routing key. Entity-change
- * messages (`entity-changes:<type>`) are broadcast to all sockets. Entity-change
- * messages forward the Redis channel name; task-status messages forward
- * `realtime:<routingKey>` and strip server-side routing fields.
+ * Routes a raw Redis Pub/Sub message to the appropriate sockets by its envelope
+ * scope, forwarding the browser-facing `{topic, payload}` (the server-side
+ * `routes` are stripped). An `authenticated_global` message is broadcast to every
+ * socket; any other scope is targeted to each of its `routes` (principal channels
+ * by default, or per-tab channels for task types that opt in). The routes are
+ * opaque here - the server does not re-derive or validate them (Superset builds
+ * every key from an authorized identity and validates policy-supplied keys before
+ * publishing).
  */
 export const routeRedisMessage = (
   channel: string,
   rawMessage: string,
 ): void => {
-  let payload: unknown;
+  let parsed: unknown;
   try {
-    payload = JSON.parse(rawMessage);
+    parsed = JSON.parse(rawMessage);
   } catch (err) {
     logger.error(`Failed to parse message on channel ${channel}: ${err}`);
     return;
   }
-  if (channel === TASK_STATUS_CHANNEL) {
-    sendTaskStatusToSubscribers(payload);
-  } else if (channel.startsWith(ENTITY_CHANGES_CHANNEL_PREFIX)) {
-    const message: OutboundMessage = { channel, payload };
-    broadcastToAll(message);
-  } else {
-    logger.debug(`Ignoring message on unrecognized channel ${channel}`);
+  const envelope = parseRealtimeEnvelope(parsed);
+  if (!envelope) {
+    logger.error(`Invalid realtime envelope on channel ${channel}`);
+    return;
   }
+  const outbound: OutboundMessage = {
+    topic: envelope.topic,
+    payload: envelope.payload,
+  };
+  if (envelope.scope === SCOPE_AUTHENTICATED_GLOBAL) {
+    broadcastToAll(outbound);
+    return;
+  }
+  // Targeted (principal/tab) scope: deliver to each named route once.
+  const sent = new Set<string>();
+  (envelope.routes ?? []).forEach(route => {
+    if (sent.has(route)) return;
+    sent.add(route);
+    sendToChannel(route, outbound);
+  });
 };
 
 /**
- * Subscribes the Redis connection to tier-1 entity-change nudges and tier-2
- * task-status fanout messages.
+ * Subscribes the Redis connection to the single `realtime` channel that carries
+ * every browser-bound message (broadcast and targeted, distinguished by each
+ * envelope's scope).
  *
- * Pub/Sub is lossy and not replayable, so neither tier offers server-side
- * catch-up: a message published while a socket was away is simply gone, and the
- * browser's interval poll is the correctness backstop.
+ * Pub/Sub is lossy and not replayable, so there is no server-side catch-up: a
+ * message published while a socket was away is simply gone, and the browser's
+ * interval poll is the correctness backstop.
  *
  * Failure to subscribe at all is observable and self-healing rather than silent:
- * if the initial ``psubscribe`` rejects (e.g. Redis unreachable at startup) it is
+ * if the initial ``subscribe`` rejects (e.g. Redis unreachable at startup) it is
  * logged and retried, so the transport can't end up running with no
- * subscription. ioredis additionally re-establishes these subscriptions
- * automatically across reconnects once they exist.
+ * subscription. ioredis additionally re-establishes the subscription
+ * automatically across reconnects once it exists.
  */
-let pmessageBound = false;
+let messageBound = false;
 
 export const subscribeToChannels = async (): Promise<void> => {
   // Bind the router exactly once; retries must not stack duplicate listeners
   // (which would route every message N times).
-  if (!pmessageBound) {
-    redisSubscriber.on(
-      'pmessage',
-      (_pattern: string, channel: string, message: string) => {
-        routeRedisMessage(channel, message);
-      },
-    );
-    pmessageBound = true;
+  if (!messageBound) {
+    redisSubscriber.on('message', (channel: string, message: string) => {
+      routeRedisMessage(channel, message);
+    });
+    messageBound = true;
   }
   try {
-    await redisSubscriber.psubscribe(
-      ENTITY_CHANGES_PATTERN,
-      TASK_STATUS_CHANNEL,
-    );
-    logger.info(
-      `Subscribed to Redis channels: ${ENTITY_CHANGES_PATTERN}, ${TASK_STATUS_CHANNEL}`,
-    );
+    await redisSubscriber.subscribe(REALTIME_CHANNEL);
+    logger.info(`Subscribed to Redis channel: ${REALTIME_CHANNEL}`);
   } catch (err) {
     logger.error(
-      `Failed to subscribe to Redis channels; retrying in ` +
+      `Failed to subscribe to Redis channel; retrying in ` +
         `${SUBSCRIBE_RETRY_MS}ms: ${err}`,
     );
     setTimeout(subscribeToChannels, SUBSCRIBE_RETRY_MS);
@@ -748,15 +754,15 @@ export const httpUpgrade = (
 
   // Optional per-tab id advertised on the connect URL (`?tab_id=<id>`), used to
   // also bind the socket to a per-tab channel for targeted task-status delivery.
-  // Parsed from the request URL (mirrors httpRequest); absent/blank -> no per-tab
-  // channel (principal-grain delivery, as before).
+  // Parsed from the request URL (mirrors httpRequest); absent/blank/invalid ->
+  // no per-tab channel (principal-grain delivery, as before).
   let tabId: string | undefined;
   try {
     const parsed = new URL(
       request.url ?? '',
       `http://${request.headers.host ?? 'localhost'}`,
     ).searchParams.get('tab_id');
-    if (parsed) tabId = parsed;
+    if (parsed && isValidTabId(parsed)) tabId = parsed;
   } catch {
     // Malformed URL: ignore the tab hint and fall back to principal-grain.
   }
@@ -871,5 +877,5 @@ if (startServer) {
 export const resetState = () => {
   channels = {};
   sockets = {};
-  pmessageBound = false;
+  messageBound = false;
 };
diff --git a/superset/config.py b/superset/config.py
index d9eee9d39d3..191b2351d44 100644
--- a/superset/config.py
+++ b/superset/config.py
@@ -2978,25 +2978,28 @@ GLOBAL_ASYNC_QUERIES_DEFAULT = True
 # views update without waiting for the interval poll (which stays as the
 # fallback). Requires the superset-websocket server, a Redis coordination
 # backend (DISTRIBUTED_COORDINATION_CONFIG), and `can_read` on `Realtime`.
-# Two channel tiers:
-#   - an authenticated broadcast per-entity-type pub/sub
-#     (e.g. entity-changes:task) for lossy list-view activity (opaque entity
-#     ids only), and
-#   - targeted task-status pub/sub messages for the dashboard chart-data path,
-#     fanned out by the websocket server to the routing keys the producer names.
-#     Keys are principal-grain by default (all of a principal's tabs); a task
-#     type may narrow them to a per-tab channel so only the tab watching a task
-#     is notified.
+# Two delivery scopes, carried on one lossy `realtime` pub/sub channel as a
+# self-describing `{topic, scope, routes, payload}` envelope:
+#   - `authenticated_global` — a broadcast nudge (e.g. topic `entity.changed`,
+#     opaque entity ids only) delivered to every authenticated socket for lossy
+#     list-view activity, and
+#   - `principal`/`tab` — targeted messages (e.g. topic `task.status` for the
+#     dashboard chart-data path), fanned out by the websocket server to the
+#     routing keys the producer names. Keys are principal-grain by default (all of
+#     a principal's tabs); a task type may narrow them to a per-tab channel so only
+#     the tab watching a task is notified. The route never reaches the browser,
+#     which dispatches on `topic`.
 # The JWT authenticates the socket connection and binds it to its principal
 # channel; a browser may also advertise a tab id on the connect URL to bind a
-# per-tab channel (derived from the authorized principal channel). The server
-# delivers targeted task-status events only to the named channels. Set a strong
+# per-tab channel (derived from the authorized principal channel). Set a strong
 # random WEBSOCKET_JWT_SECRET (>= 32 bytes) in production.
 # The websocket server can be configured with a previous validation secret
 # during rotations; the Flask app always mints new cookies with the current key.
 # The websocket server validates the signed token at connection time and
-# terminates sockets after JWT expiry, so post-mint permission revocation is
-# bounded by this lifetime plus the server ping interval.
+# terminates sockets after JWT expiry; the Flask app re-mints the cookie inside a
+# sliding window before expiry (on any request), and the browser proactively
+# refreshes and reconnects, so an active realtime surface stays connected. Post-
+# mint permission revocation is bounded by this lifetime plus the ping interval.
 WEBSOCKET_ENABLE = False
 WEBSOCKET_URL = "ws://127.0.0.1:8080/"
 WEBSOCKET_JWT_SECRET = CHANGE_ME_WEBSOCKET_JWT_SECRET
diff --git a/superset/tasks/manager.py b/superset/tasks/manager.py
index 8828cbd32ca..80417b5b58b 100644
--- a/superset/tasks/manager.py
+++ b/superset/tasks/manager.py
@@ -96,36 +96,103 @@ class TaskManager:
 
         cls._initialized = True
 
-    # Lossy pub/sub channels carrying opaque entity-change nudges, one
-    # channel per entity type (``entity-changes:task``, later ``:dashboard``,
-    # ``:chart``, ``:dataset`` etc.) so consumers subscribe only to the types they
-    # care about. The contract is general across all entity types: a nudge carries
-    # ONLY ``{entity_type, id}`` (the integer primary key) - no status or payload
-    # (status is task-specific and would not generalize). It's published once to
-    # the type's channel (not fanned out per subscriber). Anything sensitive
-    # (including a task's status/result) is delivered through targeted websocket
-    # fanout or fetched through the authorized REST API (``TaskFilter``/RLS), so
-    # this channel never carries authz-sensitive data.
-    ENTITY_CHANGES_CHANNEL_PREFIX = "entity-changes:"
+    # Single lossy Pub/Sub channel carrying every browser-bound realtime message
+    # (superset-websocket subscribes to just this one). Each message is a
+    # self-describing envelope ``{topic, scope, routes, payload}``:
+    #   - ``topic``   - the semantic stream (``task.status``, ``entity.changed``,
+    #     later ``notification.*`` etc.); the browser dispatches on it.
+    #   - ``scope``   - the delivery breadth the server routes by:
+    #     ``authenticated_global`` (broadcast to every authenticated socket) or
+    #     ``principal``/``tab`` (targeted to the keys in ``routes`` — the server
+    #     treats both the same way; the distinction is only descriptive).
+    #   - ``routes``  - server-computed routing keys (``user:<id>`` /
+    #     ``guest:<hmac>`` / per-tab ``user:<id>:<tabId>``), omitted for a
+    #     broadcast. They never reach the browser.
+    #   - ``payload`` - the feature-defined body forwarded to the browser.
+    # This separates the semantic topic (what a message is) from the route (who
+    # receives it): a new surface adds a topic without inventing channel names or
+    # overloading payload shapes. The channel name and envelope shape are a
+    # wire-protocol contract with the Node server. Pub/Sub is lossy, so no message
+    # here may carry a signal a receiver must not miss — each feature's authorized
+    # REST poll/fetch is the correctness backstop.
+    REALTIME_CHANNEL = "realtime"
+
+    # Envelope topics.
+    TOPIC_TASK_STATUS = "task.status"
+    TOPIC_ENTITY_CHANGED = "entity.changed"
+
+    # Envelope scopes (delivery breadth).
+    SCOPE_AUTHENTICATED_GLOBAL = "authenticated_global"
+    SCOPE_PRINCIPAL = "principal"
+    SCOPE_TAB = "tab"
+
+    @classmethod
+    def _publish_realtime(
+        cls,
+        topic: str,
+        scope: str,
+        payload: dict[str, Any],
+        routes: list[str] | None = None,
+    ) -> bool:
+        """Publish one realtime envelope on the shared channel (best-effort).
+
+        Returns False (no-op) when no coordination backend is configured; a
+        transient publish error propagates to the caller's best-effort guard.
+        ``routes`` carries the targeted routing keys and is omitted for a
+        broadcast (``authenticated_global``) scope.
+        """
+        from superset.coordination.base import CoordinationService
+        from superset.utils import json
+
+        if not CoordinationService.is_backend_defined():
+            return False
+        envelope: dict[str, Any] = {"topic": topic, "scope": scope, "payload": payload}
+        if routes is not None:
+            envelope["routes"] = routes
+        CoordinationService.publish(cls.REALTIME_CHANNEL, json.dumps(envelope))
+        return True
+
+    @staticmethod
+    def _authorized_routes(routes: list[str], principals: list[str]) -> list[str]:
+        """Keep only routing keys within one of the task's subscriber principals.
+
+        A subscription policy computes its own routing keys (e.g. per-tab
+        ``user:<id>:<tabId>``). This guards against a policy bug — or a future
+        policy — routing to a principal that is not a subscriber of the task: a key
+        is allowed only when it equals a subscriber principal channel or is a
+        per-client suffix of one (``<principal>:...``). Rejected keys are logged
+        and dropped.
+        """
+        allowed = set(principals)
+        authorized: list[str] = []
+        for route in routes:
+            if route in allowed or any(route.startswith(f"{p}:") for p in allowed):
+                authorized.append(route)
+            else:
+                logger.warning(
+                    "Dropping task-status route %s outside subscriber principals",
+                    route,
+                )
+        return authorized
 
     @classmethod
     def publish_entity_change(cls, task_uuid: UUID) -> bool:
         """Publish a lossy, opaque "entity changed" nudge for realtime UIs.
 
-        Best-effort pub/sub (may be dropped) carrying only ``{entity_type, id}``
+        Best-effort broadcast (may be dropped) carrying only ``{entity_type, id}``
         (the integer primary key, which a realtime list view matches and refetches
-        by) - no status or payload - published once to the per-type channel
-        (``entity-changes:task``). A browser transport (superset-websocket) forwards
-        it to authenticated sockets, which then re-fetch the actual (authz-scoped)
-        state through the authorized REST API. No-op when no coordination backend
-        is configured or the task no longer exists.
+        by) — no status or payload, which are task-specific and would not
+        generalize across entity types. Broadcast to every authenticated socket
+        (``scope=authenticated_global``); each client filters to the ids and types
+        it renders and re-fetches the actual (authz-scoped) state through the
+        authorized REST API. No-op when no coordination backend is configured or
+        the task no longer exists.
 
         :param task_uuid: UUID of the changed task
         :returns: True if the nudge was published, False otherwise
         """
         from superset.coordination.base import CoordinationService
         from superset.daos.tasks import TaskDAO
-        from superset.utils import json
 
         if not CoordinationService.is_backend_defined():
             return False
@@ -133,11 +200,11 @@ class TaskManager:
             task_id = TaskDAO.get_id(task_uuid)
             if task_id is None:
                 return False
-            CoordinationService.publish(
-                f"{cls.ENTITY_CHANGES_CHANNEL_PREFIX}task",
-                json.dumps({"entity_type": "task", "id": task_id}),
+            return cls._publish_realtime(
+                cls.TOPIC_ENTITY_CHANGED,
+                cls.SCOPE_AUTHENTICATED_GLOBAL,
+                {"entity_type": "task", "id": task_id},
             )
-            return True
         except Exception as ex:  # noqa: BLE001 pylint: disable=broad-except
             # Strictly best-effort: a Redis or serialization hiccup here must never
             # disrupt completion signalling - the client's interval poll is the
@@ -173,27 +240,24 @@ class TaskManager:
                 ex,
             )
 
-    # Lossy Pub/Sub channel for task status fanout. Superset publishes one
-    # message per status transition carrying the already-authorized realtime
-    # routing keys. The websocket server delivers to the matching sockets and
-    # strips ``channels`` before forwarding the task status to browsers.
-    TASK_STATUS_CHANNEL = "task-status"
-
     @classmethod
     def publish_task_status(cls, task_uuid: UUID, status: str) -> bool:
         """Publish one task ``status`` message for websocket fanout.
 
-        Best-effort delivery: publish ``{task_id, status, channels}`` once to
-        ``task-status``, where ``channels`` are the realtime routing keys the
-        websocket server delivers to (it prefixes each with ``realtime:``). By
-        default the keys are principal-grain (``user:<id>`` / ``guest:<hmac>``),
-        so the submitter and any SHARED-dedup joiners see the transition on their
+        Best-effort targeted delivery: publish a ``task.status`` envelope carrying
+        ``{task_id, status}`` to the realtime routing keys the websocket server
+        delivers to (it prefixes each with ``realtime:``). By default the keys are
+        principal-grain (``user:<id>`` / ``guest:<hmac>``, ``scope=principal``), so
+        the submitter and any SHARED-dedup joiners see the transition on their
         principal channel. A task type may narrow delivery via its subscription
         policy's ``routing_channels`` — chart-data returns its per-tab keys
-        (``user:<id>:<tabId>``) so only the tab watching the task is notified.
-        No-op when no coordination backend is configured or the task has no
-        resolvable routing keys; callers must never let a failure here disrupt
-        completion signalling (the interval poll is the backstop).
+        (``user:<id>:<tabId>``, ``scope=tab``) so only the tab watching the task is
+        notified. Policy-returned keys are validated against the task's own
+        subscriber principals (see ``_authorized_routes``) so a policy can never
+        route to another principal. No-op when no coordination backend is
+        configured or the task has no resolvable routing keys; callers must never
+        let a failure here disrupt completion signalling (the interval poll is the
+        backstop).
 
         :param task_uuid: public UUID of the task (also carried in the payload)
         :param status: the task's current status
@@ -202,7 +266,6 @@ class TaskManager:
         from superset.coordination.base import CoordinationService
         from superset.daos.tasks import TaskDAO
         from superset.tasks.registry import TaskRegistry
-        from superset.utils import json
 
         if not CoordinationService.is_backend_defined():
             return False
@@ -210,27 +273,33 @@ class TaskManager:
             task = TaskDAO.find_one_or_none(uuid=task_uuid, skip_base_filter=True)
             if task is None:
                 return False
+            # Principal-grain keys derived from the task's own subscribers: always
+            # trusted (built here from the authorized subscriber rows) and the set a
+            # policy's keys are validated against.
+            principal_routes = [
+                f"user:{p['sub']}" if p["principal_type"] == "user" else p["sub"]
+                for p in TaskDAO.get_subscriber_principals(task.id)
+            ]
             # A task type may target specific routing keys (e.g. chart-data's
-            # per-tab channels); otherwise fall back to principal-grain keys
-            # derived from the task's subscribers.
+            # per-tab channels); validate them against the subscriber principals and
+            # fall back to principal-grain if none survive (or no policy narrowed).
             policy = TaskRegistry.get_subscription_policy(task.task_type)
-            channels = policy.routing_channels(task) if policy else None
-            if channels is None:
-                channels = [
-                    f"user:{p['sub']}" if p["principal_type"] == "user" else p["sub"]
-                    for p in TaskDAO.get_subscriber_principals(task.id)
-                ]
-            if not channels:
+            policy_routes = policy.routing_channels(task) if policy else None
+            if policy_routes is not None:
+                routes = cls._authorized_routes(policy_routes, principal_routes)
+                scope = cls.SCOPE_TAB
+            else:
+                routes = []
+            if not routes:
+                routes, scope = principal_routes, cls.SCOPE_PRINCIPAL
+            if not routes:
                 return False
-            message = json.dumps(
-                {
-                    "task_id": str(task_uuid),
-                    "status": status,
-                    "channels": channels,
-                }
+            return cls._publish_realtime(
+                cls.TOPIC_TASK_STATUS,
+                scope,
+                {"task_id": str(task_uuid), "status": status},
+                routes=routes,
             )
-            CoordinationService.publish(cls.TASK_STATUS_CHANNEL, message)
-            return True
         except Exception as ex:  # noqa: BLE001 pylint: disable=broad-except
             # Strictly best-effort (mirrors publish_entity_change): a Redis or
             # serialization hiccup must never disrupt completion signalling.
diff --git a/superset/tasks/subscription.py b/superset/tasks/subscription.py
index 121bd68bf04..bd333b61738 100644
--- a/superset/tasks/subscription.py
+++ b/superset/tasks/subscription.py
@@ -23,6 +23,8 @@ stable routing id and the caller's opaque per-client id.
 
 from __future__ import annotations
 
+import re
+
 from flask import has_request_context, request
 from superset_core.tasks.subscription import TaskSubscriptionPolicy
 
@@ -31,6 +33,18 @@ __all__ = ["TaskSubscriptionPolicy", "principal_channel", "get_request_tab_id"]
 # Body/query key a client uses to advertise its per-tab id on submit and cancel.
 TAB_ID_KEY = "tab_id"
 
+# A client-supplied tab id is concatenated into routing keys, private task
+# properties, Redis channels, logs, and URLs. The principal prefix is
+# server-derived, but the tab suffix is client-controlled, so bound it: at most 64
+# chars from a conservative charset. Kept in lockstep with the websocket server's
+# ingress guard (superset-websocket/src/index.ts TAB_ID_PATTERN).
+_TAB_ID_RE = re.compile(r"^[A-Za-z0-9_-]{1,64}$")
+
+
+def _is_valid_tab_id(value: object) -> bool:
+    """Return whether ``value`` is a well-formed, safely-bounded tab id."""
+    return isinstance(value, str) and bool(_TAB_ID_RE.match(value))
+
 
 def principal_channel(user_id: int | None, guest_key: str | None) -> str | None:
     """Return a principal's stable routing id, or ``None`` if unidentified.
@@ -55,7 +69,8 @@ def get_request_tab_id() -> str | None:
     Clients advertise a stable per-tab id (see ``superset-frontend`` ``getTabId``)
     in the JSON body — falling back to a query arg — of chart-data submit and task
     cancel requests. It is ``None`` outside a request context (e.g. a Celery
-    worker) or when the caller supplied none, in which case the task's
+    worker), when the caller supplied none, or when the supplied value is not a
+    well-formed tab id (see ``_is_valid_tab_id``), in which case the task's
     subscription policy falls back to principal-grain behavior.
     """
     if not has_request_context():
@@ -63,7 +78,7 @@ def get_request_tab_id() -> str | None:
     body = request.get_json(silent=True)
     if isinstance(body, dict):
         tab_id = body.get(TAB_ID_KEY)
-        if isinstance(tab_id, str) and tab_id:
+        if _is_valid_tab_id(tab_id):
             return tab_id
     tab_id = request.args.get(TAB_ID_KEY)
-    return tab_id or None
+    return tab_id if _is_valid_tab_id(tab_id) else None
diff --git a/superset/views/base.py b/superset/views/base.py
index 1db18db55b9..213e211f952 100644
--- a/superset/views/base.py
+++ b/superset/views/base.py
@@ -97,6 +97,7 @@ FRONTEND_CONF_KEYS = (
     "GLOBAL_ASYNC_QUERIES_DEFAULT",
     "WEBSOCKET_ENABLE",
     "WEBSOCKET_URL",
+    "WEBSOCKET_JWT_EXPIRATION_SECONDS",
     "SQL_VALIDATORS_BY_ENGINE",
     "SQLALCHEMY_DOCS_URL",
     "SQLALCHEMY_DISPLAY_TEXT",
diff --git a/superset/websocket/channel.py b/superset/websocket/channel.py
index 6ebad6a0e3e..492cab83c98 100644
--- a/superset/websocket/channel.py
+++ b/superset/websocket/channel.py
@@ -145,8 +145,8 @@ def _valid_payload_channel(payload: dict[str, object]) -> str | None:
     return channel
 
 
-def _cookie_channel(token: str) -> str | None:
-    """Return the ``channel`` claim of a valid, unexpired channel token, else None."""
+def _decode_cookie(token: str) -> dict[str, object] | None:
+    """Return the claims of a valid, unexpired channel token, else None."""
     from flask import current_app
 
     try:
@@ -159,20 +159,46 @@ def _cookie_channel(token: str) -> str | None:
         )
     except jwt.InvalidTokenError:
         return None
-    if not isinstance(payload, dict):
-        return None
-    return _valid_payload_channel(payload)
+    return payload if isinstance(payload, dict) else None
+
+
+def _should_remint(existing: str | None, channel_id: str) -> bool:
+    """Whether the channel cookie must be (re)minted for ``channel_id``.
+
+    Re-mints when the cookie is missing, invalid/expired, bound to a different
+    principal's channel, or inside a sliding refresh window before expiry (less
+    than half its lifetime remaining). The sliding window keeps an active
+    surface's socket alive indefinitely: any request in the second half of the
+    token's life issues a fresh cookie, so the socket reconnects before the
+    server terminates it at expiry (rather than only re-minting after expiry).
+    """
+    from flask import current_app
+
+    if not existing:
+        return True
+    payload = _decode_cookie(existing)
+    if payload is None:
+        return True
+    if _valid_payload_channel(payload) != channel_id:
+        return True
+    exp = payload.get("exp")
+    if not isinstance(exp, (int, float)):
+        return True
+    lifetime = current_app.config["WEBSOCKET_JWT_EXPIRATION_SECONDS"]
+    remaining = exp - datetime.now(tz=timezone.utc).timestamp()
+    return remaining < lifetime / 2
 
 
 def register_ws_channel_cookie(app: Flask) -> None:
     """Keep the websocket channel-token cookie in sync with the request principal.
 
     Sets an ``httponly`` JWT cookie (which the ``superset-websocket`` server
-    verifies) bound to the current principal's channel. Critically, it re-mints
-    the cookie whenever the bound channel no longer matches the current principal
-    — e.g. after a logout/login in the same browser — and deletes it when there is
-    no principal (anonymous / logged out), so a stale token can never bind a new
-    session to a previous user's channel.
+    verifies) bound to the current principal's channel. Re-mints the cookie
+    whenever the bound channel no longer matches the current principal — e.g.
+    after a logout/login in the same browser — or when it is inside the sliding
+    refresh window before expiry, and deletes it when there is no principal
+    (anonymous / logged out), so a stale token can never bind a new session to a
+    previous user's channel and an active surface never silently loses realtime.
     """
     cookie_name = app.config["WEBSOCKET_JWT_COOKIE_NAME"]
     cookie_domain = app.config["WEBSOCKET_JWT_COOKIE_DOMAIN"]
@@ -193,10 +219,7 @@ def register_ws_channel_cookie(app: Flask) -> None:
             return response
 
         channel_id = principal["channel"]
-
-        # Leave a cookie that already binds the current channel; re-mint when it is
-        # missing, invalid/expired, or bound to a different principal's channel.
-        if existing and _cookie_channel(existing) == channel_id:
+        if not _should_remint(existing, channel_id):
             return response
 
         response.set_cookie(
diff --git a/tests/unit_tests/tasks/test_manager.py b/tests/unit_tests/tasks/test_manager.py
index 4187a047c8b..7b25b8416bf 100644
--- a/tests/unit_tests/tasks/test_manager.py
+++ b/tests/unit_tests/tasks/test_manager.py
@@ -159,7 +159,7 @@ class TestTaskManagerPublish:
 
 
 class TestTaskManagerEntityChange:
-    """publish_entity_change emits one opaque nudge to the per-type channel."""
+    """publish_entity_change emits one opaque broadcast nudge on ``realtime``."""
 
     def setup_method(self):
         _reset_prefixes()
@@ -178,18 +178,22 @@ class TestTaskManagerEntityChange:
     @patch(GET_ID, return_value=42)
     @patch(PUBLISH)
     @patch(IS_DEFINED, return_value=True)
-    def test_publishes_opaque_nudge_to_per_type_channel(
+    def test_publishes_opaque_broadcast_nudge(
         self, mock_defined, mock_publish, mock_get_id
     ):
         assert TaskManager.publish_entity_change(uuid.uuid4()) is True
 
-        # One publish to the task type's channel, carrying ONLY opaque ids (the
-        # integer primary key) - no status or payload (the contract is general
-        # across all entity types).
+        # One publish on the single realtime channel, an entity.changed broadcast
+        # envelope carrying ONLY opaque ids (the integer primary key) - no status
+        # (the contract is general across all entity types).
         mock_publish.assert_called_once()
         channel, message = mock_publish.call_args.args[:2]
-        assert channel == "entity-changes:task"
-        assert json.loads(message) == {"entity_type": "task", "id": 42}
+        assert channel == "realtime"
+        assert json.loads(message) == {
+            "topic": "entity.changed",
+            "scope": "authenticated_global",
+            "payload": {"entity_type": "task", "id": 42},
+        }
 
     @patch(GET_ID, return_value=None)
     @patch(PUBLISH)
@@ -238,7 +242,7 @@ class TestTaskManagerPublishRequiredByChanged:
 
 
 class TestTaskManagerPublishTaskStatus:
-    """publish_task_status emits one fanout message carrying routing channels."""
+    """publish_task_status emits one task.status envelope carrying routing keys."""
 
     def setup_method(self):
         _reset_prefixes()
@@ -259,10 +263,10 @@ class TestTaskManagerPublishTaskStatus:
     @patch(DAO)
     @patch(PUBLISH)
     @patch(IS_DEFINED, return_value=True)
-    def test_publishes_principal_channels_without_policy(
+    def test_publishes_principal_routes_without_policy(
         self, mock_defined, mock_publish, mock_dao, mock_policy
     ):
-        """No policy -> principal-grain channels derived from subscribers."""
+        """No policy -> principal-grain routes derived from subscribers."""
         task_uuid = uuid.uuid4()
         mock_dao.find_one_or_none.return_value = MagicMock(id=7, task_type="some_type")
         mock_dao.get_subscriber_principals.return_value = [
@@ -275,11 +279,12 @@ class TestTaskManagerPublishTaskStatus:
         mock_dao.get_subscriber_principals.assert_called_once_with(7)
         mock_publish.assert_called_once()
         channel, message = mock_publish.call_args.args[:2]
-        assert channel == "task-status"
+        assert channel == "realtime"
         assert json.loads(message) == {
-            "task_id": str(task_uuid),
-            "status": "success",
-            "channels": ["user:1", "guest:abc"],
+            "topic": "task.status",
+            "scope": "principal",
+            "payload": {"task_id": str(task_uuid), "status": "success"},
+            "routes": ["user:1", "guest:abc"],
         }
 
     @patch(DAO)
@@ -289,16 +294,66 @@ class TestTaskManagerPublishTaskStatus:
         """A task type's policy narrows delivery to its per-tab channels."""
         task_uuid = uuid.uuid4()
         mock_dao.find_one_or_none.return_value = MagicMock(id=7, task_type="chart")
+        # The per-tab keys are within the task's subscriber principal (user:5), so
+        # they survive validation.
+        mock_dao.get_subscriber_principals.return_value = [
+            {"principal_type": "user", "sub": "5"},
+        ]
         policy = MagicMock()
         policy.routing_channels.return_value = ["user:5:tabA", "user:5:tabB"]
 
         with patch(self.POLICY, return_value=policy):
             assert TaskManager.publish_task_status(task_uuid, "success") is True
 
-        # Per-tab keys used; the principal-grain fallback is not consulted.
-        mock_dao.get_subscriber_principals.assert_not_called()
         _, message = mock_publish.call_args.args[:2]
-        assert json.loads(message)["channels"] == ["user:5:tabA", "user:5:tabB"]
+        body = json.loads(message)
+        assert body["scope"] == "tab"
+        assert body["routes"] == ["user:5:tabA", "user:5:tabB"]
+
+    @patch(DAO)
+    @patch(PUBLISH)
+    @patch(IS_DEFINED, return_value=True)
+    def test_drops_policy_routes_outside_subscriber_principals(
+        self, mock_defined, mock_publish, mock_dao
+    ):
+        """A policy key outside the task's principals is dropped (Finding 5)."""
+        task_uuid = uuid.uuid4()
+        mock_dao.find_one_or_none.return_value = MagicMock(id=7, task_type="chart")
+        mock_dao.get_subscriber_principals.return_value = [
+            {"principal_type": "user", "sub": "5"},
+        ]
+        policy = MagicMock()
+        # user:5:tabA is valid; user:999 belongs to another principal → dropped.
+        policy.routing_channels.return_value = ["user:5:tabA", "user:999"]
+
+        with patch(self.POLICY, return_value=policy):
+            assert TaskManager.publish_task_status(task_uuid, "success") is True
+
+        _, message = mock_publish.call_args.args[:2]
+        assert json.loads(message)["routes"] == ["user:5:tabA"]
+
+    @patch(DAO)
+    @patch(PUBLISH)
+    @patch(IS_DEFINED, return_value=True)
+    def test_all_policy_routes_invalid_falls_back_to_principal(
+        self, mock_defined, mock_publish, mock_dao
+    ):
+        """When every policy key is rejected, fall back to principal-grain."""
+        task_uuid = uuid.uuid4()
+        mock_dao.find_one_or_none.return_value = MagicMock(id=7, task_type="chart")
+        mock_dao.get_subscriber_principals.return_value = [
+            {"principal_type": "user", "sub": "5"},
+        ]
+        policy = MagicMock()
+        policy.routing_channels.return_value = ["user:999:tabX"]
+
+        with patch(self.POLICY, return_value=policy):
+            assert TaskManager.publish_task_status(task_uuid, "success") is True
+
+        _, message = mock_publish.call_args.args[:2]
+        body = json.loads(message)
+        assert body["scope"] == "principal"
+        assert body["routes"] == ["user:5"]
 
     @patch(POLICY)
     @patch(DAO)
@@ -316,7 +371,9 @@ class TestTaskManagerPublishTaskStatus:
 
         assert TaskManager.publish_task_status(uuid.uuid4(), "success") is True
         _, message = mock_publish.call_args.args[:2]
-        assert json.loads(message)["channels"] == ["user:1"]
+        body = json.loads(message)
+        assert body["scope"] == "principal"
+        assert body["routes"] == ["user:1"]
 
     @patch(POLICY, return_value=None)
     @patch(DAO)
diff --git a/tests/unit_tests/tasks/test_subscription.py b/tests/unit_tests/tasks/test_subscription.py
new file mode 100644
index 00000000000..e04e4ed24a0
--- /dev/null
+++ b/tests/unit_tests/tasks/test_subscription.py
@@ -0,0 +1,68 @@
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements.  See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership.  The ASF licenses this file
+# to you under the Apache License, Version 2.0 (the
+# "License"); you may not use this file except in compliance
+# with the License.  You may obtain a copy of the License at
+#
+#   http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing,
+# software distributed under the License is distributed on an
+# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+# KIND, either express or implied.  See the License for the
+# specific language governing permissions and limitations
+# under the License.
+
+import pytest
+from flask import current_app
+
+from superset.tasks.subscription import get_request_tab_id, principal_channel
+
+
+def test_principal_channel_derivation() -> None:
+    assert principal_channel(5, None) == "user:5"
+    assert principal_channel(None, "guest:abc") == "guest:abc"
+    assert principal_channel(None, None) is None
+
+
+def test_get_request_tab_id_from_json_body() -> None:
+    with current_app.test_request_context(
+        "/api/v1/chart/data", json={"tab_id": "tab-7"}
+    ):
+        assert get_request_tab_id() == "tab-7"
+
+
+def test_get_request_tab_id_from_query_arg() -> None:
+    with current_app.test_request_context("/api/v1/chart/data?tab_id=tab-7"):
+        assert get_request_tab_id() == "tab-7"
+
+
+def test_get_request_tab_id_none_outside_request_context() -> None:
+    assert get_request_tab_id() is None
+
+
+@pytest.mark.parametrize(
+    "value",
+    [
+        "",  # empty
+        "a" * 65,  # too long
+        "tab id",  # space
+        "tab/../etc",  # path traversal chars
+        "tab:evil",  # colon (would split a routing key)
+        "tab\nid",  # newline
+        "táb",  # non-ascii
+    ],
+)
+def test_get_request_tab_id_rejects_invalid(value: str) -> None:
+    # An out-of-bound/ill-formed tab id is dropped (falls back to principal-grain),
+    # never flowing into routing keys, private props, channels, logs, or URLs.
+    with current_app.test_request_context("/api/v1/chart/data", json={"tab_id": value}):
+        assert get_request_tab_id() is None
+
+
+def test_get_request_tab_id_accepts_full_allowed_charset() -> None:
+    value = "Ab9_-" * 12  # 60 chars, within the 64 cap
+    with current_app.test_request_context("/api/v1/chart/data", json={"tab_id": value}):
+        assert get_request_tab_id() == value
diff --git a/tests/unit_tests/websocket/test_channel.py b/tests/unit_tests/websocket/test_channel.py
index e69bf3780d6..74f0c8ad809 100644
--- a/tests/unit_tests/websocket/test_channel.py
+++ b/tests/unit_tests/websocket/test_channel.py
@@ -206,6 +206,62 @@ def test_cookie_signed_with_old_secret_is_reminted_with_current_secret(mocker) -
     assert _ws_set_cookies(client.get("/_ws_probe"))
 
 
+def _mint_ws_token(
+    exp_delta_seconds: int,
+    secret: str = "x" * 40,
+    channel_id: str = "user:1",
+) -> str:
+    from superset.websocket.permissions import (
+        REALTIME_NOTIFICATION_JWT_AUDIENCE,
+        REALTIME_NOTIFICATION_JWT_ISSUER,
+    )
+
+    return jwt.encode(
+        {
+            "channel": channel_id,
+            "principal_type": "user",
+            "sub": channel_id.split(":")[1],
+            "aud": REALTIME_NOTIFICATION_JWT_AUDIENCE,
+            "iss": REALTIME_NOTIFICATION_JWT_ISSUER,
+            "exp": datetime.now(tz=timezone.utc) + timedelta(seconds=exp_delta_seconds),
+        },
+        secret,
+        algorithm="HS256",
+    )
+
+
+def test_cookie_not_reminted_when_fresh(mocker) -> None:
+    from superset.websocket import channel
+
+    client = _make_ws_app().test_client()
+    mocker.patch.object(channel, "can_access_realtime_notifications", return_value=True)
+    mocker.patch.object(
+        channel.security_manager, "get_current_guest_user_if_guest", return_value=None
+    )
+    mocker.patch.object(channel, "get_user_id", return_value=1)
+
+    # Full lifetime remaining (> half of 3600s) → the hook leaves it alone, so a
+    # Set-Cookie header is not written on every request.
+    client.set_cookie("superset-ws-token", _mint_ws_token(3600))
+    assert not _ws_set_cookies(client.get("/_ws_probe"))
+
+
+def test_cookie_reminted_inside_refresh_window(mocker) -> None:
+    from superset.websocket import channel
+
+    client = _make_ws_app().test_client()
+    mocker.patch.object(channel, "can_access_realtime_notifications", return_value=True)
+    mocker.patch.object(
+        channel.security_manager, "get_current_guest_user_if_guest", return_value=None
+    )
+    mocker.patch.object(channel, "get_user_id", return_value=1)
+
+    # Only 60s remaining (< half of 3600s) → sliding-window re-mint keeps an active
+    # surface's socket alive past the original expiry (Finding 6).
+    client.set_cookie("superset-ws-token", _mint_ws_token(60))
+    assert _ws_set_cookies(client.get("/_ws_probe"))
+
+
 def test_cookie_cleared_for_anonymous(mocker) -> None:
     from superset.websocket import channel