:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
chore(notebooks): remove legacy python, duckdb and hogql code cells (#93970)
Sinan Kucukkoseler67cb0090ffe1
diff --git a/frontend/snapshots.yml b/frontend/snapshots.ymlindex 18a052d046b2..4b0cff44a5a2 100644--- a/frontend/snapshots.yml+++ b/frontend/snapshots.yml@@ -1329,13 +1329,13 @@ snapshots:components-markdown-editor-rich--with-markdown--light:hash: v1.k794b7964.98bef7667e05e7a86864149a5db5c24b3d4733bcef7d413ab6faf3053c79fba8.evR63xGwLPTzXw6Hi35ROggl2AHmH_y5lT5p05kFGTgcomponents-markdown-notebook--component-catalog--dark:- hash: v1.k794b7964.8d4bc1ec68c46621e7f0fa8d9ab9c83fc4a5c214fbba1dec162e9bb086643758.kBJyYgTMXU0MN-WCD6K4BcTw4Dne_Y5LCut3zY83OuU+ hash: v1.k794b7964.a7705b33b2bb9d98a08dad08712a89455876a99422d2d2c60e7d2186d2412796.wxqLNiekJQaoxnPyCAogVqcN8btyRGECwxbDHFxoS2ocomponents-markdown-notebook--component-catalog--light:- hash: v1.k794b7964.a271d8587dd1ca78ee5dc1807e4ee870107b870e8dab1d0f2879793aaa8c4c47.p6UB4SqhpZmoUAnPrm9xSbDCXvoiYo5sdU8LYFXO63E+ hash: v1.k794b7964.eb844685cb6a3ab768d8c1c74fe84f4d51adc510a50a44126744dcd3b919bb1e.1s8P4Q2-sbukjdWiExZTHltVpSUJutIlxwS5brNLcHYcomponents-markdown-notebook--edit-mode--dark:- hash: v1.k794b7964.8d4bc1ec68c46621e7f0fa8d9ab9c83fc4a5c214fbba1dec162e9bb086643758.ig05ITme_EPFYL3KY08K057vpdYx-nJ8n-JQ_ZlE490+ hash: v1.k794b7964.357bbb3296468c08d63ca60dea277f8afce5c0f727506930936fa7271c8f8cab.VhQZKHHbWlE1aPqf_mSJWjjqEyvh7t8uvnPFBaKmrXUcomponents-markdown-notebook--edit-mode--light:- hash: v1.k794b7964.a271d8587dd1ca78ee5dc1807e4ee870107b870e8dab1d0f2879793aaa8c4c47.QgiUe5oowox4oU3NA1R11g63jlkj7DvNqruOFWMmcng+ hash: v1.k794b7964.2b50a7214a259cacb867278bf6dd070949e45dad815c6f4185914b945f8459a0.dPMS6jBv514DDGE-__ybAFYZGxjTLWqkPQFzn4L_Eascomponents-markdown-notebook--embeds--dark:hash: v1.k794b7964.039153a86528fc9caf6ae134f3c6a224f07d1c2d137a56b273e73f7b4771ae88.0xkasBfNfhuidhktYwUseCqBisLD2ta03gq1V1vfbLIcomponents-markdown-notebook--embeds--light:@@ -1401,9 +1401,9 @@ snapshots:components-markdown-notebook--text-only-notebook--light:hash: v1.k794b7964.49b1faad617f02f9410865aca560b5f791996f66b94386bb9d251e2d1277cb85.im1gVBON-vQHqByuqa5D0lz6iC28fyKFi6YNsTf3kdocomponents-markdown-notebook--view-mode--dark:- hash: v1.k794b7964.51ab7b78d93381f2feb60a6b11a3627b3fbd3712af9d3a69e250ed2b3e3abd60.Kj_GIFMMlxIlMtl1b633-Z_Sbl0fjjYuKAOTMGOW8t0+ hash: v1.k794b7964.65f815528713ad514b84ac27d00677dfb875533c3de1d91c1bdc8f4a8ff9c5d5.1VVFVMZ-xn5_8rZ5IEM3nqQJut84nLoDB_CQ33ijIpAcomponents-markdown-notebook--view-mode--light:- hash: v1.k794b7964.3453caeef81feb028f0eeef4c6d59a387648ff4a2ac3fa3c40485c516b0f11db.ZDJLV3a68LGPOnRLVtnJx4j-6i-M4FwBitp_iYbLw2Q+ hash: v1.k794b7964.6e095c601e0f2eeb7a171bdcaf26cae50d4f59de68401eb89190912f26c17b77.IIbj_YIF2cO5RWtf6FhWbHrJIgQaGTTN6IWiRY36TlMcomponents-mcp-hint-toast--annotations-create--dark:hash: v1.k794b7964.eec2ed99e26c3e17bb863aee733524cf25a5ae76808f594bdc41c0eddf501b8f.x88L0pkIlEBj6PedsMSeWEWk04MeGS8PbIdYCJmYYjscomponents-mcp-hint-toast--annotations-create--light:diff --git a/frontend/src/lib/api.ts b/frontend/src/lib/api.tsindex e7282477b8ba..80ee18dad72c 100644--- a/frontend/src/lib/api.ts+++ b/frontend/src/lib/api.ts@@ -4823,63 +4823,6 @@ const api = {): Promise<Record<string, any>> {return await new ApiRequest().notebook(notebookId).withAction('kernel/execute').create({ data })},- async hogqlExecute(- notebookId: NotebookType['short_id'],- data: { query: string }- ): Promise<{ columns?: string[]; results?: any[]; error?: string }> {- return await new ApiRequest().notebook(notebookId).withAction('hogql/execute').create({ data })- },- async kernelExecuteStream(- notebookId: NotebookType['short_id'],- data: {- code: string- return_variables?: boolean- timeout?: number- },- {- onMessage,- onError,- signal,- }: {- onMessage: (data: EventSourceMessage) => void- onError: (error: any) => void- signal?: AbortSignal- }- ): Promise<void> {- const url = new ApiRequest().notebook(notebookId).withAction('kernel/execute/stream').assembleFullUrl(true)- await api.stream(url, {- method: 'POST',- data,- onMessage,- onError,- signal,- })- },- async kernelDataframe(- notebookId: NotebookType['short_id'],- params: {- variable_name: string- offset?: number- limit?: number- timeout?: number- }- ): Promise<{- columns: string[]- rows: Record<string, any>[]- rowCount: number- }> {- const response = await new ApiRequest()- .notebook(notebookId)- .withAction('kernel/dataframe')- .withQueryString(params)- .get()-- return {- columns: response.columns ?? [],- rows: response.rows ?? [],- rowCount: response.row_count ?? 0,- }- },async kernelStart(notebookId: NotebookType['short_id']): Promise<Record<string, any>> {return await new ApiRequest().notebook(notebookId).withAction('kernel/start').create()},diff --git a/frontend/src/lib/components/MarkdownNotebook/MarkdownNotebook.stories.tsx b/frontend/src/lib/components/MarkdownNotebook/MarkdownNotebook.stories.tsxindex 63f533e9abaf..3d18e167d785 100644--- a/frontend/src/lib/components/MarkdownNotebook/MarkdownNotebook.stories.tsx+++ b/frontend/src/lib/components/MarkdownNotebook/MarkdownNotebook.stories.tsx@@ -44,9 +44,9 @@ const componentCatalogNotebook = `# Component catalog<Query query={{"kind":"SavedInsightNode","shortId":"abc123"}} />-<Python title="Python" code="print('hello')" />+<PythonV2 title="Python" code="print('hello')" />-<DuckSQL title="SQL (DuckDB)" code="select * from events" returnVariable="duck_df" />+<SQLV2 title="SQL" code="select * from events" returnVariable="sql_df" /><RecordingPlaylist title="Session recordings" />diff --git a/frontend/src/lib/components/MarkdownNotebook/documentModel.ts b/frontend/src/lib/components/MarkdownNotebook/documentModel.tsindex 675c2a3a6b06..111ac1794e40 100644--- a/frontend/src/lib/components/MarkdownNotebook/documentModel.ts+++ b/frontend/src/lib/components/MarkdownNotebook/documentModel.ts@@ -813,7 +813,8 @@ export function serializeNotebookNodes(nodes: NotebookBlockNode[]): string {}// Props whose value is an execution result object that can hold cached base64 media. `result` is-// the PythonV2/SQLV2 shape; the others are the legacy in-browser-kernel Python and SQL cells.+// the PythonV2/SQLV2 shape. The legacy in-browser-kernel keys stay because stored notebooks still+// hold legacy cells, which keep their tag and their media.const MEDIA_BEARING_PROP_KEYS = ['result', 'pythonExecution', 'duckExecution', 'hogqlExecution']// Remove cached media (e.g. base64 chart images) from component results so notebook markdown fitsdiff --git a/frontend/src/lib/constants.tsx b/frontend/src/lib/constants.tsxindex a86f86977f18..1b0a3d9ab835 100644--- a/frontend/src/lib/constants.tsx+++ b/frontend/src/lib/constants.tsx@@ -409,7 +409,6 @@ export const FEATURE_FLAGS = {NEW_TAB_PROJECT_EXPLORER: 'new-tab-project-explorer', // owner: #team-platform-uxNEW_TEAM_CORE_EVENTS: 'new-team-core-events', // owner: @jabahamondes #team-web-analyticsNOTEBOOK_GENERATED_WIDGETS: 'notebook-generated-widgets', // owner: #team-data-tools- NOTEBOOK_PYTHON: 'notebook-python', // owner: #team-data-toolsNOTEBOOK_SHARING: 'notebook-sharing', // owner: @reecejones #team-platform-featuresONBOARDING_AI_REPORTS: 'onboarding-role-notifications', // owner: @joethreepwood #team-growth multivariate=control,test — offers a role-tailored weekly AI report step at the end of onboarding; code additionally gates on AI subscriptions being available, so keep the flag at 100% rollout (key predates the AI-reports naming; it's bound to the live experiment)ONBOARDING_DATA_WAREHOUSE_VALUE_PROP: 'onboarding-data-warehouse-value-prop', // owner: @fercgomes #team-growth multivariate=control,table,querydiff --git a/frontend/src/scenes/notebooks/Nodes/NodeWrapper.tsx b/frontend/src/scenes/notebooks/Nodes/NodeWrapper.tsxindex 8703470e60f8..ac8aba86d81a 100644--- a/frontend/src/scenes/notebooks/Nodes/NodeWrapper.tsx+++ b/frontend/src/scenes/notebooks/Nodes/NodeWrapper.tsx@@ -5,15 +5,11 @@ import './NodeWrapper.scss'import { LemonSkeleton } from 'lib/lemon-ui/LemonSkeleton'import { BindLogic, useActions, useMountedLogic, useValues } from 'kea'import { notebookLogic } from '../Notebook/notebookLogic'-import { hashCodeForString } from 'lib/utils/strings'import { useInView } from 'react-intersection-observer'import { ErrorBoundary } from '~/layout/ErrorBoundary'import { NotebookNodeLogicProps, notebookNodeLogic } from './notebookNodeLogic'import { KNOWN_NODES } from '../utils'import { NotebookNodeTitle } from './components/NotebookNodeTitle'-import { DuckSqlRunMenu } from './components/DuckSqlRunMenu'-import { HogqlSqlRunMenu } from './components/HogqlSqlRunMenu'-import { PythonRunMenu } from './components/PythonRunMenu'import { NotebookNodeContext } from './NotebookNodeContext'import { IconCollapse, IconEllipsis, IconExpand, IconPencil } from '@posthog/icons'import {@@ -58,7 +54,7 @@ function NodeWrapper<T extends CustomNotebookNodeAttributes>(props: NodeWrapperP} = propsconst mountedNotebookLogic = useMountedLogic(notebookLogic)- const { isEditable, editingNodeIds, containerSize, notebook, isShared } = useValues(mountedNotebookLogic)+ const { isEditable, editingNodeIds, containerSize, isShared } = useValues(mountedNotebookLogic)const { unregisterNodeLogic, insertComment, selectComment } = useActions(notebookLogic)const logicProps: NotebookNodeLogicProps = {@@ -72,31 +68,13 @@ function NodeWrapper<T extends CustomNotebookNodeAttributes>(props: NodeWrapperPresizeable,expanded,nodeId,- pythonRunLoading,- duckSqlRunLoading,- duckSqlRunQueued,- hogqlSqlRunLoading,- hogqlSqlRunQueued,- pythonRunQueued,settingsPlacement: resolvedSettingsPlacement,sourceComment,- duckSqlReturnVariable,- hogqlSqlReturnVariable,customMenuItems,actions,- kernelInfo,} = useValues(nodeLogic)- const {- setRef,- setExpanded,- deleteNode,- toggleEditing,- toggleEditingTitle,- copyToClipboard,- runPythonNodeWithMode,- runDuckSqlNodeWithMode,- runHogqlSqlNodeWithMode,- } = useActions(nodeLogic)+ const { setRef, setExpanded, deleteNode, toggleEditing, toggleEditingTitle, copyToClipboard } =+ useActions(nodeLogic)const { ref: inViewRef, inView } = useInView({ triggerOnce: !unmountWhenOutOfView })@@ -129,15 +107,12 @@ function NodeWrapper<T extends CustomNotebookNodeAttributes>(props: NodeWrapperP// css resize sets the style attr so we check that to detect changes. Resize obsserver doesn't trigger for style changesconst heightAttr = contentRef.current?.style.heightif (heightAttr && heightAttr !== initialHeightAttr) {- updateAttributes({- height: contentRef.current?.clientHeight,- ...(nodeType === NotebookNodeType.Python ? { autoHeight: false } : {}),- } as any)+ updateAttributes({ height: contentRef.current?.clientHeight } as any)}}window.addEventListener('mouseup', onResizedEnd)- }, [nodeType, resizeable, updateAttributes])+ }, [resizeable, updateAttributes])const parsedHref = typeof href === 'function' ? href(attributes) : href@@ -168,75 +143,14 @@ function NodeWrapper<T extends CustomNotebookNodeAttributes>(props: NodeWrapperPwindow.removeEventListener('pointermove', onPointerMove)window.removeEventListener('pointerup', onPointerUp)- updateAttributes({- height: element.clientHeight,- ...(nodeType === NotebookNodeType.Python ? { autoHeight: false } : {}),- } as any)+ updateAttributes({ height: element.clientHeight } as any)}window.addEventListener('pointermove', onPointerMove)window.addEventListener('pointerup', onPointerUp)},- [isEditable, isResizeable, nodeType, updateAttributes]- )- const isPythonNode = nodeType === NotebookNodeType.Python- const isDuckSqlNode = nodeType === NotebookNodeType.DuckSQL- const isHogqlSqlNode = nodeType === NotebookNodeType.HogQLSQL- const runDisabledReason = !notebook ? 'Notebook not loaded' : undefined- const pythonAttributes = attributes as {- code?: string- pythonExecutionCodeHash?: number | null- pythonExecutionSandboxId?: string | null- }- const pythonExecutionCodeHash = pythonAttributes.pythonExecutionCodeHash ?? null- const pythonCodeHash = hashCodeForString(typeof pythonAttributes.code === 'string' ? pythonAttributes.code : '')- const pythonExecutionSandboxId = pythonAttributes.pythonExecutionSandboxId ?? null- const kernelSandboxId = kernelInfo?.sandbox_id ?? null- const kernelIsRunning = kernelInfo?.status === 'running'- const pythonHasExecution = pythonExecutionCodeHash !== null- const pythonSandboxMatches =- pythonExecutionSandboxId !== null && kernelSandboxId !== null && pythonExecutionSandboxId === kernelSandboxId- const pythonIsFresh =- pythonHasExecution && pythonExecutionCodeHash === pythonCodeHash && pythonSandboxMatches && kernelIsRunning- const pythonIsStale = pythonHasExecution && !pythonIsFresh- const duckSqlAttributes = attributes as {- code?: string- duckExecutionCodeHash?: number | null- duckExecutionSandboxId?: string | null- returnVariable?: string- }- const duckSqlExecutionCodeHash = duckSqlAttributes.duckExecutionCodeHash ?? null- const duckSqlCodeHash = hashCodeForString(- `${typeof duckSqlAttributes.code === 'string' ? duckSqlAttributes.code : ''}\n${duckSqlReturnVariable}`+ [isEditable, isResizeable, updateAttributes])- const duckSqlExecutionSandboxId = duckSqlAttributes.duckExecutionSandboxId ?? null- const duckSqlHasExecution = duckSqlExecutionCodeHash !== null- const duckSqlSandboxMatches =- duckSqlExecutionSandboxId !== null && kernelSandboxId !== null && duckSqlExecutionSandboxId === kernelSandboxId- const duckSqlIsFresh =- duckSqlHasExecution && duckSqlExecutionCodeHash === duckSqlCodeHash && duckSqlSandboxMatches && kernelIsRunning- const duckSqlIsStale = duckSqlHasExecution && !duckSqlIsFresh- const hogqlSqlAttributes = attributes as {- code?: string- hogqlExecutionCodeHash?: number | null- hogqlExecutionSandboxId?: string | null- returnVariable?: string- }- const hogqlSqlExecutionCodeHash = hogqlSqlAttributes.hogqlExecutionCodeHash ?? null- const hogqlSqlCodeHash = hashCodeForString(`${hogqlSqlAttributes.code ?? ''}\n${hogqlSqlReturnVariable}`)- const hogqlSqlExecutionSandboxId = hogqlSqlAttributes.hogqlExecutionSandboxId ?? null- const hogqlSqlHasExecution = hogqlSqlExecutionCodeHash !== null- const hogqlSqlSandboxMatches =- hogqlSqlExecutionSandboxId !== null &&- kernelSandboxId !== null &&- hogqlSqlExecutionSandboxId === kernelSandboxId- const hogqlSqlIsFresh =- hogqlSqlHasExecution &&- hogqlSqlExecutionCodeHash === hogqlSqlCodeHash &&- hogqlSqlSandboxMatches &&- kernelIsRunning- const hogqlSqlIsStale = hogqlSqlHasExecution && !hogqlSqlIsFresh-const defaultMenuItems: LemonMenuItems = [// Copy round-trips the node attrs through HTML for paste into another notebook — doesn't// make sense for an anonymous shared viewer who has no editor to paste into.@@ -250,10 +164,7 @@ function NodeWrapper<T extends CustomNotebookNodeAttributes>(props: NodeWrapperP? {label: 'Reset height to default',onClick: () => {- updateAttributes({- height: null,- ...(nodeType === NotebookNodeType.Python ? { autoHeight: true } : {}),- } as any)+ updateAttributes({ height: null } as any)},}: null,@@ -334,38 +245,6 @@ function NodeWrapper<T extends CustomNotebookNodeAttributes>(props: NodeWrapperP</div><div className="flex deprecated-space-x-1">- {isPythonNode ? (- <PythonRunMenu- isFresh={pythonIsFresh}- isStale={pythonIsStale}- loading={pythonRunLoading}- queued={pythonRunQueued}- disabledReason={runDisabledReason}- onRun={(mode) => void runPythonNodeWithMode({ mode })}- />- ) : null}-- {isDuckSqlNode ? (- <DuckSqlRunMenu- isFresh={duckSqlIsFresh}- isStale={duckSqlIsStale}- loading={duckSqlRunLoading}- queued={duckSqlRunQueued}- disabledReason={runDisabledReason}- onRun={(mode) => void runDuckSqlNodeWithMode({ mode })}- />- ) : null}- {isHogqlSqlNode ? (- <HogqlSqlRunMenu- isFresh={hogqlSqlIsFresh}- isStale={hogqlSqlIsStale}- loading={hogqlSqlRunLoading}- queued={hogqlSqlRunQueued}- disabledReason={runDisabledReason}- onRun={(mode) => void runHogqlSqlNodeWithMode({ mode })}- />- ) : null}-{isEditable && Settings ? (<LemonButtononClick={() => toggleEditing()}diff --git a/frontend/src/scenes/notebooks/Nodes/NotebookNodeDuckSQL.tsx b/frontend/src/scenes/notebooks/Nodes/NotebookNodeDuckSQL.tsxdeleted file mode 100644index 2ea4c9a34411..000000000000--- a/frontend/src/scenes/notebooks/Nodes/NotebookNodeDuckSQL.tsx+++ /dev/null@@ -1,335 +0,0 @@-import clsx from 'clsx'-import { useActions, useMountedLogic, useValues } from 'kea'-import { useEffect, useLayoutEffect, useMemo, useRef } from 'react'-import { useDebouncedCallback } from 'use-debounce'--import { IconCornerDownRight } from '@posthog/icons'--import { createPostHogWidgetNode } from 'scenes/notebooks/Nodes/NodeWrapper'--import { NotebookNodeAttributeProperties, NotebookNodeProps, NotebookNodeType } from '../types'-import { NotebookDataframeTable } from './components/NotebookDataframeTable'-import { getCellLabel } from './components/NotebookNodeTitle'-import { NotebookCodeSQLEditorSettings } from './components/NotebookSQLEditor'-import { notebookNodeLogic } from './notebookNodeLogic'-import { PythonExecutionMedia, PythonExecutionResult } from './pythonExecution'-import { buildMediaSource, renderAnsiText } from './utils'--export type NotebookNodeDuckSQLAttributes = {- code: string- returnVariable: string- duckExecution?: PythonExecutionResult | null- duckExecutionCodeHash?: number | null- duckExecutionSandboxId?: string | null- showSettings?: boolean-}--const OutputBlock = ({- title,- className,- toneClassName,- value,-}: {- title: string- className: string- toneClassName: string- value: string-}): JSX.Element => {- const content = useMemo(() => renderAnsiText(value), [value])-- return (- <div className={className}>- <div className="text-[10px] uppercase tracking-wide text-muted">{title}</div>- <pre- className={clsx('text-xs font-mono whitespace-pre-wrap mt-1 select-text cursor-text', toneClassName)}- contentEditable={false}- >- {content}- </pre>- </div>- )-}--const MediaBlock = ({ media }: { media: PythonExecutionMedia }): JSX.Element | null => {- const source = buildMediaSource(media)- if (!source) {- return null- }-- return (- <div>- <div className="text-[10px] uppercase tracking-wide text-muted">Image</div>- <img- src={source}- alt="SQL (DuckDB) output"- className="mt-2 max-w-full border border-border rounded bg-bg-light"- />- </div>- )-}--const DEFAULT_DUCK_SQL_NODE_HEIGHT = 100--const Component = ({- attributes,- updateAttributes,-}: NotebookNodeProps<NotebookNodeDuckSQLAttributes>): JSX.Element | null => {- const nodeLogic = useMountedLogic(notebookNodeLogic)- const {- dataframePage,- dataframePageSize,- dataframeLoading,- dataframeResult,- dataframeVariableName,- duckSqlReturnVariableUsage,- expanded,- } = useValues(nodeLogic)- const { navigateToNode, setDataframePage, setDataframePageSize } = useActions(nodeLogic)- const outputRef = useRef<HTMLDivElement | null>(null)- const footerRef = useRef<HTMLDivElement | null>(null)- const lastAutoHeightRef = useRef<number | null>(null)- const lastExecutionCodeHashRef = useRef<number | null>(null)-- const duckExecution = attributes.duckExecution ?? null- const hasResult = duckExecution?.result !== undefined && duckExecution?.result !== null- const hasExecution =- duckExecution &&- (duckExecution.stdout ||- duckExecution.stderr ||- hasResult ||- duckExecution.media?.length ||- duckExecution.traceback?.length)- const executionCodeHash = attributes.duckExecutionCodeHash ?? null-- const debouncedUpdateHeight = useDebouncedCallback((height: number) => {- updateAttributes({ height })- lastAutoHeightRef.current = height- }, 150)-- useEffect(() => {- return () => {- debouncedUpdateHeight.cancel()- }- }, [debouncedUpdateHeight])-- useLayoutEffect(() => {- if (!hasExecution) {- return- }- const output = outputRef.current- if (!output) {- return- }- const footerHeight = footerRef.current?.offsetHeight ?? 0- const desiredHeight = output.scrollHeight + footerHeight + 8- const currentHeight = typeof attributes.height === 'number' ? attributes.height : DEFAULT_DUCK_SQL_NODE_HEIGHT- const lastExecutionCodeHash = lastExecutionCodeHashRef.current- const executionChanged = executionCodeHash !== lastExecutionCodeHash-- if (executionChanged) {- lastExecutionCodeHashRef.current = executionCodeHash- lastAutoHeightRef.current = currentHeight- }-- const lastAutoHeight = lastAutoHeightRef.current- const hasManualResize =- !executionChanged &&- lastAutoHeight !== null &&- typeof currentHeight === 'number' &&- currentHeight < lastAutoHeight-- if (hasManualResize) {- return- }-- if (desiredHeight !== currentHeight) {- debouncedUpdateHeight(desiredHeight)- }- }, [- attributes.height,- dataframeLoading,- dataframePageSize,- dataframeResult,- duckExecution?.media?.length,- duckExecution?.result,- duckExecution?.stderr,- duckExecution?.stdout,- duckExecution?.traceback?.length,- executionCodeHash,- hasExecution,- debouncedUpdateHeight,- ])-- const isSettingsVisible = attributes.showSettings ?? false- const showReturnVariableRow = expanded || isSettingsVisible- const showDataframeTable = !!dataframeVariableName-- const usageLabel = (nodeType: NotebookNodeType, nodeIndex: number | undefined, title: string): string => {- const trimmedTitle = title.trim()- if (trimmedTitle) {- return trimmedTitle- }- return getCellLabel(nodeIndex, nodeType) ?? 'SQL'- }-- if (!expanded && !showReturnVariableRow) {- return null- }-- return (- <div data-attr="notebook-node-duck-sql" className="flex h-full flex-col">- {expanded ? (- <div- ref={outputRef}- className="space-y-3"- onMouseDown={(event) => event.stopPropagation()}- onDragStart={(event) => event.stopPropagation()}- >- {hasExecution ? (- <>- {duckExecution?.stdout ? (- <OutputBlock- title="Output"- className="p-2"- toneClassName="text-default"- value={duckExecution.stdout ?? ''}- />- ) : null}- {duckExecution?.stderr ? (- <OutputBlock- title="stderr"- className="p-2"- toneClassName="text-danger"- value={duckExecution.stderr ?? ''}- />- ) : null}- {hasResult && !showDataframeTable ? (- <OutputBlock- title="Result"- className="p-2"- toneClassName="text-default"- value={duckExecution.result ?? ''}- />- ) : null}- {showDataframeTable ? (- <NotebookDataframeTable- result={dataframeResult}- loading={dataframeLoading}- page={dataframePage}- pageSize={dataframePageSize}- onNextPage={() => setDataframePage(dataframePage + 1)}- onPreviousPage={() => setDataframePage(Math.max(1, dataframePage - 1))}- onPageSizeChange={setDataframePageSize}- />- ) : null}- {duckExecution?.media?.map((media, index) => (- <MediaBlock key={`duck-sql-media-${index}`} media={media} />- ))}- {duckExecution?.status === 'error' && duckExecution.traceback?.length ? (- <OutputBlock- title="Error"- className="p-2"- toneClassName="text-danger"- value={duckExecution.traceback.join('\n')}- />- ) : null}- </>- ) : (- <div className="text-xs text-muted font-mono p-2">Run the query to see execution results.</div>- )}- </div>- ) : null}- {showReturnVariableRow ? (- <div- ref={footerRef}- className="flex flex-col gap-2 text-xs text-muted border-t p-2"- onClick={(event) => event.stopPropagation()}- onMouseDown={(event) => event.stopPropagation()}- >- <div className="flex items-center gap-2">- <span className="font-mono mt-0.5">- <IconCornerDownRight />- </span>- <input- type="text"- className="rounded border border-border px-1.5 py-0.5 text-xs font-mono bg-bg-light text-default focus:outline-none focus:ring-1 focus:ring-primary"- value={attributes.returnVariable ?? ''}- onChange={(event) => updateAttributes({ returnVariable: event.target.value })}- spellCheck={false}- />- {duckSqlReturnVariableUsage.length > 0 ? (- <span className="text-muted">- Used in{' '}- {duckSqlReturnVariableUsage.map((usage) => (- <button- key={usage.nodeId}- type="button"- className="text-muted hover:text-default underline underline-offset-2 ml-1"- onClick={() => navigateToNode(usage.nodeId)}- >- {usageLabel(usage.nodeType, usage.nodeIndex, usage.title)}- </button>- ))}- </span>- ) : null}- </div>- </div>- ) : null}- </div>- )-}--const Settings = ({- attributes,- updateAttributes,-}: NotebookNodeAttributeProperties<NotebookNodeDuckSQLAttributes>): JSX.Element => {- const nodeLogic = useMountedLogic(notebookNodeLogic)- const { runDuckSqlNodeWithMode } = useActions(nodeLogic)- const { duckSqlRunLoading, duckSqlRunQueued } = useValues(nodeLogic)-- return (- <NotebookCodeSQLEditorSettings- attributes={attributes}- updateAttributes={updateAttributes}- tabIdSuffix="duck"- onRunQuery={() => {- void runDuckSqlNodeWithMode({ mode: 'auto' })- }}- runQueryLoading={duckSqlRunLoading || duckSqlRunQueued}- runQueryTooltip="Run SQL (DuckDB) query"- />- )-}--export const NotebookNodeDuckSQL = createPostHogWidgetNode<NotebookNodeDuckSQLAttributes>({- nodeType: NotebookNodeType.DuckSQL,- titlePlaceholder: 'SQL (DuckDB)',- Component,- heightEstimate: 120,- minHeight: 80,- resizeable: true,- startExpanded: true,- attributes: {- code: {- default: '',- },- returnVariable: {- default: 'duck_df',- },- duckExecution: {- default: null,- },- duckExecutionCodeHash: {- default: null,- },- duckExecutionSandboxId: {- default: null,- },- showSettings: {- default: false,- },- },- Settings,- settingsPlacement: 'inline',- serializedText: (attrs) => attrs.code,-})diff --git a/frontend/src/scenes/notebooks/Nodes/NotebookNodeHogQL.tsx b/frontend/src/scenes/notebooks/Nodes/NotebookNodeHogQL.tsxdeleted file mode 100644index 0a3eae99e8c6..000000000000--- a/frontend/src/scenes/notebooks/Nodes/NotebookNodeHogQL.tsx+++ /dev/null@@ -1,335 +0,0 @@-import clsx from 'clsx'-import { useActions, useMountedLogic, useValues } from 'kea'-import { useEffect, useLayoutEffect, useMemo, useRef } from 'react'-import { useDebouncedCallback } from 'use-debounce'--import { IconCornerDownRight } from '@posthog/icons'--import { createPostHogWidgetNode } from 'scenes/notebooks/Nodes/NodeWrapper'--import { NotebookNodeAttributeProperties, NotebookNodeProps, NotebookNodeType } from '../types'-import { NotebookDataframeTable } from './components/NotebookDataframeTable'-import { getCellLabel } from './components/NotebookNodeTitle'-import { NotebookCodeSQLEditorSettings } from './components/NotebookSQLEditor'-import { notebookNodeLogic } from './notebookNodeLogic'-import { PythonExecutionMedia, PythonExecutionResult } from './pythonExecution'-import { buildMediaSource, renderAnsiText } from './utils'--export type NotebookNodeHogQLAttributes = {- code: string- returnVariable: string- hogqlExecution?: PythonExecutionResult | null- hogqlExecutionCodeHash?: number | null- hogqlExecutionSandboxId?: string | null- showSettings?: boolean-}--const OutputBlock = ({- title,- className,- toneClassName,- value,-}: {- title: string- className: string- toneClassName: string- value: string-}): JSX.Element => {- const content = useMemo(() => renderAnsiText(value), [value])-- return (- <div className={className}>- <div className="text-[10px] uppercase tracking-wide text-muted">{title}</div>- <pre- className={clsx('text-xs font-mono whitespace-pre-wrap mt-1 select-text cursor-text', toneClassName)}- contentEditable={false}- >- {content}- </pre>- </div>- )-}--const MediaBlock = ({ media }: { media: PythonExecutionMedia }): JSX.Element | null => {- const source = buildMediaSource(media)- if (!source) {- return null- }-- return (- <div>- <div className="text-[10px] uppercase tracking-wide text-muted">Image</div>- <img- src={source}- alt="SQL (HogQL) output"- className="mt-2 max-w-full border border-border rounded bg-bg-light"- />- </div>- )-}--const DEFAULT_HOGQL_SQL_NODE_HEIGHT = 100--const Component = ({- attributes,- updateAttributes,-}: NotebookNodeProps<NotebookNodeHogQLAttributes>): JSX.Element | null => {- const nodeLogic = useMountedLogic(notebookNodeLogic)- const {- dataframePage,- dataframePageSize,- dataframeLoading,- dataframeResult,- dataframeVariableName,- hogqlReturnVariableUsage,- expanded,- } = useValues(nodeLogic)- const { navigateToNode, setDataframePage, setDataframePageSize } = useActions(nodeLogic)- const outputRef = useRef<HTMLDivElement | null>(null)- const footerRef = useRef<HTMLDivElement | null>(null)- const lastAutoHeightRef = useRef<number | null>(null)- const lastExecutionCodeHashRef = useRef<number | null>(null)-- const hogqlExecution = attributes.hogqlExecution ?? null- const hasResult = hogqlExecution?.result !== undefined && hogqlExecution?.result !== null- const hasExecution =- hogqlExecution &&- (hogqlExecution.stdout ||- hogqlExecution.stderr ||- hasResult ||- hogqlExecution.media?.length ||- hogqlExecution.traceback?.length)- const executionCodeHash = attributes.hogqlExecutionCodeHash ?? null-- const debouncedUpdateHeight = useDebouncedCallback((height: number) => {- updateAttributes({ height })- lastAutoHeightRef.current = height- }, 150)-- useEffect(() => {- return () => {- debouncedUpdateHeight.cancel()- }- }, [debouncedUpdateHeight])-- useLayoutEffect(() => {- if (!hasExecution) {- return- }- const output = outputRef.current- if (!output) {- return- }- const footerHeight = footerRef.current?.offsetHeight ?? 0- const desiredHeight = output.scrollHeight + footerHeight + 8- const currentHeight = typeof attributes.height === 'number' ? attributes.height : DEFAULT_HOGQL_SQL_NODE_HEIGHT- const lastExecutionCodeHash = lastExecutionCodeHashRef.current- const executionChanged = executionCodeHash !== lastExecutionCodeHash-- if (executionChanged) {- lastExecutionCodeHashRef.current = executionCodeHash- lastAutoHeightRef.current = currentHeight- }-- const lastAutoHeight = lastAutoHeightRef.current- const hasManualResize =- !executionChanged &&- lastAutoHeight !== null &&- typeof currentHeight === 'number' &&- currentHeight < lastAutoHeight-- if (hasManualResize) {- return- }-- if (desiredHeight !== currentHeight) {- debouncedUpdateHeight(desiredHeight)- }- }, [- attributes.height,- dataframeLoading,- dataframePageSize,- dataframeResult,- executionCodeHash,- hasExecution,- debouncedUpdateHeight,- hogqlExecution?.media?.length,- hogqlExecution?.result,- hogqlExecution?.stderr,- hogqlExecution?.stdout,- hogqlExecution?.traceback?.length,- ])-- const isSettingsVisible = attributes.showSettings ?? false- const showReturnVariableRow = expanded || isSettingsVisible- const showDataframeTable = !!dataframeVariableName-- const usageLabel = (nodeType: NotebookNodeType, nodeIndex: number | undefined, title: string): string => {- const trimmedTitle = title.trim()- if (trimmedTitle) {- return trimmedTitle- }- return getCellLabel(nodeIndex, nodeType) ?? 'SQL'- }-- if (!expanded && !showReturnVariableRow) {- return null- }-- return (- <div data-attr="notebook-node-hogql-sql" className="flex h-full flex-col">- {expanded ? (- <div- ref={outputRef}- className="space-y-3"- onMouseDown={(event) => event.stopPropagation()}- onDragStart={(event) => event.stopPropagation()}- >- {hasExecution ? (- <>- {hogqlExecution?.stdout ? (- <OutputBlock- title="Output"- className="p-2"- toneClassName="text-default"- value={hogqlExecution.stdout ?? ''}- />- ) : null}- {hogqlExecution?.stderr ? (- <OutputBlock- title="stderr"- className="p-2"- toneClassName="text-danger"- value={hogqlExecution.stderr ?? ''}- />- ) : null}- {hasResult && !showDataframeTable ? (- <OutputBlock- title="Result"- className="p-2"- toneClassName="text-default"- value={hogqlExecution.result ?? ''}- />- ) : null}- {showDataframeTable ? (- <NotebookDataframeTable- result={dataframeResult}- loading={dataframeLoading}- page={dataframePage}- pageSize={dataframePageSize}- onNextPage={() => setDataframePage(dataframePage + 1)}- onPreviousPage={() => setDataframePage(Math.max(1, dataframePage - 1))}- onPageSizeChange={setDataframePageSize}- />- ) : null}- {hogqlExecution?.media?.map((media, index) => (- <MediaBlock key={`hogql-sql-media-${index}`} media={media} />- ))}- {hogqlExecution?.status === 'error' && hogqlExecution.traceback?.length ? (- <OutputBlock- title="Error"- className="p-2"- toneClassName="text-danger"- value={hogqlExecution.traceback.join('\n')}- />- ) : null}- </>- ) : (- <div className="text-xs text-muted font-mono p-2">Run the query to see execution results.</div>- )}- </div>- ) : null}- {showReturnVariableRow ? (- <div- ref={footerRef}- className="flex flex-col gap-2 text-xs text-muted border-t p-2"- onClick={(event) => event.stopPropagation()}- onMouseDown={(event) => event.stopPropagation()}- >- <div className="flex items-center gap-2">- <span className="font-mono mt-0.5">- <IconCornerDownRight />- </span>- <input- type="text"- className="rounded border border-border px-1.5 py-0.5 text-xs font-mono bg-bg-light text-default focus:outline-none focus:ring-1 focus:ring-primary"- value={attributes.returnVariable ?? ''}- onChange={(event) => updateAttributes({ returnVariable: event.target.value })}- spellCheck={false}- />- {hogqlReturnVariableUsage.length > 0 ? (- <span className="text-muted">- Used in{' '}- {hogqlReturnVariableUsage.map((usage) => (- <button- key={usage.nodeId}- type="button"- className="text-muted hover:text-default underline underline-offset-2 ml-1"- onClick={() => navigateToNode(usage.nodeId)}- >- {usageLabel(usage.nodeType, usage.nodeIndex, usage.title)}- </button>- ))}- </span>- ) : null}- </div>- </div>- ) : null}- </div>- )-}--const Settings = ({- attributes,- updateAttributes,-}: NotebookNodeAttributeProperties<NotebookNodeHogQLAttributes>): JSX.Element => {- const nodeLogic = useMountedLogic(notebookNodeLogic)- const { runHogqlSqlNodeWithMode } = useActions(nodeLogic)- const { hogqlSqlRunLoading, hogqlSqlRunQueued } = useValues(nodeLogic)-- return (- <NotebookCodeSQLEditorSettings- attributes={attributes}- updateAttributes={updateAttributes}- tabIdSuffix="hogql"- onRunQuery={() => {- void runHogqlSqlNodeWithMode({ mode: 'auto' })- }}- runQueryLoading={hogqlSqlRunLoading || hogqlSqlRunQueued}- runQueryTooltip="Run SQL (HogQL) query"- />- )-}--export const NotebookNodeHogQL = createPostHogWidgetNode<NotebookNodeHogQLAttributes>({- nodeType: NotebookNodeType.HogQLSQL,- titlePlaceholder: 'SQL (HogQL)',- Component,- heightEstimate: 120,- minHeight: 80,- resizeable: true,- startExpanded: true,- attributes: {- code: {- default: '',- },- returnVariable: {- default: 'hogql_df',- },- hogqlExecution: {- default: null,- },- hogqlExecutionCodeHash: {- default: null,- },- hogqlExecutionSandboxId: {- default: null,- },- showSettings: {- default: false,- },- },- Settings,- settingsPlacement: 'inline',- serializedText: (attrs) => attrs.code,-})diff --git a/frontend/src/scenes/notebooks/Nodes/NotebookNodePython.tsx b/frontend/src/scenes/notebooks/Nodes/NotebookNodePython.tsxdeleted file mode 100644index 3f52d233af2f..000000000000--- a/frontend/src/scenes/notebooks/Nodes/NotebookNodePython.tsx+++ /dev/null@@ -1,394 +0,0 @@-import clsx from 'clsx'-import { useActions, useMountedLogic, useValues } from 'kea'-import { useLayoutEffect, useMemo, useRef, useState } from 'react'--import { IconCornerDownRight } from '@posthog/icons'--import { Popover } from 'lib/lemon-ui/Popover/Popover'-import { CodeEditorResizeable } from 'lib/monaco/CodeEditorResizable'-import { createPostHogWidgetNode } from 'scenes/notebooks/Nodes/NodeWrapper'--import { NotebookNodeAttributeProperties, NotebookNodeProps, NotebookNodeType } from '../types'-import { NotebookDataframeTable } from './components/NotebookDataframeTable'-import type { NotebookDependencyUsage } from './notebookNodeContent'-import { notebookNodeLogic } from './notebookNodeLogic'-import { PythonExecutionMedia, PythonExecutionResult } from './pythonExecution'-import { buildMediaSource, renderAnsiText } from './utils'--export type NotebookNodePythonAttributes = {- code: string- globalsUsed?: string[]- globalsExportedWithTypes?: { name: string; type: string }[]- globalsAnalysisHash?: string | null- pythonExecution?: PythonExecutionResult | null- pythonExecutionCodeHash?: number | null- pythonExecutionSandboxId?: string | null- showSettings?: boolean- autoHeight?: boolean-}--const VariableUsageOverlay = ({- name,- type,- hogqlQuery,- usages,- onNavigateToNode,-}: {- name: string- type: string- hogqlQuery?: string- usages: NotebookDependencyUsage[]- onNavigateToNode?: (nodeId: string) => void-}): JSX.Element => {- const groupedUsageEntries = usages.reduce<Record<string, NotebookDependencyUsage>>((acc, usage) => {- if (!acc[usage.nodeId]) {- acc[usage.nodeId] = usage- }- return acc- }, {})- const sortedUsageEntries = Object.values(groupedUsageEntries).sort((a, b) => a.nodeIndex - b.nodeIndex)-- const usageLabel = (usage: NotebookDependencyUsage): string => {- const trimmedTitle = usage.title.trim()- return trimmedTitle ? trimmedTitle : `Python cell ${usage.nodeIndex}`- }-- return (- <div className="p-2 text-xs max-w-[320px]">- <div className="flex items-center justify-between gap-2">- <span className="font-semibold text-default font-mono">{name}</span>- <span className="text-muted">Type: {type || 'unknown'}</span>- </div>- {hogqlQuery ? (- <div className="mt-2">- <div className="text-muted text-[10px] uppercase tracking-wide">HogQL query</div>- <pre className="mt-1 text-xs font-mono text-default whitespace-pre-wrap break-words max-h-24 overflow-y-auto">- {hogqlQuery}- </pre>- </div>- ) : null}- {sortedUsageEntries.length > 0 ? (- <div className="mt-2">- <div className="text-muted text-[10px] uppercase tracking-wide">Used in</div>- <div className="mt-1 space-y-1 max-h-48 overflow-y-auto">- {sortedUsageEntries.map((usage) => (- <div key={`usage-${usage.nodeIndex}`}>- {onNavigateToNode ? (- <button- type="button"- className="text-muted hover:text-default underline underline-offset-2"- onClick={() => onNavigateToNode(usage.nodeId)}- >- {usageLabel(usage)}- </button>- ) : (- <div className="text-muted">{usageLabel(usage)}</div>- )}- </div>- ))}- </div>- </div>- ) : (- <div className="mt-2 text-muted">Not used in later cells.</div>- )}- </div>- )-}--const VariableDependencyBadge = ({- name,- type,- hogqlQuery,- usages,- onNavigateToNode,-}: {- name: string- type: string- hogqlQuery?: string- usages: NotebookDependencyUsage[]- onNavigateToNode?: (nodeId: string) => void-}): JSX.Element => {- const [popoverVisible, setPopoverVisible] = useState(false)- const isUsedDownstream = usages.length > 0-- return (- <Popover- onClickOutside={() => setPopoverVisible(false)}- visible={popoverVisible}- placement="bottom-start"- overlay={- <VariableUsageOverlay- name={name}- type={type}- hogqlQuery={hogqlQuery}- usages={usages}- onNavigateToNode={(nodeId) => {- onNavigateToNode?.(nodeId)- setPopoverVisible(false)- }}- />- }- >- <button- type="button"- onClick={() => setPopoverVisible((visible) => !visible)}- className="rounded border border-border px-1.5 py-0.5 text-xs font-mono bg-bg-light text-default hover:bg-bg-light/80 transition"- >- <span className={isUsedDownstream ? 'font-semibold' : undefined}>{name}</span>- {isUsedDownstream ? <span className="text-muted"> → {usages.length}</span> : null}- </button>- </Popover>- )-}--const OutputBlock = ({- title,- toneClassName,- value,-}: {- title: string- toneClassName: string- value: string-}): JSX.Element => {- const content = useMemo(() => renderAnsiText(value), [value])-- return (- <div>- <div className="text-[10px] uppercase tracking-wide text-muted">{title}</div>- <pre- className={clsx('text-xs font-mono whitespace-pre-wrap mt-1 select-text cursor-text', toneClassName)}- contentEditable={false}- >- {content}- </pre>- </div>- )-}--const MediaBlock = ({ media }: { media: PythonExecutionMedia }): JSX.Element | null => {- const source = buildMediaSource(media)- if (!source) {- return null- }-- return (- <div>- <div className="text-[10px] uppercase tracking-wide text-muted">Image</div>- <img- src={source}- alt="Python output"- className="mt-2 max-w-full border border-border rounded bg-bg-light"- />- </div>- )-}--const DEFAULT_PYTHON_NODE_HEIGHT = 100-const MAX_PYTHON_NODE_HEIGHT = 500--const Component = ({- attributes,- updateAttributes,-}: NotebookNodeProps<NotebookNodePythonAttributes>): JSX.Element | null => {- const nodeLogic = useMountedLogic(notebookNodeLogic)- const {- dataframePage,- dataframePageSize,- dataframeLoading,- dataframeResult,- dataframeVariableName,- displayedGlobals,- expanded,- exportedGlobals,- pythonExecution,- usageByVariable,- } = useValues(nodeLogic)- const { navigateToNode, setDataframePage, setDataframePageSize } = useActions(nodeLogic)- const outputRef = useRef<HTMLDivElement | null>(null)- const footerRef = useRef<HTMLDivElement | null>(null)-- const hasResult = pythonExecution?.result !== undefined && pythonExecution?.result !== null- const hasExecution =- pythonExecution &&- (pythonExecution.stdout ||- pythonExecution.stderr ||- hasResult ||- pythonExecution.media?.length ||- pythonExecution.traceback?.length ||- pythonExecution.variables?.length)-- useLayoutEffect(() => {- if (!hasExecution || attributes.autoHeight === false) {- return- }- const output = outputRef.current- if (!output) {- return- }- const footerHeight = footerRef.current?.offsetHeight ?? 0- const desiredHeight = Math.min(MAX_PYTHON_NODE_HEIGHT, output.scrollHeight + footerHeight)- const currentHeight = typeof attributes.height === 'number' ? attributes.height : DEFAULT_PYTHON_NODE_HEIGHT-- if (desiredHeight !== currentHeight) {- updateAttributes({ height: desiredHeight })- }- }, [- attributes.height,- hasExecution,- pythonExecution?.media?.length,- pythonExecution?.result,- pythonExecution?.stderr,- pythonExecution?.stdout,- pythonExecution?.traceback?.length,- pythonExecution?.variables?.length,- updateAttributes,- ]) // oxlint-disable-line react-hooks/exhaustive-deps-- if (!expanded) {- return null- }- const showDataframeTable = !!dataframeVariableName-- return (- <div data-attr="notebook-node-python" className="flex h-full flex-col gap-2">- <div- ref={outputRef}- className="p-2 overflow-y-auto h-full space-y-3"- onMouseDown={(event) => event.stopPropagation()}- onDragStart={(event) => event.stopPropagation()}- >- {hasExecution ? (- <>- {pythonExecution?.stdout ? (- <OutputBlock- title="Output"- toneClassName="text-default"- value={pythonExecution.stdout ?? ''}- />- ) : null}- {pythonExecution?.stderr ? (- <OutputBlock- title="stderr"- toneClassName="text-danger"- value={pythonExecution.stderr ?? ''}- />- ) : null}- {hasResult && !showDataframeTable ? (- <OutputBlock- title="Result"- toneClassName="text-default"- value={pythonExecution.result ?? ''}- />- ) : null}- {showDataframeTable ? (- <NotebookDataframeTable- result={dataframeResult}- loading={dataframeLoading}- page={dataframePage}- pageSize={dataframePageSize}- onNextPage={() => setDataframePage(dataframePage + 1)}- onPreviousPage={() => setDataframePage(Math.max(1, dataframePage - 1))}- onPageSizeChange={setDataframePageSize}- />- ) : null}- {pythonExecution?.media?.map((media, index) => (- <MediaBlock key={`python-media-${index}`} media={media} />- ))}- {pythonExecution?.status === 'error' && pythonExecution.traceback?.length ? (- <OutputBlock- title="Error"- toneClassName="text-danger"- value={pythonExecution.traceback.join('\n')}- />- ) : null}- </>- ) : (- <div className="text-xs text-muted font-mono">Run the cell to see execution results.</div>- )}- </div>- {exportedGlobals.length > 0 ? (- <div ref={footerRef} className="flex items-start flex-wrap gap-2 text-xs text-muted border-t p-2">- <span className="font-mono mt-1">- <IconCornerDownRight />- </span>- <div className="flex flex-wrap gap-1">- {displayedGlobals.map(({ name, type, hogqlQuery }) => (- <VariableDependencyBadge- key={name}- name={name}- type={type}- hogqlQuery={hogqlQuery}- usages={usageByVariable[name] ?? []}- onNavigateToNode={navigateToNode}- />- ))}- </div>- </div>- ) : null}- </div>- )-}--const Settings = ({- attributes,- updateAttributes,-}: NotebookNodeAttributeProperties<NotebookNodePythonAttributes>): JSX.Element => {- const nodeLogic = useMountedLogic(notebookNodeLogic)- const { runPythonNodeWithMode } = useActions(nodeLogic)-- return (- <CodeEditorResizeable- language="python"- value={typeof attributes.code === 'string' ? attributes.code : ''}- onChange={(value) => updateAttributes({ code: value ?? '' })}- onPressCmdEnter={() => {- void runPythonNodeWithMode({ mode: 'auto' })- }}- allowManualResize={false}- minHeight={160}- embedded- />- )-}--export const NotebookNodePython = createPostHogWidgetNode<NotebookNodePythonAttributes>({- nodeType: NotebookNodeType.Python,- titlePlaceholder: 'Python',- Component,- heightEstimate: 120,- minHeight: 80,- resizeable: true,- startExpanded: true,- attributes: {- code: {- default: '',- },- globalsUsed: {- default: [],- },- globalsExportedWithTypes: {- default: [],- },- globalsAnalysisHash: {- default: null,- },- pythonExecution: {- default: null,- },- pythonExecutionCodeHash: {- default: null,- },- pythonExecutionSandboxId: {- default: null,- },- showSettings: {- default: false,- },- autoHeight: {- default: true,- },- },- Settings,- settingsPlacement: 'inline',- serializedText: (attrs) => attrs.code,-})diff --git a/frontend/src/scenes/notebooks/Nodes/NotebookNodeSQLV2.tsx b/frontend/src/scenes/notebooks/Nodes/NotebookNodeSQLV2.tsxindex 70cbb6c9f2af..29e63adf0958 100644--- a/frontend/src/scenes/notebooks/Nodes/NotebookNodeSQLV2.tsx+++ b/frontend/src/scenes/notebooks/Nodes/NotebookNodeSQLV2.tsx@@ -170,8 +170,8 @@ const Component = ({} = useValues(dataLogic)const { setPage, setPageSize, runStaleChain } = useActions(dataLogic)- const usageLabel = (nodeType: NotebookNodeType, nodeIndex: number | undefined, title: string): string =>- title.trim() || getCellLabel(nodeIndex, nodeType) || 'SQL'+ const usageLabel = (nodeIndex: number | undefined, title: string): string =>+ title.trim() || getCellLabel(nodeIndex) || 'SQL'const result = attributes.result ?? nullconst returnVariableError = returnVariableValidationError(attributes.returnVariable ?? '')@@ -374,7 +374,7 @@ const Component = ({className="text-muted hover:text-default underline underline-offset-2 ml-1"onClick={() => navigateToNode(usage.nodeId)}>- {usageLabel(usage.nodeType, usage.nodeIndex, usage.title)}+ {usageLabel(usage.nodeIndex, usage.title)}</button>))}</span>diff --git a/frontend/src/scenes/notebooks/Nodes/components/DuckSqlRunMenu.tsx b/frontend/src/scenes/notebooks/Nodes/components/DuckSqlRunMenu.tsxdeleted file mode 100644index 56c673945da6..000000000000--- a/frontend/src/scenes/notebooks/Nodes/components/DuckSqlRunMenu.tsx+++ /dev/null@@ -1,66 +0,0 @@-import { useActions, useValues } from 'kea'--import { IconChevronDown, IconPlay } from '@posthog/icons'-import { LemonButton, LemonMenuItems, LemonMenuOverlay } from '@posthog/lemon-ui'--import { featureFlagLogic } from 'lib/logic/featureFlagLogic'--import { notebookSettingsLogic } from '../../Notebook/notebookSettingsLogic'-import { isKernelUiEnabled } from '../../utils'-import { NotebookRunMode, buildRunMenuItems } from './runMenuItems'--export type DuckSqlRunMode = NotebookRunMode--type DuckSqlRunMenuProps = {- isFresh: boolean- isStale: boolean- loading: boolean- queued: boolean- disabledReason?: string- onRun: (mode: DuckSqlRunMode) => void-}--export const DuckSqlRunMenu = ({- isFresh,- isStale,- loading,- queued,- disabledReason,- onRun,-}: DuckSqlRunMenuProps): JSX.Element => {- const { featureFlags } = useValues(featureFlagLogic)- const { showKernelInfo } = useValues(notebookSettingsLogic)- const { setShowKernelInfo } = useActions(notebookSettingsLogic)- const duckSqlRunIconClass = isFresh ? 'text-success' : isStale ? 'text-danger' : undefined- const duckSqlRunTooltip = `Run SQL (DuckDB) query.${queued ? ' Queued.' : isStale ? ' Stale.' : ''}`-- const duckSqlRunMenuItems: LemonMenuItems = [...buildRunMenuItems(onRun)]-- if (isKernelUiEnabled(featureFlags)) {- duckSqlRunMenuItems.push({- label: 'Toggle kernel info',- onClick: () => setShowKernelInfo(!showKernelInfo),- })- }-- return (- <LemonButton- onClick={() => onRun('auto')}- size="small"- icon={<IconPlay className={duckSqlRunIconClass} />}- loading={loading || queued}- disabledReason={disabledReason}- tooltip={duckSqlRunTooltip}- sideAction={{- icon: <IconChevronDown />,- dropdown: {- placement: 'bottom-end',- overlay: <LemonMenuOverlay items={duckSqlRunMenuItems} />,- },- divider: false,- 'aria-label': 'Open run options',- disabledReason: disabledReason,- }}- />- )-}diff --git a/frontend/src/scenes/notebooks/Nodes/components/HogqlSqlRunMenu.tsx b/frontend/src/scenes/notebooks/Nodes/components/HogqlSqlRunMenu.tsxdeleted file mode 100644index 9ca6d917f778..000000000000--- a/frontend/src/scenes/notebooks/Nodes/components/HogqlSqlRunMenu.tsx+++ /dev/null@@ -1,66 +0,0 @@-import { useActions, useValues } from 'kea'--import { IconChevronDown, IconPlay } from '@posthog/icons'-import { LemonButton, LemonMenuItems, LemonMenuOverlay } from '@posthog/lemon-ui'--import { featureFlagLogic } from 'lib/logic/featureFlagLogic'--import { notebookSettingsLogic } from '../../Notebook/notebookSettingsLogic'-import { isKernelUiEnabled } from '../../utils'-import { NotebookRunMode, buildRunMenuItems } from './runMenuItems'--export type HogqlSqlRunMode = NotebookRunMode--type HogqlSqlRunMenuProps = {- isFresh: boolean- isStale: boolean- loading: boolean- queued: boolean- disabledReason?: string- onRun: (mode: HogqlSqlRunMode) => void-}--export const HogqlSqlRunMenu = ({- isFresh,- isStale,- loading,- queued,- disabledReason,- onRun,-}: HogqlSqlRunMenuProps): JSX.Element => {- const { featureFlags } = useValues(featureFlagLogic)- const { showKernelInfo } = useValues(notebookSettingsLogic)- const { setShowKernelInfo } = useActions(notebookSettingsLogic)- const hogqlRunIconClass = isFresh ? 'text-success' : isStale ? 'text-danger' : undefined- const hogqlRunTooltip = `Run SQL (HogQL) query.${queued ? ' Queued.' : isStale ? ' Stale.' : ''}`-- const hogqlRunMenuItems: LemonMenuItems = [...buildRunMenuItems(onRun)]-- if (isKernelUiEnabled(featureFlags)) {- hogqlRunMenuItems.push({- label: 'Toggle kernel info',- onClick: () => setShowKernelInfo(!showKernelInfo),- })- }-- return (- <LemonButton- onClick={() => onRun('auto')}- size="small"- icon={<IconPlay className={hogqlRunIconClass} />}- loading={loading || queued}- disabledReason={disabledReason}- tooltip={hogqlRunTooltip}- sideAction={{- icon: <IconChevronDown />,- dropdown: {- placement: 'bottom-end',- overlay: <LemonMenuOverlay items={hogqlRunMenuItems} />,- },- divider: false,- 'aria-label': 'Open run options',- disabledReason: disabledReason,- }}- />- )-}diff --git a/frontend/src/scenes/notebooks/Nodes/components/NotebookNodeTitle.test.tsx b/frontend/src/scenes/notebooks/Nodes/components/NotebookNodeTitle.test.tsxindex b81449a4b647..e8843d11f578 100644--- a/frontend/src/scenes/notebooks/Nodes/components/NotebookNodeTitle.test.tsx+++ b/frontend/src/scenes/notebooks/Nodes/components/NotebookNodeTitle.test.tsx@@ -24,7 +24,7 @@ jest.mock('../notebookNodeLogic', () => ({}))jest.mock('~/queries/utils', () => ({- isHogQLQuery: jest.fn(() => false),+ isHogQLQuery: jest.fn((query: unknown) => (query as { kind?: string } | undefined)?.kind === 'HogQLQuery'),}))jest.mock('@posthog/lemon-ui', () => ({@@ -73,10 +73,7 @@ function isNotebookNodeLogicRef(logic: unknown): boolean {const defaultNotebookLogicValues = {isEditable: true,- pythonNodeIndices: new Map<string, number>(),sqlNodeIndices: new Map<string, number>(),- duckSqlNodeIndices: new Map<string, number>(),- hogqlSqlNodeIndices: new Map<string, number>(),}const mockUpdateAttributes = jest.fn()@@ -106,14 +103,11 @@ function setupMocks(nodeLogicValues: Record<string, unknown>, notebookValues: Redescribe('getCellLabel', () => {test.each([- { nodeIndex: undefined, nodeType: NotebookNodeType.Python, expected: null },- { nodeIndex: 0, nodeType: NotebookNodeType.Python, expected: null },- { nodeIndex: 1, nodeType: NotebookNodeType.Python, expected: 'Python 1' },- { nodeIndex: 3, nodeType: NotebookNodeType.DuckSQL, expected: 'SQL (DuckDB) 3' },- { nodeIndex: 2, nodeType: NotebookNodeType.HogQLSQL, expected: 'SQL (HogQL) 2' },- { nodeIndex: 5, nodeType: NotebookNodeType.Query, expected: 'SQL 5' },- ])('returns $expected for index=$nodeIndex type=$nodeType', ({ nodeIndex, nodeType, expected }) => {- expect(getCellLabel(nodeIndex, nodeType)).toBe(expected)+ { nodeIndex: undefined, expected: null },+ { nodeIndex: 0, expected: null },+ { nodeIndex: 5, expected: 'SQL 5' },+ ])('returns $expected for index=$nodeIndex', ({ nodeIndex, expected }) => {+ expect(getCellLabel(nodeIndex)).toBe(expected)})})@@ -139,30 +133,30 @@ describe('NotebookNodeTitle', () => {{scenario: 'indexed cell without custom title displays cell label',nodeValues: {- nodeAttributes: { nodeId: 'py1', title: undefined },- title: 'Python',- titlePlaceholder: 'Python',+ nodeAttributes: { nodeId: 'sql1', title: undefined, query: { kind: 'HogQLQuery' } },+ title: 'SQL',+ titlePlaceholder: 'SQL',isEditingTitle: false,- nodeType: NotebookNodeType.Python,+ nodeType: NotebookNodeType.Query,},notebookValues: {- pythonNodeIndices: new Map([['py1', 1]]),+ sqlNodeIndices: new Map([['sql1', 1]]),},- expectedText: 'Python 1',+ expectedText: 'SQL 1',},{scenario: 'indexed cell with custom title displays both',nodeValues: {- nodeAttributes: { nodeId: 'py1', title: 'Data cleanup' },- title: 'Python',- titlePlaceholder: 'Python',+ nodeAttributes: { nodeId: 'sql1', title: 'Data cleanup', query: { kind: 'HogQLQuery' } },+ title: 'SQL',+ titlePlaceholder: 'SQL',isEditingTitle: false,- nodeType: NotebookNodeType.Python,+ nodeType: NotebookNodeType.Query,},notebookValues: {- pythonNodeIndices: new Map([['py1', 1]]),+ sqlNodeIndices: new Map([['sql1', 1]]),},- expectedText: 'Python 1',+ expectedText: 'SQL 1',alsoExpected: 'Data cleanup',},])(@@ -217,28 +211,28 @@ describe('NotebookNodeTitle', () => {{scenario: 'indexed cell without custom title pre-fills empty',nodeValues: {- nodeAttributes: { nodeId: 'py1', title: undefined },- title: 'Python',- titlePlaceholder: 'Python',+ nodeAttributes: { nodeId: 'sql1', title: undefined, query: { kind: 'HogQLQuery' } },+ title: 'SQL',+ titlePlaceholder: 'SQL',isEditingTitle: true,- nodeType: NotebookNodeType.Python,+ nodeType: NotebookNodeType.Query,},notebookValues: {- pythonNodeIndices: new Map([['py1', 1]]),+ sqlNodeIndices: new Map([['sql1', 1]]),},expectedValue: '',},{scenario: 'indexed cell with custom title pre-fills with custom title',nodeValues: {- nodeAttributes: { nodeId: 'py1', title: 'My Script' },- title: 'Python',- titlePlaceholder: 'Python',+ nodeAttributes: { nodeId: 'sql1', title: 'My Script', query: { kind: 'HogQLQuery' } },+ title: 'SQL',+ titlePlaceholder: 'SQL',isEditingTitle: true,- nodeType: NotebookNodeType.Python,+ nodeType: NotebookNodeType.Query,},notebookValues: {- pythonNodeIndices: new Map([['py1', 1]]),+ sqlNodeIndices: new Map([['sql1', 1]]),},expectedValue: 'My Script',},@@ -268,14 +262,14 @@ describe('NotebookNodeTitle', () => {{scenario: 'indexed cell blur without editing does not save',nodeValues: {- nodeAttributes: { nodeId: 'py1', title: undefined },- title: 'Python',- titlePlaceholder: 'Python',+ nodeAttributes: { nodeId: 'sql1', title: undefined, query: { kind: 'HogQLQuery' } },+ title: 'SQL',+ titlePlaceholder: 'SQL',isEditingTitle: true,- nodeType: NotebookNodeType.Python,+ nodeType: NotebookNodeType.Query,},notebookValues: {- pythonNodeIndices: new Map([['py1', 1]]),+ sqlNodeIndices: new Map([['sql1', 1]]),},},{@@ -367,14 +361,14 @@ describe('NotebookNodeTitle', () => {it('clearing the title saves undefined', () => {setupMocks({- nodeAttributes: { nodeId: 'py1', title: 'My Script' },- title: 'Python',- titlePlaceholder: 'Python',+ nodeAttributes: { nodeId: 'sql1', title: 'My Script', query: { kind: 'HogQLQuery' } },+ title: 'SQL',+ titlePlaceholder: 'SQL',isEditingTitle: true,- nodeType: NotebookNodeType.Python,+ nodeType: NotebookNodeType.Query,},{- pythonNodeIndices: new Map([['py1', 1]]),+ sqlNodeIndices: new Map([['sql1', 1]]),})render(<NotebookNodeTitle />)diff --git a/frontend/src/scenes/notebooks/Nodes/components/NotebookNodeTitle.tsx b/frontend/src/scenes/notebooks/Nodes/components/NotebookNodeTitle.tsxindex fc5364226846..c6f966390472 100644--- a/frontend/src/scenes/notebooks/Nodes/components/NotebookNodeTitle.tsx+++ b/frontend/src/scenes/notebooks/Nodes/components/NotebookNodeTitle.tsx@@ -12,88 +12,28 @@ import { isHogQLQuery } from '~/queries/utils'import { NotebookNodeType } from '../../types'import { notebookNodeLogic } from '../notebookNodeLogic'-const getNodeIndex = ({- isPythonNode,- isDuckSqlNode,- isHogqlSqlNode,- isSqlNode,- nodeId,- pythonNodeIndices,- duckSqlNodeIndices,- hogqlSqlNodeIndices,- sqlNodeIndices,-}: {- isPythonNode: boolean- isDuckSqlNode: boolean- isHogqlSqlNode: boolean- isSqlNode: boolean- nodeId: string- pythonNodeIndices: Map<string, number>- duckSqlNodeIndices: Map<string, number>- hogqlSqlNodeIndices: Map<string, number>- sqlNodeIndices: Map<string, number>-}): number | undefined => {- if (isPythonNode) {- return pythonNodeIndices.get(nodeId)- }- if (isDuckSqlNode) {- return duckSqlNodeIndices.get(nodeId)- }- if (isHogqlSqlNode) {- return hogqlSqlNodeIndices.get(nodeId)- }- if (isSqlNode) {- return sqlNodeIndices.get(nodeId)- }- return undefined-}--export const getCellLabel = (nodeIndex: number | undefined, nodeType: NotebookNodeType): string | null => {+export const getCellLabel = (nodeIndex: number | undefined): string | null => {if (!nodeIndex) {return null}-- if (nodeType === NotebookNodeType.Python) {- return `Python ${nodeIndex}`- }- if (nodeType === NotebookNodeType.DuckSQL) {- return `SQL (DuckDB) ${nodeIndex}`- }- if (nodeType === NotebookNodeType.HogQLSQL) {- return `SQL (HogQL) ${nodeIndex}`- }return `SQL ${nodeIndex}`}export function NotebookNodeTitle(): JSX.Element {- const { isEditable, pythonNodeIndices, sqlNodeIndices, duckSqlNodeIndices, hogqlSqlNodeIndices } =- useValues(notebookLogic)+ const { isEditable, sqlNodeIndices } = useValues(notebookLogic)const { editableTitle, nodeAttributes, title, titlePlaceholder, titleStatus, isEditingTitle, nodeType } =useValues(notebookNodeLogic)const { updateAttributes, toggleEditingTitle } = useActions(notebookNodeLogic)const [newValue, setNewValue] = useState('')const initialValueRef = useRef('')- const isPythonNode = nodeType === NotebookNodeType.Python- const isDuckSqlNode = nodeType === NotebookNodeType.DuckSQL- const isHogqlSqlNode = nodeType === NotebookNodeType.HogQLSQLconst isSqlNode =nodeType === NotebookNodeType.Query &&(isHogQLQuery(nodeAttributes.query) ||(nodeAttributes.query.source && isHogQLQuery(nodeAttributes.query.source)))- const nodeIndex = getNodeIndex({- isPythonNode,- isDuckSqlNode,- isHogqlSqlNode,- isSqlNode,- nodeId: nodeAttributes.nodeId,- pythonNodeIndices,- duckSqlNodeIndices,- hogqlSqlNodeIndices,- sqlNodeIndices,- })- const cellLabel = getCellLabel(nodeIndex, nodeType)+ const nodeIndex = isSqlNode ? sqlNodeIndices.get(nodeAttributes.nodeId) : undefined+ const cellLabel = getCellLabel(nodeIndex)const customTitle = nodeAttributes.titleconst cellTitle = cellLabel ? (customTitle ? `${cellLabel} • ${customTitle}` : cellLabel) : titlediff --git a/frontend/src/scenes/notebooks/Nodes/components/PythonRunMenu.tsx b/frontend/src/scenes/notebooks/Nodes/components/PythonRunMenu.tsxdeleted file mode 100644index 4222228e5e85..000000000000--- a/frontend/src/scenes/notebooks/Nodes/components/PythonRunMenu.tsx+++ /dev/null@@ -1,61 +0,0 @@-import { useActions, useValues } from 'kea'--import { IconChevronDown, IconPlay } from '@posthog/icons'-import { LemonButton, LemonMenuItems, LemonMenuOverlay } from '@posthog/lemon-ui'--import { notebookSettingsLogic } from '../../Notebook/notebookSettingsLogic'-import { NotebookRunMode, buildRunMenuItems } from './runMenuItems'--export type PythonRunMode = NotebookRunMode--type PythonRunMenuProps = {- isFresh: boolean- isStale: boolean- loading: boolean- queued: boolean- disabledReason?: string- onRun: (mode: PythonRunMode) => void-}--export const PythonRunMenu = ({- isFresh,- isStale,- loading,- queued,- disabledReason,- onRun,-}: PythonRunMenuProps): JSX.Element => {- const { showKernelInfo } = useValues(notebookSettingsLogic)- const { setShowKernelInfo } = useActions(notebookSettingsLogic)- const pythonRunIconClass = isFresh ? 'text-success' : isStale ? 'text-danger' : undefined- const pythonRunTooltip = `Run Python cell.${queued ? ' Queued.' : isStale ? ' Stale.' : ''}`-- const pythonRunMenuItems: LemonMenuItems = [- ...buildRunMenuItems(onRun),- {- label: 'Toggle kernel info',- onClick: () => setShowKernelInfo(!showKernelInfo),- },- ]-- return (- <LemonButton- onClick={() => onRun('auto')}- size="small"- icon={<IconPlay className={pythonRunIconClass} />}- loading={loading || queued}- disabledReason={disabledReason}- tooltip={pythonRunTooltip}- sideAction={{- icon: <IconChevronDown />,- dropdown: {- placement: 'bottom-end',- overlay: <LemonMenuOverlay items={pythonRunMenuItems} />,- },- divider: false,- 'aria-label': 'Open run options',- disabledReason: disabledReason,- }}- />- )-}diff --git a/frontend/src/scenes/notebooks/Nodes/components/runMenuItems.ts b/frontend/src/scenes/notebooks/Nodes/components/runMenuItems.tsdeleted file mode 100644index 36563b89371e..000000000000--- a/frontend/src/scenes/notebooks/Nodes/components/runMenuItems.ts+++ /dev/null@@ -1,22 +0,0 @@-import { LemonMenuItems } from '@posthog/lemon-ui'--export type NotebookRunMode = 'auto' | 'cell_upstream' | 'cell' | 'cell_downstream'--export const buildRunMenuItems = (onRun: (mode: NotebookRunMode) => void): LemonMenuItems => [- {- label: 'Run (auto)',- onClick: () => onRun('auto'),- },- {- label: 'Run cell + upstream',- onClick: () => onRun('cell_upstream'),- },- {- label: 'Run cell',- onClick: () => onRun('cell'),- },- {- label: 'Run cell + downstream',- onClick: () => onRun('cell_downstream'),- },-]diff --git a/frontend/src/scenes/notebooks/Nodes/notebookNodeContent.ts b/frontend/src/scenes/notebooks/Nodes/notebookNodeContent.tsindex aecee1a990b3..dea2d0cd4104 100644--- a/frontend/src/scenes/notebooks/Nodes/notebookNodeContent.ts+++ b/frontend/src/scenes/notebooks/Nodes/notebookNodeContent.ts@@ -4,31 +4,6 @@ import { JSONContent } from 'lib/components/RichContentEditor/types'import { NOTEBOOK_NODE_TYPE_TO_MARKDOWN_TAG, getSqlV2PropsFromQueryProp } from '../Notebook/markdownNotebookV2'import { NotebookNodeType } from '../types'-export type PythonNodeSummary = {- nodeId: string- code: string- globalsUsed: string[]- pythonIndex: number- title: string-}--export type DuckSqlNodeSummary = {- nodeId: string- code: string- returnVariable: string- tablesUsed: string[]- duckSqlIndex: number- title: string-}--export type HogqlSqlNodeSummary = {- nodeId: string- code: string- returnVariable: string- hogqlSqlIndex: number- title: string-}-export type SqlV2NodeSummary = {nodeId: stringcode: string@@ -74,24 +49,6 @@ const stripSqlComments = (sql: string): string => {return sql.replace(/--.*$/gm, '').replace(/\/\*[\s\S]*?\*\//g, '')}-export const extractHogqlPlaceholders = (sql: string): string[] => {- const cleanedSql = stripSqlComments(sql || '')- const placeholders: string[] = []- const placeholderPattern = /\{([A-Za-z_][\w$]*)\}/g- const excludedPlaceholderNames = new Set([- 'filters', // Reserved for auto-injected global date/property filters in HogQL notebook queries.- ])- let match = placeholderPattern.exec(cleanedSql)- while (match) {- const name = match[1]- if (name && !excludedPlaceholderNames.has(name) && !placeholders.includes(name)) {- placeholders.push(name)- }- match = placeholderPattern.exec(cleanedSql)- }- return placeholders-}-const extractCteNames = (sql: string): Set<string> => {const cteNames = new Set<string>()const ctePattern = /(?:with|,)\s*([A-Za-z_][\w$]*)\s+as\s*\(/gi@@ -158,106 +115,6 @@ export const extractPythonIdentifiers = (code: string): string[] => {return Array.from(identifiers)}-export const normalizeDuckSqlIdentifier = (identifier: string): string => {- return normalizeSqlIdentifier(identifier)-}--export const resolveDuckSqlReturnVariable = (returnVariable: string): string => {- return returnVariable.trim() || 'duck_df'-}--const buildUniqueDuckSqlReturnVariable = (baseReturnVariable: string, used: Set<string>): string => {- const normalizedBase = normalizeDuckSqlIdentifier(baseReturnVariable)- if (!used.has(normalizedBase)) {- return baseReturnVariable- }-- let suffix = 2- while (true) {- const candidate = `${baseReturnVariable}_${suffix}`- if (!used.has(normalizeDuckSqlIdentifier(candidate))) {- return candidate- }- suffix += 1- }-}--export const getUniqueDuckSqlReturnVariable = (- nodes: DuckSqlNodeSummary[],- nodeId: string,- fallbackReturnVariable: string-): string => {- const used = new Set<string>()- let resolvedReturnVariable = resolveDuckSqlReturnVariable(fallbackReturnVariable)- let resolvedFromNodes = false-- nodes.forEach((node) => {- const baseReturnVariable = resolveDuckSqlReturnVariable(node.returnVariable)- const uniqueReturnVariable = buildUniqueDuckSqlReturnVariable(baseReturnVariable, used)- used.add(normalizeDuckSqlIdentifier(uniqueReturnVariable))-- if (node.nodeId === nodeId) {- resolvedReturnVariable = uniqueReturnVariable- resolvedFromNodes = true- }- })-- if (!resolvedFromNodes) {- resolvedReturnVariable = buildUniqueDuckSqlReturnVariable(resolvedReturnVariable, used)- }-- return resolvedReturnVariable-}--export const resolveHogqlReturnVariable = (returnVariable: string): string => {- return returnVariable.trim() || 'hogql_df'-}--const buildUniqueHogqlReturnVariable = (baseReturnVariable: string, used: Set<string>): string => {- const normalizedBase = normalizeSqlIdentifier(baseReturnVariable)- if (!used.has(normalizedBase)) {- return baseReturnVariable- }-- let suffix = 2- while (true) {- const candidate = `${baseReturnVariable}_${suffix}`- if (!used.has(normalizeSqlIdentifier(candidate))) {- return candidate- }- suffix += 1- }-}--export const getUniqueHogqlReturnVariable = (- nodes: HogqlSqlNodeSummary[],- nodeId: string,- fallbackReturnVariable: string-): string => {- const used = new Set<string>()- let resolvedReturnVariable = resolveHogqlReturnVariable(fallbackReturnVariable)- let resolvedFromNodes = false-- nodes.forEach((node) => {- const baseReturnVariable = resolveHogqlReturnVariable(node.returnVariable)- const uniqueReturnVariable = buildUniqueHogqlReturnVariable(baseReturnVariable, used)- used.add(normalizeSqlIdentifier(uniqueReturnVariable))-- if (node.nodeId === nodeId) {- resolvedReturnVariable = uniqueReturnVariable- resolvedFromNodes = true- }- })-- if (!resolvedFromNodes) {- resolvedReturnVariable = buildUniqueHogqlReturnVariable(resolvedReturnVariable, used)- }-- return resolvedReturnVariable-}--// SQLV2 nodes reference upstream nodes by bare table name (like DuckSQL) but use HogQL-// identifiers (like the HogQL node), so they reuse both extraction helpers.export const resolveSqlV2ReturnVariable = (returnVariable: string): string => {return returnVariable.trim() || 'sql_df'}@@ -436,36 +293,6 @@ export const collectSqlV2Nodes = (content?: JSONContent | null): SqlV2NodeSummarreturn nodes}-export const collectPythonNodes = (content?: JSONContent | null): PythonNodeSummary[] => {- if (!content || typeof content !== 'object') {- return []- }-- const nodes: PythonNodeSummary[] = []-- const walk = (node: any): void => {- if (!node || typeof node !== 'object') {- return- }- if (node.type === NotebookNodeType.Python) {- const attrs = node.attrs ?? {}- nodes.push({- nodeId: attrs.nodeId ?? '',- code: typeof attrs.code === 'string' ? attrs.code : '',- globalsUsed: Array.isArray(attrs.globalsUsed) ? attrs.globalsUsed : [],- pythonIndex: nodes.length + 1,- title: typeof attrs.title === 'string' ? attrs.title : '',- })- }- if (Array.isArray(node.content)) {- node.content.forEach(walk)- }- }-- walk(content)- return nodes-}-export type NotebookFrameNodeSummary = {nodeId: stringname: string@@ -570,9 +397,8 @@ export type PythonKernelNodeSummary = {// the kernel namespace. Unlike the SQL collectors the names are NOT disambiguated — they are// exactly the kernel variables, so a duplicated returnVariable means last-run-wins, matching// kernel semantics. A blank name is a display-only cell that binds nothing (see the SQLV2-// collector); only a missing attribute takes the legacy 'df' default. Markdown-aware (unlike-// the legacy collectPythonNodes) because revamped markdown notebooks store their cells as-// `<PythonV2 …/>` component tags.+// collector); only a missing attribute takes the legacy 'df' default. Markdown-aware because+// revamped markdown notebooks store their cells as `<PythonV2 …/>` component tags.export const collectPythonKernelNodes = (content?: JSONContent | null): PythonKernelNodeSummary[] => {if (!content || typeof content !== 'object') {return []@@ -601,81 +427,6 @@ export const collectPythonKernelNodes = (content?: JSONContent | null): PythonKereturn nodes}-export const collectHogqlSqlNodes = (content?: JSONContent | null): HogqlSqlNodeSummary[] => {- if (!content || typeof content !== 'object') {- return []- }-- const nodes: HogqlSqlNodeSummary[] = []- const usedReturnVariables = new Set<string>()-- const walk = (node: any): void => {- if (!node || typeof node !== 'object') {- return- }- if (node.type === NotebookNodeType.HogQLSQL) {- const attrs = node.attrs ?? {}- const code = typeof attrs.code === 'string' ? attrs.code : ''- const baseReturnVariable = resolveHogqlReturnVariable(- typeof attrs.returnVariable === 'string' ? attrs.returnVariable : 'hogql_df'- )- const returnVariable = buildUniqueHogqlReturnVariable(baseReturnVariable, usedReturnVariables)- usedReturnVariables.add(normalizeSqlIdentifier(returnVariable))- nodes.push({- nodeId: attrs.nodeId ?? '',- code,- returnVariable,- hogqlSqlIndex: nodes.length + 1,- title: typeof attrs.title === 'string' ? attrs.title : '',- })- }- if (Array.isArray(node.content)) {- node.content.forEach(walk)- }- }-- walk(content)- return nodes-}--export const collectDuckSqlNodes = (content?: JSONContent | null): DuckSqlNodeSummary[] => {- if (!content || typeof content !== 'object') {- return []- }-- const nodes: DuckSqlNodeSummary[] = []- const usedReturnVariables = new Set<string>()-- const walk = (node: any): void => {- if (!node || typeof node !== 'object') {- return- }- if (node.type === NotebookNodeType.DuckSQL) {- const attrs = node.attrs ?? {}- const code = typeof attrs.code === 'string' ? attrs.code : ''- const baseReturnVariable = resolveDuckSqlReturnVariable(- typeof attrs.returnVariable === 'string' ? attrs.returnVariable : 'duck_df'- )- const returnVariable = buildUniqueDuckSqlReturnVariable(baseReturnVariable, usedReturnVariables)- usedReturnVariables.add(normalizeDuckSqlIdentifier(returnVariable))- nodes.push({- nodeId: attrs.nodeId ?? '',- code,- returnVariable,- tablesUsed: extractDuckSqlTables(code),- duckSqlIndex: nodes.length + 1,- title: typeof attrs.title === 'string' ? attrs.title : '',- })- }- if (Array.isArray(node.content)) {- node.content.forEach(walk)- }- }-- walk(content)- return nodes-}-const buildDependencyUsage = (node: NotebookDependencyNode): NotebookDependencyUsage => {return {nodeId: node.nodeId,@@ -685,12 +436,7 @@ const buildDependencyUsage = (node: NotebookDependencyNode): NotebookDependencyU}}-const matchesUsage = (exportName: string, usageName: string, usageNodeType: NotebookNodeType): boolean => {- if (usageNodeType === NotebookNodeType.DuckSQL) {- return normalizeDuckSqlIdentifier(exportName) === normalizeDuckSqlIdentifier(usageName)- }- return exportName === usageName-}+const matchesUsage = (exportName: string, usageName: string): boolean => exportName === usageNameexport type NotebookDependencyDirection = 'upstream' | 'downstream'@@ -745,13 +491,8 @@ export const buildNotebookDependencyGraph = (content?: JSONContent | null): Note}const nodes: NotebookDependencyNode[] = []- let pythonIndex = 0let pythonV2Index = 0- let duckSqlIndex = 0- let hogqlSqlIndex = 0let sqlV2Index = 0- const usedDuckSqlReturnVariables = new Set<string>()- const usedHogqlReturnVariables = new Set<string>()const usedSqlV2ReturnVariables = new Set<string>()const walk = (node: any): void => {@@ -759,65 +500,6 @@ export const buildNotebookDependencyGraph = (content?: JSONContent | null): Notereturn}- if (node.type === NotebookNodeType.Python) {- const attrs = node.attrs ?? {}- pythonIndex += 1- const exportedGlobals = Array.isArray(attrs.globalsExportedWithTypes)- ? attrs.globalsExportedWithTypes.map((entry: any) => entry?.name).filter(Boolean)- : []- nodes.push({- nodeId: attrs.nodeId ?? '',- nodeType: NotebookNodeType.Python,- nodeIndex: pythonIndex,- title: typeof attrs.title === 'string' ? attrs.title : '',- exports: exportedGlobals,- uses: Array.isArray(attrs.globalsUsed) ? attrs.globalsUsed : [],- code: typeof attrs.code === 'string' ? attrs.code : '',- })- }-- if (node.type === NotebookNodeType.DuckSQL) {- const attrs = node.attrs ?? {}- duckSqlIndex += 1- const baseReturnVariable = resolveDuckSqlReturnVariable(- typeof attrs.returnVariable === 'string' ? attrs.returnVariable : 'duck_df'- )- const returnVariable = buildUniqueDuckSqlReturnVariable(baseReturnVariable, usedDuckSqlReturnVariables)- usedDuckSqlReturnVariables.add(normalizeDuckSqlIdentifier(returnVariable))- const code = typeof attrs.code === 'string' ? attrs.code : ''- nodes.push({- nodeId: attrs.nodeId ?? '',- nodeType: NotebookNodeType.DuckSQL,- nodeIndex: duckSqlIndex,- title: typeof attrs.title === 'string' ? attrs.title : '',- exports: returnVariable ? [returnVariable] : [],- uses: extractDuckSqlTables(code),- code,- returnVariable,- })- }-- if (node.type === NotebookNodeType.HogQLSQL) {- const attrs = node.attrs ?? {}- hogqlSqlIndex += 1- const baseReturnVariable = resolveHogqlReturnVariable(- typeof attrs.returnVariable === 'string' ? attrs.returnVariable : 'hogql_df'- )- const returnVariable = buildUniqueHogqlReturnVariable(baseReturnVariable, usedHogqlReturnVariables)- usedHogqlReturnVariables.add(normalizeSqlIdentifier(returnVariable))- const code = typeof attrs.code === 'string' ? attrs.code : ''- nodes.push({- nodeId: attrs.nodeId ?? '',- nodeType: NotebookNodeType.HogQLSQL,- nodeIndex: hogqlSqlIndex,- title: typeof attrs.title === 'string' ? attrs.title : '',- exports: returnVariable ? [returnVariable] : [],- uses: extractHogqlPlaceholders(code),- code,- returnVariable,- })- }-if (node.type === NotebookNodeType.SQLV2) {const attrs = node.attrs ?? {}sqlV2Index += 1@@ -897,7 +579,7 @@ export const buildNotebookDependencyGraph = (content?: JSONContent | null): Noteconst upstreamSources = node.uses.reduce<Record<string, NotebookDependencyUsage>>((acc, usageName) => {const source = upstreamNodes.find((upstreamNode) =>- upstreamNode.exports.some((exportName) => matchesUsage(exportName, usageName, node.nodeType))+ upstreamNode.exports.some((exportName) => matchesUsage(exportName, usageName)))if (source) {acc[usageName] = buildDependencyUsage(source)@@ -908,9 +590,7 @@ export const buildNotebookDependencyGraph = (content?: JSONContent | null): Noteconst downstreamUsage = node.exports.reduce<Record<string, NotebookDependencyUsage[]>>((acc, exportName) => {acc[exportName] = downstreamNodes.filter((downstreamNode) =>- downstreamNode.uses.some((usageName) =>- matchesUsage(exportName, usageName, downstreamNode.nodeType)- )+ downstreamNode.uses.some((usageName) => matchesUsage(exportName, usageName))).map(buildDependencyUsage)return accdiff --git a/frontend/src/scenes/notebooks/Nodes/notebookNodeLogic.ts b/frontend/src/scenes/notebooks/Nodes/notebookNodeLogic.tsindex 1e5da06f6e6c..8ad5ec49f825 100644--- a/frontend/src/scenes/notebooks/Nodes/notebookNodeLogic.ts+++ b/frontend/src/scenes/notebooks/Nodes/notebookNodeLogic.ts@@ -17,12 +17,8 @@ import posthog from 'posthog-js'import { LemonMenuItems } from '@posthog/lemon-ui'-import api from 'lib/api'import type { NotebookComponentToolbarTitleStatus } from 'lib/components/MarkdownNotebook/componentToolbarExtras'import { JSONContent, RichContentNode } from 'lib/components/RichContentEditor/types'-import { hashCodeForString } from 'lib/utils/strings'-import { sqlEditorLogic } from 'scenes/data-warehouse/editor/sqlEditorLogic'-import { SQLEditorMode } from 'scenes/data-warehouse/editor/sqlEditorModes'import { isHogQLQuery, isNodeWithSource } from '~/queries/utils'@@ -32,7 +28,6 @@ import {insertMarkdownNotebookBlockAfterNode,isMarkdownNotebookContent,} from '../Notebook/markdownNotebookV2'-import type { NotebookKernelInfo } from '../Notebook/notebookKernelInfoLogic'import type { notebookLogicType } from '../Notebook/notebookLogic'import {CustomNotebookNodeAttributes,@@ -45,70 +40,15 @@ import {NotebookNodeType,} from '../types'import type { NotebookType } from '../types'-import { getNotebookSqlEditorTabId } from './components/NotebookSQLEditor'import { NotebookNodeMessages, NotebookNodeMessagesListeners } from './messaging/notebook-node-messages'import {- type DuckSqlNodeSummary,- type HogqlSqlNodeSummary,type NotebookDependencyGraph,- type NotebookDependencyNode,type NotebookDependencyUsage,- collectDependencyNodeIds,- extractHogqlPlaceholders,- getUniqueDuckSqlReturnVariable,- getUniqueHogqlReturnVariable,getUniqueSqlV2ReturnVariable,- resolveDuckSqlReturnVariable,- resolveHogqlReturnVariable,} from './notebookNodeContent'-import type { PythonNodeSummary, SqlV2NodeSummary } from './notebookNodeContent'-import {- NotebookDataframeResult,- PythonExecutionResult,- PythonExecutionVariable,- PythonKernelExecuteResponse,- PythonKernelVariableResponse,- buildPythonExecutionError,- buildPythonExecutionResult,- buildPythonExecutionRunning,- mergeExecutionVariables,-} from './pythonExecution'+import type { SqlV2NodeSummary } from './notebookNodeContent'import { buildNotebookNodeClipboardHTML } from './utils'-export type PythonRunMode = 'auto' | 'cell_upstream' | 'cell' | 'cell_downstream'-export type DuckSqlRunMode = 'auto' | 'cell_upstream' | 'cell' | 'cell_downstream'-export type HogqlSqlRunMode = 'auto' | 'cell_upstream' | 'cell' | 'cell_downstream'--type RunPythonCellParams = {- notebookId: string- code: string- exportedGlobals: { name: string; type: string }[]- updateAttributes: (attributes: Partial<NotebookNodeAttributes<any>>) => void- setPythonRunLoading: (loading: boolean) => void- executionSandboxId: string | null-}--type RunDuckSqlCellParams = {- notebookId: string- code: string- returnVariable: string- pageSize: number- updateAttributes: (attributes: Partial<NotebookNodeAttributes<any>>) => void- setDuckSqlRunLoading: (loading: boolean) => void- executionSandboxId: string | null-}--type RunHogqlSqlCellParams = {- notebookId: string- code: string- placeholders: string[]- returnVariable: string- pageSize: number- updateAttributes: (attributes: Partial<NotebookNodeAttributes<any>>) => void- setHogqlSqlRunLoading: (loading: boolean) => void- executionSandboxId: string | null-}-const isSqlQueryNode = (nodeAttributes: NotebookNodeAttributes<any>): boolean => {const query = nodeAttributes?.queryif (!query) {@@ -123,747 +63,6 @@ const isSqlQueryNode = (nodeAttributes: NotebookNodeAttributes<any>): boolean =>return false}-const DEFAULT_DATAFRAME_PAGE_SIZE = 10--const getMountedNotebookSqlEditorCode = (nodeId: string | null | undefined, suffix: string): string | null =>- sqlEditorLogic.findMounted({ tabId: getNotebookSqlEditorTabId(nodeId, suffix), mode: SQLEditorMode.Embedded })- ?.values.queryInput ?? null--const buildDuckSqlCode = (code: string, returnVariable: string, pageSize: number): string => {- const resolvedReturnVariable = resolveDuckSqlReturnVariable(returnVariable)- const sqlLiteral = JSON.stringify(code ?? '')- const tableNameLiteral = JSON.stringify(resolvedReturnVariable)- const previewPageSize = Math.max(1, pageSize || DEFAULT_DATAFRAME_PAGE_SIZE)- return (- `import json\n` +- `${resolvedReturnVariable} = duck_execute(${sqlLiteral})\n` +- `duck_save_table(${tableNameLiteral}, ${resolvedReturnVariable})\n` +- `json.dumps(notebook_dataframe_page(${resolvedReturnVariable}, offset=0, limit=${previewPageSize}))`- )-}--type HogqlExecuteResponse = {- results?: any[]- columns?: string[]- error?: string-}--const buildHogqlSqlAssignmentCode = (code: string, returnVariable: string): string => {- const resolvedReturnVariable = resolveHogqlReturnVariable(returnVariable)- const sqlLiteral = JSON.stringify(code ?? '')- return `${resolvedReturnVariable} = hogql_execute(${sqlLiteral})`-}--const buildHogqlSqlExecutionCode = (- code: string,- returnVariable: string,- pageSize: number,- placeholders: string[]-): string => {- const resolvedReturnVariable = resolveHogqlReturnVariable(returnVariable)- const sqlLiteral = JSON.stringify(code ?? '')- const placeholdersLiteral = JSON.stringify(placeholders)- const previewPageSize = Math.max(1, pageSize || DEFAULT_DATAFRAME_PAGE_SIZE)- return (- `import json\n` +- `${resolvedReturnVariable} = hogql_execute(${sqlLiteral}, placeholders=${placeholdersLiteral})\n` +- `json.dumps(notebook_dataframe_page(${resolvedReturnVariable}, offset=0, limit=${previewPageSize}))`- )-}--const buildHogqlDataframeResult = (- response: HogqlExecuteResponse,- pageSize: number-): NotebookDataframeResult | null => {- const columns = Array.isArray(response.columns) ? response.columns : []- const results = Array.isArray(response.results) ? response.results : []- const resolvedPageSize = Math.max(1, pageSize || DEFAULT_DATAFRAME_PAGE_SIZE)- const limitedResults = results.slice(0, resolvedPageSize)- const rows = limitedResults.map((row) => {- if (row && typeof row === 'object' && !Array.isArray(row)) {- return row as Record<string, any>- }- if (Array.isArray(row)) {- const rowObject: Record<string, any> = {}- if (columns.length > 0) {- columns.forEach((column, index) => {- rowObject[column] = row[index]- })- } else {- row.forEach((value, index) => {- rowObject[`column_${index + 1}`] = value- })- }- return rowObject- }- if (columns.length === 1) {- return { [columns[0]]: row }- }- return { value: row }- })- const resolvedColumns = columns.length > 0 ? columns : rows.length > 0 ? Object.keys(rows[0]) : []- return {- columns: resolvedColumns,- rows,- rowCount: results.length,- }-}--const buildHogqlExecutionResult = ({- response,- exportedGlobals,- returnVariable,- query,- pageSize,-}: {- response: HogqlExecuteResponse- exportedGlobals: { name: string; type: string }[]- returnVariable: string- query: string- pageSize: number-}): PythonExecutionResult => {- const isError = Boolean(response.error)- const dataframeResult = isError ? null : buildHogqlDataframeResult(response, pageSize)- const variableResponse: PythonKernelVariableResponse = isError- ? {- status: 'error',- type: 'DataFrame',- ename: 'HogQLQueryError',- evalue: response.error,- traceback: response.error ? [response.error] : [],- }- : {- status: 'ok',- type: 'DataFrame',- hogql_query: query,- }- return {- status: isError ? 'error' : 'ok',- stdout: '',- stderr: isError ? (response.error ?? 'Failed to run HogQL query.') : '',- result: dataframeResult ? JSON.stringify(dataframeResult) : undefined,- errorName: isError ? 'HogQLQueryError' : null,- traceback: isError && response.error ? [response.error] : [],- variables: mergeExecutionVariables(exportedGlobals, {- [returnVariable]: variableResponse,- }),- }-}--type DependencyRunDirection = 'upstream' | 'downstream'--const getDependencyNodesForRun = (- dependencyGraph: NotebookDependencyGraph,- startNodeId: string,- direction: DependencyRunDirection-): NotebookDependencyNode[] => {- const nodeIds = collectDependencyNodeIds(dependencyGraph, startNodeId, direction)- if (nodeIds.size === 0) {- return []- }-- return dependencyGraph.nodes.filter((node) => nodeIds.has(node.nodeId))-}--const getDependencyEntriesWithLogic = ({- dependencyGraph,- nodeId,- direction,- notebookLogic,-}: {- dependencyGraph: NotebookDependencyGraph- nodeId: string- direction: DependencyRunDirection- notebookLogic: BuiltLogic<notebookLogicType>-}): { node: NotebookDependencyNode; nodeLogic: BuiltLogic<notebookNodeLogicType> }[] => {- const nodesToRun = getDependencyNodesForRun(dependencyGraph, nodeId, direction)- if (nodesToRun.length === 0) {- return []- }-- return nodesToRun- .map((node) => ({- node,- nodeLogic: notebookLogic.values.findNodeLogicById(node.nodeId),- }))- .filter(- (- entry- ): entry is {- node: (typeof nodesToRun)[number]- nodeLogic: BuiltLogic<notebookNodeLogicType>- } => !!entry.nodeLogic- )-}--const isPythonExecutionFresh = (nodeLogic: BuiltLogic<notebookNodeLogicType>, code: string): boolean => {- const { pythonExecutionCodeHash, pythonExecution, pythonExecutionSandboxId } = nodeLogic.values.nodeAttributes- const codeHash = hashCodeForString(code)- const kernelSandboxId = nodeLogic.values.kernelInfo?.sandbox_id ?? null- const kernelIsRunning = nodeLogic.values.kernelInfo?.status === 'running'- const sandboxMatches =- pythonExecutionSandboxId && kernelSandboxId !== null && pythonExecutionSandboxId === kernelSandboxId- return (- pythonExecutionCodeHash &&- pythonExecutionCodeHash === codeHash &&- pythonExecution?.status === 'ok' &&- sandboxMatches &&- kernelIsRunning- )-}--const isDuckSqlExecutionFresh = (- nodeLogic: BuiltLogic<notebookNodeLogicType>,- code: string,- returnVariable: string-): boolean => {- const { duckExecutionCodeHash, duckExecution, duckExecutionSandboxId } = nodeLogic.values.nodeAttributes- const codeHash = hashCodeForString(`${code}\n${returnVariable}`)- const kernelSandboxId = nodeLogic.values.kernelInfo?.sandbox_id ?? null- const kernelIsRunning = nodeLogic.values.kernelInfo?.status === 'running'- const sandboxMatches =- duckExecutionSandboxId && kernelSandboxId !== null && duckExecutionSandboxId === kernelSandboxId- return (- duckExecutionCodeHash &&- duckExecutionCodeHash === codeHash &&- duckExecution?.status === 'ok' &&- sandboxMatches &&- kernelIsRunning- )-}--const isHogqlSqlExecutionFresh = (- nodeLogic: BuiltLogic<notebookNodeLogicType>,- code: string,- returnVariable: string-): boolean => {- const { hogqlExecutionCodeHash, hogqlExecution, hogqlExecutionSandboxId } = nodeLogic.values.nodeAttributes- const codeHash = hashCodeForString(`${code}\n${returnVariable}`)- const kernelSandboxId = nodeLogic.values.kernelInfo?.sandbox_id ?? null- const kernelIsRunning = nodeLogic.values.kernelInfo?.status === 'running'- const sandboxMatches =- hogqlExecutionSandboxId && kernelSandboxId !== null && hogqlExecutionSandboxId === kernelSandboxId- return (- hogqlExecutionCodeHash &&- hogqlExecutionCodeHash === codeHash &&- hogqlExecution?.status === 'ok' &&- sandboxMatches &&- kernelIsRunning- )-}--const setDependencyNodeQueued = (- nodeLogic: BuiltLogic<notebookNodeLogicType>,- nodeType: NotebookNodeType,- queued: boolean-): void => {- if (nodeType === NotebookNodeType.Python) {- nodeLogic.actions.setPythonRunQueued(queued)- return- }- if (nodeType === NotebookNodeType.DuckSQL) {- nodeLogic.actions.setDuckSqlRunQueued(queued)- return- }- if (nodeType === NotebookNodeType.HogQLSQL) {- nodeLogic.actions.setHogqlSqlRunQueued(queued)- }-}--const runDependencyNodes = async ({- entries,- notebookId,- mode,- duckSqlNodeSummaries,- hogqlSqlNodeSummaries,- currentNodeId,- skipDataframeVariableUpdateForNodeId,-}: {- entries: { node: NotebookDependencyNode; nodeLogic: BuiltLogic<notebookNodeLogicType> }[]- notebookId: string- mode: PythonRunMode | DuckSqlRunMode | HogqlSqlRunMode- duckSqlNodeSummaries: DuckSqlNodeSummary[]- hogqlSqlNodeSummaries: HogqlSqlNodeSummary[]- currentNodeId: string- skipDataframeVariableUpdateForNodeId?: string-}): Promise<void> => {- entries.forEach(({ node, nodeLogic }) => setDependencyNodeQueued(nodeLogic, node.nodeType, true))-- try {- for (const { node, nodeLogic } of entries) {- setDependencyNodeQueued(nodeLogic, node.nodeType, false)- if (node.nodeType === NotebookNodeType.Python) {- const nodeAttributes = nodeLogic.values.nodeAttributes as {- code?: string- pythonExecutionSandboxId?: string | null- }- const nodeCode = nodeAttributes.code ?? node.code ?? ''- const executionSandboxId =- nodeLogic.values.kernelInfo?.sandbox_id ?? nodeAttributes.pythonExecutionSandboxId ?? null- if (mode === 'auto' && node.nodeId !== currentNodeId && isPythonExecutionFresh(nodeLogic, nodeCode)) {- continue- }- const { executed, execution } = await runPythonCell({- notebookId,- code: nodeCode,- exportedGlobals: nodeLogic.values.exportedGlobals,- updateAttributes: nodeLogic.actions.updateAttributes,- setPythonRunLoading: nodeLogic.actions.setPythonRunLoading,- executionSandboxId,- })-- const isSuccess = executed && execution?.status === 'ok'- if (isSuccess) {- const dataframeVariable = findDataframeVariable(execution?.variables)- nodeLogic.actions.setDataframeVariableName(dataframeVariable)- } else {- nodeLogic.actions.setDataframeVariableName(null)- }- if (!isSuccess) {- break- }- continue- }-- if (node.nodeType === NotebookNodeType.DuckSQL) {- const nodeAttributes = nodeLogic.values.nodeAttributes as {- code?: string- returnVariable?: string- duckExecutionSandboxId?: string | null- }- const mountedEditorCode = getMountedNotebookSqlEditorCode(node.nodeId, 'duck')- const nodeCode = mountedEditorCode ?? nodeAttributes.code ?? node.code ?? ''- if (mountedEditorCode !== null && mountedEditorCode !== nodeAttributes.code) {- nodeLogic.actions.updateAttributes({ code: mountedEditorCode })- }- const nodeReturnVariable = getUniqueDuckSqlReturnVariable(- duckSqlNodeSummaries,- node.nodeId,- nodeAttributes.returnVariable ?? node.returnVariable ?? 'duck_df'- )- const executionSandboxId =- nodeLogic.values.kernelInfo?.sandbox_id ?? nodeAttributes.duckExecutionSandboxId ?? null- if (- mode === 'auto' &&- node.nodeId !== currentNodeId &&- isDuckSqlExecutionFresh(nodeLogic, nodeCode, nodeReturnVariable)- ) {- continue- }- const { executed, execution } = await runDuckSqlCell({- notebookId,- code: nodeCode,- returnVariable: nodeReturnVariable,- pageSize: nodeLogic.values.dataframePageSize,- updateAttributes: nodeLogic.actions.updateAttributes,- setDuckSqlRunLoading: nodeLogic.actions.setDuckSqlRunLoading,- executionSandboxId,- })-- const isSuccess = executed && execution?.status === 'ok'- if (isSuccess) {- const previewResult = parseDataframePreview(execution?.result)- const shouldUpdateDataframeVariable =- node.nodeId !== skipDataframeVariableUpdateForNodeId || !nodeLogic.values.dataframeVariableName- if (shouldUpdateDataframeVariable) {- nodeLogic.actions.setDataframeVariableName(- nodeLogic.values.duckSqlReturnVariable,- previewResult- )- }- } else {- nodeLogic.actions.setDataframeVariableName(null)- }- if (!isSuccess) {- break- }- }-- if (node.nodeType === NotebookNodeType.HogQLSQL) {- const nodeAttributes = nodeLogic.values.nodeAttributes as {- code?: string- returnVariable?: string- hogqlExecutionSandboxId?: string | null- }- const mountedEditorCode = getMountedNotebookSqlEditorCode(node.nodeId, 'hogql')- const nodeCode = mountedEditorCode ?? nodeAttributes.code ?? node.code ?? ''- if (mountedEditorCode !== null && mountedEditorCode !== nodeAttributes.code) {- nodeLogic.actions.updateAttributes({ code: mountedEditorCode })- }- const nodeReturnVariable = getUniqueHogqlReturnVariable(- hogqlSqlNodeSummaries,- node.nodeId,- nodeAttributes.returnVariable ?? node.returnVariable ?? 'hogql_df'- )- const placeholders = extractHogqlPlaceholders(nodeCode)- const executionSandboxId =- nodeLogic.values.kernelInfo?.sandbox_id ?? nodeAttributes.hogqlExecutionSandboxId ?? null- if (- mode === 'auto' &&- node.nodeId !== currentNodeId &&- isHogqlSqlExecutionFresh(nodeLogic, nodeCode, nodeReturnVariable)- ) {- continue- }- const { executed, execution } = await runHogqlSqlCell({- notebookId,- code: nodeCode,- placeholders,- returnVariable: nodeReturnVariable,- pageSize: nodeLogic.values.dataframePageSize,- updateAttributes: nodeLogic.actions.updateAttributes,- setHogqlSqlRunLoading: nodeLogic.actions.setHogqlSqlRunLoading,- executionSandboxId,- })-- const isSuccess = executed && execution?.status === 'ok'- if (isSuccess) {- const previewResult = parseDataframePreview(execution?.result)- const shouldUpdateDataframeVariable =- node.nodeId !== skipDataframeVariableUpdateForNodeId || !nodeLogic.values.dataframeVariableName- if (shouldUpdateDataframeVariable) {- nodeLogic.actions.setDataframeVariableName(- nodeLogic.values.hogqlSqlReturnVariable,- previewResult- )- }- } else {- nodeLogic.actions.setDataframeVariableName(null)- }- if (!isSuccess) {- break- }- }- }- } finally {- entries.forEach(({ node, nodeLogic }) => setDependencyNodeQueued(nodeLogic, node.nodeType, false))- }-}--const runPythonCell = async ({- notebookId,- code,- exportedGlobals,- updateAttributes,- setPythonRunLoading,- executionSandboxId,-}: RunPythonCellParams): Promise<{ executed: boolean; execution: PythonExecutionResult | null }> => {- setPythonRunLoading(true)- try {- let stdout = ''- let stderr = ''- let executionResult: PythonExecutionResult | null = null- let kernelResponse: PythonKernelExecuteResponse | null = null- let didFail = false- const codeHash = hashCodeForString(code)-- updateAttributes({- pythonExecution: buildPythonExecutionRunning(exportedGlobals),- pythonExecutionCodeHash: codeHash,- pythonExecutionSandboxId: executionSandboxId,- })-- await api.notebooks.kernelExecuteStream(- notebookId,- {- code,- return_variables: exportedGlobals.length > 0,- },- {- onMessage: (event) => {- if (event.event === 'stdout') {- const payload = JSON.parse(event.data) as { text?: string }- stdout = `${stdout}${payload.text ?? ''}`- updateAttributes({- pythonExecution: buildPythonExecutionRunning(exportedGlobals, stdout, stderr),- })- return- }- if (event.event === 'stderr') {- const payload = JSON.parse(event.data) as { text?: string }- stderr = `${stderr}${payload.text ?? ''}`- updateAttributes({- pythonExecution: buildPythonExecutionRunning(exportedGlobals, stdout, stderr),- })- return- }- if (event.event === 'error') {- const payload = JSON.parse(event.data) as { error?: string }- const message = payload.error ?? 'Failed to run Python cell.'- executionResult = buildPythonExecutionError(message, exportedGlobals)- didFail = true- updateAttributes({- pythonExecution: executionResult,- pythonExecutionCodeHash: codeHash,- pythonExecutionSandboxId: executionSandboxId,- })- return- }- if (event.event === 'result') {- kernelResponse = JSON.parse(event.data) as PythonKernelExecuteResponse- executionResult = buildPythonExecutionResult(kernelResponse, exportedGlobals)- const runtimeSandboxId = kernelResponse.kernel_runtime?.sandbox_id ?? executionSandboxId- updateAttributes({- pythonExecution: executionResult,- pythonExecutionCodeHash: codeHash,- pythonExecutionSandboxId: runtimeSandboxId,- })- }- },- onError: (error) => {- const message = error instanceof Error ? error.message : 'Failed to run Python cell.'- executionResult = buildPythonExecutionError(message, exportedGlobals)- didFail = true- updateAttributes({- pythonExecution: executionResult,- pythonExecutionCodeHash: codeHash,- pythonExecutionSandboxId: executionSandboxId,- })- throw error- },- }- )-- if (!executionResult && kernelResponse) {- executionResult = buildPythonExecutionResult(kernelResponse, exportedGlobals)- }-- if (!executionResult) {- throw new Error('Python execution did not return a result.')- }-- return { executed: !didFail, execution: executionResult }- } catch (error) {- if (error instanceof Error && error.message === 'Python execution did not return a result.') {- const executionResult = buildPythonExecutionError(error.message, exportedGlobals)- updateAttributes({- pythonExecution: executionResult,- pythonExecutionCodeHash: hashCodeForString(code),- pythonExecutionSandboxId: executionSandboxId,- })- return { executed: false, execution: executionResult }- }- const message = error instanceof Error ? error.message : 'Failed to run Python cell.'- const executionResult = buildPythonExecutionError(message, exportedGlobals)- updateAttributes({- pythonExecution: executionResult,- pythonExecutionCodeHash: hashCodeForString(code),- pythonExecutionSandboxId: executionSandboxId,- })- return { executed: false, execution: executionResult }- } finally {- setPythonRunLoading(false)- }-}--const runDuckSqlCell = async ({- notebookId,- code,- returnVariable,- pageSize,- updateAttributes,- setDuckSqlRunLoading,- executionSandboxId,-}: RunDuckSqlCellParams): Promise<{ executed: boolean; execution: PythonExecutionResult | null }> => {- setDuckSqlRunLoading(true)- const resolvedReturnVariable = resolveDuckSqlReturnVariable(returnVariable)- const executionCode = buildDuckSqlCode(code, returnVariable, pageSize)- try {- let executionResult: PythonExecutionResult | null = null- let kernelResponse: PythonKernelExecuteResponse | null = null- const codeHash = hashCodeForString(`${code}\n${resolvedReturnVariable}`)- const exportedGlobals = [{ name: resolvedReturnVariable, type: 'DataFrame' }]-- updateAttributes({- duckExecution: buildPythonExecutionRunning(exportedGlobals),- duckExecutionCodeHash: codeHash,- duckExecutionSandboxId: executionSandboxId,- })-- kernelResponse = (await api.notebooks.kernelExecute(notebookId, {- code: executionCode,- return_variables: true,- })) as PythonKernelExecuteResponse- executionResult = buildPythonExecutionResult(kernelResponse, exportedGlobals)- const runtimeSandboxId = kernelResponse.kernel_runtime?.sandbox_id ?? executionSandboxId- updateAttributes({- duckExecution: executionResult,- duckExecutionCodeHash: codeHash,- duckExecutionSandboxId: runtimeSandboxId,- })-- if (!executionResult && kernelResponse) {- executionResult = buildPythonExecutionResult(kernelResponse, exportedGlobals)- }-- if (!executionResult) {- throw new Error('DuckDB execution did not return a result.')- }-- return { executed: true, execution: executionResult }- } catch (error) {- const message = error instanceof Error ? error.message : 'Failed to run SQL (DuckDB) query.'- const executionResult = buildPythonExecutionError(message, [- { name: resolvedReturnVariable, type: 'DataFrame' },- ])- updateAttributes({- duckExecution: executionResult,- duckExecutionCodeHash: hashCodeForString(`${code}\n${resolvedReturnVariable}`),- duckExecutionSandboxId: executionSandboxId,- })- return { executed: false, execution: executionResult }- } finally {- setDuckSqlRunLoading(false)- }-}--const runHogqlSqlCell = async ({- notebookId,- code,- placeholders,- returnVariable,- pageSize,- updateAttributes,- setHogqlSqlRunLoading,- executionSandboxId,-}: RunHogqlSqlCellParams): Promise<{ executed: boolean; execution: PythonExecutionResult | null }> => {- setHogqlSqlRunLoading(true)- const resolvedReturnVariable = resolveHogqlReturnVariable(returnVariable)- const placeholderNames = placeholders.filter((placeholder) => placeholder.trim().length > 0)- const shouldExecuteInKernel = placeholderNames.length > 0- const executionCode = shouldExecuteInKernel- ? buildHogqlSqlExecutionCode(code, returnVariable, pageSize, placeholderNames)- : buildHogqlSqlAssignmentCode(code, returnVariable)- let runtimeSandboxId = executionSandboxId- try {- let executionResult: PythonExecutionResult | null = null- let kernelResponse: PythonKernelExecuteResponse | null = null- const codeHash = hashCodeForString(`${code}\n${resolvedReturnVariable}`)- const exportedGlobals = [{ name: resolvedReturnVariable, type: 'DataFrame' }]-- updateAttributes({- hogqlExecution: buildPythonExecutionRunning(exportedGlobals),- hogqlExecutionCodeHash: codeHash,- hogqlExecutionSandboxId: executionSandboxId,- })-- kernelResponse = (await api.notebooks.kernelExecute(notebookId, {- code: executionCode,- return_variables: shouldExecuteInKernel,- })) as PythonKernelExecuteResponse- runtimeSandboxId = kernelResponse.kernel_runtime?.sandbox_id ?? executionSandboxId-- if (kernelResponse.status === 'error') {- executionResult = buildPythonExecutionResult(kernelResponse, exportedGlobals)- updateAttributes({- hogqlExecution: executionResult,- hogqlExecutionCodeHash: codeHash,- hogqlExecutionSandboxId: runtimeSandboxId,- })- return { executed: true, execution: executionResult }- }-- if (shouldExecuteInKernel) {- executionResult = buildPythonExecutionResult(kernelResponse, exportedGlobals)- updateAttributes({- hogqlExecution: executionResult,- hogqlExecutionCodeHash: codeHash,- hogqlExecutionSandboxId: runtimeSandboxId,- })- return { executed: true, execution: executionResult }- }-- const queryResponse = await api.notebooks.hogqlExecute(notebookId, {- query: code,- })- executionResult = buildHogqlExecutionResult({- response: queryResponse,- exportedGlobals,- returnVariable: resolvedReturnVariable,- query: code,- pageSize,- })- updateAttributes({- hogqlExecution: executionResult,- hogqlExecutionCodeHash: codeHash,- hogqlExecutionSandboxId: runtimeSandboxId,- })-- if (executionResult.status === 'error') {- return { executed: true, execution: executionResult }- }-- return { executed: true, execution: executionResult }- } catch (error) {- const message = error instanceof Error ? error.message : 'Failed to run SQL (HogQL) query.'- const executionResult = buildPythonExecutionError(message, [- { name: resolvedReturnVariable, type: 'DataFrame' },- ])- updateAttributes({- hogqlExecution: executionResult,- hogqlExecutionCodeHash: hashCodeForString(`${code}\n${resolvedReturnVariable}`),- hogqlExecutionSandboxId: runtimeSandboxId,- })- return { executed: false, execution: executionResult }- } finally {- setHogqlSqlRunLoading(false)- }-}--const findDataframeVariable = (variables?: PythonExecutionVariable[]): string | null => {- if (!variables) {- return null- }- const match = variables.find((variable) => variable.type?.toLowerCase() === 'dataframe')- return match?.name ?? null-}--const parseDataframePreview = (preview?: string | null): NotebookDataframeResult | null => {- if (!preview) {- return null- }- const trimmed = preview.trim()- if (!trimmed) {- return null- }- const candidates = [trimmed]- if (trimmed.startsWith('"') && trimmed.endsWith('"')) {- try {- candidates.push(JSON.parse(trimmed))- } catch {- // oh well, not for us- }- } else if (trimmed.startsWith("'") && trimmed.endsWith("'")) {- // we can't JSON.escape single quoted strings, so we'll have to do this manually- const stripped = trimmed.slice(1, -1)- const unescaped = stripped.replace(/\\'/g, "'").replace(/\\\\/g, '\\')- candidates.push(unescaped)- }-- for (const candidate of candidates) {- try {- const parsed = JSON.parse(candidate) as {- columns?: string[]- rows?: Record<string, any>[]- rowCount?: number- row_count?: number- }- if (!parsed || typeof parsed !== 'object') {- continue- }- const columns = Array.isArray(parsed.columns) ? parsed.columns : []- const rows = Array.isArray(parsed.rows) ? parsed.rows : []- const rowCount = parsed.rowCount || parsed.row_count || rows.length- return {- columns,- rows,- rowCount,- }- } catch {}- }- return null-}-export type NotebookNodeLogicProps = {nodeType: NotebookNodeTypenotebookLogic: BuiltLogic<notebookLogicType>@@ -880,47 +79,15 @@ export type NotebookNodeLogicProps = {export interface notebookNodeLogicValues {comments: CommentType[] | null // props.notebookLogicdependencyGraph: NotebookDependencyGraph // props.notebookLogic- duckSqlNodeSummaries: DuckSqlNodeSummary[] // props.notebookLogic- hogqlSqlNodeSummaries: HogqlSqlNodeSummary[] // props.notebookLogicisEditable: boolean // props.notebookLogic- kernelInfo: NotebookKernelInfo | null // props.notebookLogicnotebook: NotebookType | null // props.notebookLogic- pythonNodeSummaries: PythonNodeSummary[] // props.notebookLogicsqlV2NodeSummaries: SqlV2NodeSummary[] // props.notebookLogicSettings: NotebookNodeSettings | nullactions: NotebookNodeAction[]children: NotebookNodeResource[]customMenuItems: LemonMenuItems | null- dataframeError: string | null- dataframeLoading: boolean- dataframePage: number- dataframePageSize: number- dataframeResult: NotebookDataframeResult | null- dataframeRowCount: number- dataframeVariableName: string | null- displayedGlobals: {- hogqlQuery?: string- name: string- type: string- }[]- duckSqlNodeIndex: number- duckSqlReturnVariable: string- duckSqlReturnVariableUsage: NotebookDependencyUsage[]- duckSqlRunLoading: boolean- duckSqlRunQueued: boolean- duckSqlTablesUsed: string[]- duckSqlUpstreamTableSources: Record<string, NotebookDependencyUsage>editableTitle: booleanexpanded: boolean- exportedGlobals: {- name: string- type: string- }[]- hogqlReturnVariableUsage: NotebookDependencyUsage[]- hogqlSqlNodeIndex: number- hogqlSqlReturnVariable: string- hogqlSqlRunLoading: boolean- hogqlSqlRunQueued: booleanisEditingTitle: booleanmessageListeners: NotebookNodeMessagesListenersnextNode: RichContentNode | null@@ -929,10 +96,6 @@ export interface notebookNodeLogicValues {nodeType: NotebookNodeTypenotebookLogic: BuiltLogic<notebookLogicType>previousNode: RichContentNode | null- pythonExecution: PythonExecutionResult | null- pythonNodeIndex: number- pythonRunLoading: boolean- pythonRunQueued: booleanref: HTMLElement | nullresizeable: booleansendMessage: <T extends keyof NotebookNodeMessages>(message: T, payload: NotebookNodeMessages[T]) => boolean@@ -944,7 +107,6 @@ export interface notebookNodeLogicValues {title: anytitlePlaceholder: stringtitleStatus: NotebookComponentToolbarTitleStatus | null- usageByVariable: Record<string, NotebookDependencyUsage[]>}// Generated by kea-typegen. Update if you're an agent, ignore if you're human.@@ -961,77 +123,18 @@ export interface notebookNodeLogicActions {insertAfter: (content: JSONContent) => {content: JSONContent}- loadDataframePage: (payload: { pageSize?: number; variableName: string }) => {- pageSize?: number | undefined- variableName: string- }navigateToNode: (nodeId: string) => {nodeId: string}- resetDataframeResults: () => {- value: true- }- runDuckSqlNode: () => {- value: true- }- runDuckSqlNodeWithMode: (payload: { mode: DuckSqlRunMode }) => {- mode: DuckSqlRunMode- }- runHogqlSqlNode: () => {- value: true- }- runHogqlSqlNodeWithMode: (payload: { mode: HogqlSqlRunMode }) => {- mode: HogqlSqlRunMode- }- runPythonNode: (payload: { code: string }) => {- code: string- }- runPythonNodeWithMode: (payload: { mode: PythonRunMode }) => {- mode: PythonRunMode- }selectNode: (scroll?: boolean) => {scroll: boolean | undefined}setActions: (actions: (NotebookNodeAction | undefined)[]) => {actions: (NotebookNodeAction | undefined)[]}- setDataframeError: (error: string | null) => {- error: string | null- }- setDataframeLoading: (loading: boolean) => {- loading: boolean- }- setDataframePage: (page: number) => {- page: number- }- setDataframePageSize: (pageSize: number) => {- pageSize: number- }- setDataframeResult: (result: NotebookDataframeResult | null) => {- result: NotebookDataframeResult | null- }- setDataframeVariableName: (- variableName: string | null,- initialResult?: NotebookDataframeResult | null- ) => {- initialResult: NotebookDataframeResult | null | undefined- variableName: string | null- }- setDuckSqlRunLoading: (loading: boolean) => {- loading: boolean- }- setDuckSqlRunQueued: (queued: boolean) => {- queued: boolean- }setExpanded: (expanded: boolean) => {expanded: boolean}- setHogqlSqlRunLoading: (loading: boolean) => {- loading: boolean- }- setHogqlSqlRunQueued: (queued: boolean) => {- queued: boolean- }setMenuItems: (menuItems: LemonMenuItems | null) => {menuItems: LemonMenuItems | null}@@ -1044,12 +147,6 @@ export interface notebookNodeLogicActions {setPreviousNode: (node: RichContentNode | null) => {node: RichContentNode | null}- setPythonRunLoading: (loading: boolean) => {- loading: boolean- }- setPythonRunQueued: (queued: boolean) => {- queued: boolean- }setRef: (ref: HTMLElement | null) => {ref: HTMLElement | null}@@ -1089,65 +186,12 @@ export interface notebookNodeLogicMeta {editableTitle: (arg: any) => booleantitle: (titlePlaceholder: string, nodeAttributes: any, editableTitle: boolean) => anychildren: (nodeAttributes: any) => NotebookNodeResource[]- exportedGlobals: (nodeAttributes: any) => {- name: string- type: string- }[]- pythonExecution: (nodeAttributes: any) => PythonExecutionResult | null- displayedGlobals: (- exportedGlobals: {- name: string- type: string- }[],- pythonExecution: PythonExecutionResult | null- ) => {- hogqlQuery?: string- name: string- type: string- }[]- pythonNodeIndex: (pythonNodeSummaries: PythonNodeSummary[], nodeId: string) => number- duckSqlNodeIndex: (duckSqlNodeSummaries: DuckSqlNodeSummary[], nodeId: string) => number- duckSqlReturnVariable: (- duckSqlNodeSummaries: DuckSqlNodeSummary[],- nodeId: string,- nodeAttributes: any- ) => string- hogqlSqlNodeIndex: (hogqlSqlNodeSummaries: HogqlSqlNodeSummary[], nodeId: string) => number- hogqlSqlReturnVariable: (- hogqlSqlNodeSummaries: HogqlSqlNodeSummary[],- nodeId: string,- nodeAttributes: any- ) => string- dataframeRowCount: (dataframeResult: NotebookDataframeResult | null) => number- duckSqlTablesUsed: (dependencyGraph: NotebookDependencyGraph, nodeId: string) => string[]- duckSqlUpstreamTableSources: (- dependencyGraph: NotebookDependencyGraph,- nodeId: string- ) => Record<string, NotebookDependencyUsage>- duckSqlReturnVariableUsage: (- dependencyGraph: NotebookDependencyGraph,- nodeId: string,- duckSqlReturnVariable: string- ) => NotebookDependencyUsage[]- hogqlReturnVariableUsage: (- dependencyGraph: NotebookDependencyGraph,- nodeId: string,- hogqlSqlReturnVariable: string- ) => NotebookDependencyUsage[]sqlV2ReturnVariable: (sqlV2NodeSummaries: SqlV2NodeSummary[], nodeId: string, nodeAttributes: any) => stringsqlV2ReturnVariableUsage: (dependencyGraph: NotebookDependencyGraph,nodeId: string,sqlV2ReturnVariable: string) => NotebookDependencyUsage[]- usageByVariable: (- dependencyGraph: NotebookDependencyGraph,- exportedGlobals: {- name: string- type: string- }[],- nodeId: string- ) => Record<string, NotebookDependencyUsage[]>sendMessage: (messageListeners: NotebookNodeMessagesListeners) => <T extends keyof NotebookNodeMessages>(message: T, payload: NotebookNodeMessages[T]) => boolean@@ -1187,46 +231,10 @@ export const notebookNodeLogic = kea<notebookNodeLogicType>([toggleEditingTitle: (editing?: boolean) => ({ editing }),copyToClipboard: true,navigateToNode: (nodeId: string) => ({ nodeId }),- runPythonNode: (payload: { code: string }) => payload,- runPythonNodeWithMode: (payload: { mode: PythonRunMode }) => payload,- setPythonRunLoading: (loading: boolean) => ({ loading }),- setPythonRunQueued: (queued: boolean) => ({ queued }),- runDuckSqlNode: true,- runDuckSqlNodeWithMode: (payload: { mode: DuckSqlRunMode }) => payload,- setDuckSqlRunLoading: (loading: boolean) => ({ loading }),- setDuckSqlRunQueued: (queued: boolean) => ({ queued }),- runHogqlSqlNode: true,- runHogqlSqlNodeWithMode: (payload: { mode: HogqlSqlRunMode }) => payload,- setHogqlSqlRunLoading: (loading: boolean) => ({ loading }),- setHogqlSqlRunQueued: (queued: boolean) => ({ queued }),- setDataframeVariableName: (variableName: string | null, initialResult?: NotebookDataframeResult | null) => ({- variableName,- initialResult,- }),- setDataframePage: (page: number) => ({ page }),- setDataframePageSize: (pageSize: number) => ({ pageSize }),- loadDataframePage: (payload: { variableName: string; pageSize?: number }) => payload,- setDataframeResult: (result: NotebookDataframeResult | null) => ({ result }),- setDataframeLoading: (loading: boolean) => ({ loading }),- setDataframeError: (error: string | null) => ({ error }),- resetDataframeResults: true,}),connect((props: NotebookNodeLogicProps) => ({- values: [- props.notebookLogic,- [- 'isEditable',- 'comments',- 'pythonNodeSummaries',- 'duckSqlNodeSummaries',- 'hogqlSqlNodeSummaries',- 'sqlV2NodeSummaries',- 'dependencyGraph',- 'notebook',- 'kernelInfo',- ],- ],+ values: [props.notebookLogic, ['isEditable', 'comments', 'sqlV2NodeSummaries', 'dependencyGraph', 'notebook']],})),reducers(({ props }) => ({@@ -1302,83 +310,6 @@ export const notebookNodeLogic = kea<notebookNodeLogicType>([toggleEditingTitle: (state, { editing }) => (typeof editing === 'boolean' ? editing : !state),},],- pythonRunLoading: [- false,- {- setPythonRunLoading: (_, { loading }) => loading,- },- ],- pythonRunQueued: [- false,- {- setPythonRunQueued: (_, { queued }) => queued,- },- ],- duckSqlRunLoading: [- false,- {- setDuckSqlRunLoading: (_, { loading }) => loading,- },- ],- duckSqlRunQueued: [- false,- {- setDuckSqlRunQueued: (_, { queued }) => queued,- },- ],- hogqlSqlRunLoading: [- false,- {- setHogqlSqlRunLoading: (_, { loading }) => loading,- },- ],- hogqlSqlRunQueued: [- false,- {- setHogqlSqlRunQueued: (_, { queued }) => queued,- },- ],- dataframeVariableName: [- null as string | null,- {- setDataframeVariableName: (_, { variableName }) => variableName,- },- ],- dataframePage: [- 1,- {- setDataframePage: (_, { page }) => page,- setDataframePageSize: () => 1,- resetDataframeResults: () => 1,- },- ],- dataframePageSize: [- DEFAULT_DATAFRAME_PAGE_SIZE as number,- {- setDataframePageSize: (_, { pageSize }) => pageSize,- },- ],- dataframeResult: [- null as NotebookDataframeResult | null,- {- setDataframeResult: (_, { result }) => result,- resetDataframeResults: () => null,- },- ],- dataframeLoading: [- false,- {- setDataframeLoading: (_, { loading }) => loading,- resetDataframeResults: () => false,- },- ],- dataframeError: [- null as string | null,- {- setDataframeError: (_, { error }) => error,- resetDataframeResults: () => null,- },- ],})),selectors({@@ -1414,98 +345,6 @@ export const notebookNodeLogic = kea<notebookNodeLogicType>([Array.isArray(nodeAttributes.children) ? nodeAttributes.children : [],],- exportedGlobals: [- (s) => [s.nodeAttributes],- (nodeAttributes): { name: string; type: string }[] => nodeAttributes.globalsExportedWithTypes ?? [],- ],- pythonExecution: [- (s) => [s.nodeAttributes],- (nodeAttributes): PythonExecutionResult | null => nodeAttributes.pythonExecution ?? null,- ],- displayedGlobals: [- (s) => [s.exportedGlobals, s.pythonExecution],- (- exportedGlobals: {- name: string- type: string- }[],- pythonExecution: PythonExecutionResult | null- ): { name: string; type: string; hogqlQuery?: string }[] => {- if (!pythonExecution?.variables?.length) {- return exportedGlobals- }-- const detailsByName = new Map<string, { type: string; hogqlQuery?: string }>(- pythonExecution.variables.map((variable: PythonExecutionVariable) => [- variable.name,- { type: variable.type, hogqlQuery: variable.hogqlQuery },- ])- )- return exportedGlobals.map(({ name, type }) => ({- name,- type: detailsByName.get(name)?.type ?? type,- hogqlQuery: detailsByName.get(name)?.hogqlQuery,- }))- },- ],-- pythonNodeIndex: [- (s) => [s.pythonNodeSummaries, s.nodeId],- (pythonNodeSummaries: PythonNodeSummary[], nodeId: string) =>- pythonNodeSummaries.findIndex((node) => node.nodeId === nodeId),- ],- duckSqlNodeIndex: [- (s) => [s.duckSqlNodeSummaries, s.nodeId],- (duckSqlNodeSummaries: DuckSqlNodeSummary[], nodeId: string) =>- duckSqlNodeSummaries.findIndex((node) => node.nodeId === nodeId),- ],- duckSqlReturnVariable: [- (s) => [s.duckSqlNodeSummaries, s.nodeId, s.nodeAttributes],- (duckSqlNodeSummaries: DuckSqlNodeSummary[], nodeId: string, nodeAttributes): string =>- getUniqueDuckSqlReturnVariable(duckSqlNodeSummaries, nodeId, nodeAttributes.returnVariable ?? ''),- ],- hogqlSqlNodeIndex: [- (s) => [s.hogqlSqlNodeSummaries, s.nodeId],- (hogqlSqlNodeSummaries: HogqlSqlNodeSummary[], nodeId: string) =>- hogqlSqlNodeSummaries.findIndex((node) => node.nodeId === nodeId),- ],- hogqlSqlReturnVariable: [- (s) => [s.hogqlSqlNodeSummaries, s.nodeId, s.nodeAttributes],- (hogqlSqlNodeSummaries: HogqlSqlNodeSummary[], nodeId: string, nodeAttributes): string =>- getUniqueHogqlReturnVariable(hogqlSqlNodeSummaries, nodeId, nodeAttributes.returnVariable ?? ''),- ],- dataframeRowCount: [- (s) => [s.dataframeResult],- (dataframeResult: NotebookDataframeResult | null): number => dataframeResult?.rowCount ?? 0,- ],- duckSqlTablesUsed: [- (s) => [s.dependencyGraph, s.nodeId],- (dependencyGraph: NotebookDependencyGraph, nodeId: string): string[] =>- dependencyGraph.nodesById[nodeId]?.uses ?? [],- ],- duckSqlUpstreamTableSources: [- (s) => [s.dependencyGraph, s.nodeId],- (dependencyGraph: NotebookDependencyGraph, nodeId: string): Record<string, NotebookDependencyUsage> =>- dependencyGraph.upstreamSourcesByNode[nodeId] ?? {},- ],- duckSqlReturnVariableUsage: [- (s) => [s.dependencyGraph, s.nodeId, s.duckSqlReturnVariable],- (- dependencyGraph: NotebookDependencyGraph,- nodeId: string,- duckSqlReturnVariable: string- ): NotebookDependencyUsage[] =>- dependencyGraph.downstreamUsageByNode[nodeId]?.[duckSqlReturnVariable] ?? [],- ],- hogqlReturnVariableUsage: [- (s) => [s.dependencyGraph, s.nodeId, s.hogqlSqlReturnVariable],- (- dependencyGraph: NotebookDependencyGraph,- nodeId: string,- hogqlSqlReturnVariable: string- ): NotebookDependencyUsage[] =>- dependencyGraph.downstreamUsageByNode[nodeId]?.[hogqlSqlReturnVariable] ?? [],- ],sqlV2ReturnVariable: [(s) => [s.sqlV2NodeSummaries, s.nodeId, s.nodeAttributes],(sqlV2NodeSummaries: SqlV2NodeSummary[], nodeId: string, nodeAttributes): string =>@@ -1520,27 +359,6 @@ export const notebookNodeLogic = kea<notebookNodeLogicType>([): NotebookDependencyUsage[] => dependencyGraph.downstreamUsageByNode[nodeId]?.[sqlV2ReturnVariable] ?? [],],- usageByVariable: [- (s) => [s.dependencyGraph, s.exportedGlobals, s.nodeId],- (- dependencyGraph: NotebookDependencyGraph,- exportedGlobals: {- name: string- type: string- }[],- nodeId: string- ): Record<string, NotebookDependencyUsage[]> => {- const usageMap: Record<string, NotebookDependencyUsage[]> = {}-- exportedGlobals.forEach(({ name }) => {- const usages = dependencyGraph.downstreamUsageByNode[nodeId]?.[name] ?? []- usageMap[name] = usages.filter((usage) => usage.nodeType === NotebookNodeType.Python)- })-- return usageMap- },- ],-sendMessage: [(s) => [s.messageListeners],(messageListeners: NotebookNodeMessagesListeners) => {@@ -1613,17 +431,13 @@ export const notebookNodeLogic = kea<notebookNodeLogicType>([const shouldShowThis = typeof visible === 'boolean' ? visible : !isEditingprops.notebookLogic.actions.setEditingNodeEditing(values.nodeId, shouldShowThis)- if (- props.nodeType === NotebookNodeType.Python ||- (props.nodeType === NotebookNodeType.Query && isSqlQueryNode(values.nodeAttributes)) ||- props.nodeType === NotebookNodeType.DuckSQL ||- props.nodeType === NotebookNodeType.HogQLSQL- ) {+ if (props.nodeType === NotebookNodeType.Query && isSqlQueryNode(values.nodeAttributes)) {actions.updateAttributes({ showSettings: shouldShowThis })}},initializeNode: () => {const { __init } = values.nodeAttributes+ const isSqlQuery = props.nodeType === NotebookNodeType.Query && isSqlQueryNode(values.nodeAttributes)if (__init) {if (__init.expanded) {@@ -1632,78 +446,17 @@ export const notebookNodeLogic = kea<notebookNodeLogicType>([if (__init.showSettings) {actions.toggleEditing(true)}- if (- (props.nodeType === NotebookNodeType.Python ||- (props.nodeType === NotebookNodeType.Query && isSqlQueryNode(values.nodeAttributes)) ||- props.nodeType === NotebookNodeType.DuckSQL ||- props.nodeType === NotebookNodeType.HogQLSQL) &&- __init.showSettings- ) {+ if (isSqlQuery && __init.showSettings) {actions.updateAttributes({ showSettings: true })}props.updateAttributes({ __init: null })}- if (- props.nodeType === NotebookNodeType.Python ||- (props.nodeType === NotebookNodeType.Query && isSqlQueryNode(values.nodeAttributes)) ||- props.nodeType === NotebookNodeType.DuckSQL ||- props.nodeType === NotebookNodeType.HogQLSQL- ) {+ if (isSqlQuery) {const shouldShowSettings = __init?.showSettings ?? values.nodeAttributes.showSettingsif (typeof shouldShowSettings === 'boolean') {props.notebookLogic.actions.setEditingNodeEditing(values.nodeId, shouldShowSettings)}}- if (props.nodeType === NotebookNodeType.DuckSQL) {- const currentReturnVariable =- typeof values.nodeAttributes.returnVariable === 'string'- ? values.nodeAttributes.returnVariable- : 'duck_df'- const uniqueReturnVariable = getUniqueDuckSqlReturnVariable(- values.duckSqlNodeSummaries,- values.nodeId,- currentReturnVariable- )- if (uniqueReturnVariable !== resolveDuckSqlReturnVariable(currentReturnVariable)) {- actions.updateAttributes({ returnVariable: uniqueReturnVariable })- }- const cachedExecution = values.nodeAttributes.duckExecution- if (- !values.dataframeVariableName &&- cachedExecution?.status === 'ok' &&- typeof cachedExecution.result === 'string'- ) {- const previewResult = parseDataframePreview(cachedExecution.result)- if (previewResult) {- actions.setDataframeVariableName(values.duckSqlReturnVariable, previewResult)- }- }- }- if (props.nodeType === NotebookNodeType.HogQLSQL) {- const currentReturnVariable =- typeof values.nodeAttributes.returnVariable === 'string'- ? values.nodeAttributes.returnVariable- : 'hogql_df'- const uniqueReturnVariable = getUniqueHogqlReturnVariable(- values.hogqlSqlNodeSummaries,- values.nodeId,- currentReturnVariable- )- if (uniqueReturnVariable !== resolveHogqlReturnVariable(currentReturnVariable)) {- actions.updateAttributes({ returnVariable: uniqueReturnVariable })- }- const cachedExecution = values.nodeAttributes.hogqlExecution- if (- !values.dataframeVariableName &&- cachedExecution?.status === 'ok' &&- typeof cachedExecution.result === 'string'- ) {- const previewResult = parseDataframePreview(cachedExecution.result)- if (previewResult) {- actions.setDataframeVariableName(values.hogqlSqlReturnVariable, previewResult)- }- }- }},copyToClipboard: async () => {@@ -1712,330 +465,6 @@ export const notebookNodeLogic = kea<notebookNodeLogicType>([const blob = new Blob([html], { type })await window.navigator.clipboard.write([new ClipboardItem({ [type]: blob })])},- runPythonNode: async ({ code }) => {- if (props.nodeType !== NotebookNodeType.Python) {- return- }- const notebook = values.notebook- if (!notebook) {- return- }- const executionSandboxId =- values.kernelInfo?.sandbox_id ??- (values.nodeAttributes as { pythonExecutionSandboxId?: string | null }).pythonExecutionSandboxId ??- null- const { executed, execution } = await runPythonCell({- notebookId: notebook.short_id,- code,- exportedGlobals: values.exportedGlobals,- updateAttributes: actions.updateAttributes,- setPythonRunLoading: actions.setPythonRunLoading,- executionSandboxId,- })- if (!executed) {- actions.setDataframeVariableName(null)- return- }- const dataframeVariable = findDataframeVariable(execution?.variables)- actions.setDataframeVariableName(dataframeVariable)- },-- runDuckSqlNode: async () => {- if (props.nodeType !== NotebookNodeType.DuckSQL) {- return- }- const notebook = values.notebook- if (!notebook) {- return- }- const { code: attributesCode = '', returnVariable = 'duck_df' } = values.nodeAttributes as {- code?: string- returnVariable?: string- duckExecutionSandboxId?: string | null- }- const mountedEditorCode = getMountedNotebookSqlEditorCode(values.nodeId, 'duck')- const code = mountedEditorCode ?? attributesCode- if (mountedEditorCode !== null && mountedEditorCode !== attributesCode) {- actions.updateAttributes({ code: mountedEditorCode })- }- const executionSandboxId =- values.kernelInfo?.sandbox_id ?? values.nodeAttributes.duckExecutionSandboxId ?? null- const resolvedReturnVariable = getUniqueDuckSqlReturnVariable(- values.duckSqlNodeSummaries,- values.nodeId,- returnVariable- )- const { executed, execution } = await runDuckSqlCell({- notebookId: notebook.short_id,- code,- returnVariable: resolvedReturnVariable,- pageSize: values.dataframePageSize,- updateAttributes: actions.updateAttributes,- setDuckSqlRunLoading: actions.setDuckSqlRunLoading,- executionSandboxId,- })- if (!executed || execution?.status !== 'ok') {- actions.setDataframeVariableName(null)- return- }- const previewResult = parseDataframePreview(execution?.result)- actions.setDataframeVariableName(values.duckSqlReturnVariable, previewResult)- },- runDuckSqlNodeWithMode: async ({ mode }) => {- if (props.nodeType !== NotebookNodeType.DuckSQL) {- return- }- const notebook = values.notebook- if (!notebook) {- return- }-- if (mode === 'cell') {- await actions.runDuckSqlNode()- return- }-- const direction: DependencyRunDirection = mode === 'cell_downstream' ? 'downstream' : 'upstream'- const nodesToRunWithLogic = getDependencyEntriesWithLogic({- dependencyGraph: values.dependencyGraph,- nodeId: values.nodeId,- direction,- notebookLogic: values.notebookLogic,- })- if (nodesToRunWithLogic.length === 0) {- await actions.runDuckSqlNode()- return- }-- await runDependencyNodes({- entries: nodesToRunWithLogic,- notebookId: notebook.short_id,- mode,- duckSqlNodeSummaries: values.duckSqlNodeSummaries,- hogqlSqlNodeSummaries: values.hogqlSqlNodeSummaries,- currentNodeId: values.nodeId,- })- },-- runHogqlSqlNode: async () => {- if (props.nodeType !== NotebookNodeType.HogQLSQL) {- return- }- const notebook = values.notebook- if (!notebook) {- return- }- const { code: attributesCode = '', returnVariable = 'hogql_df' } = values.nodeAttributes as {- code?: string- returnVariable?: string- hogqlExecutionSandboxId?: string | null- }- const mountedEditorCode = getMountedNotebookSqlEditorCode(values.nodeId, 'hogql')- const code = mountedEditorCode ?? attributesCode- if (mountedEditorCode !== null && mountedEditorCode !== attributesCode) {- actions.updateAttributes({ code: mountedEditorCode })- }- const executionSandboxId =- values.kernelInfo?.sandbox_id ?? values.nodeAttributes.hogqlExecutionSandboxId ?? null- const resolvedReturnVariable = getUniqueHogqlReturnVariable(- values.hogqlSqlNodeSummaries,- values.nodeId,- returnVariable- )- const placeholders = extractHogqlPlaceholders(code)- const { executed, execution } = await runHogqlSqlCell({- notebookId: notebook.short_id,- code,- placeholders,- returnVariable: resolvedReturnVariable,- pageSize: values.dataframePageSize,- updateAttributes: actions.updateAttributes,- setHogqlSqlRunLoading: actions.setHogqlSqlRunLoading,- executionSandboxId,- })- if (!executed || execution?.status !== 'ok') {- actions.setDataframeVariableName(null)- return- }- const previewResult = parseDataframePreview(execution?.result)- actions.setDataframeVariableName(values.hogqlSqlReturnVariable, previewResult)- },- runHogqlSqlNodeWithMode: async ({ mode }) => {- if (props.nodeType !== NotebookNodeType.HogQLSQL) {- return- }- const notebook = values.notebook- if (!notebook) {- return- }-- if (mode === 'cell') {- await actions.runHogqlSqlNode()- return- }-- const direction: DependencyRunDirection = mode === 'cell_downstream' ? 'downstream' : 'upstream'- const nodesToRunWithLogic = getDependencyEntriesWithLogic({- dependencyGraph: values.dependencyGraph,- nodeId: values.nodeId,- direction,- notebookLogic: values.notebookLogic,- })- if (nodesToRunWithLogic.length === 0) {- await actions.runHogqlSqlNode()- return- }-- await runDependencyNodes({- entries: nodesToRunWithLogic,- notebookId: notebook.short_id,- mode,- duckSqlNodeSummaries: values.duckSqlNodeSummaries,- hogqlSqlNodeSummaries: values.hogqlSqlNodeSummaries,- currentNodeId: values.nodeId,- })- },-- runPythonNodeWithMode: async ({ mode }) => {- if (props.nodeType !== NotebookNodeType.Python) {- return- }- const notebook = values.notebook- if (!notebook) {- return- }-- if (mode === 'cell') {- await actions.runPythonNode({ code: (values.nodeAttributes as { code?: string }).code ?? '' })- return- }-- const direction: DependencyRunDirection = mode === 'cell_downstream' ? 'downstream' : 'upstream'- const nodesToRunWithLogic = getDependencyEntriesWithLogic({- dependencyGraph: values.dependencyGraph,- nodeId: values.nodeId,- direction,- notebookLogic: values.notebookLogic,- })- if (nodesToRunWithLogic.length === 0) {- await actions.runPythonNode({ code: (values.nodeAttributes as { code?: string }).code ?? '' })- return- }-- await runDependencyNodes({- entries: nodesToRunWithLogic,- notebookId: notebook.short_id,- mode,- duckSqlNodeSummaries: values.duckSqlNodeSummaries,- hogqlSqlNodeSummaries: values.hogqlSqlNodeSummaries,- currentNodeId: values.nodeId,- })- },- setDataframeVariableName: ({ variableName, initialResult }) => {- actions.resetDataframeResults()- if (variableName) {- if (initialResult) {- actions.setDataframeResult(initialResult)- } else {- actions.loadDataframePage({ variableName })- }- }- },- setDataframePage: () => {- if (!values.dataframeVariableName) {- return- }- actions.loadDataframePage({ variableName: values.dataframeVariableName })- },- setDataframePageSize: ({ pageSize }) => {- if (!values.dataframeVariableName) {- return- }- actions.loadDataframePage({ variableName: values.dataframeVariableName, pageSize })- },- loadDataframePage: async ({ variableName, pageSize }) => {- const notebook = values.notebook- if (!notebook) {- return- }- const nodeLogic = values.notebookLogic.values.findNodeLogicById(values.nodeId)- if (- props.nodeType === NotebookNodeType.DuckSQL &&- nodeLogic &&- !isDuckSqlExecutionFresh(- nodeLogic,- getMountedNotebookSqlEditorCode(values.nodeId, 'duck') ??- (values.nodeAttributes as { code?: string }).code ??- '',- values.duckSqlReturnVariable- )- ) {- const nodesToRunWithLogic = getDependencyEntriesWithLogic({- dependencyGraph: values.dependencyGraph,- nodeId: values.nodeId,- direction: 'upstream',- notebookLogic: values.notebookLogic,- })- if (nodesToRunWithLogic.length > 0) {- await runDependencyNodes({- entries: nodesToRunWithLogic,- notebookId: notebook.short_id,- mode: 'cell_upstream',- duckSqlNodeSummaries: values.duckSqlNodeSummaries,- hogqlSqlNodeSummaries: values.hogqlSqlNodeSummaries,- currentNodeId: values.nodeId,- skipDataframeVariableUpdateForNodeId: values.nodeId,- })- }- }- if (- props.nodeType === NotebookNodeType.HogQLSQL &&- nodeLogic &&- !isHogqlSqlExecutionFresh(- nodeLogic,- getMountedNotebookSqlEditorCode(values.nodeId, 'hogql') ??- (values.nodeAttributes as { code?: string }).code ??- '',- values.hogqlSqlReturnVariable- )- ) {- const nodesToRunWithLogic = getDependencyEntriesWithLogic({- dependencyGraph: values.dependencyGraph,- nodeId: values.nodeId,- direction: 'upstream',- notebookLogic: values.notebookLogic,- })- if (nodesToRunWithLogic.length > 0) {- await runDependencyNodes({- entries: nodesToRunWithLogic,- notebookId: notebook.short_id,- mode: 'cell_upstream',- duckSqlNodeSummaries: values.duckSqlNodeSummaries,- hogqlSqlNodeSummaries: values.hogqlSqlNodeSummaries,- currentNodeId: values.nodeId,- skipDataframeVariableUpdateForNodeId: values.nodeId,- })- }- }- actions.setDataframeLoading(true)- actions.setDataframeError(null)- const resolvedPageSize = pageSize ?? values.dataframePageSize- const offset = (values.dataframePage - 1) * resolvedPageSize- try {- const response = await api.notebooks.kernelDataframe(notebook.short_id, {- variable_name: variableName,- offset,- limit: resolvedPageSize,- })- actions.setDataframeResult(response)- } catch (error) {- const message = error instanceof Error ? error.message : 'Failed to load dataframe results.'- actions.setDataframeError(message)- actions.setDataframeResult(null)- } finally {- actions.setDataframeLoading(false)- }- },})),afterMount((logic) => {diff --git a/frontend/src/scenes/notebooks/Nodes/pythonExecution.ts b/frontend/src/scenes/notebooks/Nodes/pythonExecution.tsindex 0ee93f19062a..ad9ec73e7070 100644--- a/frontend/src/scenes/notebooks/Nodes/pythonExecution.ts+++ b/frontend/src/scenes/notebooks/Nodes/pythonExecution.ts@@ -1,34 +1,3 @@-export type PythonExecutionVariableStatus = 'ok' | 'error' | 'missing'--export type PythonExecutionVariable = {- name: string- type: string- status: PythonExecutionVariableStatus- value?: string- error?: string- traceback?: string[]- hogqlQuery?: string-}--export type PythonExecutionMedia = {- mimeType: string- data: string-}--export type PythonExecutionResult = {- status: string- stdout: string- stderr: string- result?: string- executionCount?: number | null- errorName?: string | null- traceback?: string[]- variables?: PythonExecutionVariable[]- media?: PythonExecutionMedia[]- startedAt?: string- completedAt?: string-}-export type NotebookDataframeResult = {columns: string[]rows: Record<string, any>[]@@ -65,118 +34,3 @@ export type PythonKernelExecuteResponse = {sandbox_id?: string | null}}--const extractTextValue = (data?: Record<string, any> | null): string | undefined => {- if (!data) {- return undefined- }-- const preferred = data['text/plain'] ?? data['text/html']- if (typeof preferred === 'string') {- return preferred- }-- const imageMimeTypes = ['image/png', 'image/jpeg', 'image/jpg', 'image/svg+xml', 'image/gif', 'image/webp']-- if (imageMimeTypes.some((mimeType) => data[mimeType])) {- return undefined- }-- try {- return JSON.stringify(data)- } catch {- return undefined- }-}--const formatExecutionError = (ename?: string | null, evalue?: string | null): string | undefined => {- if (!ename && !evalue) {- return undefined- }- if (!ename) {- return evalue ?? undefined- }- if (!evalue) {- return ename- }- return `${ename}: ${evalue}`-}--export const mergeExecutionVariables = (- exportedGlobals: { name: string; type: string }[],- variables?: Record<string, PythonKernelVariableResponse> | null-): PythonExecutionVariable[] => {- return exportedGlobals.map(({ name, type }) => {- const variable = variables?.[name]- const resolvedType = variable?.type ?? type- if (!variable) {- return {- name,- type: resolvedType,- status: 'missing',- }- }- if (variable.status === 'error') {- return {- name,- type: resolvedType,- status: 'error',- error: formatExecutionError(variable.ename, variable.evalue),- traceback: variable.traceback ?? [],- }- }- return {- name,- type: resolvedType,- status: 'ok',- value: extractTextValue(variable.data),- hogqlQuery: variable.hogql_query ?? undefined,- }- })-}--export const buildPythonExecutionResult = (- response: PythonKernelExecuteResponse,- exportedGlobals: { name: string; type: string }[]-): PythonExecutionResult => {- return {- status: response.status,- stdout: response.stdout ?? '',- stderr: response.stderr ?? '',- result: extractTextValue(response.result ?? undefined),- media: response.media?.map((item) => ({ mimeType: item.mime_type, data: item.data })) ?? [],- executionCount: response.execution_count ?? null,- errorName: response.error_name ?? null,- traceback: response.traceback ?? [],- variables: mergeExecutionVariables(exportedGlobals, response.variables ?? undefined),- startedAt: response.started_at,- completedAt: response.completed_at,- }-}--export const buildPythonExecutionError = (- message: string,- exportedGlobals: { name: string; type: string }[]-): PythonExecutionResult => {- return {- status: 'error',- stdout: '',- stderr: '',- errorName: 'RuntimeError',- traceback: [message],- variables: mergeExecutionVariables(exportedGlobals, {}),- }-}--export const buildPythonExecutionRunning = (- exportedGlobals: { name: string; type: string }[],- stdout = '',- stderr = ''-): PythonExecutionResult => {- return {- status: 'running',- stdout,- stderr,- variables: mergeExecutionVariables(exportedGlobals, {}),- }-}diff --git a/frontend/src/scenes/notebooks/Notebook/MarkdownNotebookV2RendererUI.test.tsx b/frontend/src/scenes/notebooks/Notebook/MarkdownNotebookV2RendererUI.test.tsxindex f643814cd9af..0d0ce75afe20 100644--- a/frontend/src/scenes/notebooks/Notebook/MarkdownNotebookV2RendererUI.test.tsx+++ b/frontend/src/scenes/notebooks/Notebook/MarkdownNotebookV2RendererUI.test.tsx@@ -54,8 +54,8 @@ describe('MarkdownNotebookV2Renderer UI', () => {beforeEach(async () => {localStorage.clear()initKeaTests()- featureFlagLogic.actions.setFeatureFlags([FEATURE_FLAGS.NOTEBOOK_PYTHON], {- [FEATURE_FLAGS.NOTEBOOK_PYTHON]: true,+ featureFlagLogic.actions.setFeatureFlags([FEATURE_FLAGS.REVAMPED_PY_NOTEBOOKS], {+ [FEATURE_FLAGS.REVAMPED_PY_NOTEBOOKS]: true,})jest.spyOn(api.notebooks, 'collabStream').mockResolvedValue(undefined as any)diff --git a/frontend/src/scenes/notebooks/Notebook/markdownNotebookInlineAI.test.ts b/frontend/src/scenes/notebooks/Notebook/markdownNotebookInlineAI.test.tsindex 2949acc90e4d..716db7c91142 100644--- a/frontend/src/scenes/notebooks/Notebook/markdownNotebookInlineAI.test.ts+++ b/frontend/src/scenes/notebooks/Notebook/markdownNotebookInlineAI.test.ts@@ -68,61 +68,49 @@ describe('markdown notebook inline AI completion', () => {expect(markdown).toContain(imageData)})- it('strips media even when a malformed prop makes the serializer prefer raw', () => {- const imageData = 'a'.repeat(120_000)- // A trailing unterminated quote makes the tag parse with an error, so it keeps `raw` and- // `errors` alongside a fully parsed `result.media`.- const markdown = `<PythonV2 code="print('chart')" result={{"columns":[],"stdout":"done","media":[{"mime_type":"image/png","data":"${imageData}"}]}} broken="unterminated />`-- // Guard the precondition: without errors + raw the serializer never hits the raw branch.- const parsed = parseMarkdownNotebook(markdown)- const componentNode = parsed.nodes.find((node) => node.type === 'component')- expect(componentNode?.type).toBe('component')- if (componentNode?.type === 'component') {- expect(componentNode.errors?.length).toBeGreaterThan(0)- expect(componentNode.raw).toContain(imageData)- expect((componentNode.props.result as { media?: unknown[] }).media?.length).toBeGreaterThan(0)+ // A trailing unterminated quote makes the tag parse with an error, so it keeps `raw` and+ // `errors` alongside a fully parsed execution prop. The content migration also skips a legacy+ // cell in that state, which is the only way a legacy tag still reaches the AI context.+ it.each([+ {+ cell: 'a PythonV2 cell',+ executionProp: 'result',+ buildMarkdown: (imageData: string) =>+ `<PythonV2 code="print('chart')" result={{"columns":[],"stdout":"done","media":[{"mime_type":"image/png","data":"${imageData}"}]}} broken="unterminated />`,+ },+ {+ cell: 'a legacy Python cell the migration could not convert',+ executionProp: 'pythonExecution',+ buildMarkdown: (imageData: string) =>+ `<Python code="print('chart')" pythonExecution={{"status":"ok","stdout":"done","media":[{"mimeType":"image/png","data":"${imageData}"}]}} broken="unterminated />`,+ },+ ])(+ 'strips media from $cell even when a malformed prop makes the serializer prefer raw',+ ({ executionProp, buildMarkdown }) => {+ const imageData = 'a'.repeat(120_000)+ const markdown = buildMarkdown(imageData)++ // Guard the precondition: without errors + raw the serializer never hits the raw branch.+ const parsed = parseMarkdownNotebook(markdown)+ const componentNode = parsed.nodes.find((node) => node.type === 'component')+ expect(componentNode?.type).toBe('component')+ if (componentNode?.type === 'component') {+ expect(componentNode.errors?.length).toBeGreaterThan(0)+ expect(componentNode.raw).toContain(imageData)+ expect((componentNode.props[executionProp] as { media?: unknown[] }).media?.length).toBeGreaterThan(0)+ }++ const uiContext = getInlineNotebookAIUIContext({+ notebookShortId: 'test-notebook',+ notebookTitle: 'Test notebook',+ markdown,+ conversationId: 'test-conversation',+ })+ const contextMarkdown = uiContext?.notebooks?.[0].markdown_with_insertion_placeholder ?? ''++ expect(contextMarkdown).not.toContain(imageData)+ expect(contextMarkdown).not.toContain('"media"')+ expect(contextMarkdown).toContain(`code="print('chart')"`)}-- const uiContext = getInlineNotebookAIUIContext({- notebookShortId: 'test-notebook',- notebookTitle: 'Test notebook',- markdown,- conversationId: 'test-conversation',- })- const contextMarkdown = uiContext?.notebooks?.[0].markdown_with_insertion_placeholder ?? ''-- expect(contextMarkdown).not.toContain(imageData)- expect(contextMarkdown).not.toContain('"media"')- expect(contextMarkdown).toContain(`code="print('chart')"`)- })-- it('strips media from legacy Python execution props', () => {- const imageData = 'a'.repeat(120_000)- // Legacy cells nest media inside pythonExecution/duckExecution/hogqlExecution, not a- // top-level result.- const markdown = `<Python pythonExecution={{"status":"ok","stdout":"done","result":"42","media":[{"mimeType":"image/png","data":"${imageData}"}]}} />`-- // Guard the precondition: the media really lives under the execution prop, not `result`.- const parsed = parseMarkdownNotebook(markdown)- const componentNode = parsed.nodes.find((node) => node.type === 'component')- expect(componentNode?.type).toBe('component')- if (componentNode?.type === 'component') {- expect((componentNode.props.pythonExecution as { media?: unknown[] }).media?.length).toBeGreaterThan(0)- }-- const uiContext = getInlineNotebookAIUIContext({- notebookShortId: 'test-notebook',- notebookTitle: 'Test notebook',- markdown,- conversationId: 'test-conversation',- })- const contextMarkdown = uiContext?.notebooks?.[0].markdown_with_insertion_placeholder ?? ''-- expect(contextMarkdown).not.toContain(imageData)- expect(contextMarkdown).not.toContain('"media"')- expect(contextMarkdown).toContain('"stdout":"done"')- expect(contextMarkdown).toContain('"result":"42"')- expect(markdown).toContain(imageData)- })+ )})diff --git a/frontend/src/scenes/notebooks/Notebook/markdownNotebookRegistry.test.tsx b/frontend/src/scenes/notebooks/Notebook/markdownNotebookRegistry.test.tsxindex 3b221098ed6a..8aefa3bcf3c9 100644--- a/frontend/src/scenes/notebooks/Notebook/markdownNotebookRegistry.test.tsx+++ b/frontend/src/scenes/notebooks/Notebook/markdownNotebookRegistry.test.tsx@@ -71,13 +71,15 @@ describe('markdownNotebookRegistry', () => {describe('getMarkdownRegistryForFeatureFlags', () => {it('offers a single SQL and Python cell, gated by the revamped notebooks flag', () => {// The unified insert surface: SQLV2 ("SQL") and PythonV2 ("Python") are the only- // insertable code cells with the flag on; the legacy SQL/Python cells and the- // legacy query node render but must never be insertable in markdown notebooks.+ // insertable code cells with the flag on. The legacy query node renders but must never+ // be insertable, and the removed legacy code cells are not registered at all: the+ // content migration rewrites them to SQLV2/PythonV2 before the registry sees them.const flagOn = getMarkdownRegistryForFeatureFlags({ [FEATURE_FLAGS.REVAMPED_PY_NOTEBOOKS]: true })expect(flagOn.components.SQLV2.insertCommand).toBeTruthy()expect(flagOn.components.PythonV2.insertCommand).toBeTruthy()- for (const legacyTag of ['Query', 'Python', 'DuckSQL', 'HogQLSQL']) {- expect(flagOn.components[legacyTag].insertCommand).toBeUndefined()+ expect(flagOn.components.Query.insertCommand).toBeUndefined()+ for (const legacyTag of ['Python', 'DuckSQL', 'HogQLSQL']) {+ expect(flagOn.components).not.toHaveProperty(legacyTag)}const flagOff = getMarkdownRegistryForFeatureFlags({})diff --git a/frontend/src/scenes/notebooks/Notebook/markdownNotebookRegistry.tsx b/frontend/src/scenes/notebooks/Notebook/markdownNotebookRegistry.tsxindex d9c526ca1caf..1c7d5ba10802 100644--- a/frontend/src/scenes/notebooks/Notebook/markdownNotebookRegistry.tsx+++ b/frontend/src/scenes/notebooks/Notebook/markdownNotebookRegistry.tsx@@ -2,7 +2,6 @@ import '../Nodes/NotebookNodeCohort'import '../Nodes/NotebookNodeDashboard'import '../Nodes/NotebookNodeCustomerJourney/NotebookNodeCustomerJourney'import '../Nodes/NotebookNodeSQLV2'-import '../Nodes/NotebookNodeDuckSQL'import '../Nodes/NotebookNodeEarlyAccessFeature'import '../Nodes/NotebookNodeEmbed'import '../Nodes/NotebookNodeExperiment'@@ -11,7 +10,6 @@ import '../Nodes/NotebookNodeFlag'import '../Nodes/NotebookNodeFlagCodeExample'import '../Nodes/NotebookNodeGroup'import '../Nodes/NotebookNodeGroupProperties'-import '../Nodes/NotebookNodeHogQL'import '../Nodes/NotebookNodeImage'import '../Nodes/NotebookNodeIssues'import '../Nodes/NotebookNodeLatex'@@ -21,7 +19,6 @@ import '../Nodes/NotebookNodePerson'import '../Nodes/NotebookNodePersonFeed/NotebookNodePersonFeed'import '../Nodes/NotebookNodePersonProperties'import '../Nodes/NotebookNodePlaylist'-import '../Nodes/NotebookNodePython'import '../Nodes/NotebookNodePythonV2'import '../Nodes/NotebookNodeQuery'import '../Nodes/NotebookNodeRecording'@@ -170,10 +167,7 @@ export const MARKDOWN_TAG_TO_NOTEBOOK_NODE_TYPE: Partial<Record<string, NotebookDashboard: NotebookNodeType.Dashboard,Action: NotebookNodeType.Action,Workflow: NotebookNodeType.Workflow,- Python: NotebookNodeType.Python,PythonV2: NotebookNodeType.PythonV2,- DuckSQL: NotebookNodeType.DuckSQL,- HogQLSQL: NotebookNodeType.HogQLSQL,SQLV2: NotebookNodeType.SQLV2,Widget: NotebookNodeType.GeneratedWidget,Recording: NotebookNodeType.Recording,@@ -252,11 +246,7 @@ export const MARKDOWN_NODE_DEFINITIONS: {{ tagName: 'Dashboard', category: 'Insight' },{ tagName: 'Action', category: 'Data' },{ tagName: 'Workflow', category: 'PostHog' },- // Legacy in-browser-kernel Python cell: still renders where it exists, but new cells- // are always the revamped PythonV2 below, so it has no insertCommand.- { tagName: 'Python', category: 'Code' },- // The revamped (sandbox-kernel) Python cell; insertion gated like SQLV2 in- // getMarkdownRegistryForFeatureFlags.+ // The sandbox-kernel Python cell; insertion gated like SQLV2 in getMarkdownRegistryForFeatureFlags.{tagName: 'PythonV2',category: 'Code',@@ -271,15 +261,11 @@ export const MARKDOWN_NODE_DEFINITIONS: {}),},},- { tagName: 'DuckSQL', category: 'SQL', label: 'SQL (DuckDB)' },- { tagName: 'HogQLSQL', category: 'SQL', label: 'SQL (HogQL)' },// insertCommand makes it show in the markdown insert menu; the feature-flag gate in// getMarkdownRegistryForFeatureFlags strips it when revamped-py-notebooks is off.{tagName: 'SQLV2',category: 'SQL',- // The single SQL node once the legacy SQL cells are deprecated (they render but- // are not insertable), so it reads as plain "SQL" in the insert menu.label: 'SQL',ToolbarComponent: NotebookCodeCellRunButton,insertCommand: {@@ -464,13 +450,7 @@ export function getMarkdownNotebookNodeTitle(fallback)}- if (- nodeType === NotebookNodeType.Python ||- nodeType === NotebookNodeType.PythonV2 ||- nodeType === NotebookNodeType.SQLV2 ||- nodeType === NotebookNodeType.DuckSQL ||- nodeType === NotebookNodeType.HogQLSQL- ) {+ if (nodeType === NotebookNodeType.PythonV2 || nodeType === NotebookNodeType.SQLV2) {// Never suggest the code/SQL body itself as a title — fall back to the language labelreturn fallback}diff --git a/frontend/src/scenes/notebooks/Notebook/markdownNotebookV2.test.ts b/frontend/src/scenes/notebooks/Notebook/markdownNotebookV2.test.tsindex cdb5733eae39..962dd20a0c58 100644--- a/frontend/src/scenes/notebooks/Notebook/markdownNotebookV2.test.ts+++ b/frontend/src/scenes/notebooks/Notebook/markdownNotebookV2.test.ts@@ -615,7 +615,7 @@ after`)attrs: { level: 2 },content: [{ type: 'text', text: 'Where to improve' }],},- { type: NotebookNodeType.Python, attrs: { code: 'print(1)', hideFilters: true } },+ { type: NotebookNodeType.PythonV2, attrs: { code: 'print(1)', hideFilters: true } },],},],@@ -628,14 +628,14 @@ after`)expect(markdown).toContain('> Quoted context')expect(markdown).toContain('\n\n<Query ')expect(markdown).toContain('> ## Where to improve')- expect(markdown).toContain('\n\n<Python ')+ expect(markdown).toContain('\n\n<PythonV2 ')expect(markdown).not.toContain('> <')const parsed = parseMarkdownNotebook(markdown)expect(parsed.errors).toEqual([])expect(parsed.nodes.flatMap((node) => (node.type === 'component' ? [node.tagName] : []))).toEqual(['Query',- 'Python',+ 'PythonV2',])const quotedHeading = parsed.nodes.find((node) => node.type === 'heading')expect(quotedHeading?.type === 'heading' && quotedHeading.blockquote).toBe(true)diff --git a/frontend/src/scenes/notebooks/Notebook/markdownNotebookV2.ts b/frontend/src/scenes/notebooks/Notebook/markdownNotebookV2.tsindex e4208c12d414..19bcf44a7ac1 100644--- a/frontend/src/scenes/notebooks/Notebook/markdownNotebookV2.ts+++ b/frontend/src/scenes/notebooks/Notebook/markdownNotebookV2.ts@@ -50,10 +50,7 @@ export const NOTEBOOK_NODE_TYPE_TO_MARKDOWN_TAG: Partial<Record<NotebookNodeType[NotebookNodeType.Dashboard]: 'Dashboard',[NotebookNodeType.Action]: 'Action',[NotebookNodeType.Workflow]: 'Workflow',- [NotebookNodeType.Python]: 'Python',[NotebookNodeType.PythonV2]: 'PythonV2',- [NotebookNodeType.DuckSQL]: 'DuckSQL',- [NotebookNodeType.HogQLSQL]: 'HogQLSQL',[NotebookNodeType.SQLV2]: 'SQLV2',[NotebookNodeType.GeneratedWidget]: 'Widget',[NotebookNodeType.Recording]: 'Recording',diff --git a/frontend/src/scenes/notebooks/Notebook/notebookLogic.ts b/frontend/src/scenes/notebooks/Notebook/notebookLogic.tsindex 03410b299f90..3d38fd57284c 100644--- a/frontend/src/scenes/notebooks/Notebook/notebookLogic.ts+++ b/frontend/src/scenes/notebooks/Notebook/notebookLogic.ts@@ -71,21 +71,11 @@ import type { NotebookCollabCursorApi } from 'products/notebooks/frontend/generaimport type { CommentType, UserType } from '../../../types'import {buildNotebookDependencyGraph,- collectDuckSqlNodes,- collectHogqlSqlNodes,collectNodeIndices,- collectPythonNodes,collectNotebookFrameNodes,collectSqlV2Nodes,} from '../Nodes/notebookNodeContent'-import type {- DuckSqlNodeSummary,- HogqlSqlNodeSummary,- NotebookDependencyGraph,- PythonNodeSummary,- NotebookFrameNodeSummary,- SqlV2NodeSummary,-} from '../Nodes/notebookNodeContent'+import type { NotebookDependencyGraph, NotebookFrameNodeSummary, SqlV2NodeSummary } from '../Nodes/notebookNodeContent'import type { notebookNodeLogicType } from '../Nodes/notebookNodeLogic'import { NotebookNodeType, NotebookSyncStatus, NotebookTarget, NotebookType } from '../types'import type { NotebookListItemType, NotebookVariableApi } from '../types'@@ -312,8 +302,6 @@ export interface notebookLogicValues {content: JSONContentcontentAtLastRun: JSONContent | nulldependencyGraph: NotebookDependencyGraph- duckSqlNodeIndices: Map<string, number>- duckSqlNodeSummaries: DuckSqlNodeSummary[]editingNodeIds: Record<string, true>editingNodeLogics: BuiltLogic<notebookNodeLogicType>[]findNodeLogic: (type: NotebookNodeType, attributes: Record<string, any>) => notebookNodeLogicType | null@@ -322,8 +310,6 @@ export interface notebookLogicValues {getSharedCachedInlineQueryResults: (nodeId: string | null | undefined) => AnyResponseType | nullgetSharedCachedInsight: (shortId: string | null | undefined) => InsightModel | nullhasUnsavedVariables: boolean- hogqlSqlNodeIndices: Map<string, number>- hogqlSqlNodeSummaries: HogqlSqlNodeSummary[]isEditable: booleanisLocalOnly: booleanisShareModalOpen: boolean@@ -355,8 +341,6 @@ export interface notebookLogicValues {notebookPresenceParticipants: NotebookPresenceParticipant[]personUUIDFromCanvasOverride: string | nullpreviewContent: JSONContent | null- pythonNodeIndices: Map<string, number>- pythonNodeSummaries: PythonNodeSummary[]runnableVariables: NotebookVariable[]shortId: stringshouldBeEditable: boolean@@ -696,16 +680,10 @@ export interface notebookLogicMeta {nodeLogics: Record<string, BuiltLogic<notebookNodeLogicType>>,content: JSONContent) => BuiltLogic<notebookNodeLogicType>[]- pythonNodeSummaries: (content: JSONContent) => PythonNodeSummary[]- duckSqlNodeSummaries: (content: JSONContent) => DuckSqlNodeSummary[]- hogqlSqlNodeSummaries: (content: JSONContent) => HogqlSqlNodeSummary[]sqlV2NodeSummaries: (content: JSONContent) => SqlV2NodeSummary[]frameNodeSummaries: (content: JSONContent) => NotebookFrameNodeSummary[]dependencyGraph: (contentAtLastRun: JSONContent | null) => NotebookDependencyGraph- pythonNodeIndices: (content: JSONContent) => Map<string, number>sqlNodeIndices: (content: JSONContent) => Map<string, number>- duckSqlNodeIndices: (content: JSONContent) => Map<string, number>- hogqlSqlNodeIndices: (content: JSONContent) => Map<string, number>isShowingLeftColumn: (showHistory: boolean) => booleanvariables: (localVariables: NotebookVariable[] | null, notebook: NotebookType | null) => NotebookVariable[]variableErrors: (variables: NotebookVariable[], content: JSONContent) => (string | null)[]@@ -1460,9 +1438,6 @@ export const notebookLogic = kea<notebookLogicType>([},],- pythonNodeSummaries: [(s) => [s.content], (content: JSONContent) => collectPythonNodes(content)],- duckSqlNodeSummaries: [(s) => [s.content], (content: JSONContent) => collectDuckSqlNodes(content)],- hogqlSqlNodeSummaries: [(s) => [s.content], (content: JSONContent) => collectHogqlSqlNodes(content)],sqlV2NodeSummaries: [(s) => [s.content], (content: JSONContent) => collectSqlV2Nodes(content)],frameNodeSummaries: [(s) => [s.content], (content: JSONContent) => collectNotebookFrameNodes(content)],dependencyGraph: [@@ -1471,11 +1446,6 @@ export const notebookLogic = kea<notebookLogicType>([(contentAtLastRun: JSONContent | null) => buildNotebookDependencyGraph(contentAtLastRun),],- pythonNodeIndices: [- (s) => [s.content],- (content: JSONContent) => collectNodeIndices(content, (node) => node.type === NotebookNodeType.Python),- ],-sqlNodeIndices: [(s) => [s.content],(content: JSONContent) =>@@ -1487,14 +1457,6 @@ export const notebookLogic = kea<notebookLogicType>([(node.attrs?.query?.source && isHogQLQuery(node.attrs.query.source)))),],- duckSqlNodeIndices: [- (s) => [s.content],- (content: JSONContent) => collectNodeIndices(content, (node) => node.type === NotebookNodeType.DuckSQL),- ],- hogqlSqlNodeIndices: [- (s) => [s.content],- (content: JSONContent) => collectNodeIndices(content, (node) => node.type === NotebookNodeType.HogQLSQL),- ],isShowingLeftColumn: [(s) => [s.showHistory], (showHistory: boolean) => showHistory],diff --git a/frontend/src/scenes/notebooks/NotebooksTable/ContainsTypeFilter.tsx b/frontend/src/scenes/notebooks/NotebooksTable/ContainsTypeFilter.tsxindex 302bdaa40f25..a946c90ea967 100644--- a/frontend/src/scenes/notebooks/NotebooksTable/ContainsTypeFilter.tsx+++ b/frontend/src/scenes/notebooks/NotebooksTable/ContainsTypeFilter.tsx@@ -29,11 +29,8 @@ export const fromNodeTypeToLabel: Omit<[NotebookNodeType.Dashboard]: 'Dashboards',[NotebookNodeType.Action]: 'Actions',[NotebookNodeType.Workflow]: 'Workflows',- [NotebookNodeType.Python]: 'Python',- [NotebookNodeType.PythonV2]: 'Python (v2)',- [NotebookNodeType.DuckSQL]: 'SQL (DuckDB)',- [NotebookNodeType.HogQLSQL]: 'SQL (HogQL)',- [NotebookNodeType.SQLV2]: 'SQL (v2)',+ [NotebookNodeType.PythonV2]: 'Python',+ [NotebookNodeType.SQLV2]: 'SQL',[NotebookNodeType.Recording]: 'Session recordings',[NotebookNodeType.RecordingPlaylist]: 'Session replay playlists',[NotebookNodeType.ReplayTimestamp]: 'Session recording comments',diff --git a/frontend/src/scenes/notebooks/nodeIcons.tsx b/frontend/src/scenes/notebooks/nodeIcons.tsxindex e227ad003f94..651c55d407fe 100644--- a/frontend/src/scenes/notebooks/nodeIcons.tsx+++ b/frontend/src/scenes/notebooks/nodeIcons.tsx@@ -33,10 +33,7 @@ export const NODE_ICONS: Partial<Record<NotebookNodeType, JSX.Element>> = {[NotebookNodeType.Dashboard]: <IconPieChart />,[NotebookNodeType.Action]: <IconList />,[NotebookNodeType.Workflow]: <IconUserPaths />,- [NotebookNodeType.HogQLSQL]: <IconBracketsChart />,- [NotebookNodeType.DuckSQL]: <IconBracketsChart />,[NotebookNodeType.SQLV2]: <IconBracketsChart />,- [NotebookNodeType.Python]: <IconPython />,[NotebookNodeType.PythonV2]: <IconPython />,[NotebookNodeType.GeneratedWidget]: <IconAI />,[NotebookNodeType.Latex]: <IconSquareRoot />,diff --git a/frontend/src/scenes/notebooks/types.ts b/frontend/src/scenes/notebooks/types.tsindex 6ace5e17d720..0c2fb7198e5c 100644--- a/frontend/src/scenes/notebooks/types.ts+++ b/frontend/src/scenes/notebooks/types.ts@@ -50,12 +50,9 @@ export enum NotebookNodeType {Dashboard = 'ph-dashboard-widget',Action = 'ph-action',Workflow = 'ph-workflow',- Python = 'ph-python',- // The revamped Python cell: runs in the notebook's sandbox kernel via the SQLV2 run- // path, unlike the legacy ph-python node's in-browser kernel.+ // Runs in the notebook's sandbox kernel via the SQLV2 run path. The "V2" suffix is a wire+ // string: persisted notebooks carry `<PythonV2 />` / `<SQLV2 />` tags and `ph-*-v2` node types.PythonV2 = 'ph-python-v2',- DuckSQL = 'ph-duck-sql',- HogQLSQL = 'ph-hogql-sql',SQLV2 = 'ph-sql-v2',GeneratedWidget = 'ph-generated-widget',Recording = 'ph-recording',diff --git a/frontend/src/scenes/notebooks/utils.ts b/frontend/src/scenes/notebooks/utils.tsindex dd54c4ad98c4..d6ac3eecaff1 100644--- a/frontend/src/scenes/notebooks/utils.ts+++ b/frontend/src/scenes/notebooks/utils.ts@@ -8,7 +8,7 @@ import { CreatePostHogWidgetNodeOptions } from './types'export const KNOWN_NODES: Record<string, CreatePostHogWidgetNodeOptions<any>> = {}export function isKernelUiEnabled(featureFlags: FeatureFlagsSet): boolean {- return !!featureFlags[FEATURE_FLAGS.NOTEBOOK_PYTHON] || !!featureFlags[FEATURE_FLAGS.REVAMPED_PY_NOTEBOOKS]+ return !!featureFlags[FEATURE_FLAGS.REVAMPED_PY_NOTEBOOKS]}export function defaultNotebookContent(title?: string, content?: JSONContent[]): JSONContent {diff --git a/products/notebooks/backend/markdown_conversion.py b/products/notebooks/backend/markdown_conversion.pyindex e3ad02a8e674..3b2a04b07a36 100644--- a/products/notebooks/backend/markdown_conversion.py+++ b/products/notebooks/backend/markdown_conversion.py@@ -15,9 +15,6 @@ JSONContent = dict[str, Any]NOTEBOOK_NODE_TYPE_TO_MARKDOWN_TAG: Mapping[str, str] = {"ph-query": "Query",- "ph-python": "Python",- "ph-duck-sql": "DuckSQL",- "ph-hogql-sql": "HogQLSQL","ph-recording": "Recording","ph-recording-playlist": "RecordingPlaylist","ph-feature-flag": "FeatureFlag",diff --git a/products/notebooks/backend/test/test_markdown_migration.py b/products/notebooks/backend/test/test_markdown_migration.pyindex f260a9da0a1c..ddc16954347c 100644--- a/products/notebooks/backend/test/test_markdown_migration.py+++ b/products/notebooks/backend/test/test_markdown_migration.py@@ -281,7 +281,7 @@ class TestNotebookMarkdownConversion(BaseTest):assert "> Quoted context" in markdownassert "\n\n<Query " in markdownassert "\n\n## Where to improve" in markdown- assert "\n\n<Python " in markdown+ assert '\n\n<UnknownNode nodeType="ph-python" ' in markdownassert "> ! Watch this" in markdownassert "> <" not in markdown