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

alexandrusoare pushed a commit to branch 
alexandrusoare/feat/canvas-instrumentation
in repository https://gitbox.apache.org/repos/asf/superset.git

commit a89536bc9339b65dfa5bedaf7d6ba42cb0b03dbc
Author: alexandrusoare <[email protected]>
AuthorDate: Tue Nov 17 17:37:44 2026 +0200

    feat(canvas): raise canvas events from the frontend
    
    The canvas pages produced no telemetry of any kind: grepping the whole
    feature for `logEvent`, `Logger` or `LOG_ACTIONS` returned nothing. Worse,
    the logger middleware had no canvas branch, so even the `load_chart` and
    `render_chart` events that shared chart components raise *inside* a canvas
    shipped with no source and no id attached.
    
    Attribute events from `activeCanvas` rather than adding redux state or
    parsing the URL. The canvas page already keeps it current and clears it on
    the way out, so reading it covers every event raised while a canvas is
    open, including those raised by components that know nothing about canvas.
    It is imported from `src/core/canvas` directly rather than through the
    `src/core` barrel: the barrel reaches the telemetry namespace, which
    imports the store, which applies this middleware.
    
    Add the `canvas_*` event names, following the `sqllab_*` precedent, and a
    `useCanvasLogger` hook that attaches the canvas's context. The hook is not
    `useLogAction` because that one nests its fields under a `payload` key,
    which would hide `canvas_id` from both the beacon's query-parameter lift
    and the per-record fallback that fills the column. It includes `canvas_id`
    in the body as well, since the beacon derives its query parameters from the
    first event in a batch and a batch spanning a navigation would otherwise
    mislabel the rest.
    
    Two producers to start: `canvas_mount`, raised once the canvas is really on
    screen so its duration means something, and `canvas_load_definition`. The
    latter also covers the worst of the silent failures -- a refresh that fails
    keeps the last good definition and tells the user nothing, so the event
    carries `is_silent` and is the only signal that path will ever produce.
    
    Only ids, types, counts and booleans are recorded. No filter values, no
    widget data, no titles, and never a token or a full URL, since a draft's
    URL ends in `#draft=<token>`.
---
 .../src/features/canvas/useCanvasDefinition.ts     | 38 +++++++++-
 .../src/features/canvas/useCanvasLogger.ts         | 85 ++++++++++++++++++++++
 superset-frontend/src/logger/LogUtils.ts           | 36 +++++++++
 .../src/middleware/loggerMiddleware.ts             | 27 ++++++-
 superset-frontend/src/pages/Canvas/index.tsx       | 25 +++++++
 5 files changed, 207 insertions(+), 4 deletions(-)

diff --git a/superset-frontend/src/features/canvas/useCanvasDefinition.ts 
b/superset-frontend/src/features/canvas/useCanvasDefinition.ts
index d4a6f89f906..a11a6ddabd6 100644
--- a/superset-frontend/src/features/canvas/useCanvasDefinition.ts
+++ b/superset-frontend/src/features/canvas/useCanvasDefinition.ts
@@ -24,7 +24,13 @@ import {
   subscribeRealtimeOpen,
 } from 'src/middleware/realtime';
 import getBootstrapData from 'src/utils/getBootstrapData';
+import {
+  Logger,
+  LOG_ACTIONS_CANVAS_ERROR,
+  LOG_ACTIONS_CANVAS_LOAD_DEFINITION,
+} from 'src/logger/LogUtils';
 import { CanvasDefinitionResult } from './types';
+import { useCanvasLogger } from './useCanvasLogger';
 
 /** Draft tokens travel in this header, never in a URL. */
 export const DRAFT_TOKEN_HEADER = 'X-Canvas-Draft';
@@ -64,12 +70,18 @@ export function useCanvasDefinition(canvasId: number, 
draftToken?: string) {
   });
   const revision = useRef<number>();
   const loadedCanvas = useRef<number>();
+  // The source a complete result was last loaded for, so a failed refresh can
+  // tell itself apart from a failed first open without reading state.
+  const loaded = useRef<string>();
   // Drops a response for a source the page has since moved off.
   const source = useRef<string>();
   source.current = `${canvasId}:${draftToken ?? ''}`;
 
+  const log = useCanvasLogger(canvasId, { isDraft: Boolean(draftToken) });
+
   const load = useCallback(async () => {
     const requested = `${canvasId}:${draftToken ?? ''}`;
+    const startedAt = Logger.getTimestamp();
     try {
       const { json } = await SupersetClient.get(
         draftToken
@@ -81,19 +93,41 @@ export function useCanvasDefinition(canvasId: number, 
draftToken?: string) {
       );
       if (source.current !== requested) return;
       revision.current = json.result.revision;
+      loaded.current = requested;
       setState({ status: 'complete', result: json.result, draftToken });
+      log(LOG_ACTIONS_CANVAS_LOAD_DEFINITION, {
+        revision: json.result.revision,
+        definition_version: json.result.definition?.version,
+        widget_count: Object.keys(json.result.definition?.nodes ?? {}).length,
+        duration: Logger.getTimestamp() - startedAt,
+      });
     } catch (response) {
       const error = await getClientErrorObject(response);
       if (source.current !== requested) return;
       // Keep showing the last good definition if a refresh of the same
-      // source fails; a draft that fails to open is an error.
+      // source fails; a draft that fails to open is an error. Read from a ref
+      // rather than from `state`, which would put `state` in this callback's
+      // dependencies and make every load schedule the next one.
+      const silent = loaded.current === requested;
       setState(previous =>
         previous.status === 'complete' && previous.draftToken === draftToken
           ? previous
           : { status: 'error', error },
       );
+      // `is_silent` marks the refresh case above, which shows the user
+      // nothing at all. This event is the only signal it ever produces.
+      log(LOG_ACTIONS_CANVAS_ERROR, {
+        scope: 'definition_load',
+        status: error.status,
+        // The typed error, where the server classified one. Never
+        // `error.message`: it is server-authored prose that can quote SQL,
+        // column names or row values.
+        error_type: error.errors?.[0]?.error_type,
+        has_err: true,
+        is_silent: silent,
+      });
     }
-  }, [canvasId, draftToken]);
+  }, [canvasId, draftToken, log]);
 
   useEffect(() => {
     revision.current = undefined;
diff --git a/superset-frontend/src/features/canvas/useCanvasLogger.ts 
b/superset-frontend/src/features/canvas/useCanvasLogger.ts
new file mode 100644
index 00000000000..20443cb5809
--- /dev/null
+++ b/superset-frontend/src/features/canvas/useCanvasLogger.ts
@@ -0,0 +1,85 @@
+/**
+ * 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.
+ */
+
+/**
+ * @fileoverview Raising canvas events, with the canvas's own context attached.
+ *
+ * Deliberately not `useLogAction`: that hook nests its fields under a
+ * `payload` key, which would hide `canvas_id` from both the beacon's
+ * query-parameter lift and the per-record fallback the DB event logger uses to
+ * fill `logs.canvas_id`.
+ *
+ * What may be recorded: ids, types, counts, durations and booleans. What may
+ * not: filter values, widget data, canvas or widget titles, a draft token, or
+ * a full URL -- a draft's URL ends in `#draft=<token>`.
+ */
+
+import { useCallback, useMemo } from 'react';
+import { useDispatch } from 'react-redux';
+import { logEvent } from 'src/logger/actions';
+
+/** Scalars only, so content cannot be dropped into a log row wholesale. */
+export type CanvasEventData = Record<
+  string,
+  string | number | boolean | null | undefined
+>;
+
+export interface CanvasLogContext {
+  /** Whether the change is happening in a draft rather than on the canvas. */
+  isDraft?: boolean;
+  /** Set while a published version is being previewed. */
+  versionUuid?: string;
+}
+
+export type CanvasLogger = (name: string, data?: CanvasEventData) => void;
+
+/**
+ * Returns a function that raises a canvas event.
+ *
+ * `canvas_id` is included in the event body as well as being derived by the
+ * logger middleware from the open canvas. The middleware fills the beacon's
+ * query parameters from the batch's *first* event only, so a batch spanning a
+ * navigation would otherwise label the rest with the wrong id.
+ */
+export function useCanvasLogger(
+  canvasId: number | undefined,
+  context: CanvasLogContext = {},
+): CanvasLogger {
+  const dispatch = useDispatch();
+  const { isDraft, versionUuid } = context;
+
+  const shared = useMemo(
+    () => ({
+      canvas_id: canvasId,
+      is_draft: Boolean(isDraft),
+      ...(versionUuid ? { version_uuid: versionUuid } : {}),
+    }),
+    [canvasId, isDraft, versionUuid],
+  );
+
+  return useCallback(
+    (name: string, data: CanvasEventData = {}) => {
+      if (canvasId === undefined) return;
+      dispatch(logEvent(name, { ...shared, ...data }));
+    },
+    [canvasId, dispatch, shared],
+  );
+}
+
+export default useCanvasLogger;
diff --git a/superset-frontend/src/logger/LogUtils.ts 
b/superset-frontend/src/logger/LogUtils.ts
index 3ea9d1f7172..50fd0efd5c1 100644
--- a/superset-frontend/src/logger/LogUtils.ts
+++ b/superset-frontend/src/logger/LogUtils.ts
@@ -92,6 +92,34 @@ export const LOG_ACTIONS_SQLLAB_LOAD_TAB_STATE = 
'sqllab_load_tab_state';
 export const LOG_ACTIONS_SQLLAB_SWITCH_SOUTH_PANE_TAB =
   'sqllab_switch_south_pane_tab';
 
+// Canvas 
-----------------------------------------------------------------------
+// Every canvas event carries `canvas_id`, which `loggerMiddleware` fills from
+// the open canvas. Record ids and types only: never a filter value, never a
+// widget's data, never a canvas or widget title, and never a draft token or a
+// full URL -- a draft's URL ends in `#draft=<token>`, which is why the token
+// travels in a header in the first place. Whether a change is happening in a
+// draft is reported as the boolean `is_draft`.
+export const LOG_ACTIONS_CANVAS_MOUNT = 'canvas_mount';
+export const LOG_ACTIONS_CANVAS_LOAD_DEFINITION = 'canvas_load_definition';
+// `canvas_edit_layout` is the user's intent, recorded once per completed
+// gesture; `canvas_write_layout` is what the server did with it. They are
+// separate because an optimistic write can be rolled back, and counting only
+// the gesture would read every attempt as a success.
+export const LOG_ACTIONS_CANVAS_EDIT_LAYOUT = 'canvas_edit_layout';
+export const LOG_ACTIONS_CANVAS_WRITE_LAYOUT = 'canvas_write_layout';
+export const LOG_ACTIONS_CANVAS_DRAFT_START = 'canvas_draft_start';
+// Carries `outcome: 'commit' | 'discard'` rather than splitting into two
+// events: the funnel is then arithmetic against `canvas_draft_start`, and an
+// abandoned draft is the absence of this event, which no constant can capture.
+export const LOG_ACTIONS_CANVAS_DRAFT_END = 'canvas_draft_end';
+export const LOG_ACTIONS_CANVAS_DRAFT_HISTORY = 'canvas_draft_history';
+export const LOG_ACTIONS_CANVAS_FILTER_CHANGE = 'canvas_filter_change';
+export const LOG_ACTIONS_CANVAS_REFRESH_WIDGET = 'canvas_refresh_widget';
+export const LOG_ACTIONS_CANVAS_VERSION_PREVIEW = 'canvas_version_preview';
+export const LOG_ACTIONS_CANVAS_VERSION_RESTORE = 'canvas_version_restore';
+export const LOG_ACTIONS_CANVAS_CHAT_PANEL = 'canvas_chat_panel';
+export const LOG_ACTIONS_CANVAS_ERROR = 'canvas_error';
+
 // Log event types 
--------------------------------------------------------------
 export const LOG_EVENT_TYPE_TIMING = new Set([
   LOG_ACTIONS_LOAD_CHART,
@@ -99,6 +127,14 @@ export const LOG_EVENT_TYPE_TIMING = new Set([
   LOG_ACTIONS_HIDE_BROWSER_TAB,
   LOG_ACTIONS_SQLLAB_FETCH_FAILED_QUERY,
   LOG_ACTIONS_SQLLAB_LOAD_TAB_STATE,
+  // Both follow a user action they should attach to. Membership has a
+  // consequence the name hides: a timing event gets no `event_id` of its own
+  // and inherits `trigger_event` instead. That is wrong for
+  // `canvas_error`, which often fires with no preceding user action -- a
+  // background poll failing, a widget throwing during render -- so it stays a
+  // user-type event and keeps its own id.
+  LOG_ACTIONS_CANVAS_LOAD_DEFINITION,
+  LOG_ACTIONS_CANVAS_WRITE_LAYOUT,
 ]);
 export const LOG_EVENT_TYPE_USER = new Set([
   LOG_ACTIONS_MOUNT_DASHBOARD,
diff --git a/superset-frontend/src/middleware/loggerMiddleware.ts 
b/superset-frontend/src/middleware/loggerMiddleware.ts
index f4627df0272..4a2ed0641bf 100644
--- a/superset-frontend/src/middleware/loggerMiddleware.ts
+++ b/superset-frontend/src/middleware/loggerMiddleware.ts
@@ -29,6 +29,7 @@ import {
   LOG_ACTIONS_SPA_NAVIGATION,
 } from '../logger/LogUtils';
 import DebouncedMessageQueue from '../utils/DebouncedMessageQueue';
+import { canvas } from '../core/canvas';
 import { ensureAppRoot } from '../utils/navigationUtils';
 import type { DashboardInfo, DashboardLayoutState } from '../dashboard/types';
 import type { QueryEditor } from '../SqlLab/types';
@@ -38,13 +39,15 @@ type LogEventSource =
   | 'embedded_dashboard'
   | 'explore'
   | 'sqlLab'
-  | 'slice';
+  | 'slice'
+  | 'canvas';
 
 interface LogEventData {
   source?: LogEventSource;
   source_id?: string | number;
   dashboard_id?: number;
   slice_id?: number;
+  canvas_id?: number;
   db_id?: number;
   schema?: string;
   impression_id?: string;
@@ -108,6 +111,8 @@ const sendBeacon = (events: LogEventData[]): void => {
     endpoint += `&dashboard_id=${source_id}`;
   } else if (source === 'slice') {
     endpoint += `&slice_id=${source_id}`;
+  } else if (source === 'canvas') {
+    endpoint += `&canvas_id=${source_id}`;
   }
 
   if (navigator.sendBeacon) {
@@ -177,7 +182,25 @@ const loggerMiddleware: Middleware<
     // and `/embedded/:uuid/`) rather than any URL containing "/embedded/", 
which
     // would misclassify a regular dashboard whose slug is "embedded".
     const isEmbedded = EMBEDDED_ROUTE_REGEX.test(path ?? '');
-    if (dashboardInfo?.id && (path?.includes('/dashboard/') || isEmbedded)) {
+    // The canvas page keeps `activeCanvas` current and clears it on the way
+    // out, so reading it attributes every event raised while a canvas is open
+    // -- including the `load_chart` and `render_chart` events that shared 
chart
+    // components raise inside one, which otherwise carry no source at all.
+    // Imported from the module rather than the `src/core` barrel: the barrel
+    // reaches the telemetry namespace, which imports the store, which applies
+    // this middleware.
+    const activeCanvas = canvas.getActiveCanvas();
+    if (activeCanvas) {
+      logMetadata = {
+        source: 'canvas',
+        source_id: activeCanvas.id,
+        canvas_id: activeCanvas.id,
+        ...logMetadata,
+      };
+    } else if (
+      dashboardInfo?.id &&
+      (path?.includes('/dashboard/') || isEmbedded)
+    ) {
       logMetadata = {
         source: isEmbedded ? 'embedded_dashboard' : 'dashboard',
         source_id: dashboardInfo.id,
diff --git a/superset-frontend/src/pages/Canvas/index.tsx 
b/superset-frontend/src/pages/Canvas/index.tsx
index 507ec625102..15ae409c038 100644
--- a/superset-frontend/src/pages/Canvas/index.tsx
+++ b/superset-frontend/src/pages/Canvas/index.tsx
@@ -44,6 +44,8 @@ import { useCanvasDefinition } from 
'src/features/canvas/useCanvasDefinition';
 import { useDraftToken } from 'src/features/canvas/useDraftToken';
 import { registerBuiltinRenderers } from 
'src/features/canvas/builtinRenderers';
 import { useCanvasId } from 'src/features/canvas/useCanvasId';
+import { useCanvasLogger } from 'src/features/canvas/useCanvasLogger';
+import { Logger, LOG_ACTIONS_CANVAS_MOUNT } from 'src/logger/LogUtils';
 import { useCanvasRefresh } from 'src/features/canvas/useCanvasRefresh';
 import CanvasBody from 'src/features/canvas/CanvasBody';
 import CanvasVersionHistory from 
'src/features/canvas/versionHistory/CanvasVersionHistory';
@@ -189,6 +191,29 @@ function CanvasContent({ id }: { id: number }) {
   }, [id, title, revision]);
   useEffect(() => () => setActiveCanvas(undefined), [id]);
 
+  // Raised once the canvas is actually on screen -- both the metadata and the
+  // definition have arrived -- rather than when the component first renders,
+  // so `mount_duration` measures what the user waited for.
+  const log = useCanvasLogger(id, { isDraft: Boolean(draft.token) });
+  const mounted = useRef(false);
+  const nodeCount =
+    state.status === 'complete'
+      ? Object.keys(state.result.definition.nodes).length
+      : undefined;
+  useEffect(() => {
+    if (mounted.current || nodeCount === undefined || revision === undefined) {
+      return;
+    }
+    mounted.current = true;
+    log(LOG_ACTIONS_CANVAS_MOUNT, {
+      revision,
+      widget_count: nodeCount,
+      is_empty: nodeCount === 0,
+      is_version_preview: Boolean(history.preview),
+      mount_duration: Logger.getTimestamp(),
+    });
+  }, [log, nodeCount, revision, history.preview]);
+
   if (draft.token && state.status === 'error') {
     return (
       <EmptyState

Reply via email to