: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
fix(notebooks): repair widget generation and dataframe reuse (#100112)
Marius Andra8152d31b7012
diff --git a/.github/workflows/ci-mcp.yml b/.github/workflows/ci-mcp.ymlindex 6f99a7519f6e..46958c067ea1 100644--- a/.github/workflows/ci-mcp.yml+++ b/.github/workflows/ci-mcp.yml@@ -171,6 +171,7 @@ jobs:# Python backend. WF009 keeps the list in step with what MCP imports.mcp-typescript:- 'packages/quill/**'+ - 'products/notebooks/**'- 'products/product_analytics/frontend/insights/**'- 'products/*/frontend/generated/**'- 'frontend/src/mocks/fixtures/**'diff --git a/docs/internal/generated-notebook-widgets.md b/docs/internal/generated-notebook-widgets.mdindex 483e4e190bae..a8da27bb5ef1 100644--- a/docs/internal/generated-notebook-widgets.md+++ b/docs/internal/generated-notebook-widgets.md@@ -80,6 +80,31 @@ Reusable widgets remain behind the `notebook-generated-widgets` feature flag and## Agent access+New widgets default to Claude Sonnet 5. An explicitly selected model stays selected.+Widget IDs are saved when their settings, title, or panel visibility change, so editing a widget keeps its generation history attached.++New SQL cells receive a unique name beginning with `sql_df_`; Python cells receive one beginning with `df_`.+You can rename a dataframe in its result panel.+The SQL and insight dataframe name rows are visible when either `revamped-py-notebooks` or `notebook-generated-widgets` is enabled.+The widget flag enables HogQL dataframe preparation. Python, kernel-backed SQL, and direct connections require `revamped-py-notebooks`.+Insights that expose SQL have the same dataframe name field below their results, starting with `insight_df` (with a numeric suffix when needed).+An editor prepares the insight's dataframe when a SQL or Python cell first references it, before generating a widget, or when rerunning a widget's data dependencies.+Widgets that use only insight dataframes refresh after preparation without requiring a SQL or Python cell.+Opening a notebook, renaming a dataframe, or refreshing an insight's display does not prepare dataframes or save preparation metadata.+Preparation uses the insight query cache and saves the run reference and column metadata only after the SQL run completes.+If the insight query changes during preparation, the completed result is discarded and the editor can try again.+Concurrent preparation requests from the same user reuse the same matching run for up to one hour.+Run reuse is disabled for token-only callers because runs do not record their individual identities.+An unchanged insight with a saved completed run reuses that snapshot. **Refresh dataframe** prepares a fresh snapshot; **Try again** retries a failed preparation.+Viewers and shared notebooks do not show insight dataframe controls or prepare dataframes.++SQL and Python cells save their run ID, column metadata, and row count in the notebook.+A bounded preview keeps at most five rows within 8 KiB and up to 2,048 characters per console stream in the notebook, including runs created through MCP.+The preview helper is shared with MCP, so the MCP TypeScript CI filter covers `products/notebooks/**`.+Full results and images load from the saved run. Older browser tabs can still display the small preview.+Saved result reads remain available if the execution flags are disabled, subject to notebook and query permissions.+Loading a saved result does not execute a cell or mark dependent cells stale. If a saved run is unavailable, the preview stays visible and the cell offers a rerun.+New notebooks place the typing caret in the title, including when opened through the command menu. Enter continues into the notebook body.The notebook's inline **Ask AI** uses LangGraph and receives widget authoring instructions when `notebook-generated-widgets` is enabled for the user.The bookmark toggle **Keep question with answer** is on by default, retaining the question and the submitting user's name above the answer. Turning it off saves `keepQuestion={false}` on that prompt.diff --git a/frontend/snapshots.yml b/frontend/snapshots.ymlindex 414079e7880d..c0ae72087e13 100644--- a/frontend/snapshots.yml+++ b/frontend/snapshots.yml@@ -6485,9 +6485,9 @@ snapshots:replay-player-controller--default--light:hash: v1.k794b7964.0bbf7a8cd9b409886483405c5d64aa19e48a12687bab491a27a215f5146d5b06.K8bF16EHTA82qWpCZ-sKJHeizESmVUofMHUQThB3scQreplay-player-controller--narrow--dark:- hash: v1.k794b7964.faa47c275c39f21281fe185f5f7d1ec3362381663b63e8faf8959595debc6bb0.bNBbYsI-Gi6RQ1zT71h3E9vjRuNI4hwiO_BBoc47VJo+ hash: v1.k794b7964.fb8c53836443cf16b8b07b5bc6cb55ce8a97bbfe50d30492ea5066ef3d74e32e.bFLciH0a6MvcII0cUGVaRZHySzRCX2vYRLQtJimzCzIreplay-player-controller--narrow--light:- hash: v1.k794b7964.c69a69ba05746718904b32f423b5064842f9363aca53764ba18ed93104c9880f.xokFqFU1kfYzuRlqVVYXqKvGgUgY_n5xrM6bj79ILAE+ hash: v1.k794b7964.f6f95433163205f48bde9bd51bc5e07142af86699a19857b6e7ad157df27aa36.jNVcVWshGGenshUqM9pEeZDzktHLTuaYqcJnnV3OSvcreplay-player-controller--notebook-mode--dark:hash: v1.k794b7964.f4a6ee136f65d9abf52123cf59834a6ca3849851ec71b00f210b541f2e532ed7.ifidoJSOxG3FPTATJiOEbsi6HAiUr0M-j88ex_yIJ5Ereplay-player-controller--notebook-mode--light:@@ -9189,9 +9189,9 @@ snapshots:scenes-app-notebooks-widget-views--group-views--light:hash: v1.k794b7964.a622eda529140b0da26febf0295d5afe02224a095b690d699c90d37d189fd615.2nmLTPSj2A2MQ3TYzkrkcCOHhvvB3-4GiRvFJN_9tXIscenes-app-notebooks-widget-views--insight-views--dark:- hash: v1.k794b7964.e244662a3673ec7ba165c44cf182061da92bf464f4dd906d4a14a21097fd642a.FIzEr05lCLHYNsnjsOKAPba8sOdGAhy0to264af4mi0+ hash: v1.k794b7964.e25c1892d4ab208af5c14ddbd62850287baa0f564b2bcd67309e9357ebae2e9c.uP6ZYZ2y2epiADizyQmS0p921z8XYO4RssS_4Ns2228scenes-app-notebooks-widget-views--insight-views--light:- hash: v1.k794b7964.453689f7cbcada239210a4e86acbb1bf636b42dd8a221ebec99a697e095b4ccc.8rMJvAEuKIZteiL98EOHI4399p25PSlnJCbjkLZTXZU+ hash: v1.k794b7964.5369699ec2675bd48c1df9f62bb8b5c8e95821ed26a4ed8a2d46cc07a547e8a5.Lx0HDMJJDnUu1yL_liJyEQ-rRlhY4p5a8bqTL2C6gegscenes-app-notebooks-widget-views--llm-trace-views--dark:hash: v1.k794b7964.4e1ab634bae8a93e4e3c6fed3c379cd10791a8cdfaa37c551ffc10cbb5c2d738.zBi7T4pmBEu1EV1ID04nuFxNs7iSFBMDc-tCKVEmy70scenes-app-notebooks-widget-views--llm-trace-views--light:diff --git a/frontend/src/lib/api.ts b/frontend/src/lib/api.tsindex 944d634a426b..d5b0f3b1968c 100644--- a/frontend/src/lib/api.ts+++ b/frontend/src/lib/api.ts@@ -4852,6 +4852,7 @@ const api = {async sqlV2Run(notebookId: NotebookType['short_id'],data: {+ reuse_results?: booleannode_id: stringcode: stringrefs?: Record<string, { node_id: string; kind: 'hogql' | 'local' }>diff --git a/frontend/src/lib/components/MarkdownNotebook/NotebookComponentShell.tsx b/frontend/src/lib/components/MarkdownNotebook/NotebookComponentShell.tsxindex a646874aaff6..76307fe24652 100644--- a/frontend/src/lib/components/MarkdownNotebook/NotebookComponentShell.tsx+++ b/frontend/src/lib/components/MarkdownNotebook/NotebookComponentShell.tsx@@ -290,6 +290,7 @@ export function NotebookComponentShell({raw: undefined,errors: undefined,props: {+ ...(definition?.persistNodeId ? { nodeId: currentNode.id } : {}),...Object.entries(currentNode.props).reduce<NotebookComponentProps>((accumulator, [key, value]) => {if (!propKeysToRemove.has(key)) {@@ -304,7 +305,7 @@ export function NotebookComponentShell({}})},- [node.id, updateNode]+ [definition?.persistNodeId, node.id, updateNode])const commitTitle = (): void => {if (cancellingTitleRef.current) {diff --git a/frontend/src/lib/components/MarkdownNotebook/componentPanels.ts b/frontend/src/lib/components/MarkdownNotebook/componentPanels.tsindex a01af409c8e9..4ad169891950 100644--- a/frontend/src/lib/components/MarkdownNotebook/componentPanels.ts+++ b/frontend/src/lib/components/MarkdownNotebook/componentPanels.ts@@ -65,7 +65,10 @@ export function withPersistedComponentPanelProps(return {...node,- props: getComponentPropsWithPanelVisibility(node.props, panels),+ props: getComponentPropsWithPanelVisibility(+ definition?.persistNodeId ? { nodeId: node.id, ...node.props } : node.props,+ panels+ ),}}diff --git a/frontend/src/lib/components/MarkdownNotebook/types.ts b/frontend/src/lib/components/MarkdownNotebook/types.tsindex cd9ae4f719a9..3ad9c5c9231c 100644--- a/frontend/src/lib/components/MarkdownNotebook/types.ts+++ b/frontend/src/lib/components/MarkdownNotebook/types.ts@@ -171,6 +171,7 @@ export type NotebookComponentDefinition = {validateProps?: (props: NotebookComponentProps) => string[]getTitle?: (node: NotebookComponentBlockNode) => string | null | undefinededitableTitle?: boolean+ persistNodeId?: boolean/** Canonical PostHog URL the block points at (e.g. the insight, recording, or person it renders), opened in a new tab from the toolbar. */getHref?: (node: NotebookComponentBlockNode) => string | null | undefinedViewComponent: (props: NotebookComponentRenderProps) => JSX.Elementdiff --git a/frontend/src/scenes/notebooks/Nodes/NotebookNodePythonV2.tsx b/frontend/src/scenes/notebooks/Nodes/NotebookNodePythonV2.tsxindex 5565762ef943..d2f457b40820 100644--- a/frontend/src/scenes/notebooks/Nodes/NotebookNodePythonV2.tsx+++ b/frontend/src/scenes/notebooks/Nodes/NotebookNodePythonV2.tsx@@ -5,6 +5,8 @@ import { CodeEditorResizeable } from 'lib/monaco/CodeEditorResizable'import { createPostHogWidgetNode } from 'scenes/notebooks/Nodes/NodeWrapper'import type { NotebookNodeRunTerminalStatus } from 'scenes/notebooks/Notebook/notebookNodeStalenessLogic'+import { notebookCodeCellLogic } from 'products/notebooks/frontend/notebookCodeCellLogic'+import { NotebookNodeAttributeProperties, NotebookNodeProps, NotebookNodeType } from '../types'import { NotebookCellOutputHeader } from './components/NotebookCellOutputHeader'import { NotebookCellOutputNameFooter } from './components/NotebookCellOutputNameFooter'@@ -14,7 +16,7 @@ import { NotebookStaleCellBanner } from './components/NotebookStaleCellBanner'import { notebookNodeLogic } from './notebookNodeLogic'import { countTextLines, initialSizedRunId, outputHeightForShape } from './notebookNodeOutputHeight'import type { NotebookNodeSQLV2Result } from './NotebookNodeSQLV2'-import { SQL_V2_DEFAULT_PAGE_SIZE, notebookNodeSQLV2Logic } from './notebookNodeSQLV2Logic'+import { SQL_V2_DEFAULT_PAGE_SIZE } from './notebookNodeSQLV2Logic'import { NotebookDataframeResult } from './pythonExecution'// The revamped Python cell: code runs in the notebook's sandbox kernel via the SQLV2 run@@ -54,20 +56,13 @@ const Component = ({}: NotebookNodeProps<NotebookNodePythonV2Attributes>): JSX.Element | null => {const nodeLogic = useMountedLogic(notebookNodeLogic)const { nodeId, notebookLogic, expanded, isEditable } = useValues(nodeLogic)- const notebookShortId = notebookLogic.props.shortId- const dataLogic = notebookNodeSQLV2Logic({- nodeId,- notebookShortId,- updateAttributes,- runId: attributes.runId ?? null,- hasResult: !!attributes.result,- getContent: () => notebookLogic.values.content ?? null,- getVariables: () => notebookLogic.values.runnableVariables,- })+ const dataLogic = notebookCodeCellLogic(nodeId, notebookLogic, attributes, updateAttributes)const {isRunning,runError,+ isRestoringResult,+ resultRestoreUnavailable,page,pageSize,pageResult,@@ -78,10 +73,11 @@ const Component = ({isChainRunning,staleDownstreamCount,pendingKernelStart,+ result: runResult,} = useValues(dataLogic)const { setPage, setPageSize, runStaleChain } = useActions(dataLogic)- const result = attributes.result ?? null+ const result = runResult ?? attributes.result ?? nullconst dataframeResult = useMemo(() => {if (pageResult) {return toDataframeResult({@@ -175,13 +171,18 @@ const Component = ({))}</div>) : null}+ {resultRestoreUnavailable ? (+ <div className="p-2 text-xs text-muted">Run the cell again to see its full results.</div>+ ) : isRestoringResult ? (+ <div className="p-2 text-xs text-muted">Loading saved results…</div>+ ) : null}{runError ? (<div className="p-2 text-xs font-mono text-danger whitespace-pre-wrap">{runError}</div>) : dataframeResult ? (<div className="min-h-0 flex-1 overflow-y-auto"><NotebookDataframeTableresult={dataframeResult}- loading={isRunning || pageLoading}+ loading={isRunning || pageLoading || (isRestoringResult && !result?.first_page?.length)}page={page}pageSize={pageSize}hasMore={hasMorePages}@@ -218,17 +219,8 @@ const Settings = ({}: NotebookNodeAttributeProperties<NotebookNodePythonV2Attributes>): JSX.Element => {const nodeLogic = useMountedLogic(notebookNodeLogic)const { nodeId, notebookLogic } = useValues(nodeLogic)- const notebookShortId = notebookLogic.props.shortId- const dataLogic = notebookNodeSQLV2Logic({- nodeId,- notebookShortId,- updateAttributes,- runId: attributes.runId ?? null,- hasResult: !!attributes.result,- getContent: () => notebookLogic.values.content ?? null,- getVariables: () => notebookLogic.values.runnableVariables,- })+ const dataLogic = notebookCodeCellLogic(nodeId, notebookLogic, attributes, updateAttributes)const { runNode } = useActions(dataLogic)// Read the run state imperatively: Monaco binds Cmd+Enter once at editor mount, so a captured@@ -273,10 +265,8 @@ export const NotebookNodePythonV2 = createPostHogWidgetNode<NotebookNodePythonV2code: {default: '',},- // Optional: empty means the cell binds no dataframe, so nothing downstream can read it.- // A cell that predates the optional name carries its persisted name and keeps exporting it.returnVariable: {- default: '',+ default: 'df',},runId: {default: null,diff --git a/frontend/src/scenes/notebooks/Nodes/NotebookNodeQuery.tsx b/frontend/src/scenes/notebooks/Nodes/NotebookNodeQuery.tsxindex 92ac2e75161f..689aeff7c8d8 100644--- a/frontend/src/scenes/notebooks/Nodes/NotebookNodeQuery.tsx+++ b/frontend/src/scenes/notebooks/Nodes/NotebookNodeQuery.tsx@@ -29,6 +29,9 @@ import {} from '~/queries/utils'import { InsightLogicProps, InsightShortId } from '~/types'+import { NotebookInsightDataframe } from 'products/notebooks/frontend/NotebookInsightDataframe'+import type { InsightDataframeAttributes } from 'products/notebooks/frontend/notebookInsightDataframeLogic'+import { NotebookNodeAttributeProperties, NotebookNodeProps, NotebookNodeType } from '../types'import {getSqlEditorSourceQuery,@@ -103,6 +106,10 @@ const Component = ({: {dashboardItemId: query.kind === NodeKind.SavedInsightNode ? query.shortId : ('new' as const),}+ const dataframeInsightProps: InsightLogicProps =+ query.kind === NodeKind.SavedInsightNode+ ? insightLogicProps+ : { dashboardItemId: `new-AdHoc.notebook.${notebookLogic.props.shortId}.${nodeId}`, query }const { insightName } = useValues(insightLogic(insightLogicProps))const isOutputPaneOpen = componentPanelState?.showViewPanel ?? expandedconst showSqlOutputToolbar = getNotebookSqlOutputToolbarVisibility({@@ -233,6 +240,7 @@ const Component = ({<QueryuniqueKey={nodeId + '-component'}query={modifiedQuery}+ context={isInsightVizNode(modifiedQuery) ? { insightProps: dataframeInsightProps } : undefined}attachTo={notebookLogic}setQuery={(t) => {updateAttributes({@@ -257,12 +265,19 @@ const Component = ({{queryComponent}</ScrollableShadows>)}+ {isInsightViz ? (+ <NotebookInsightDataframe+ insightProps={dataframeInsightProps}+ attributes={attributes}+ updateAttributes={updateAttributes}+ />+ ) : null}</BindLogic></div>)}-type NotebookNodeQueryAttributes = {+type NotebookNodeQueryAttributes = InsightDataframeAttributes & {query: QuerySchemaid?: InsightShortIdview?: string@@ -475,6 +490,13 @@ export const NotebookNodeQuery = createPostHogWidgetNode<NotebookNodeQueryAttriboutputTab: {default: OutputTab.Results,},+ nodeId: {},+ returnVariable: {},+ dataframeSource: {},+ dataframeQuery: {},+ runId: {},+ result: {},+ runStatus: {},},href: (attributes) => {const query = getResolvedNotebookQuery(attributes)diff --git a/frontend/src/scenes/notebooks/Nodes/NotebookNodeSQLV2.tsx b/frontend/src/scenes/notebooks/Nodes/NotebookNodeSQLV2.tsxindex cc101ba23d83..c7026796bdac 100644--- a/frontend/src/scenes/notebooks/Nodes/NotebookNodeSQLV2.tsx+++ b/frontend/src/scenes/notebooks/Nodes/NotebookNodeSQLV2.tsx@@ -1,7 +1,9 @@import { useActions, useMountedLogic, useValues } from 'kea'import { useEffect, useMemo, useRef, useState } from 'react'+import { FEATURE_FLAGS } from 'lib/constants'import { LemonTabs } from 'lib/lemon-ui/LemonTabs'+import { featureFlagLogic } from 'lib/logic/featureFlagLogic'import { OutputTab } from 'scenes/data-warehouse/editor/outputPaneLogic'import { createPostHogWidgetNode } from 'scenes/notebooks/Nodes/NodeWrapper'import type { NotebookNodeRunTerminalStatus } from 'scenes/notebooks/Notebook/notebookNodeStalenessLogic'@@ -10,6 +12,8 @@ import { Query } from '~/queries/Query/Query'import { DataVisualizationNode, HogQLQueryResponse, NodeKind } from '~/queries/schema/schema-general'import { ChartDisplayType } from '~/types'+import { notebookCodeCellLogic } from 'products/notebooks/frontend/notebookCodeCellLogic'+import { NotebookNodeAttributeProperties, NotebookNodeProps, NotebookNodeType } from '../types'import { NotebookCellOutputHeader } from './components/NotebookCellOutputHeader'import { NotebookCellOutputNameFooter } from './components/NotebookCellOutputNameFooter'@@ -22,7 +26,7 @@ import { NotebookCodeSQLEditorSettings } from './components/NotebookSQLEditor'import { NotebookStaleCellBanner } from './components/NotebookStaleCellBanner'import { notebookNodeLogic } from './notebookNodeLogic'import { initialSizedRunId, outputHeightForShape } from './notebookNodeOutputHeight'-import { SQL_V2_DEFAULT_PAGE_SIZE, notebookNodeSQLV2Logic } from './notebookNodeSQLV2Logic'+import { SQL_V2_DEFAULT_PAGE_SIZE } from './notebookNodeSQLV2Logic'import { NotebookDataframeResult } from './pythonExecution'export type NotebookNodeSQLV2Media = { mime_type: string; data: string }@@ -31,7 +35,8 @@ export type NotebookNodeSQLV2Result = {columns: string[]types?: [string, string][]row_count: number- first_page: (string | number | null)[][]+ first_page?: (string | number | null)[][]+ previewOnly?: booleanhas_more?: boolean// Python node output: captured streams and rich media (e.g. matplotlib PNGs).stdout?: string@@ -63,7 +68,7 @@ const VIZ_MIN_HEIGHT = 350// when a python cell reads the frame, so it must be a plain identifier. Empty is fine —// the cell is then display-only.const VALID_RETURN_VARIABLE = /^[A-Za-z_][A-Za-z0-9_]*$/-const returnVariableValidationError = (returnVariable: string): string | null => {+export const returnVariableValidationError = (returnVariable: string): string | null => {if (!returnVariable || VALID_RETURN_VARIABLE.test(returnVariable)) {return null}@@ -101,9 +106,7 @@ const inferTypes = (result: NotebookNodeSQLV2Result): [string, string][] =>return [column, typeof sample === 'number' ? 'Float64' : 'String']})-// A notebook stores the whole result envelope, and a cell the sandbox kernel ran can hold raw-// pandas dtypes ('float64', 'str'). The chart layer reads ClickHouse names to decide which-// columns can go on a numeric axis, so map those over rather than make a saved cell re-run.+// Kernel results can contain pandas dtypes. Charts need ClickHouse type names to select numeric axes.const PANDAS_DTYPE_NAMES: Record<string, string> = {bool: 'Bool',boolean: 'Bool',@@ -142,22 +145,18 @@ const Component = ({updateAttributes,}: NotebookNodeProps<NotebookNodeSQLV2Attributes>): JSX.Element | null => {const nodeLogic = useMountedLogic(notebookNodeLogic)- const { nodeId, notebookLogic, expanded, sqlV2ReturnVariableUsage, isEditable } = useValues(nodeLogic)+ const { featureFlags } = useValues(featureFlagLogic)+ const { nodeId, notebookLogic, expanded, sqlV2ReturnVariable, sqlV2ReturnVariableUsage, isEditable } =+ useValues(nodeLogic)const { navigateToNode } = useActions(nodeLogic)const notebookShortId = notebookLogic.props.shortId- const dataLogic = notebookNodeSQLV2Logic({- nodeId,- notebookShortId,- updateAttributes,- runId: attributes.runId ?? null,- hasResult: !!attributes.result,- getContent: () => notebookLogic.values.content ?? null,- getVariables: () => notebookLogic.values.runnableVariables,- })+ const dataLogic = notebookCodeCellLogic(nodeId, notebookLogic, attributes, updateAttributes)const {isRunning,runError,+ isRestoringResult,+ resultRestoreUnavailable,page,pageSize,pageResult,@@ -168,14 +167,15 @@ const Component = ({isChainRunning,staleDownstreamCount,pendingKernelStart,+ result: runResult,} = useValues(dataLogic)const { setPage, setPageSize, runStaleChain } = useActions(dataLogic)const usageLabel = (nodeIndex: number | undefined, title: string): string =>title.trim() || getCellLabel(nodeIndex) || 'SQL'- const result = attributes.result ?? null- const returnVariable = attributes.returnVariable ?? ''+ const result = runResult ?? attributes.result ?? null+ const returnVariable = sqlV2ReturnVariableconst returnVariableError = returnVariableValidationError(returnVariable)// A callback ref, not useRef: the hint anchors to this input, and a ref assignment alone// wouldn't re-render the Popover with the element it needs to position against.@@ -279,6 +279,11 @@ const Component = ({{isRunning && pendingKernelStart ? (<div className="shrink-0 px-2 pt-1 pb-2 text-xs text-muted">Starting compute sandbox…</div>) : null}+ {resultRestoreUnavailable ? (+ <div className="p-2 text-xs text-muted">Run the cell again to see its full results.</div>+ ) : isRestoringResult ? (+ <div className="p-2 text-xs text-muted">Loading saved results…</div>+ ) : null}{runError ? (<div className="p-2 text-xs font-mono text-danger whitespace-pre-wrap">{runError}</div>) : dataframeResult && cachedResults ? (@@ -309,7 +314,9 @@ const Component = ({<div className="min-h-0 flex-1 overflow-y-auto"><NotebookDataframeTableresult={dataframeResult}- loading={isRunning || pageLoading}+ loading={+ isRunning || pageLoading || (isRestoringResult && !result?.first_page?.length)+ }page={page}pageSize={pageSize}hasMore={hasMorePages}@@ -358,33 +365,36 @@ const Component = ({<div className="text-xs text-muted font-mono p-2">Run the query to see execution results.</div>)}</div>- <NotebookCellOutputNameFooter- returnVariable={returnVariable}- onChange={(returnVariable) => updateAttributes({ returnVariable })}- inputRef={setReturnVariableInput}- >- <NotebookDataframeHintPopover- nodeId={nodeId}- notebookShortId={notebookShortId}- referenceElement={returnVariableInput}- />- {returnVariableError ? <span className="text-danger">{returnVariableError}</span> : null}- {sqlV2ReturnVariableUsage.length > 0 ? (- <span className="text-muted">- Used in{' '}- {sqlV2ReturnVariableUsage.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.nodeIndex, usage.title)}- </button>- ))}- </span>- ) : null}- </NotebookCellOutputNameFooter>+ {(featureFlags[FEATURE_FLAGS.REVAMPED_PY_NOTEBOOKS] ||+ featureFlags[FEATURE_FLAGS.NOTEBOOK_GENERATED_WIDGETS]) && (+ <NotebookCellOutputNameFooter+ returnVariable={returnVariable}+ onChange={(returnVariable) => updateAttributes({ returnVariable })}+ inputRef={setReturnVariableInput}+ >+ <NotebookDataframeHintPopover+ nodeId={nodeId}+ notebookShortId={notebookShortId}+ referenceElement={returnVariableInput}+ />+ {returnVariableError ? <span className="text-danger">{returnVariableError}</span> : null}+ {sqlV2ReturnVariableUsage.length > 0 ? (+ <span className="text-muted">+ Used in{' '}+ {sqlV2ReturnVariableUsage.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.nodeIndex, usage.title)}+ </button>+ ))}+ </span>+ ) : null}+ </NotebookCellOutputNameFooter>+ )}</div>)}@@ -395,17 +405,8 @@ const Settings = ({}: NotebookNodeAttributeProperties<NotebookNodeSQLV2Attributes>): JSX.Element => {const nodeLogic = useMountedLogic(notebookNodeLogic)const { nodeId, notebookLogic } = useValues(nodeLogic)- const notebookShortId = notebookLogic.props.shortId- const dataLogic = notebookNodeSQLV2Logic({- nodeId,- notebookShortId,- updateAttributes,- runId: attributes.runId ?? null,- hasResult: !!attributes.result,- getContent: () => notebookLogic.values.content ?? null,- getVariables: () => notebookLogic.values.runnableVariables,- })+ const dataLogic = notebookCodeCellLogic(nodeId, notebookLogic, attributes, updateAttributes)const { isRunning } = useValues(dataLogic)const { runNode } = useActions(dataLogic)@@ -437,10 +438,8 @@ export const NotebookNodeSQLV2 = createPostHogWidgetNode<NotebookNodeSQLV2Attribcode: {default: '',},- // Optional: empty means the cell binds no dataframe (display-only). Existing cells- // carry their persisted name ('sql_df' was the old default) and keep exporting it.returnVariable: {- default: '',+ default: 'sql_df',},connectionId: {default: null,diff --git a/frontend/src/scenes/notebooks/Nodes/components/NotebookCodeCellRunButton.tsx b/frontend/src/scenes/notebooks/Nodes/components/NotebookCodeCellRunButton.tsxindex 8a28b875f0e5..ee11f7d3b4f7 100644--- a/frontend/src/scenes/notebooks/Nodes/components/NotebookCodeCellRunButton.tsx+++ b/frontend/src/scenes/notebooks/Nodes/components/NotebookCodeCellRunButton.tsx@@ -10,12 +10,11 @@ import { IconCancel } from 'lib/lemon-ui/icons'import { LemonButton } from 'lib/lemon-ui/LemonButton'import { sqlEditorLogic } from 'scenes/data-warehouse/editor/sqlEditorLogic'+import { notebookCodeCellLogic } from 'products/notebooks/frontend/notebookCodeCellLogic'+import { notebookLogic } from '../../Notebook/notebookLogic'-import {- type NotebookNodeSQLV2LogicProps,- type RunNodeOverrides,- notebookNodeSQLV2Logic,-} from '../notebookNodeSQLV2Logic'+import type { NotebookNodeSQLV2Result } from '../NotebookNodeSQLV2'+import { type NotebookNodeSQLV2LogicProps, type RunNodeOverrides } from '../notebookNodeSQLV2Logic'import { getNotebookSqlEditorTabId } from './NotebookSQLEditor'/**@@ -37,14 +36,15 @@ export function NotebookCodeCellRunButton({ node, updateProps }: NotebookCompone[updateProps])- const dataLogic = notebookNodeSQLV2Logic({+ const dataLogic = notebookCodeCellLogic(nodeId,- notebookShortId: mountedNotebookLogic.props.shortId,- updateAttributes,- runId: typeof node.props.runId === 'string' ? node.props.runId : null,- hasResult: !!node.props.result,- getContent: () => mountedNotebookLogic.values.content ?? null,- })+ mountedNotebookLogic,+ {+ runId: typeof node.props.runId === 'string' ? node.props.runId : null,+ result: node.props.result as NotebookNodeSQLV2Result | undefined,+ },+ updateAttributes+ )const { isRunning, isInterrupting, operationBlockReason } = useValues(dataLogic)const { runNode, interruptRun } = useActions(dataLogic)diff --git a/frontend/src/scenes/notebooks/Nodes/notebookNodeContent.test.ts b/frontend/src/scenes/notebooks/Nodes/notebookNodeContent.test.tsindex dde9f3bf4d4d..30ea9eae86e1 100644--- a/frontend/src/scenes/notebooks/Nodes/notebookNodeContent.test.ts+++ b/frontend/src/scenes/notebooks/Nodes/notebookNodeContent.test.ts@@ -1,5 +1,7 @@import * as markdownNotebookParser from 'lib/components/MarkdownNotebook/markdown'+import dataframeNameCases from 'products/notebooks/dataframe-names.test.json'+import { buildMarkdownNotebookContent, serializeMarkdownNotebookComponent } from '../Notebook/markdownNotebookV2'import { NotebookNodeType } from '../types'import {@@ -9,6 +11,17 @@ import {} from './notebookNodeContent'describe('buildNotebookDependencyGraph', () => {+ it.each(dataframeNameCases)('$name', ({ markdown, owners }) => {+ const content = buildMarkdownNotebookContent(markdown)+ expect(+ Object.fromEntries(collectNotebookFrameNodes(content).map(({ name, nodeId }) => [name, nodeId]))+ ).toEqual(owners)+ const graph = buildNotebookDependencyGraph(content)+ expect(+ Object.fromEntries(graph.nodes.flatMap(({ nodeId, exports }) => exports.map((name) => [name, nodeId])))+ ).toEqual(owners)+ })+afterEach(() => {jest.restoreAllMocks()})diff --git a/frontend/src/scenes/notebooks/Nodes/notebookNodeContent.ts b/frontend/src/scenes/notebooks/Nodes/notebookNodeContent.tsindex dea2d0cd4104..53625415ea63 100644--- a/frontend/src/scenes/notebooks/Nodes/notebookNodeContent.ts+++ b/frontend/src/scenes/notebooks/Nodes/notebookNodeContent.ts@@ -4,6 +4,18 @@ import { JSONContent } from 'lib/components/RichContentEditor/types'import { NOTEBOOK_NODE_TYPE_TO_MARKDOWN_TAG, getSqlV2PropsFromQueryProp } from '../Notebook/markdownNotebookV2'import { NotebookNodeType } from '../types'+function isInsightDataframeNode(node: JSONContent): boolean {+ return (+ node.type === NotebookNodeType.Query &&+ !!(+ node.attrs?.id ||+ node.attrs?.query?.kind === 'InsightVizNode' ||+ node.attrs?.query?.kind === 'SavedInsightNode' ||+ node.attrs?.dataframeQuery+ )+ )+}+export type SqlV2NodeSummary = {nodeId: stringcode: string@@ -215,6 +227,9 @@ const expandMarkdownNotebookNodesOfTypes = (node: any, nodeTypes: NotebookNodeTyconst tag = NOTEBOOK_NODE_TYPE_TO_MARKDOWN_TAG[nodeType]if (tag) {nodeTypeByTag.set(tag, nodeType)+ if (nodeType === NotebookNodeType.Query) {+ nodeTypeByTag.set('Insight', nodeType)+ }}}return parseMarkdownNotebookNodeCached(node).nodes.flatMap((block): JSONContent[] => {@@ -245,54 +260,115 @@ const expandMarkdownNotebookNodesOfTypes = (node: any, nodeTypes: NotebookNodeTyconst expandMarkdownNotebookNodesOfType = (node: any, nodeType: NotebookNodeType): JSONContent[] =>expandMarkdownNotebookNodesOfTypes(node, [nodeType])-const expandMarkdownNotebookSqlV2Nodes = (node: any): JSONContent[] =>- expandMarkdownNotebookNodesOfType(node, NotebookNodeType.SQLV2)+export interface NotebookDataframeNode {+ node: JSONContent+ nodeId: string+ nodeIndex: number+ returnVariable: string+ exportedName: string+}++const dataframeNodesByContent = new WeakMap<object, NotebookDataframeNode[]>()-export const collectSqlV2Nodes = (content?: JSONContent | null): SqlV2NodeSummary[] => {+export function collectNotebookDataframeNodes(content?: JSONContent | null): NotebookDataframeNode[] {if (!content || typeof content !== 'object') {return []}-- const nodes: SqlV2NodeSummary[] = []- const usedReturnVariables = new Set<string>()-- const walk = (node: any): void => {+ const cached = dataframeNodesByContent.get(content)+ if (cached) {+ return cached+ }+ const nodes: NotebookDataframeNode[] = []+ const counters: Record<string, number> = {}+ const walk = (node: JSONContent): void => {if (!node || typeof node !== 'object') {return}- if (node.type === NotebookNodeType.SQLV2) {- const attrs = node.attrs ?? {}- const code = typeof attrs.code === 'string' ? attrs.code : ''- // A missing attribute predates the optional name (legacy default); an explicit- // blank or invalid one binds no dataframe (nothing can reference it).- const rawReturnVariable = typeof attrs.returnVariable === 'string' ? attrs.returnVariable : 'sql_df'- const returnVariable = isReferenceableSqlV2FrameName(rawReturnVariable)- ? buildUniqueSqlV2ReturnVariable(resolveSqlV2ReturnVariable(rawReturnVariable), usedReturnVariables)- : ''- if (returnVariable) {- usedReturnVariables.add(normalizeSqlIdentifier(returnVariable))- }+ if (+ (node.type === NotebookNodeType.SQLV2 ||+ node.type === NotebookNodeType.PythonV2 ||+ isInsightDataframeNode(node)) &&+ node.attrs?.nodeId+ ) {+ const type = node.type ?? ''+ counters[type] = (counters[type] ?? 0) + 1nodes.push({- nodeId: attrs.nodeId ?? '',- code,- returnVariable,- tablesUsed: extractDuckSqlTables(code),- sqlV2Index: nodes.length + 1,- title: typeof attrs.title === 'string' ? attrs.title : '',+ node,+ nodeId: node.attrs.nodeId,+ nodeIndex: counters[type],+ returnVariable: '',+ exportedName: '',})}if (node.type === NotebookNodeType.MarkdownNotebook) {- expandMarkdownNotebookSqlV2Nodes(node).forEach(walk)- }- if (Array.isArray(node.content)) {- node.content.forEach(walk)+ expandMarkdownNotebookNodesOfTypes(node, [+ NotebookNodeType.SQLV2,+ NotebookNodeType.PythonV2,+ NotebookNodeType.Query,+ ]).forEach(walk)}+ node.content?.forEach(walk)}-walk(content)+ const used = new Set<string>()+ for (const type of [NotebookNodeType.SQLV2, NotebookNodeType.Query, NotebookNodeType.PythonV2]) {+ for (const entry of nodes.filter(({ node }) => node.type === type)) {+ const attrs = entry.node.attrs ?? {}+ const baseName =+ typeof attrs.returnVariable === 'string'+ ? attrs.returnVariable.trim()+ : type === NotebookNodeType.Query+ ? 'insight_df'+ : type === NotebookNodeType.SQLV2+ ? 'sql_df'+ : 'df'+ entry.returnVariable = baseName+ if (+ !isReferenceableSqlV2FrameName(baseName) ||+ (type === NotebookNodeType.Query && !attrs.dataframeQuery?.trim())+ ) {+ continue+ }+ if (type === NotebookNodeType.PythonV2 && used.has(normalizeSqlIdentifier(baseName))) {+ continue+ }+ entry.returnVariable =+ type === NotebookNodeType.PythonV2 ? baseName : buildUniqueSqlV2ReturnVariable(baseName, used)+ entry.exportedName = entry.returnVariable+ used.add(normalizeSqlIdentifier(entry.returnVariable))+ }+ }+ for (const entry of nodes.filter(+ ({ node }) => node.type === NotebookNodeType.Query && !node.attrs?.dataframeQuery?.trim()+ )) {+ if (isReferenceableSqlV2FrameName(entry.returnVariable)) {+ entry.returnVariable = buildUniqueSqlV2ReturnVariable(entry.returnVariable, used)+ used.add(normalizeSqlIdentifier(entry.returnVariable))+ }+ }+ dataframeNodesByContent.set(content, nodes)return nodes}+export const collectSqlV2Nodes = (content?: JSONContent | null): SqlV2NodeSummary[] =>+ collectNotebookDataframeNodes(content)+ .filter(+ ({ node, exportedName }) =>+ node.type === NotebookNodeType.SQLV2 || (node.type === NotebookNodeType.Query && !!exportedName)+ )+ .map(({ node, nodeId, nodeIndex, exportedName }) => {+ const code =+ node.type === NotebookNodeType.Query ? (node.attrs?.dataframeQuery ?? '') : (node.attrs?.code ?? '')+ return {+ nodeId,+ code,+ returnVariable: exportedName,+ tablesUsed: extractDuckSqlTables(code),+ sqlV2Index: nodeIndex,+ title: node.attrs?.title ?? '',+ }+ })+export type NotebookFrameNodeSummary = {nodeId: stringname: string@@ -333,60 +409,18 @@ const frameNodeColumns = (result: any): [string, string][] => {* Names follow each collector's existing rules — SQL names disambiguated as the dependency* graph does, Python names left as the raw kernel variables.*/-export const collectNotebookFrameNodes = (content?: JSONContent | null): NotebookFrameNodeSummary[] => {- if (!content || typeof content !== 'object') {- return []- }-- const nodes: NotebookFrameNodeSummary[] = []- const usedReturnVariables = new Set<string>()-- const walk = (node: any): void => {- if (!node || typeof node !== 'object') {- return- }- if (node.type === NotebookNodeType.SQLV2 || node.type === NotebookNodeType.PythonV2) {- const attrs = node.attrs ?? {}- const isSql = node.type === NotebookNodeType.SQLV2- // A missing attribute predates the optional name (legacy 'sql_df'/'df' defaults);- // an explicit blank or invalid one binds no dataframe — nothing to browse.- const rawReturnVariable =- typeof attrs.returnVariable === 'string' ? attrs.returnVariable : isSql ? 'sql_df' : 'df'- let name: string | null- if (isSql) {- name = isReferenceableSqlV2FrameName(rawReturnVariable)- ? buildUniqueSqlV2ReturnVariable(resolveSqlV2ReturnVariable(rawReturnVariable), usedReturnVariables)- : null- if (name) {- usedReturnVariables.add(normalizeSqlIdentifier(name))- }- } else {- name = rawReturnVariable.trim()- }- if (name) {- const result = attrs.result ?? null- nodes.push({- nodeId: attrs.nodeId ?? '',- name,- nodeType: isSql ? 'sql' : 'python',- columns: frameNodeColumns(result),- rowCount: typeof result?.row_count === 'number' ? result.row_count : null,- hasRun: Boolean(result),- code: typeof attrs.code === 'string' ? attrs.code : '',- })- }- }- if (node.type === NotebookNodeType.MarkdownNotebook) {- expandMarkdownNotebookNodesOfTypes(node, [NotebookNodeType.SQLV2, NotebookNodeType.PythonV2]).forEach(walk)- }- if (Array.isArray(node.content)) {- node.content.forEach(walk)- }- }-- walk(content)- return nodes-}+export const collectNotebookFrameNodes = (content?: JSONContent | null): NotebookFrameNodeSummary[] =>+ collectNotebookDataframeNodes(content)+ .filter(({ exportedName }) => !!exportedName)+ .map(({ node, nodeId, exportedName }) => ({+ nodeId,+ name: exportedName,+ nodeType: node.type === NotebookNodeType.PythonV2 ? 'python' : 'sql',+ columns: frameNodeColumns(node.attrs?.result),+ rowCount: node.attrs?.result?.row_count ?? null,+ hasRun: !!node.attrs?.result,+ code: node.type === NotebookNodeType.Query ? (node.attrs?.dataframeQuery ?? '') : (node.attrs?.code ?? ''),+ }))export type PythonKernelNodeSummary = {nodeId: string@@ -490,78 +524,31 @@ export const buildNotebookDependencyGraph = (content?: JSONContent | null): Note}}- const nodes: NotebookDependencyNode[] = []- let pythonV2Index = 0- let sqlV2Index = 0- const usedSqlV2ReturnVariables = new Set<string>()-- const walk = (node: any): void => {- if (!node || typeof node !== 'object') {- return- }-- if (node.type === NotebookNodeType.SQLV2) {+ const nodes: NotebookDependencyNode[] = collectNotebookDataframeNodes(content).map(+ ({ node, nodeId, nodeIndex, returnVariable, exportedName }) => {const attrs = node.attrs ?? {}- sqlV2Index += 1- // Blank or invalid name = display-only cell: it exports nothing (see collectSqlV2Nodes).- const rawReturnVariable = typeof attrs.returnVariable === 'string' ? attrs.returnVariable : 'sql_df'- const returnVariable = isReferenceableSqlV2FrameName(rawReturnVariable)- ? buildUniqueSqlV2ReturnVariable(- resolveSqlV2ReturnVariable(rawReturnVariable),- usedSqlV2ReturnVariables- )- : ''- if (returnVariable) {- usedSqlV2ReturnVariables.add(normalizeSqlIdentifier(returnVariable))- }- const code = typeof attrs.code === 'string' ? attrs.code : ''+ const code = node.type === NotebookNodeType.Query ? (attrs.dataframeQuery ?? '') : (attrs.code ?? '')const connectionId =typeof attrs.connectionId === 'string' && attrs.connectionId ? attrs.connectionId : null- nodes.push({- nodeId: attrs.nodeId ?? '',- nodeType: NotebookNodeType.SQLV2,- nodeIndex: sqlV2Index,- title: typeof attrs.title === 'string' ? attrs.title : '',- exports: returnVariable ? [returnVariable] : [],- uses: extractDuckSqlTables(code),+ return {+ nodeId,+ nodeType: node.type as NotebookNodeType,+ nodeIndex,+ title: attrs.title ?? '',+ exports: exportedName ? [exportedName] : [],+ uses:+ node.type === NotebookNodeType.Query+ ? []+ : node.type === NotebookNodeType.PythonV2+ ? extractPythonIdentifiers(code)+ : extractDuckSqlTables(code),code,returnVariable,connectionId,sendRawQuery: !!connectionId && !!attrs.sendRawQuery,- })- }-- if (node.type === NotebookNodeType.PythonV2) {- const attrs = node.attrs ?? {}- pythonV2Index += 1- // The returnVariable IS the kernel variable, never disambiguated — the same- // last-write-wins semantics as collectPythonKernelNodes. Blank = exports nothing.- const returnVariable = typeof attrs.returnVariable === 'string' ? attrs.returnVariable.trim() : 'df'- const code = typeof attrs.code === 'string' ? attrs.code : ''- nodes.push({- nodeId: attrs.nodeId ?? '',- nodeType: NotebookNodeType.PythonV2,- nodeIndex: pythonV2Index,- title: typeof attrs.title === 'string' ? attrs.title : '',- exports: returnVariable ? [returnVariable] : [],- uses: extractPythonIdentifiers(code),- code,- returnVariable,- })- }-- if (node.type === NotebookNodeType.MarkdownNotebook) {- // Markdown notebooks (the only V2 surface) store cells as component tags, so both- // V2 cell types must be expanded in one pass to preserve dependency order.- expandMarkdownNotebookNodesOfTypes(node, [NotebookNodeType.SQLV2, NotebookNodeType.PythonV2]).forEach(walk)- }-- if (Array.isArray(node.content)) {- node.content.forEach(walk)+ }}- }-- walk(content)+ )const nodesById = nodes.reduce<Record<string, NotebookDependencyNode>>((acc, node) => {if (node.nodeId) {@@ -573,9 +560,9 @@ export const buildNotebookDependencyGraph = (content?: JSONContent | null): Noteconst upstreamSourcesByNode: Record<string, Record<string, NotebookDependencyUsage>> = {}const downstreamUsageByNode: Record<string, Record<string, NotebookDependencyUsage[]>> = {}- nodes.forEach((node, nodeIndex) => {- const upstreamNodes = nodes.slice(0, nodeIndex)- const downstreamNodes = nodes.slice(nodeIndex + 1)+ nodes.forEach((node) => {+ const upstreamNodes = nodes.filter((candidate) => candidate.nodeId !== node.nodeId)+ const downstreamNodes = upstreamNodesconst upstreamSources = node.uses.reduce<Record<string, NotebookDependencyUsage>>((acc, usageName) => {const source = upstreamNodes.find((upstreamNode) =>diff --git a/frontend/src/scenes/notebooks/Nodes/notebookNodeSQLV2Logic.test.ts b/frontend/src/scenes/notebooks/Nodes/notebookNodeSQLV2Logic.test.tsindex cda9b065aba7..3cdb34f3acd5 100644--- a/frontend/src/scenes/notebooks/Nodes/notebookNodeSQLV2Logic.test.ts+++ b/frontend/src/scenes/notebooks/Nodes/notebookNodeSQLV2Logic.test.ts@@ -330,30 +330,71 @@ describe('notebookNodeSQLV2Logic', () => {})})- it('maps a done envelope into the node result and stops the spinner', async () => {+ it.each([false, true])('loads a completed result (restoring metadata: %s)', async (hasResultMetadata) => {resultSpy.mockResolvedValue({status: 'done',result: { columns: ['a'], first_page: [[1]], row_count: 1, has_more: false },error: null,})- mount({ runId: 'r1', hasResult: false })+ mount({ runId: 'r1', hasResult: false, hasResultMetadata })await expectLogic(logic).toFinishAllListeners()- expect(updateAttributes).toHaveBeenCalledWith({- result: {- columns: ['a'],- types: [],- row_count: 1,- first_page: [[1]],- has_more: false,- stdout: '',- stderr: '',- media: [],- },- runStatus: 'done',+ expect(logic.values.result).toEqual({+ columns: ['a'],+ types: [],+ row_count: 1,+ first_page: [[1]],+ has_more: false,+ stdout: '',+ stderr: '',+ media: [],})+ if (hasResultMetadata) {+ expect(updateAttributes).not.toHaveBeenCalled()+ expect(logic.values.lastRunNodeId).toBeNull()+ } else {+ expect(updateAttributes).toHaveBeenCalledWith({+ result: {+ columns: ['a'],+ types: [],+ row_count: 1,+ has_more: false,+ first_page: [[1]],+ stdout: '',+ stderr: '',+ previewOnly: true,+ },+ runStatus: 'done',+ })+ }expect(logic.values.isRunning).toBe(false)})+ it.each(['failed', 'interrupted', 'unavailable'] as const)(+ 'keeps a %s saved-result load separate from execution',+ async (status) => {+ if (status === 'unavailable') {+ resultSpy.mockRejectedValue(new ApiError('Result not found', 404))+ } else {+ resultSpy.mockResolvedValue({ status, result: null, error: 'Old run failed' })+ }+ mount({ runId: 'saved', hasResultMetadata: true, hasResult: false })+ await expectLogic(logic).toFinishAllListeners()+ expect(logic.values.runError).toBeNull()+ expect(logic.values.lastRunNodeId).toBeNull()+ expect(logic.values.isRunning).toBe(false)+ expect(logic.values.isRestoringResult).toBe(false)+ expect(updateAttributes).not.toHaveBeenCalled()+ resultSpy.mockResolvedValue({+ status: 'done',+ result: { columns: ['a'], first_page: [[1]], row_count: 1 },+ error: null,+ })+ await logic.asyncActions.runQuery('select 1', {})+ await expectLogic(logic).toFinishAllListeners()+ expect(updateAttributes).toHaveBeenCalledWith(expect.objectContaining({ runStatus: 'done' }))+ }+ )+it('surfaces a failed run as an error', async () => {resultSpy.mockResolvedValue({ status: 'failed', result: null, error: 'no such table' })mount({ runId: 'r1', hasResult: false })@@ -372,10 +413,18 @@ describe('notebookNodeSQLV2Logic', () => {})mount({ runId: 'r1', hasResult: false })await expectLogic(logic).toFinishAllListeners()- // The outcome is persisted with the partial result: without it a reload can't tell this- // apart from a completed run, since both leave a result behind.+ expect(logic.values.result).toEqual(expect.objectContaining({ stdout: 'partial output' }))expect(updateAttributes).toHaveBeenCalledWith({- result: expect.objectContaining({ stdout: 'partial output' }),+ result: {+ columns: [],+ types: [],+ row_count: 0,+ has_more: false,+ first_page: [],+ stdout: 'partial output',+ stderr: '',+ previewOnly: true,+ },runStatus: 'interrupted',})expect(logic.values.runError).toBe('Run interrupted.')@@ -450,8 +499,7 @@ describe('notebookNodeSQLV2Logic', () => {runSpy.mockResolvedValueOnce({ run_id: 'r2' })logic.actions.runQuery('select 2')await expectLogic(logic).toFinishAllListeners()- const resultWrites = updateAttributes.mock.calls.map((c) => c[0]).filter((a) => a.result)- expect(resultWrites.at(-1).result).toEqual(expect.objectContaining({ columns: ['b'], first_page: [[2]] }))+ expect(logic.values.result).toEqual(expect.objectContaining({ columns: ['b'], first_page: [[2]] }))})it('ignores a stale poll from a previous run', async () => {@@ -482,6 +530,7 @@ describe('notebookNodeSQLV2Logic', () => {await expectLogic(logic).toFinishAllListeners()// The stale result must not overwrite the node, and r2's run must keep polling (not stopped).+ expect(logic.values.result).toBeNull()expect(updateAttributes).not.toHaveBeenCalledWith(expect.objectContaining({ result: expect.objectContaining({ columns: ['old'] }) }))diff --git a/frontend/src/scenes/notebooks/Nodes/notebookNodeSQLV2Logic.ts b/frontend/src/scenes/notebooks/Nodes/notebookNodeSQLV2Logic.tsindex b3d22dbd2fb9..06cabd82609b 100644--- a/frontend/src/scenes/notebooks/Nodes/notebookNodeSQLV2Logic.ts+++ b/frontend/src/scenes/notebooks/Nodes/notebookNodeSQLV2Logic.ts@@ -12,6 +12,7 @@ import {reducers,selectors,} from 'kea'+import posthog from 'posthog-js'import api from 'lib/api'import { ApiError } from 'lib/api-error'@@ -20,6 +21,8 @@ import { FEATURE_FLAGS } from 'lib/constants'import { lemonToast } from 'lib/lemon-ui/LemonToast/LemonToast'import { FeatureFlagsSet, featureFlagLogic } from 'lib/logic/featureFlagLogic'+import { notebookResultPreview } from 'products/notebooks/notebookResultPreview'+import { notebookKernelInfoLogic } from '../Notebook/notebookKernelInfoLogic'import {NotebookNodeRunTerminalStatus,@@ -33,8 +36,7 @@ import { sandboxStartMessage } from '../Notebook/SandboxStartMessage'import { NotebookNodeType } from '../types'import {buildNotebookDependencyGraph,- collectPythonKernelNodes,- collectSqlV2Nodes,+ collectNotebookDataframeNodes,extractDuckSqlTables,} from './notebookNodeContent'import { NotebookNodeSQLV2Result } from './NotebookNodeSQLV2'@@ -75,16 +77,9 @@ export function sqlV2RunErrorMessage(// supplies the wiring.export function collectSqlV2Refs(doc: JSONContent | null | undefined, selfNodeId: string): Record<string, SqlV2RunRef> {const refs: Record<string, SqlV2RunRef> = {}- for (const node of collectSqlV2Nodes(doc)) {- // An unnamed cell (blank dataframe name) is display-only: nothing can reference it.- if (node.nodeId && node.nodeId !== selfNodeId && node.returnVariable) {- refs[node.returnVariable] = { node_id: node.nodeId, kind: 'hogql' }- }- }- for (const node of collectPythonKernelNodes(doc)) {- // An unnamed python cell binds nothing in the kernel, so there is no frame to reference.- if (node.nodeId && node.nodeId !== selfNodeId && node.returnVariable && !(node.returnVariable in refs)) {- refs[node.returnVariable] = { node_id: node.nodeId, kind: 'local' }+ for (const { node, nodeId, exportedName } of collectNotebookDataframeNodes(doc)) {+ if (nodeId !== selfNodeId && exportedName) {+ refs[exportedName] = { node_id: nodeId, kind: node.type === NotebookNodeType.PythonV2 ? 'local' : 'hogql' }}}return refs@@ -150,8 +145,11 @@ export interface NotebookNodeSQLV2LogicProps {// Current node attributes, so a fresh mount can recover an in-flight/finished run by its runId.runId?: string | nullhasResult?: boolean+ hasResultMetadata?: boolean+ prepareInsightDataframes?: (code: string, nodeType: 'python' | 'hogql') => Promise<void>updateAttributes: (attrs: {nodeId?: string+ returnVariable?: stringrunId?: string | nullresult?: NotebookNodeSQLV2Result | nullrunStatus?: NotebookNodeRunTerminalStatus | null@@ -175,6 +173,7 @@ export interface notebookNodeSQLV2LogicValues {isBusy: boolean // notebookOperationsLogicdirectRows: NotebookNodeSQLV2DirectRows | nullisInterrupting: boolean+ isRestoringResult: booleanisRunning: booleanisSandboxComputeFree: booleanisStale: boolean@@ -184,6 +183,8 @@ export interface notebookNodeSQLV2LogicValues {pageResult: NotebookNodeSQLV2Page | nullpageSize: numberpendingKernelStart: boolean+ result: NotebookNodeSQLV2Result | null+ resultRestoreUnavailable: booleanrunError: string | nullstaleDownstreamCount: numberstaleReason: NotebookStaleReason | null@@ -240,6 +241,9 @@ export interface notebookNodeSQLV2LogicActions {resetPaging: () => {value: true}+ resultRestoreFailed: () => {+ value: true+ }runNode: (overrides?: RunNodeOverrides) => {overrides: RunNodeOverrides}@@ -276,10 +280,17 @@ export interface notebookNodeSQLV2LogicActions {setPendingKernelStart: (pendingKernelStart: boolean) => {pendingKernelStart: boolean}+ setResult: (result: NotebookNodeSQLV2Result | null) => {+ result: NotebookNodeSQLV2Result | null+ }setRunError: (runError: string | null) => {runError: string | null}- startPolling: (runId: string) => {+ startPolling: (+ runId: string,+ restoring?: boolean+ ) => {+ restoring: booleanrunId: string}stopPolling: () => {@@ -329,6 +340,7 @@ export const notebookNodeSQLV2Logic = kea<notebookNodeSQLV2LogicType>([],})),actions({+ setResult: (result: NotebookNodeSQLV2Result | null) => ({ result }),// refs maps each named sibling cell's dataframe name to {node id, kind}. A SQL node// inlines referenced hogql refs as CTEs (Journey 3) — or runs locally in DuckDB when// it references a local frame (Journey 5); a python node materializes the hogql refs@@ -343,7 +355,8 @@ export const notebookNodeSQLV2Logic = kea<notebookNodeSQLV2LogicType>([// every run trigger — the toolbar button, Cmd+Enter, a chain dispatch — so a cell runs the// same way whether or not its editor is on screen.runNode: (overrides: RunNodeOverrides = {}) => ({ overrides }),- startPolling: (runId: string) => ({ runId }),+ startPolling: (runId: string, restoring: boolean = false) => ({ runId, restoring }),+ resultRestoreFailed: true,pollResult: (runId: string) => ({ runId }),stopPolling: true,interruptRun: true,@@ -360,12 +373,27 @@ export const notebookNodeSQLV2Logic = kea<notebookNodeSQLV2LogicType>([announceSandboxStart: (hourlyPrice: number | null) => ({ hourlyPrice }),}),reducers({+ isRestoringResult: [+ false,+ { startPolling: (_, { restoring }) => restoring, stopPolling: () => false, runQuery: () => false },+ ],+ resultRestoreUnavailable: [+ false,+ { resultRestoreFailed: () => true, runQuery: () => false, startPolling: () => false },+ ],+ result: [+ null as NotebookNodeSQLV2Result | null,+ {+ runQuery: () => null,+ setResult: (_, { result }) => result,+ },+ ],// Tracks the run being in progress; driven by the run's status, not a socket lifecycle.isRunning: [false,{runQuery: () => true,- startPolling: () => true,+ startPolling: (_, { restoring }) => !restoring,setIsRunning: (_, { isRunning }) => isRunning,},],@@ -533,6 +561,12 @@ export const notebookNodeSQLV2Logic = kea<notebookNodeSQLV2LogicType>([setPage: loadCurrentPage,setPageSize: loadCurrentPage,runQuery: async ({ code, refs, opts }) => {+ if (cache.preparingInputs) {+ return+ }+ cache.isRestoringResult = false+ cache.activeRunId = null+ cache.disposables.dispose('pollResult')if (!code.trim()) {actions.setRunError('Nothing to run — type some code first.')actions.setIsRunning(false)@@ -552,6 +586,20 @@ export const notebookNodeSQLV2Logic = kea<notebookNodeSQLV2LogicType>([// and never when it targets an external connection (the sandbox can't reach one).// The backend stays authoritative — this only drives the kernel panel, never// dispatch.+ if (props.prepareInsightDataframes) {+ cache.preparingInputs = true+ try {+ await props.prepareInsightDataframes(code, opts.nodeType ?? 'hogql')+ refs = collectSqlV2Refs(props.getContent?.() ?? null, props.nodeId)+ } catch (error) {+ actions.setRunError(sqlV2RunErrorMessage(error, 'Could not prepare insight dataframes'))+ actions.setIsRunning(false)+ actions.nodeRunFinished(props.nodeId, 'failed', null)+ return+ } finally {+ cache.preparingInputs = false+ }+ }const isKernelLane =opts.nodeType === 'python' ||(!opts.connectionId && extractDuckSqlTables(code).some((name) => refs[name]?.kind === 'local'))@@ -601,6 +649,7 @@ export const notebookNodeSQLV2Logic = kea<notebookNodeSQLV2LogicType>([// would orphan this run's node_id and break refs to this cell.props.updateAttributes({nodeId: props.nodeId,+ ...(opts.outputName !== undefined ? { returnVariable: opts.outputName } : {}),runId: run_id,result: null,runStatus: null,@@ -651,9 +700,12 @@ export const notebookNodeSQLV2Logic = kea<notebookNodeSQLV2LogicType>([actions.runNode()}},- startPolling: ({ runId }) => {+ startPolling: ({ runId, restoring }) => {+ cache.isRestoringResult = restoring// Idempotent re-register: also covers a remount resuming a persisted in-flight run.- actions.startOperation(runOperation)+ if (!cache.isRestoringResult) {+ actions.startOperation(runOperation)+ }cache.activeRunId = runIdcache.pollWaitedMs = 0actions.pollResult(runId)@@ -682,6 +734,7 @@ export const notebookNodeSQLV2Logic = kea<notebookNodeSQLV2LogicType>([}, 'pollResult')},pollResult: async ({ runId }) => {+ const restoring = !!cache.isRestoringResultif (cache.pollInFlight) {return}@@ -692,9 +745,17 @@ export const notebookNodeSQLV2Logic = kea<notebookNodeSQLV2LogicType>([if (cache.pollWaitedMs > MAX_POLL_WAIT_MS) {// Past every backend budget, so the server is unreachable rather than slow.// The run keeps whatever outcome the server gave it; only this client gave up.- actions.setRunError('Stopped checking for a result. Reload the page to see if the run finished.')+ if (restoring) {+ actions.resultRestoreFailed()+ } else {+ actions.setRunError(+ 'Stopped checking for a result. Reload the page to see if the run finished.'+ )+ }actions.stopPolling()- actions.nodeRunFinished(props.nodeId, 'failed', null)+ if (!restoring) {+ actions.nodeRunFinished(props.nodeId, 'failed', null)+ }return}cache.pollInFlight = true@@ -727,6 +788,7 @@ export const notebookNodeSQLV2Logic = kea<notebookNodeSQLV2LogicType>([media: result.media ?? [],}: null+ const resultMetadata = envelopeResult ? notebookResultPreview(envelopeResult) : nullif (status === 'done') {// A direct run's full capped row set arrives with the result — keep it// in memory for client-side paging (kernel runs return no rows here).@@ -741,34 +803,58 @@ export const notebookNodeSQLV2Logic = kea<notebookNodeSQLV2LogicType>([)// The outcome rides along with the result so a reload can tell a completed// run from an interrupted one — both leave a result behind.- props.updateAttributes({ result: envelopeResult, runStatus: 'done' })+ actions.setResult(envelopeResult)+ if (!restoring) {+ props.updateAttributes({ result: resultMetadata, runStatus: 'done' })+ }// A fresh envelope replaces whatever page the user had drilled into.actions.resetPaging()actions.stopPolling()// Downstream cells now derive from outdated data — mark them stale// against the document as it stands now (Journey 10).- actions.nodeRunFinished(props.nodeId, 'done', props.getContent?.() ?? null)+ if (!restoring) {+ actions.nodeRunFinished(props.nodeId, 'done', props.getContent?.() ?? null)+ }} else if (status === 'interrupted') {// A user-requested stop: the envelope still carries whatever stdout,// stderr, and figures the cell produced before the interrupt landed.- props.updateAttributes({ result: envelopeResult, runStatus: 'interrupted' })- actions.setRunError(error ?? 'Run interrupted.')+ actions.setResult(envelopeResult)+ if (!restoring) {+ props.updateAttributes({ result: resultMetadata, runStatus: 'interrupted' })+ }+ if (!restoring) {+ actions.setRunError(error ?? 'Run interrupted.')+ }actions.resetPaging()actions.stopPolling()- actions.nodeRunFinished(props.nodeId, 'interrupted', null)+ if (!restoring) {+ actions.nodeRunFinished(props.nodeId, 'interrupted', null)+ }} else if (status === 'failed') {- actions.setRunError(error ?? 'Run failed')+ if (restoring) {+ actions.resultRestoreFailed()+ } else {+ actions.setRunError(error ?? 'Run failed')+ }actions.stopPolling()- actions.nodeRunFinished(props.nodeId, 'failed', null)+ if (!restoring) {+ actions.nodeRunFinished(props.nodeId, 'failed', null)+ }}// 'running' → keep polling} catch (error) {if (runId !== cache.activeRunId) {return}- actions.setRunError(sqlV2RunErrorMessage(error, 'Failed to fetch result'))+ if (restoring) {+ actions.resultRestoreFailed()+ } else {+ actions.setRunError(sqlV2RunErrorMessage(error, 'Failed to fetch result'))+ }actions.stopPolling()- actions.nodeRunFinished(props.nodeId, 'failed', null)+ if (!restoring) {+ actions.nodeRunFinished(props.nodeId, 'failed', null)+ }} finally {cache.pollInFlight = false}@@ -793,7 +879,14 @@ export const notebookNodeSQLV2Logic = kea<notebookNodeSQLV2LogicType>([lemonToast.error(error?.detail || error?.message || 'Failed to stop the run')}},+ resultRestoreFailed: () => {+ posthog.capture('notebook result restore failed', {+ notebook_short_id: props.notebookShortId,+ node_id: props.nodeId,+ })+ },stopPolling: () => {+ cache.isRestoringResult = falsecache.disposables.dispose('pollResult')actions.setIsRunning(false)actions.finishOperation(runOperation.id)@@ -810,7 +903,7 @@ export const notebookNodeSQLV2Logic = kea<notebookNodeSQLV2LogicType>([(s) => [s.activeOperation],(activeOperation: NotebookOperation | null): string | null =>activeOperation && activeOperation.nodeId !== props.nodeId- ? 'Another operation is running in this notebook'+ ? (activeOperation.label ?? 'Another operation is running in this notebook'): null,],// An upstream cell's run landed after this cell last ran (Journey 10).@@ -839,7 +932,7 @@ export const notebookNodeSQLV2Logic = kea<notebookNodeSQLV2LogicType>([// Recover after a reload/remount: a persisted runId with no result means the run may still be// in flight or already finished — poll to catch up rather than lose the result.if (props.runId && !props.hasResult) {- actions.startPolling(props.runId)+ actions.startPolling(props.runId, !!props.hasResultMetadata)}}),beforeUnmount(({ props, actions, values }) => {diff --git a/frontend/src/scenes/notebooks/Notebook/NotebookWidgetViews.stories.tsx b/frontend/src/scenes/notebooks/Notebook/NotebookWidgetViews.stories.tsxindex 6794c5cf4fa4..11612627fc21 100644--- a/frontend/src/scenes/notebooks/Notebook/NotebookWidgetViews.stories.tsx+++ b/frontend/src/scenes/notebooks/Notebook/NotebookWidgetViews.stories.tsx@@ -3,6 +3,7 @@ import { MOCK_DEFAULT_BASIC_USER } from 'lib/api.mock'import { Meta, StoryObj } from '@storybook/react'import { HttpResponse } from 'msw'+import { FEATURE_FLAGS } from 'lib/constants'import { App } from 'scenes/App'import dashboardFixture from 'scenes/dashboard/__mocks__/dashboard.json'import { recordingMetaJson } from 'scenes/session-recordings/__mocks__/recording_meta'@@ -325,9 +326,41 @@ const meta: Meta = {decorators: [mswDecorator({get: {+ '/api/projects/:team_id/notebooks/:short_id/sql_v2/runs/:run_id': {+ status: 'done',+ result: {+ columns: ['event', 'count'],+ types: [+ ['event', 'String'],+ ['count', 'Int64'],+ ],+ row_count: 1,+ },+ rows: [['$pageview', 42]],+ error: null,+ },+ '/api/projects/:team_id/notebooks/kernel/compute_options': {+ currency: 'USD',+ cpu_rate_per_core_hour: 0.2,+ memory_rate_per_gb_hour: 0.025,+ default_preset_key: 'small',+ presets: [+ {+ key: 'small',+ name: 'Small',+ description: 'Exploring data and working with small dataframes.',+ cpu_cores: 1,+ memory_gb: 2,+ hourly_price: 0.25,+ },+ ],+ allowed_cpu_cores: [1],+ allowed_memory_gb: [2],+ allowed_idle_timeout_seconds: [3600],+ },'/api/projects/:team_id/notebooks/:short_id': ({ params }) => [200,- notebooks[params.short_id as keyof typeof notebooks],+ { ...notebooks[params.short_id as keyof typeof notebooks], short_id: params.short_id },],[`/api/projects/:team_id/feature_flags/${FEATURE_FLAG_ID}/`]: featureFlag,[`/api/projects/:team_id/feature_flags/${FEATURE_FLAG_ID}/status`]: {@@ -349,6 +382,7 @@ const meta: Meta = {[`/api/projects/:team_id/cohorts/${COHORT_ID}/`]: cohort,[`/api/environments/:team_id/insights/${INSIGHT_ID}/`]: insight,[`/api/projects/:team_id/insights/${INSIGHT_ID}/`]: insight,+ '/api/environments/:team_id/insights/': { results: [insight], count: 1, next: null, previous: null },'/api/environments/:team_id/session_recordings/:id': recording,'/api/environments/:team_id/session_recordings/:id/snapshots': ({ request }) => {if (new URL(request.url).searchParams.get('source') === 'blob_v2') {@@ -403,12 +437,30 @@ const meta: Meta = {'/api/environments/:team_id/default_release_conditions/': [],},patch: {+ '/api/projects/:team_id/notebooks/:short_id': async ({ params, request }) => ({+ ...notebooks[params.short_id as keyof typeof notebooks],+ short_id: params.short_id,+ ...((await request.json()) as Record<string, unknown>),+ }),'/api/projects/:team_id/session_recording_playlists/:playlist_id': async ({ request }) => {const body = (await request.json()) as Record<string, unknown>return { ...playlist, ...body }},},post: {+ '/api/projects/:team_id/notebooks/:short_id/collab/markdown_save': async ({ params, request }) => {+ const body = (await request.json()) as Record<string, unknown> & { version: number }+ return {+ ...notebooks[params.short_id as keyof typeof notebooks],+ short_id: params.short_id,+ ...body,+ version: body.version + 1,+ }+ },+ '/api/projects/:team_id/notebooks/:short_id/sql_v2/run': async ({ request }) => {+ const body = (await request.json()) as { node_id: string }+ return { run_id: `run-${body.node_id}`, starts_sandbox: false }+ },'/api/projects/:team_id/session_recording_playlists/:playlist_id/playlist_viewed': { success: true },'/api/environments/:team_id/query/:kind': async ({ request }) => {const body = (await request.json()) as {@@ -416,6 +468,9 @@ const meta: Meta = {}const query = body.query+ if (query?.kind === NodeKind.TrendsQuery) {+ return { results: insight.result, hogql: 'SELECT event, count() FROM events GROUP BY event' }+ }if (query?.kind === NodeKind.TraceQuery) {return { results: [traceWithoutContent] }}@@ -463,7 +518,10 @@ export const EarlyAccessFeatureViews: Story = {}export const CohortViews: Story = { parameters: { pageUrl: urls.notebook('cohort-widget-views') } }export const InsightViews: Story = {- parameters: { pageUrl: urls.notebook('insight-widget-views') },+ parameters: {+ pageUrl: urls.notebook('insight-widget-views'),+ featureFlags: [FEATURE_FLAGS.REVAMPED_PY_NOTEBOOKS],+ },play: async ({ canvasElement }) => {await waitFor(() => {expect(diff --git a/frontend/src/scenes/notebooks/Notebook/markdownNotebookRegistry.test.tsx b/frontend/src/scenes/notebooks/Notebook/markdownNotebookRegistry.test.tsxindex 5371597daf4f..7eb9b6d534eb 100644--- a/frontend/src/scenes/notebooks/Notebook/markdownNotebookRegistry.test.tsx+++ b/frontend/src/scenes/notebooks/Notebook/markdownNotebookRegistry.test.tsx@@ -9,7 +9,9 @@ import {import {type ComponentPanelVisibility,getInsertedComponentPanelVisibility,+ withPersistedComponentPanelProps,} from 'lib/components/MarkdownNotebook/componentPanels'+import { parseMarkdownNotebook } from 'lib/components/MarkdownNotebook/markdown'import { NotebookComponentShell } from 'lib/components/MarkdownNotebook/NotebookComponentShell'import type { NotebookComponentBlockNode } from 'lib/components/MarkdownNotebook/types'import { FEATURE_FLAGS } from 'lib/constants'@@ -71,6 +73,18 @@ function getInsertCommandsByLabel(}describe('markdownNotebookRegistry', () => {+ it.each([undefined, 'saved-widget'])('pins widget identity when opening filters (explicit ID: %s)', (nodeId) => {+ const node = parseMarkdownNotebook(`<Widget prompt="Draw a chart"${nodeId ? ` nodeId="${nodeId}"` : ''} />`)+ .nodes[0] as NotebookComponentBlockNode+ const updated = withPersistedComponentPanelProps(node, NOTEBOOK_MARKDOWN_REGISTRY.components.Widget, {+ filters: true,+ results: true,+ })++ expect(updated.props.nodeId).toBe(nodeId ?? node.id)+ expect(updated.props.showFilters).toBe(true)+ })+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@@ -125,10 +139,16 @@ describe('markdownNotebookRegistry', () => {noop)+ commands.find((command) => command.key === commandKey)?.run('target-node')commands.find((command) => command.key === commandKey)?.run('target-node')- expect(insertedNodes).toHaveLength(1)+ expect(insertedNodes).toHaveLength(2)+ expect(insertedNodes[0].props.nodeId).not.toEqual(insertedNodes[1].props.nodeId)expect(getInsertedComponentPanelVisibility(insertedNodes[0]).filters).toBe(true)+ if (_label !== 'Widget') {+ expect(insertedNodes[0].props.returnVariable).toMatch(/^[A-Za-z_][A-Za-z0-9_]*$/)+ expect(insertedNodes[0].props.returnVariable).not.toEqual(insertedNodes[1].props.returnVariable)+ }})})@@ -450,6 +470,19 @@ describe('markdownNotebookRegistry', () => {)})+ it.each(['Query', 'Insight'])('assigns distinct render IDs to identical ID-less %s blocks', (tagName) => {+ const nodes = parseMarkdownNotebook(`<${tagName} id="example" />\n\n<${tagName} id="example" />`)+ .nodes as NotebookComponentBlockNode[]+ const attributes = nodes.map((node) =>+ getNodeAttributes(node.props, node.id, KNOWN_NODES[NotebookNodeType.Query], NotebookNodeType.Query, false)+ )++ expect(attributes.map(({ nodeId }) => nodeId)).toEqual(nodes.map(({ id }) => id))+ expect(attributes[0].nodeId).toBeTruthy()+ expect(attributes[1].nodeId).toBeTruthy()+ expect(attributes[0].nodeId).not.toEqual(attributes[1].nodeId)+ })+it('renders a SQL cell whose query arrived as a query prop', () => {// Regression: a `<SQLV2 query={…} />` cell (the shape AI-authored notebooks use) has no// `code` prop, so the editor rendered blank with no way to see or run the query.diff --git a/frontend/src/scenes/notebooks/Notebook/markdownNotebookRegistry.tsx b/frontend/src/scenes/notebooks/Notebook/markdownNotebookRegistry.tsxindex 69c2a059c6ed..1de5e103da66 100644--- a/frontend/src/scenes/notebooks/Notebook/markdownNotebookRegistry.tsx+++ b/frontend/src/scenes/notebooks/Notebook/markdownNotebookRegistry.tsx@@ -211,6 +211,12 @@ const INLINE_QUERY_NOTEBOOK_NODE_OPTIONS: CreatePostHogWidgetNodeOptions<any> =isDefaultFilterApplied: KNOWN_NODES[NotebookNodeType.Query].attributes.isDefaultFilterApplied,showSettings: KNOWN_NODES[NotebookNodeType.Query].attributes.showSettings,outputTab: KNOWN_NODES[NotebookNodeType.Query].attributes.outputTab,+ returnVariable: KNOWN_NODES[NotebookNodeType.Query].attributes.returnVariable,+ dataframeSource: KNOWN_NODES[NotebookNodeType.Query].attributes.dataframeSource,+ dataframeQuery: KNOWN_NODES[NotebookNodeType.Query].attributes.dataframeQuery,+ runId: KNOWN_NODES[NotebookNodeType.Query].attributes.runId,+ result: KNOWN_NODES[NotebookNodeType.Query].attributes.result,+ runStatus: KNOWN_NODES[NotebookNodeType.Query].attributes.runStatus,},defaultView: undefined,views: undefined,@@ -260,11 +266,15 @@ export const MARKDOWN_NODE_DEFINITIONS: {category: COMMON_INSERT_COMMAND_CATEGORY,badge: 'New',aliases: ['python', 'py'],- defaultProps: () => ({- ...getDefaultPropsForNodeType(NotebookNodeType.PythonV2),- ...INPUT_PANEL_OPEN_PROPS,- nodeId: uuid(),- }),+ defaultProps: () => {+ const nodeId = uuid()+ return {+ ...getDefaultPropsForNodeType(NotebookNodeType.PythonV2),+ ...INPUT_PANEL_OPEN_PROPS,+ nodeId,+ returnVariable: `df_${nodeId.slice(0, 8)}`,+ }+ },},},// insertCommand makes it show in the markdown insert menu; the feature-flag gate in@@ -283,11 +293,15 @@ export const MARKDOWN_NODE_DEFINITIONS: {// New cells get a durable nodeId up front: parsed markdown block ids are content// fingerprints, so without a persisted id every prop change (running the cell// writes runId/result) would orphan the cell's run history and cross-cell refs.- defaultProps: () => ({- ...getDefaultPropsForNodeType(NotebookNodeType.SQLV2),- ...INPUT_PANEL_OPEN_PROPS,- nodeId: uuid(),- }),+ defaultProps: () => {+ const nodeId = uuid()+ return {+ ...getDefaultPropsForNodeType(NotebookNodeType.SQLV2),+ ...INPUT_PANEL_OPEN_PROPS,+ nodeId,+ returnVariable: `sql_df_${nodeId.slice(0, 8)}`,+ }+ },},},{@@ -356,6 +370,7 @@ export const NOTEBOOK_MARKDOWN_REGISTRY: NotebookComponentRegistry = createMarkdToolbarComponent: definition.ToolbarComponent,exclusiveEditPanel: definition.exclusiveEditPanel,editableTitle: options?.editableTitle,+ persistNodeId: ['Widget', 'SQLV2', 'PythonV2', 'Insight', 'Query'].includes(definition.tagName),// Nodes with a Settings panel keep their filters toggle on read-only canvases// (customer profiles), where the panel is the only way to configure them.viewModeFilters: !!options?.Settings,diff --git a/frontend/src/scenes/notebooks/Notebook/notebookOperationsLogic.ts b/frontend/src/scenes/notebooks/Notebook/notebookOperationsLogic.tsindex 5cd3559702d0..3fc9a9ed0db6 100644--- a/frontend/src/scenes/notebooks/Notebook/notebookOperationsLogic.ts+++ b/frontend/src/scenes/notebooks/Notebook/notebookOperationsLogic.ts@@ -9,6 +9,7 @@ export type NotebookOperation = {id: stringnodeId: stringkind: 'run' | 'page'+ label?: string}// Generated by kea-typegen. Update if you're an agent, ignore if you're human.diff --git a/posthog/api/test/notebooks/test_notebook.py b/posthog/api/test/notebooks/test_notebook.pyindex 60f91e26d8e7..fed2eacc5947 100644--- a/posthog/api/test/notebooks/test_notebook.py+++ b/posthog/api/test/notebooks/test_notebook.py@@ -289,17 +289,10 @@ class TestNotebooks(APIBaseTest, QueryMatchingTest):"cannot be stored as a markdown notebook",),(- "rich_text_over_the_cell_limit",- {- "type": "doc",- "content": [- {- "type": "ph-query",- "attrs": {"nodeId": f"q{i}", "query": {"kind": "SavedInsightNode", "shortId": "abc"}},- }- for i in range(51)- ],- },+ "markdown_over_the_cell_limit",+ build_markdown_notebook_content(+ "\n\n".join(f'<SQLV2 nodeId="s{i}" code="select 1" />' for i in range(51))+ ),"limit of 50 cells",),]diff --git a/products/customer_analytics/backend/test/test_views.py b/products/customer_analytics/backend/test/test_views.pyindex 1ae577e0938e..aabb5be93a0c 100644--- a/products/customer_analytics/backend/test/test_views.py+++ b/products/customer_analytics/backend/test/test_views.py@@ -1346,17 +1346,10 @@ class TestAccountNotebookViewSet(APIBaseTest):},),(- "rich_text_over_the_cell_limit",- {- "type": "doc",- "content": [- {- "type": "ph-query",- "attrs": {"nodeId": f"q{i}", "query": {"kind": "SavedInsightNode", "shortId": "abc"}},- }- for i in range(51)- ],- },+ "markdown_over_the_cell_limit",+ build_markdown_notebook_content(+ "\n\n".join(f'<SQLV2 nodeId="s{i}" code="select 1" />' for i in range(51))+ ),),])diff --git a/products/notebooks/backend/models.py b/products/notebooks/backend/models.pyindex 3bf1e8d1945d..b0976bb44d0c 100644--- a/products/notebooks/backend/models.py+++ b/products/notebooks/backend/models.py@@ -229,8 +229,8 @@ class NotebookNodeRun(TeamScopedRootMixin, UUIDModel):# Who ran it. Kernels are per user, so this is the second half of a KernelRuntime's scope —# the callback needs it to file the frame snapshot without a user-blind lookup by id.# db_constraint=False: a real FK to the hot posthog_user table locks it on deploy.- # db_index=False: nothing queries runs by user — it is only ever read off a run we already- # hold. DO_NOTHING keeps that true: SET_NULL would have Django's collector issue an+ # db_index=False: user-scoped lookups also filter by the indexed notebook and node.+ # DO_NOTHING avoids having Django's collector issue an# `UPDATE … WHERE user_id = …` against this unindexed column on every user delete, on the# table that grows fastest. Nothing enforces referential integrity here anyway# (db_constraint=False), and a dangling id already reads back as None.diff --git a/products/notebooks/backend/presentation/views/notebook.py b/products/notebooks/backend/presentation/views/notebook.pyindex 5398d2923ab3..4552d47346bb 100644--- a/products/notebooks/backend/presentation/views/notebook.py+++ b/products/notebooks/backend/presentation/views/notebook.py@@ -1,6 +1,7 @@import mathimport hashlibfrom collections import Counter+from datetime import timedeltafrom typing import Any, castfrom django.conf import settings@@ -1826,18 +1827,25 @@ class NotebookViewSet(TeamAndOrgViewSetMixin, AccessControlViewSetMixin, ForbidDdescription=("Dispatch an asynchronous run of a notebook SQL or Python cell. Returns a run_id immediately; ""poll the run result endpoint until the status is terminal. One run at a time per notebook. "- "Flag-gated (revamped-py-notebooks)."+ "Python notebooks enable all run types. Generated widgets enable HogQL runs without a connection or kernel."),)@action(methods=["POST"], url_path="sql_v2/run", detail=True, required_scopes=["notebook:write", "query:read"])def sql_v2_run(self, request: Request, **kwargs):user = self._current_user()# Server-side gate is permissive in local dev (frontend still gates the UI); prod is flag-gated.- if not (settings.DEBUG or is_sql_v2_enabled(user)):+ full_compute_enabled = settings.DEBUG or is_sql_v2_enabled(user)+ if not full_compute_enabled and not is_notebook_widget_enabled(user):raise Http404()serializer = NotebookSQLV2RunRequestSerializer(data=request.data)serializer.is_valid(raise_exception=True)+ if not full_compute_enabled and (+ serializer.validated_data["node_type"] != "hogql"+ or serializer.validated_data.get("connection_id") is not None+ or any(ref["kind"] == "local" for ref in serializer.validated_data["refs"].values())+ ):+ raise Http404()notebook = self._get_notebook_for_kernel()self._require_query_access()@@ -1941,6 +1949,42 @@ class NotebookViewSet(TeamAndOrgViewSetMixin, AccessControlViewSetMixin, ForbidDexcept (SQLV2ReferenceError, NotebookVariableError, ExposedHogQLError) as e:return Response({"detail": str(e)}, status=400)+ if not full_compute_enabled and plan.node_type != "hogql":+ raise Http404()++ reusable_runs = (+ NotebookNodeRun.objects.for_team(self.team_id)+ .filter(+ notebook=notebook,+ user=user,+ node_id=serializer.validated_data["node_id"],+ code=plan.code,+ node_type="hogql",+ connection_id__isnull=True,+ status__in=[NotebookNodeRun.Status.RUNNING, NotebookNodeRun.Status.DONE],+ created_at__gte=now() - timedelta(hours=1),+ )+ .order_by("-created_at")+ if serializer.validated_data["reuse_results"]+ and user is not None+ and plan.node_type == "hogql"+ and connection_id is None+ else None+ )++ def reused_response() -> Response | None:+ existing_run = reusable_runs.first() if reusable_runs is not None else None+ if existing_run is None:+ return None+ return Response(+ NotebookSQLV2RunResponseSerializer(+ {"run_id": str(existing_run.id), "starts_sandbox": False, "sandbox_hourly_price": None}+ ).data+ )++ if cached_response := reused_response():+ return cached_response+# Taken before the row exists, so a refused dispatch writes nothing: an agent retrying# into a full ceiling must not leave a trail of rows behind it. The id is minted here# because the slot is keyed on it and has to be released by the run that took it.@@ -1950,6 +1994,8 @@ class NotebookViewSet(TeamAndOrgViewSetMixin, AccessControlViewSetMixin, ForbidDtry:acquire_run_slots(self.team_id, notebook.short_id, str(new_run_id))except NotebookRunBusy as e:+ if cached_response := reused_response():+ return cached_response# 409, not 429: a conflict with the notebook's state rather than a rate. The MCP# client retries every 429 with backoff and then replaces the body with its own# rate-limit message, so a 429 here would cost an agent seconds of pointless waiting@@ -1958,6 +2004,10 @@ class NotebookViewSet(TeamAndOrgViewSetMixin, AccessControlViewSetMixin, ForbidDexcept TeamRunCapacityFull as e:return Response({"detail": str(e)}, status=429)+ if cached_response := reused_response():+ release_run_slots(self.team_id, notebook.short_id, str(new_run_id))+ return cached_response+try:run = NotebookNodeRun.objects.create(id=new_run_id,@@ -2055,7 +2105,7 @@ class NotebookViewSet(TeamAndOrgViewSetMixin, AccessControlViewSetMixin, ForbidDdescription=("Read a run's durable state: its status, and — once done or interrupted — the result envelope ""(columns, first rows, stdout/stderr, media, error). Poll until terminal. "- "Flag-gated (revamped-py-notebooks)."+ "Requires notebook and query read access, including after a notebook feature flag is disabled."),)@action(@@ -2068,7 +2118,7 @@ class NotebookViewSet(TeamAndOrgViewSetMixin, AccessControlViewSetMixin, ForbidD# The node short-polls this durable read to learn when its run finishes. One indexed# query, no held connection — resilient to reloads/remounts (see sql_v2_result_delivery.md).user = self._current_user()- if not (settings.DEBUG or is_sql_v2_enabled(user)) or run_id is None:+ if run_id is None:raise Http404()# Scope to the notebook (via get_object → per-notebook access control), not just thediff --git a/products/notebooks/backend/sql_v2_serializers.py b/products/notebooks/backend/sql_v2_serializers.pyindex ef5be869988d..f9e01bfe617e 100644--- a/products/notebooks/backend/sql_v2_serializers.py+++ b/products/notebooks/backend/sql_v2_serializers.py@@ -119,6 +119,11 @@ class NotebookSQLV2NodeType(models.TextChoices):class NotebookSQLV2RunRequestSerializer(serializers.Serializer):+ reuse_results = serializers.BooleanField(+ required=False,+ default=False,+ help_text="Reuse the requesting user's running or completed HogQL run with the same cell and resolved query from the last hour. Does not apply to token-only callers, kernel runs, or connection runs.",+ )node_id = serializers.CharField(help_text="ProseMirror node id of the SQLV2 node being run.")node_type = serializers.ChoiceField(choices=NotebookSQLV2NodeType.choices,@@ -420,7 +425,7 @@ class NotebookCellStateSerializer(serializers.Serializer):node_id = serializers.CharField(help_text="Durable cell identity, used by the cell run and edit endpoints.")cell_type = serializers.CharField(help_text=(- "Cell kind: 'sql', 'python', 'saved_insight' (embedded insight, never runs), or "+ "Cell kind: 'sql', 'python', 'saved_insight' (an insight with an optional prepared dataframe), or ""'markdown' (prose, a heading, or a fenced block; never runs and joins no dependency graph)."))diff --git a/products/notebooks/backend/sql_v2_state.py b/products/notebooks/backend/sql_v2_state.pyindex a9514d9fe2d1..aa458a0f6e13 100644--- a/products/notebooks/backend/sql_v2_state.py+++ b/products/notebooks/backend/sql_v2_state.py@@ -34,7 +34,7 @@ from products.notebooks.backend.util import (iter_markdown_blocks,)-_CELL_TAGS = {"SQLV2": "sql", "PythonV2": "python", "Query": "saved_insight"}+_CELL_TAGS = {"SQLV2": "sql", "PythonV2": "python", "Query": "saved_insight", "Insight": "saved_insight"}# Prose sits outside the runnable-cell ceiling below, so this is the only bound on how many# cells one save can turn into. The reader is an agent that pays context for every block it is@@ -83,8 +83,12 @@ def extract_cells(content: Any) -> list[NotebookCellState]:node_id = props.get("nodeId")if not isinstance(node_id, str) or not node_id:continue- code = props.get("code")+ code = props.get("dataframeQuery") if cell_type == "saved_insight" else props.get("code")dataframe_name = props.get("returnVariable")+ if not isinstance(dataframe_name, str):+ dataframe_name = {"sql": "sql_df", "python": "df", "saved_insight": "insight_df"}[cell_type]+ if cell_type == "saved_insight" and not (isinstance(code, str) and code.strip()):+ dataframe_name = ""cells.append(NotebookCellState(node_id=node_id,@@ -93,6 +97,17 @@ def extract_cells(content: Any) -> list[NotebookCellState]:code=code if isinstance(code, str) else "",))+ used_names: set[str] = set()+ for cell_type in ("sql", "saved_insight"):+ for cell in cells:+ if cell.cell_type != cell_type or not _DATAFRAME_NAME.fullmatch(cell.dataframe_name):+ continue+ base_name = cell.dataframe_name+ suffix = 2+ while cell.dataframe_name.lower() in used_names:+ cell.dataframe_name = f"{base_name}_{suffix}"+ suffix += 1+ used_names.add(cell.dataframe_name.lower())return cells@@ -103,8 +118,9 @@ def validate_cell_count(previous_content: Any, next_content: Any) -> None:or by a path that predates it — stays editable, so its owner can delete cells down insteadof finding every save rejected. A save that leaves the count unchanged always passes."""- next_count = len(extract_cells(next_content))- if next_count <= MAX_NOTEBOOK_CELLS or next_count <= len(extract_cells(previous_content)):+ next_count = sum(cell.cell_type != "saved_insight" for cell in extract_cells(next_content))+ previous_count = sum(cell.cell_type != "saved_insight" for cell in extract_cells(previous_content))+ if next_count <= MAX_NOTEBOOK_CELLS or next_count <= previous_count:returnraise NotebookCellLimitExceeded(f"This notebook is at its limit of {MAX_NOTEBOOK_CELLS} cells. "@@ -131,16 +147,24 @@ def _referenced_names(cell: NotebookCellState, candidates: set[str]) -> set[str]return set()+def get_dataframe_owners(cells: list[NotebookCellState]) -> dict[str, str]:+ eligible_cells = [cell for cell in cells if _DATAFRAME_NAME.fullmatch(cell.dataframe_name)]+ preferred_owners: dict[str, str] = {}+ for cell_type in ("sql", "saved_insight", "python"):+ for cell in eligible_cells:+ if cell.cell_type == cell_type:+ preferred_owners.setdefault(cell.dataframe_name.lower(), cell.node_id)+ owners: dict[str, str] = {}+ for cell in eligible_cells:+ if preferred_owners.get(cell.dataframe_name.lower()) == cell.node_id:+ owners.setdefault(cell.dataframe_name, cell.node_id)+ return owners++def build_dependency_edges(cells: list[NotebookCellState]) -> None:"""Populate depends_on/dependents in place. Names follow the run-ref convention:SQL cells win dataframe-name collisions, unnamed cells export nothing."""- owner_by_name: dict[str, str] = {}- for cell in cells:- if cell.cell_type == "sql" and _DATAFRAME_NAME.match(cell.dataframe_name):- owner_by_name.setdefault(cell.dataframe_name, cell.node_id)- for cell in cells:- if cell.cell_type == "python" and _DATAFRAME_NAME.match(cell.dataframe_name):- owner_by_name.setdefault(cell.dataframe_name, cell.node_id)+ owner_by_name = get_dataframe_owners(cells)by_node: dict[str, NotebookCellState] = {cell.node_id: cell for cell in cells}for cell in cells:@@ -164,7 +188,9 @@ def _is_stale(upstream = cells_by_node[upstream_id]upstream_run = latest_done_by_node.get(upstream_id)refs[upstream.dataframe_name] = (- upstream_run.code if upstream_run is not None and upstream.cell_type == "sql" else None+ upstream_run.code+ if upstream_run is not None and upstream.cell_type in ("sql", "saved_insight")+ else None)try:# Same order as dispatch (resolve_sql_node_run): variables bind before the CTE@@ -196,26 +222,23 @@ def _is_stale(def annotate_run_state(cells: list[NotebookCellState], team_id: int, notebook: Any) -> None:- runnable_ids = [cell.node_id for cell in cells if cell.cell_type in ("sql", "python")]+ runnable_ids = [cell.node_id for cell in cells if cell.cell_type in ("sql", "python", "saved_insight")]if not runnable_ids:return- latest_by_node: dict[str, NotebookNodeRun] = {}- latest_done_by_node: dict[str, NotebookNodeRun] = {}runs = (NotebookNodeRun.objects.for_team(team_id).filter(notebook=notebook, node_id__in=runnable_ids).order_by("node_id", "-created_at"))- for run in runs:- if run.node_id not in latest_by_node:- latest_by_node[run.node_id] = run- if run.status == NotebookNodeRun.Status.DONE and run.node_id not in latest_done_by_node:- latest_done_by_node[run.node_id] = run+ latest_by_node = {run.node_id: run for run in runs.distinct("node_id")}+ latest_done_by_node = {+ run.node_id: run for run in runs.filter(status=NotebookNodeRun.Status.DONE).distinct("node_id")+ }cells_by_node = {cell.node_id: cell for cell in cells}variables = build_notebook_variables(notebook.variables or [])for cell in cells:- if cell.cell_type not in ("sql", "python"):+ if cell.cell_type not in ("sql", "python", "saved_insight"):continuelatest = latest_by_node.get(cell.node_id)if latest is None:diff --git a/products/notebooks/backend/test/test_sql_v2.py b/products/notebooks/backend/test/test_sql_v2.pyindex 4b3fb1037fc6..c84b541c0b78 100644--- a/products/notebooks/backend/test/test_sql_v2.py+++ b/products/notebooks/backend/test/test_sql_v2.py@@ -17,7 +17,7 @@ from typing import Anyimport time_machinefrom posthog.test.base import APIBaseTest-from unittest.mock import patch+from unittest.mock import Mock, patchfrom django.conf import settingsfrom django.core import signing@@ -61,6 +61,7 @@ from products.notebooks.backend.sql_v2 import (dispatch_sql_v2_run,ensure_sql_v2_server,fetch_sql_v2_page,+ is_sql_v2_enabled,kernel_server_secret,mint_callback_token,mint_command_token,@@ -447,6 +448,70 @@ class TestSQLV2Run(APIBaseTest):mock_start.assert_not_called()self.assertFalse(KernelRuntime.objects.filter(team=self.team).exists())+ @parameterized.expand(+ [+ ("hogql", {"code": "select 1"}, 200),+ ("python", {"code": "1", "node_type": "python"}, 404),+ ("local_ref", {"code": "select * from df", "refs": {"df": {"node_id": "p", "kind": "local"}}}, 404),+ ("connection", {"code": "select 1", "connection_id": "00000000-0000-0000-0000-000000000001"}, 404),+ ]+ )+ @override_settings(DEBUG=False)+ @patch("products.notebooks.backend.presentation.views.notebook.is_sql_v2_enabled", return_value=False)+ @patch("products.notebooks.backend.presentation.views.notebook.is_notebook_widget_enabled", return_value=True)+ @patch("products.notebooks.backend.presentation.views.notebook.enqueue_direct_run")+ @patch("products.notebooks.backend.presentation.views.notebook.start_sql_v2_run_workflow")+ def test_widget_only_access(self, _name, payload, expected_status, start_workflow, enqueue, _widget, _python):+ response = self.client.post(self.run_url, data={"node_id": "n1", **payload}, format="json")+ assert response.status_code == expected_status+ assert enqueue.call_count == (1 if expected_status == 200 else 0)+ start_workflow.assert_not_called()+ assert not KernelRuntime.objects.filter(team=self.team).exists()++ @parameterized.expand(+ [+ ("running", "self", True),+ ("done", "self", True),+ ("failed", "self", False),+ ("interrupted", "self", False),+ ("running", "collaborator", False),+ ("done", "collaborator", False),+ ("running", "unknown", False),+ ("done", "unknown", False),+ ("done", "token", False),+ ]+ )+ @patch("products.notebooks.backend.presentation.views.notebook.is_sql_v2_enabled", return_value=True)+ @patch("products.notebooks.backend.presentation.views.notebook.enqueue_direct_run")+ def test_reuses_only_matching_active_or_completed_run(+ self, status: str, principal: str, should_reuse: bool, enqueue: Mock, _enabled: Mock+ ) -> None:+ owner = self.user if principal == "self" else None+ if principal == "collaborator":+ owner = User.objects.create_and_join(self.organization, "[email protected]", None)+ with team_scope(self.team.id):+ saved = NotebookNodeRun.objects.create(+ team=self.team,+ notebook=self.notebook,+ user=owner,+ node_id="n1",+ code="select 1",+ node_type="hogql",+ status=status,+ )+ with patch(+ "products.notebooks.backend.presentation.views.notebook.NotebookViewSet._current_user",+ return_value=None if principal == "token" else self.user,+ ):+ response = self.client.post(+ self.run_url, data={"node_id": "n1", "code": "select 1", "reuse_results": True}, format="json"+ )+ assert response.status_code == 200+ assert (response.json()["run_id"] == str(saved.id)) is should_reuse+ assert enqueue.call_count == (0 if should_reuse else 1)+ if not should_reuse:+ assert enqueue.call_args.args[1] == (None if principal == "token" else self.user)+def _age_slot(self, run_id: str) -> None:"""Backdate a held slot so it reads as old enough to have been abandoned.@@ -1451,6 +1516,7 @@ class TestSQLV2PageDispatch(APIBaseTest):fetch_sql_v2_page(self.notebook, self.user, self.node_run, offset=0, limit=50)+@override_settings(DEBUG=False)class TestSQLV2RunResult(APIBaseTest):def setUp(self):super().setUp()@@ -1486,7 +1552,7 @@ class TestSQLV2RunResult(APIBaseTest):),])- @patch("products.notebooks.backend.presentation.views.notebook.is_sql_v2_enabled", return_value=True)+ @patch("products.notebooks.backend.presentation.views.notebook.is_sql_v2_enabled", return_value=False)def test_result_shape_by_status(self, status, envelope, error, expected_result, expected_error, _mock_enabled):run = self._create_run(status, envelope=envelope, error=error)response = self.client.get(self._url(str(run.id)))@@ -1498,11 +1564,11 @@ class TestSQLV2RunResult(APIBaseTest):self.assertEqual(body["error"], expected_error)@parameterized.expand([("00000000-0000-0000-0000-000000000000",), ("not-a-uuid",)])- @patch("products.notebooks.backend.presentation.views.notebook.is_sql_v2_enabled", return_value=True)+ @patch("products.notebooks.backend.presentation.views.notebook.is_sql_v2_enabled", return_value=False)def test_missing_or_malformed_run_returns_404(self, run_id, _mock_enabled):self.assertEqual(self.client.get(self._url(run_id)).status_code, 404)- @patch("products.notebooks.backend.presentation.views.notebook.is_sql_v2_enabled", return_value=True)+ @patch("products.notebooks.backend.presentation.views.notebook.is_sql_v2_enabled", return_value=False)def test_run_from_another_notebook_is_not_readable(self, _mock_enabled):# IDOR guard: a run belonging to a different notebook in the same team must not be# fetchable through this notebook's endpoint, even with a valid run_id.@@ -1513,7 +1579,7 @@ class TestSQLV2RunResult(APIBaseTest):)self.assertEqual(self.client.get(self._url(str(other_run.id))).status_code, 404)- @patch("products.notebooks.backend.presentation.views.notebook.is_sql_v2_enabled", return_value=True)+ @patch("products.notebooks.backend.presentation.views.notebook.is_sql_v2_enabled", return_value=False)def test_query_restricted_member_cannot_read_result(self, _mock_enabled):# The result envelope is analytics rows, so a query-denied notebook reader must not read them back.run = self._create_run(NotebookNodeRun.Status.DONE, envelope={"first_page": [[42]]})@@ -1529,7 +1595,7 @@ class TestSQLV2RunResult(APIBaseTest):("kernel", NotebookNodeRun.NodeType.PYTHON, "never reported"),])- @patch("products.notebooks.backend.presentation.views.notebook.is_sql_v2_enabled", return_value=True)+ @patch("products.notebooks.backend.presentation.views.notebook.is_sql_v2_enabled", return_value=False)def test_running_run_expires_to_failed_after_grace(self, _name, node_type, expected_error, _mock_enabled):# This poll is the watchdog for both lanes. Within the grace window it keeps waiting,# which for hogql also covers pre-deploy kernel-executed runs whose callback is due.@@ -1544,7 +1610,7 @@ class TestSQLV2RunResult(APIBaseTest):self.assertEqual(body["status"], NotebookNodeRun.Status.RUNNING)@patch("products.notebooks.backend.sql_v2_direct.get_query_status")- @patch("products.notebooks.backend.presentation.views.notebook.is_sql_v2_enabled", return_value=True)+ @patch("products.notebooks.backend.presentation.views.notebook.is_sql_v2_enabled", return_value=False)def test_query_error_fails_the_direct_run_with_its_message(self, _mock_enabled, mock_status):# An errored query must fail the run with the user-facing message, or the node# polls a RUNNING row forever.@@ -1866,7 +1932,25 @@ class TestSQLV2DataPlaneToken(SimpleTestCase):verify_data_plane_token(make_token())-class TestFrameStoreFlagResolution(SimpleTestCase):+class TestNotebookFlagResolution(SimpleTestCase):+ @parameterized.expand(+ [+ ("neither", False, False, True, False),+ ("python_only", True, False, True, True),+ ("widgets_only", False, True, True, False),+ ("both", True, True, True, True),+ ("anonymous", True, True, False, False),+ ]+ )+ def test_full_compute_requires_python_flag(+ self, _name: str, python_enabled: bool, widgets_enabled: bool, has_user: bool, expected: bool+ ) -> None:+ enabled = {"revamped-py-notebooks": python_enabled, "notebook-generated-widgets": widgets_enabled}+ user = Mock(spec=User, distinct_id="example-user", organization=None) if has_user else None+ with patch("products.notebooks.backend.sql_v2.posthoganalytics.feature_enabled") as feature_enabled:+ feature_enabled.side_effect = lambda flag, *_args, **_kwargs: enabled.get(flag, False)+ assert is_sql_v2_enabled(user) is expected+@parameterized.expand([("enabled", True), ("disabled", False)])def test_frame_store_flag_is_its_own_flag(self, _name, flag_value):# Every other frame-store test patches is_frame_store_enabled, so this is the onlydiff --git a/products/notebooks/backend/test/test_sql_v2_state.py b/products/notebooks/backend/test/test_sql_v2_state.pyindex 9b446bf242b6..ee483b7f0032 100644--- a/products/notebooks/backend/test/test_sql_v2_state.py+++ b/products/notebooks/backend/test/test_sql_v2_state.py@@ -1,3 +1,5 @@+import json+from pathlib import Pathfrom typing import Anyfrom posthog.test.base import APIBaseTest@@ -17,6 +19,7 @@ from products.notebooks.backend.sql_v2_state import (build_dependency_edges,build_notebook_cell_state,extract_cells,+ get_dataframe_owners,validate_cell_count,)from products.notebooks.backend.sql_v2_variables import (@@ -37,6 +40,15 @@ def markdown_content(markdown: str) -> dict[str, Any]:class TestCellExtractionAndEdges(SimpleTestCase):+ @parameterized.expand(+ [+ (case["name"], case["markdown"], case["owners"])+ for case in json.loads((Path(__file__).parents[2] / "dataframe-names.test.json").read_text())+ ]+ )+ def test_shared_dataframe_names(self, _name: str, markdown: str, owners: dict[str, str]) -> None:+ assert get_dataframe_owners(extract_cells(markdown_content(markdown))) == owners+def test_extracts_runnable_cells_and_skips_unknown_or_idless_tags(self) -> None:content = markdown_content("# Doc\n\n"@@ -45,6 +57,7 @@ class TestCellExtractionAndEdges(SimpleTestCase):'<PythonV2 nodeId="p2" code="import pandas as pd\n\nout = pd.DataFrame()" returnVariable="multiline" />\n\n''\\<PythonV2 nodeId="p3" code="\\# Build the frame\n\nout = df.head()" returnVariable="recovered" />\n\n''<Query nodeId="q1" query={{"kind":"SavedInsightNode","shortId":"abc"}} />\n\n'+ '<Insight nodeId="i1" id="example" returnVariable="insight_df" dataframeQuery="SELECT 1" />\n\n''<SQLV2 code="select 2" returnVariable="anon" />\n\n''<RevenueCard metric="arr" />\n')@@ -55,9 +68,11 @@ class TestCellExtractionAndEdges(SimpleTestCase):("p2", "python", "multiline"),("p3", "python", "recovered"),("q1", "saved_insight", ""),+ ("i1", "saved_insight", "insight_df"),]assert cells[2].code == "import pandas as pd\n\nout = pd.DataFrame()"assert cells[3].code == "# Build the frame\n\nout = df.head()"+ assert cells[5].code == "SELECT 1"@parameterized.expand([@@ -99,18 +114,30 @@ class TestCellExtractionAndEdges(SimpleTestCase):# Python deps come from globals analysis, so a comment mention is not an edge.("python_comment", '<PythonV2 nodeId="b" code="# df\\nx = 1" returnVariable="" />', []),("python_use", '<PythonV2 nodeId="b" code="x = df.head()" returnVariable="" />', ["a"]),+ ("insight_source", '<SQLV2 nodeId="b" code="select * from df" returnVariable="" />', ["a"]),])def test_dependency_edges(self, _name: str, downstream_tag: str, expected_depends_on: list[str]) -> None:- content = markdown_content(f'<SQLV2 nodeId="a" code="select 1" returnVariable="df" />\n\n{downstream_tag}\n')+ source = (+ '<Insight nodeId="a" id="example" dataframeQuery="select 1" returnVariable="df" />'+ if _name == "insight_source"+ else '<SQLV2 nodeId="a" code="select 1" returnVariable="df" />'+ )+ content = markdown_content(f"{source}\n\n{downstream_tag}\n")cells = extract_cells(content)build_dependency_edges(cells)assert cells[1].depends_on == expected_depends_onassert cells[0].dependents == (["b"] if expected_depends_on else [])- def test_sql_wins_dataframe_name_collision(self) -> None:+ @parameterized.expand(+ [+ ("python", '<PythonV2 nodeId="p" code="df = 1" returnVariable="df" />'),+ ("insight", '<Insight nodeId="i" dataframeQuery="select 2" returnVariable="df" />'),+ ]+ )+ def test_sql_wins_dataframe_name_collision(self, _name: str, other_source: str) -> None:content = markdown_content(- '<PythonV2 nodeId="p" code="df = 1" returnVariable="df" />\n\n'+ f"{other_source}\n\n"'<SQLV2 nodeId="s" code="select 1" returnVariable="df" />\n\n''<SQLV2 nodeId="user" code="select * from df" returnVariable="" />\n')@@ -118,6 +145,25 @@ class TestCellExtractionAndEdges(SimpleTestCase):build_dependency_edges(cells)assert cells[2].depends_on == ["s"]+ @parameterized.expand(+ [+ ("missing_name", 'dataframeQuery="select 1"', "insight_df", ["a"]),+ ("blank_name", 'dataframeQuery="select 1" returnVariable=""', "", []),+ ("missing_query", "", "", []),+ ]+ )+ def test_insight_default_dataframe_binding(+ self, _name: str, props: str, expected_name: str, expected_depends_on: list[str]+ ) -> None:+ cells = extract_cells(+ markdown_content(+ f'<Insight nodeId="a" id="example" {props} />\n\n<SQLV2 nodeId="b" code="select * from insight_df" />'+ )+ )+ build_dependency_edges(cells)+ assert cells[0].dataframe_name == expected_name+ assert cells[1].depends_on == expected_depends_on+def cells_markdown(count: int) -> dict[str, Any]:return markdown_content(@@ -212,8 +258,9 @@ class TestCellCountLimit(SimpleTestCase):blocks = iter_markdown_blocks(markdown, max_prose_blocks=MAX_ADDRESSABLE_PROSE_BLOCKS)assert [block.node_id for block in blocks if block.kind == "component"] == ["s1"]- def test_prose_does_not_count_toward_the_ceiling(self) -> None:- prose = "\n\n".join(f"Paragraph {index}." for index in range(MAX_NOTEBOOK_CELLS * 2))+ @parameterized.expand([("prose", "Paragraph {index}."), ("insights", '<Insight nodeId="i{index}" id="example" />')])+ def test_display_cells_do_not_count_toward_the_ceiling(self, _name: str, template: str) -> None:+ prose = "\n\n".join(template.format(index=index) for index in range(MAX_NOTEBOOK_CELLS * 2))validate_cell_count(None, markdown_content(prose))def test_a_notebook_already_over_the_ceiling_still_cannot_grow(self) -> None:diff --git a/products/notebooks/backend/test/test_widgets.py b/products/notebooks/backend/test/test_widgets.pyindex 0b215a6270ba..040fcfd4602a 100644--- a/products/notebooks/backend/test/test_widgets.py+++ b/products/notebooks/backend/test/test_widgets.py@@ -387,11 +387,11 @@ class TestWidgetGeneration(SimpleTestCase):assert "public_df" in request["messages"][0]["content"]stream.close.assert_called_once()- def test_generate_request_defaults_to_the_balanced_model(self) -> None:+ def test_generate_request_defaults_to_sonnet_5(self) -> None:serializer = WidgetGenerateRequestSerializer(data={"prompt": "Render a globe", "generation_id": str(uuid4())})assert serializer.is_valid(), serializer.errors- assert serializer.validated_data["model"] == DEFAULT_WIDGET_MODEL+ assert serializer.validated_data["model"] == "claude-sonnet-5"def test_generate_request_rejects_an_unlisted_model(self) -> None:serializer = WidgetGenerateRequestSerializer(@@ -481,13 +481,19 @@ class TestWidgetGeneration(SimpleTestCase):'<PythonV2 nodeId="source" returnVariable="locations_df" />\n\n''<SQLV2 nodeId="summary" returnVariable="summary_df" />\n\n''<Query nodeId="saved" returnVariable="saved_df" />\n\n'+ '<Insight nodeId="insight" dataframeQuery="SELECT 1" />\n\n''<Widget nodeId="globe" prompt="Render a globe" />\n\n''<PythonV2 nodeId="later" returnVariable="future_df" />')),)- assert infer_widget_inputs(notebook, "globe") == ["locations_df", "summary_df", "future_df"]+ assert infer_widget_inputs(notebook, "globe") == [+ "locations_df",+ "summary_df",+ "insight_df",+ "future_df",+ ]@parameterized.expand([("generated_widget", "GeneratedWidget"), ("genui", "GenUI")])def test_rejects_removed_widget_tags(self, _name: str, tag_name: str) -> None:diff --git a/products/notebooks/backend/widget_models.py b/products/notebooks/backend/widget_models.pyindex 242bfe370648..c122ebf854d0 100644--- a/products/notebooks/backend/widget_models.py+++ b/products/notebooks/backend/widget_models.py@@ -5,7 +5,7 @@ WIDGET_MODEL_CHOICES = ("claude-opus-5",)-DEFAULT_WIDGET_MODEL = "claude-sonnet-4-6"+DEFAULT_WIDGET_MODEL = "claude-sonnet-5"WIDGET_LIFECYCLE_STATUS_CHOICES = ("awaiting_generation",diff --git a/products/notebooks/backend/widgets.py b/products/notebooks/backend/widgets.pyindex 6e3c1cbeb4ac..e7fe5b971e38 100644--- a/products/notebooks/backend/widgets.py+++ b/products/notebooks/backend/widgets.py@@ -29,7 +29,7 @@ from products.notebooks.backend.models import (NotebookWidgetInstance,)from products.notebooks.backend.sql_v2 import SQLV2KernelNotRunning, SQLV2PageError, fetch_sql_v2_page-from products.notebooks.backend.sql_v2_state import extract_cells+from products.notebooks.backend.sql_v2_state import extract_cells, get_dataframe_ownersfrom products.notebooks.backend.temporal.client import start_widget_generation_workflowfrom products.notebooks.backend.util import (_create_stable_markdown_node_id,@@ -299,18 +299,7 @@ def assert_widget_node_exists(notebook: Notebook, node_id: str) -> None:def _dataframe_owners(notebook: Notebook) -> dict[str, str]:- cells = extract_cells(notebook.content)- eligible_cells = [cell for cell in cells if _INPUT_NAME.fullmatch(cell.dataframe_name)]- preferred_owners: dict[str, str] = {}- for cell_type in ("sql", "python"):- for cell in eligible_cells:- if cell.cell_type == cell_type:- preferred_owners.setdefault(cell.dataframe_name, cell.node_id)- owners: dict[str, str] = {}- for cell in eligible_cells:- if preferred_owners.get(cell.dataframe_name) == cell.node_id:- owners.setdefault(cell.dataframe_name, cell.node_id)- return owners+ return get_dataframe_owners(extract_cells(notebook.content))def infer_widget_inputs(notebook: Notebook, node_id: str) -> list[str]:diff --git a/products/notebooks/dataframe-names.test.json b/products/notebooks/dataframe-names.test.jsonnew file mode 100644index 000000000000..4bc2e595112a--- /dev/null+++ b/products/notebooks/dataframe-names.test.json@@ -0,0 +1,17 @@+[+ {+ "name": "sql owns collisions before prepared insights and python",+ "markdown": "<Insight nodeId=\"insight\" id=\"example\" returnVariable=\"shared\" dataframeQuery=\"SELECT 1\" />\n\n<SQLV2 nodeId=\"sql\" returnVariable=\"shared\" code=\"SELECT 1\" />\n\n<SQLV2 nodeId=\"sql2\" returnVariable=\"shared\" code=\"SELECT 2\" />\n\n<PythonV2 nodeId=\"python\" returnVariable=\"shared\" code=\"shared = 1\" />",+ "owners": { "shared_3": "insight", "shared": "sql", "shared_2": "sql2" }+ },+ {+ "name": "unprepared insight does not shadow python",+ "markdown": "<Insight nodeId=\"insight\" id=\"example\" returnVariable=\"df\" />\n\n<PythonV2 nodeId=\"python\" code=\"df = 1\" />",+ "owners": { "df": "python" }+ },+ {+ "name": "defaults blank names and case insensitive collisions",+ "markdown": "<SQLV2 nodeId=\"sql\" code=\"SELECT 1\" />\n\n<SQLV2 nodeId=\"blank\" returnVariable=\"\" code=\"SELECT 2\" />\n\n<Insight nodeId=\"insight\" id=\"example\" dataframeQuery=\"SELECT 3\" />\n\n<Insight nodeId=\"second\" id=\"example2\" returnVariable=\"INSIGHT_DF\" dataframeQuery=\"SELECT 4\" />\n\n<PythonV2 nodeId=\"python\" returnVariable=\"SQL_DF\" code=\"SQL_DF = 1\" />",+ "owners": { "sql_df": "sql", "insight_df": "insight", "INSIGHT_DF_2": "second" }+ }+]diff --git a/products/notebooks/frontend/NotebookInsightDataframe.tsx b/products/notebooks/frontend/NotebookInsightDataframe.tsxnew file mode 100644index 000000000000..22c57b938e9c--- /dev/null+++ b/products/notebooks/frontend/NotebookInsightDataframe.tsx@@ -0,0 +1,43 @@+import { useValues } from 'kea'++import { FEATURE_FLAGS } from 'lib/constants'+import { featureFlagLogic } from 'lib/logic/featureFlagLogic'+import { useRequiredNotebookNode } from 'scenes/notebooks/Nodes/NotebookNodeContext'++import type { InsightLogicProps } from '~/types'++import { NotebookInsightDataframeFooter } from './NotebookInsightDataframeFooter'+import { InsightDataframeAttributes } from './notebookInsightDataframeLogic'++export function NotebookInsightDataframe({+ insightProps,+ attributes,+ updateAttributes,+}: {+ insightProps: InsightLogicProps+ attributes: InsightDataframeAttributes+ updateAttributes: (attributes: Partial<InsightDataframeAttributes>) => void+}): JSX.Element | null {+ const { notebookLogic, nodeId } = useValues(useRequiredNotebookNode())+ const { canEditNotebook, isShared } = useValues(notebookLogic)+ const { featureFlags } = useValues(featureFlagLogic)+ const enabled =+ !!(+ featureFlags[FEATURE_FLAGS.REVAMPED_PY_NOTEBOOKS] || featureFlags[FEATURE_FLAGS.NOTEBOOK_GENERATED_WIDGETS]+ ) &&+ canEditNotebook &&+ !isShared+ if (!enabled) {+ return null+ }+ return (+ <NotebookInsightDataframeFooter+ notebookLogic={notebookLogic}+ nodeId={nodeId}+ insightProps={insightProps}+ attributes={attributes}+ updateAttributes={updateAttributes}+ enabled+ />+ )+}diff --git a/products/notebooks/frontend/NotebookInsightDataframeFooter.tsx b/products/notebooks/frontend/NotebookInsightDataframeFooter.tsxnew file mode 100644index 000000000000..0ba257dfc17e--- /dev/null+++ b/products/notebooks/frontend/NotebookInsightDataframeFooter.tsx@@ -0,0 +1,45 @@+import { useActions, useValues } from 'kea'++import { LemonButton, Spinner } from '@posthog/lemon-ui'++import { NotebookCellOutputNameFooter } from 'scenes/notebooks/Nodes/components/NotebookCellOutputNameFooter'+import { returnVariableValidationError } from 'scenes/notebooks/Nodes/NotebookNodeSQLV2'++import { notebookInsightDataframeLogic, NotebookInsightDataframeLogicProps } from './notebookInsightDataframeLogic'++export function NotebookInsightDataframeFooter(props: NotebookInsightDataframeLogicProps): JSX.Element {+ const logic = notebookInsightDataframeLogic(props)+ const { returnVariable, isPreparing, error, unsupported } = useValues(logic)+ const { setReturnVariable, retry } = useActions(logic)+ return (+ <NotebookCellOutputNameFooter returnVariable={returnVariable} onChange={setReturnVariable}>+ {returnVariableValidationError(returnVariable) ? (+ <span className="text-danger">{returnVariableValidationError(returnVariable)}</span>+ ) : isPreparing ? (+ <span className="flex items-center gap-1">+ <Spinner className="text-sm" /> Preparing {returnVariable}+ </span>+ ) : error ? (+ <span className="flex flex-wrap items-center gap-1">+ <span className={unsupported ? 'text-secondary' : 'text-danger'}>{error}</span>+ {!unsupported && (+ <LemonButton size="xsmall" type="tertiary" onClick={retry}>+ Try again+ </LemonButton>+ )}+ </span>+ ) : props.attributes.runId ? (+ <LemonButton+ size="xsmall"+ type="tertiary"+ onClick={retry}+ disabledReason={isPreparing ? 'Preparing dataframe' : undefined}+ >+ Refresh dataframe+ </LemonButton>+ ) : (+ <span className="text-secondary">Prepared when used</span>+ )}+ </NotebookCellOutputNameFooter>+ )+}diff --git a/products/notebooks/frontend/NotebookNodeGeneratedWidget/NotebookGeneratedWidgetRunButton.tsx b/products/notebooks/frontend/NotebookNodeGeneratedWidget/NotebookGeneratedWidgetRunButton.tsxindex 7934285ff817..c7858ca6b1bb 100644--- a/products/notebooks/frontend/NotebookNodeGeneratedWidget/NotebookGeneratedWidgetRunButton.tsx+++ b/products/notebooks/frontend/NotebookNodeGeneratedWidget/NotebookGeneratedWidgetRunButton.tsx@@ -11,6 +11,7 @@ import { teamLogic } from 'scenes/teamLogic'import { resolveToolCall, useToolStreamListener } from 'products/posthog_ai/frontend/api/logics'+import { prepareNotebookInsightDataframes } from '../prepareNotebookInsightDataframes'import { notebookNodeGeneratedWidgetLogic } from './notebookNodeGeneratedWidgetLogic'import { NotebookWidgetPublishModal } from './NotebookWidgetPublishModal'import { NotebookWidgetSourceModal } from './NotebookWidgetSourceModal'@@ -55,6 +56,7 @@ function EditableNotebookGeneratedWidgetRunButton({prompt: typeof node.props.prompt === 'string' ? node.props.prompt : '',model,isEditable: canEditNotebook,+ prepareInsightDataframes: () => prepareNotebookInsightDataframes(mountedNotebookLogic),persistNotebook: async (): Promise<void> => {await mountedNotebookLogic.asyncActions.saveNotebook({content: mountedNotebookLogic.values.content,diff --git a/products/notebooks/frontend/NotebookNodeGeneratedWidget/NotebookNodeGeneratedWidget.test.tsx b/products/notebooks/frontend/NotebookNodeGeneratedWidget/NotebookNodeGeneratedWidget.test.tsxindex bd49e3e9a3b6..9002ec70e03a 100644--- a/products/notebooks/frontend/NotebookNodeGeneratedWidget/NotebookNodeGeneratedWidget.test.tsx+++ b/products/notebooks/frontend/NotebookNodeGeneratedWidget/NotebookNodeGeneratedWidget.test.tsx@@ -5,6 +5,7 @@ import { BindLogic } from 'kea'import { expectLogic } from 'kea-test-utils'import api from 'lib/api'+import { parseMarkdownNotebook } from 'lib/components/MarkdownNotebook/markdown'import { buildMarkdownNotebookContent, getMarkdownNotebookMarkdown } from 'scenes/notebooks/Notebook/markdownNotebookV2'import { MarkdownNotebookV2 } from 'scenes/notebooks/Notebook/MarkdownNotebookV2Renderer'import { NotebookLogicProps, notebookLogic } from 'scenes/notebooks/Notebook/notebookLogic'@@ -128,6 +129,59 @@ describe('NotebookNodeGeneratedWidget', () => {await waitFor(() => expect(screen.getAllByText('Regenerating widget…')).toHaveLength(1))})+ it('keeps a markdown widget identity when its instructions are edited', async () => {+ const markdown =+ '<Widget showFilters title="Hourly chart" prompt="Plot hourly totals" model="claude-sonnet-5" />'+ const originalId = parseMarkdownNotebook(markdown).nodes[0].id+ logic.unmount()+ const editProps = { ...logicProps, shortId: 'widget-identity-edit' }+ const notebook = {+ ...cachedNotebook,+ short_id: editProps.shortId,+ content: buildMarkdownNotebookContent(markdown),+ }+ jest.mocked(api.notebooks.get).mockResolvedValue(notebook)+ jest.spyOn(api.notebooks, 'update').mockResolvedValue(notebook)+ jest.mocked(notebooksWidgetStatus).mockResolvedValue({+ lifecycle_status: 'awaiting_generation',+ has_versions: false,+ current_version_id: null,+ active_job: null,+ artifact_url: null,+ error_detail: null,+ frame_names: [],+ input_bindings: {},+ input_contract: [],+ pinned_version_id: null,+ is_reusable: false,+ widget_id: null,+ instance_id: null,+ security_review: null,+ build_hash: null,+ })+ logic = notebookLogic(editProps)+ logic.mount()+ logic.actions.loadNotebook()+ await expectLogic(logic).toDispatchActions(['loadNotebookSuccess']).toFinishAllListeners()+ logic.actions.setEditable(true)+ render(+ <BindLogic logic={notebookLogic} props={editProps}>+ <MarkdownNotebookV2 />+ </BindLogic>+ )++ fireEvent.change(await screen.findByLabelText('Instructions'), { target: { value: 'Plot daily totals' } })++ await waitFor(() => {+ const node = parseMarkdownNotebook(getMarkdownNotebookMarkdown(logic.values.content)).nodes.find(+ (node) => node.type === 'component'+ )+ expect(node?.type === 'component' && node.props).toEqual(+ expect.objectContaining({ nodeId: originalId, prompt: 'Plot daily totals' })+ )+ })+ })+it('renders without crashing when the markdown tag has a non-string prompt or unknown model', async () => {logic.unmount()const notebookWithMalformedTag = {diff --git a/products/notebooks/frontend/NotebookNodeGeneratedWidget/NotebookNodeGeneratedWidget.tsx b/products/notebooks/frontend/NotebookNodeGeneratedWidget/NotebookNodeGeneratedWidget.tsxindex 41ea4549424b..18477d90a463 100644--- a/products/notebooks/frontend/NotebookNodeGeneratedWidget/NotebookNodeGeneratedWidget.tsx+++ b/products/notebooks/frontend/NotebookNodeGeneratedWidget/NotebookNodeGeneratedWidget.tsx@@ -14,6 +14,7 @@ import { teamLogic } from 'scenes/teamLogic'import { urls } from 'scenes/urls'import { userLogic } from 'scenes/userLogic'+import { prepareNotebookInsightDataframes } from '../prepareNotebookInsightDataframes'import { applyReusableWidgetBinding, getReusableWidgetInputBinding } from '../ReusableWidget/reusableWidgetBindings'import {formatWidgetElapsed,@@ -81,6 +82,7 @@ function ExpandedWidget({prompt,model,isEditable,+ prepareInsightDataframes: () => prepareNotebookInsightDataframes(notebookLogic),persistNotebook: async (): Promise<void> => {await notebookLogic.asyncActions.saveNotebook({content: notebookLogic.values.content,diff --git a/products/notebooks/frontend/NotebookNodeGeneratedWidget/NotebookNodeGeneratedWidgetSettings.tsx b/products/notebooks/frontend/NotebookNodeGeneratedWidget/NotebookNodeGeneratedWidgetSettings.tsxindex 3ece7367d64d..20fb34672d57 100644--- a/products/notebooks/frontend/NotebookNodeGeneratedWidget/NotebookNodeGeneratedWidgetSettings.tsx+++ b/products/notebooks/frontend/NotebookNodeGeneratedWidget/NotebookNodeGeneratedWidgetSettings.tsx@@ -12,6 +12,7 @@ import { notebookNodeLogic } from 'scenes/notebooks/Nodes/notebookNodeLogic'import type { NotebookNodeAttributeProperties } from 'scenes/notebooks/types'import { teamLogic } from 'scenes/teamLogic'+import { prepareNotebookInsightDataframes } from '../prepareNotebookInsightDataframes'import {ReusableWidgetPickerLogicProps,reusableWidgetPickerLogic,@@ -46,6 +47,7 @@ export function NotebookNodeGeneratedWidgetSettings({prompt: attributes.prompt ?? '',model: attributes.model ?? DEFAULT_WIDGET_MODEL,isEditable,+ prepareInsightDataframes: () => prepareNotebookInsightDataframes(notebookLogic),persistNotebook: async (): Promise<void> => {await notebookLogic.asyncActions.saveNotebook({content: notebookLogic.values.content,diff --git a/products/notebooks/frontend/NotebookNodeGeneratedWidget/notebookNodeGeneratedWidgetLogic.test.ts b/products/notebooks/frontend/NotebookNodeGeneratedWidget/notebookNodeGeneratedWidgetLogic.test.tsindex ced3bb85934b..16a2a92f051e 100644--- a/products/notebooks/frontend/NotebookNodeGeneratedWidget/notebookNodeGeneratedWidgetLogic.test.ts+++ b/products/notebooks/frontend/NotebookNodeGeneratedWidget/notebookNodeGeneratedWidgetLogic.test.ts@@ -929,6 +929,78 @@ describe('notebookNodeGeneratedWidgetLogic', () => {})})+ it.each<{ frameName: string; inputBindings: WidgetStatusApi['input_bindings'] }>([+ { frameName: 'insight_df', inputBindings: {} },+ { frameName: 'widget_input', inputBindings: { widget_input: { source: 'insight_df' } } },+ ])(+ 'prepares $frameName before refreshing widget data and ignores repeated clicks',+ async ({ frameName, inputBindings }) => {+ let content: JSONContent = {+ type: 'doc',+ content: [{ type: NotebookNodeType.Query, attrs: { nodeId: 'insight', returnVariable: 'insight_df' } }],+ }+ let finishPreparation: () => void = () => undefined+ const preparation = new Promise<void>((resolve) => {+ finishPreparation = resolve+ })+ const prepareInsightDataframes = jest.fn(async () => {+ await preparation+ content = {+ type: 'doc',+ content: [+ {+ type: NotebookNodeType.Query,+ attrs: { nodeId: 'insight', returnVariable: 'insight_df', dataframeQuery: 'SELECT 1' },+ },+ ],+ }+ })+ jest.mocked(notebooksWidgetStatus).mockResolvedValue(+ status({+ lifecycle_status: 'ready',+ frame_names: [frameName],+ input_bindings: inputBindings,+ has_versions: true,+ })+ )+ logic = notebookNodeGeneratedWidgetLogic({ ...props, getContent: () => content, prepareInsightDataframes })+ logic.mount()+ await expectLogic(logic).toFinishAllListeners()++ logic.actions.runDataDependencies()+ logic.actions.runDataDependencies()+ expect(logic.values.dataRefreshInFlight).toBe(true)+ expect(prepareInsightDataframes).toHaveBeenCalledTimes(1)+ expect(notebooksWidgetStatus).toHaveBeenCalledTimes(1)++ finishPreparation()+ await expectLogic(logic).toFinishAllListeners()+ expect(props.persistNotebook).toHaveBeenCalledTimes(1)+ expect(notebooksWidgetStatus).toHaveBeenCalledTimes(2)+ expect(logic.values.runtimeError).toBeNull()+ expect(logic.values.dataRefreshInFlight).toBe(false)+ }+ )++ it('allows retrying widget data refresh after insight preparation fails', async () => {+ const prepareInsightDataframes = jest.fn().mockRejectedValue(new Error('Preparation failed. Try again.'))+ jest.mocked(notebooksWidgetStatus).mockResolvedValue(+ status({ lifecycle_status: 'ready', frame_names: ['insight_df'], has_versions: true })+ )+ logic = notebookNodeGeneratedWidgetLogic({ ...props, prepareInsightDataframes })+ logic.mount()+ await expectLogic(logic).toFinishAllListeners()+ const toastError = jest.spyOn(lemonToast, 'error').mockReturnValue('toast-id')++ await logic.asyncActions.runDataDependencies()+ expect(logic.values.runtimeError).toBe('Preparation failed. Try again.')+ expect(toastError).toHaveBeenCalledWith('Preparation failed. Try again.')+ expect(logic.values.dataRefreshInFlight).toBe(false)+ expect(props.persistNotebook).not.toHaveBeenCalled()+ await logic.asyncActions.runDataDependencies()+ expect(prepareInsightDataframes).toHaveBeenCalledTimes(2)+ })+it('uses notebook-local dataframe names when resolving reusable widget dependencies', () => {expect(getWidgetSourceFrameNames(['customers', 'revenue'], {@@ -1145,7 +1217,7 @@ describe('notebookNodeGeneratedWidgetLogic', () => {logic.actions.generateWidget('Render a globe', 'claude-sonnet-4-6', 'initial')await expectLogic(logic).toFinishAllListeners()- expect(props.persistNotebook).toHaveBeenCalledTimes(1)+ expect(props.persistNotebook).toHaveBeenCalledTimes(2)expect(notebooksWidgetGenerate).toHaveBeenCalledTimes(2)expect(jest.mocked(notebooksWidgetGenerate).mock.calls[1][3].generation_id).toBe(jest.mocked(notebooksWidgetGenerate).mock.calls[0][3].generation_iddiff --git a/products/notebooks/frontend/NotebookNodeGeneratedWidget/notebookNodeGeneratedWidgetLogic.ts b/products/notebooks/frontend/NotebookNodeGeneratedWidget/notebookNodeGeneratedWidgetLogic.tsindex b59a159a6848..f4258869ff0c 100644--- a/products/notebooks/frontend/NotebookNodeGeneratedWidget/notebookNodeGeneratedWidgetLogic.ts+++ b/products/notebooks/frontend/NotebookNodeGeneratedWidget/notebookNodeGeneratedWidgetLogic.ts@@ -84,6 +84,7 @@ export type NotebookNodeGeneratedWidgetLogicProps = {prompt: stringmodel: WidgetModelisEditable: boolean+ prepareInsightDataframes?: () => Promise<void>persistNotebook: () => Promise<void>getContent: () => JSONContent | nullreusableWidgetId?: string@@ -302,7 +303,7 @@ export function getWidgetDataDependencies(frameNames: string[]): { missingFrameNames: string[]; nodeIds: string[] } {if (!content || !frameNames.length) {- return { missingFrameNames: [], nodeIds: [] }+ return { missingFrameNames: frameNames, nodeIds: [] }}const graph = buildNotebookDependencyGraph(content)const frameNodes = collectNotebookFrameNodes(content)@@ -1122,6 +1123,8 @@ export const notebookNodeGeneratedWidgetLogic: LogicWrapper<notebookNodeGenerateconst generationId = uuidv4()let aborted = falsetry {+ await props.prepareInsightDataframes?.()+ await props.persistNotebook()const requestGeneration = async (): Promise<WidgetStatusApi> =>await requestWithTimeout((signal) =>notebooksWidgetGenerate(@@ -1406,35 +1409,42 @@ export const notebookNodeGeneratedWidgetLogic: LogicWrapper<notebookNodeGenerate}actions.loadSource()},- runDataDependencies: () => {+ runDataDependencies: async () => {if (values.dataRefreshInFlight || values.runDataDependenciesDisabledReason) {return}- const content = props.getContent()- const sourceFrameNames = getWidgetSourceFrameNames(- values.activeFrameNames,- values.status?.input_bindings ?? {}- )- const { missingFrameNames, nodeIds } = getWidgetDataDependencies(content, sourceFrameNames)- if (missingFrameNames.length) {- const message =- 'The widget expects notebook data that is no longer available. Restore the missing SQL or Python cell, or update the widget source.'+ actions.setRuntimeError(null)+ actions.dataRefreshStarted()+ try {+ await props.prepareInsightDataframes?.()+ if (props.prepareInsightDataframes) {+ await props.persistNotebook()+ }+ const content = props.getContent()+ const sourceFrameNames = getWidgetSourceFrameNames(+ values.activeFrameNames,+ values.status?.input_bindings ?? {}+ )+ const { missingFrameNames, nodeIds } = getWidgetDataDependencies(content, sourceFrameNames)+ if (missingFrameNames.length) {+ throw new Error(+ 'The widget expects notebook data that is no longer available. Restore the missing insight, SQL, or Python cell, or update the widget source.'+ )+ }+ if (!nodeIds.length) {+ actions.widgetDataChainFinished([])+ return+ }+ actions.runWidgetDataChain(content, nodeIds)+ } catch (error) {+ cache.widgetDataRefreshRequested = false+ actions.dataRefreshFinished()+ const message = errorMessage(error)actions.setRuntimeError(message)// The runtimeError banner only renders in the expanded preview, so a toast keeps// the failure visible when the widget is collapsed or still behind the trust gate.lemonToast.error(message)- return}- if (!nodeIds.length) {- const message = 'No matching notebook data cells were found. Check the widget source.'- actions.setRuntimeError(message)- lemonToast.error(message)- return- }- actions.setRuntimeError(null)- cache.widgetDataRefreshRequested = true- actions.dataRefreshStarted()- actions.runWidgetDataChain(content, nodeIds)},restoreSelectedVersion: async () => {const expectedCurrentVersionId = values.status?.current_version_iddiff --git a/products/notebooks/frontend/NotebookNodeGeneratedWidget/widgetModels.ts b/products/notebooks/frontend/NotebookNodeGeneratedWidget/widgetModels.tsindex 153a57673c16..3f46fbef7856 100644--- a/products/notebooks/frontend/NotebookNodeGeneratedWidget/widgetModels.ts+++ b/products/notebooks/frontend/NotebookNodeGeneratedWidget/widgetModels.ts@@ -4,7 +4,7 @@ import type { WidgetGenerateRequestApi } from 'products/notebooks/frontend/generexport type WidgetModel = NonNullable<WidgetGenerateRequestApi['model']>-export const DEFAULT_WIDGET_MODEL: WidgetModel = 'claude-sonnet-4-6'+export const DEFAULT_WIDGET_MODEL: WidgetModel = 'claude-sonnet-5'export const DEFAULT_WIDGET_PROMPT = 'Create an interactive visualization of the data in this notebook.'export const MAX_WIDGET_PROMPT_LENGTH = 20_000export const MAX_WIDGET_EFFECTIVE_PROMPT_LENGTH = 50_000diff --git a/products/notebooks/frontend/generated/api.schemas.ts b/products/notebooks/frontend/generated/api.schemas.tsindex ab48a7573327..4a22fa13e05a 100644--- a/products/notebooks/frontend/generated/api.schemas.ts+++ b/products/notebooks/frontend/generated/api.schemas.ts@@ -996,6 +996,8 @@ export const NotebookSQLV2NodeTypeEnumApi = {} as constexport interface NotebookSQLV2RunRequestApi {+ /** Reuse the requesting user's running or completed HogQL run with the same cell and resolved query from the last hour. Does not apply to token-only callers, kernel runs, or connection runs. */+ reuse_results?: boolean/** ProseMirror node id of the SQLV2 node being run. */node_id: string/** Execution kind. 'hogql' is a SQL node — pushed to ClickHouse, or rerouted to the sandbox's DuckDB when it references a local frame; 'python' runs the code in the sandbox kernel, materializing referenced upstream nodes as pandas frames first.@@ -1147,7 +1149,7 @@ export interface NotebookCellLastRunApi {export interface NotebookCellStateApi {/** Durable cell identity, used by the cell run and edit endpoints. */node_id: string- /** Cell kind: 'sql', 'python', 'saved_insight' (embedded insight, never runs), or 'markdown' (prose, a heading, or a fenced block; never runs and joins no dependency graph). */+ /** Cell kind: 'sql', 'python', 'saved_insight' (an insight with an optional prepared dataframe), or 'markdown' (prose, a heading, or a fenced block; never runs and joins no dependency graph). */cell_type: string/** Name other cells reference this cell's result by; blank means display-only. */dataframe_name: stringdiff --git a/products/notebooks/frontend/generated/api.ts b/products/notebooks/frontend/generated/api.tsindex 4775c2f33f76..32f1a7c0b68a 100644--- a/products/notebooks/frontend/generated/api.ts+++ b/products/notebooks/frontend/generated/api.ts@@ -660,7 +660,7 @@ export const getNotebooksSqlV2RunCreateUrl = (projectId: string, shortId: string}/**- * Dispatch an asynchronous run of a notebook SQL or Python cell. Returns a run_id immediately; poll the run result endpoint until the status is terminal. One run at a time per notebook. Flag-gated (revamped-py-notebooks).+ * Dispatch an asynchronous run of a notebook SQL or Python cell. Returns a run_id immediately; poll the run result endpoint until the status is terminal. One run at a time per notebook. Python notebooks enable all run types. Generated widgets enable HogQL runs without a connection or kernel.*/export const notebooksSqlV2RunCreate = async (projectId: string,@@ -681,7 +681,7 @@ export const getNotebooksSqlV2RunsRetrieveUrl = (projectId: string, shortId: str}/**- * Read a run's durable state: its status, and — once done or interrupted — the result envelope (columns, first rows, stdout/stderr, media, error). Poll until terminal. Flag-gated (revamped-py-notebooks).+ * Read a run's durable state: its status, and — once done or interrupted — the result envelope (columns, first rows, stdout/stderr, media, error). Poll until terminal. Requires notebook and query read access, including after a notebook feature flag is disabled.*/export const notebooksSqlV2RunsRetrieve = async (projectId: string,diff --git a/products/notebooks/frontend/generated/api.zod.ts b/products/notebooks/frontend/generated/api.zod.tsindex d986024b0f25..e481c57e9117 100644--- a/products/notebooks/frontend/generated/api.zod.ts+++ b/products/notebooks/frontend/generated/api.zod.ts@@ -32,7 +32,7 @@ export const ReusableWidgetsDiscardVersionBody = /* @__PURE__ */ zod.object({export const reusableWidgetsGenerateBodyPromptMax = 50000-export const reusableWidgetsGenerateBodyModelDefault = `claude-sonnet-4-6`+export const reusableWidgetsGenerateBodyModelDefault = `claude-sonnet-5`export const reusableWidgetsGenerateBodyGenerationOperationDefault = `regenerate`export const ReusableWidgetsGenerateBody = /* @__PURE__ */ zod.object({@@ -633,8 +633,9 @@ export const NotebooksKernelStopCreateBody = /* @__PURE__ */ zod.object({})/**- * Dispatch an asynchronous run of a notebook SQL or Python cell. Returns a run_id immediately; poll the run result endpoint until the status is terminal. One run at a time per notebook. Flag-gated (revamped-py-notebooks).+ * Dispatch an asynchronous run of a notebook SQL or Python cell. Returns a run_id immediately; poll the run result endpoint until the status is terminal. One run at a time per notebook. Python notebooks enable all run types. Generated widgets enable HogQL runs without a connection or kernel.*/+export const notebooksSqlV2RunCreateBodyReuseResultsDefault = falseexport const notebooksSqlV2RunCreateBodyNodeTypeDefault = `hogql`export const notebooksSqlV2RunCreateBodyOutputNameDefault = ``export const notebooksSqlV2RunCreateBodyRefsKindDefault = `hogql`@@ -643,6 +644,12 @@ export const notebooksSqlV2RunCreateBodyVariablesItemNameMax = 200export const notebooksSqlV2RunCreateBodySendRawQueryDefault = falseexport const NotebooksSqlV2RunCreateBody = /* @__PURE__ */ zod.object({+ reuse_results: zod+ .boolean()+ .default(notebooksSqlV2RunCreateBodyReuseResultsDefault)+ .describe(+ "Reuse the requesting user's running or completed HogQL run with the same cell and resolved query from the last hour. Does not apply to token-only callers, kernel runs, or connection runs."+ ),node_id: zod.string().describe('ProseMirror node id of the SQLV2 node being run.'),node_type: zod.enum(['hogql', 'python'])@@ -765,7 +772,7 @@ export const NotebooksWidgetForkBody = /* @__PURE__ */ zod.object({*/export const notebooksWidgetGenerateBodyPromptMax = 50000-export const notebooksWidgetGenerateBodyModelDefault = `claude-sonnet-4-6`+export const notebooksWidgetGenerateBodyModelDefault = `claude-sonnet-5`export const notebooksWidgetGenerateBodyGenerationOperationDefault = `regenerate`export const NotebooksWidgetGenerateBody = /* @__PURE__ */ zod.object({diff --git a/products/notebooks/frontend/notebookCodeCellLogic.ts b/products/notebooks/frontend/notebookCodeCellLogic.tsnew file mode 100644index 000000000000..83d7a8c8c229--- /dev/null+++ b/products/notebooks/frontend/notebookCodeCellLogic.ts@@ -0,0 +1,31 @@+import type { BuiltLogic } from 'kea'++import { extractDuckSqlTables, extractPythonIdentifiers } from 'scenes/notebooks/Nodes/notebookNodeContent'+import type { NotebookNodeSQLV2Result } from 'scenes/notebooks/Nodes/NotebookNodeSQLV2'+import { notebookNodeSQLV2Logic, NotebookNodeSQLV2LogicProps } from 'scenes/notebooks/Nodes/notebookNodeSQLV2Logic'+import type { notebookLogicType } from 'scenes/notebooks/Notebook/notebookLogic'++import { prepareNotebookInsightDataframes } from './prepareNotebookInsightDataframes'++export function notebookCodeCellLogic(+ nodeId: string,+ notebook: BuiltLogic<notebookLogicType>,+ attributes: { runId?: string | null; result?: NotebookNodeSQLV2Result | null },+ updateAttributes: NotebookNodeSQLV2LogicProps['updateAttributes']+): ReturnType<typeof notebookNodeSQLV2Logic.build> {+ return notebookNodeSQLV2Logic({+ nodeId,+ notebookShortId: notebook.props.shortId,+ updateAttributes,+ runId: attributes.runId ?? null,+ hasResult: Array.isArray(attributes.result?.first_page) && !attributes.result?.previewOnly,+ hasResultMetadata: !!attributes.result,+ prepareInsightDataframes: (code, nodeType) =>+ prepareNotebookInsightDataframes(+ notebook,+ nodeType === 'python' ? extractPythonIdentifiers(code) : extractDuckSqlTables(code)+ ),+ getContent: () => notebook.values.content ?? null,+ getVariables: () => notebook.values.runnableVariables,+ })+}diff --git a/products/notebooks/frontend/notebookInsightDataframe.test.ts b/products/notebooks/frontend/notebookInsightDataframe.test.tsnew file mode 100644index 000000000000..19ee60a4525a--- /dev/null+++ b/products/notebooks/frontend/notebookInsightDataframe.test.ts@@ -0,0 +1,244 @@+import { expectLogic } from 'kea-test-utils'++import api from 'lib/api'+import { insightDataLogic } from 'scenes/insights/insightDataLogic'+import { collectNotebookFrameNodes } from 'scenes/notebooks/Nodes/notebookNodeContent'+import { collectSqlV2Refs } from 'scenes/notebooks/Nodes/notebookNodeSQLV2Logic'+import { buildMarkdownNotebookContent } from 'scenes/notebooks/Notebook/markdownNotebookV2'+import { notebookLogic } from 'scenes/notebooks/Notebook/notebookLogic'++import { dataNodeLogic } from '~/queries/nodes/DataNode/dataNodeLogic'+import { insightVizDataNodeKey } from '~/queries/nodes/InsightViz/insightVizKeys'+import * as queries from '~/queries/query'+import { NodeKind, TrendsQuery } from '~/queries/schema/schema-general'+import { initKeaTests } from '~/test/init'+import type { InsightLogicProps } from '~/types'++import { notebookCodeCellLogic } from './notebookCodeCellLogic'+import { InsightDataframeAttributes, notebookInsightDataframeLogic } from './notebookInsightDataframeLogic'++describe('insight dataframes', () => {+ let notebook: ReturnType<typeof notebookLogic.build>+ let data: ReturnType<typeof dataNodeLogic.build>+ let insight: ReturnType<typeof insightDataLogic.build>+ let creator: ReturnType<typeof notebookInsightDataframeLogic.build>+ let attributes: InsightDataframeAttributes+ let insightProps: InsightLogicProps+ const response = { results: [], hogql: 'SELECT count() FROM events', last_refresh: '2026-01-01T00:00:00Z' }++ beforeEach(() => {+ initKeaTests()+ jest.spyOn(api.notebooks, 'sqlV2Run').mockResolvedValue({ run_id: 'insight-run', starts_sandbox: false })+ jest.spyOn(api.notebooks, 'sqlV2RunResult').mockResolvedValue({+ status: 'done',+ result: { columns: ['count'], types: [['count', 'Int64']], row_count: 1, first_page: [[12]] },+ rows: [[12]],+ error: null,+ })+ notebook = notebookLogic({ shortId: 'insight-dataframes', mode: 'canvas' })+ notebook.mount()+ notebook.actions.setEditable(true)+ const source: TrendsQuery = {+ kind: NodeKind.TrendsQuery,+ series: [{ kind: NodeKind.EventsNode, event: '$pageview' }],+ }+ insightProps = { dashboardItemId: 'new-AdHoc.dataframe-test', query: { kind: NodeKind.InsightVizNode, source } }+ notebook.actions.setLocalContent(+ buildMarkdownNotebookContent(`<Query nodeId="source" query={${JSON.stringify(insightProps.query)}} />`)+ )+ data = dataNodeLogic({ key: insightVizDataNodeKey(insightProps), query: source, cachedResults: response })+ insight = insightDataLogic(insightProps)+ data.mount()+ insight.mount()+ attributes = {}+ })++ afterEach(() => {+ creator?.unmount()+ insight.unmount()+ data.unmount()+ notebook.unmount()+ jest.restoreAllMocks()+ })++ function mountCreator(): void {+ creator = notebookInsightDataframeLogic({+ notebookLogic: notebook,+ nodeId: 'source',+ insightProps,+ attributes,+ enabled: true,+ updateAttributes: (patch) => {+ attributes = { ...attributes, ...patch }+ notebookInsightDataframeLogic({ ...creator.props, attributes })+ },+ })+ creator.mount()+ }++ it('prepares on first use and persists only completed result metadata', async () => {+ const content = notebook.values.content+ mountCreator()+ await expectLogic(creator).toFinishAllListeners()+ expect(api.notebooks.sqlV2Run).not.toHaveBeenCalled()+ expect(attributes).toEqual({})+ await creator.asyncActions.syncDataframe()+ expect(api.notebooks.sqlV2Run).toHaveBeenCalledTimes(1)+ expect(api.notebooks.sqlV2Run).toHaveBeenCalledWith(+ 'insight-dataframes',+ expect.objectContaining({+ node_id: 'source',+ code: response.hogql,+ })+ )+ expect(attributes).toMatchObject({+ returnVariable: 'insight_df',+ runId: 'insight-run',+ dataframeQuery: response.hogql,+ })+ expect(attributes.result).toEqual({+ columns: ['count'],+ types: [['count', 'Int64']],+ row_count: 1,+ has_more: false,+ })+ expect(notebook.values.content).toEqual(content)+ })++ it('does not run on mount, rename, or insight refresh, and reuses a completed query on first use', async () => {+ attributes = {+ returnVariable: 'insight_df',+ runId: 'cached-run',+ result: { columns: ['count'], row_count: 1 },+ dataframeSource: JSON.stringify(insight.values.query),+ dataframeQuery: response.hogql,+ }+ mountCreator()+ await expectLogic(creator).toFinishAllListeners()+ creator.actions.setReturnVariable('renamed_df')+ await expectLogic(creator).toFinishAllListeners()+ expect(attributes.returnVariable).toBe('renamed_df')+ expect(api.notebooks.sqlV2Run).not.toHaveBeenCalled()+ expect(api.notebooks.sqlV2RunResult).not.toHaveBeenCalled()++ data.actions.loadDataSuccess({ ...response, last_refresh: '2026-01-02T00:00:00Z' })+ await expectLogic(creator).toFinishAllListeners()+ expect(api.notebooks.sqlV2Run).not.toHaveBeenCalled()+ await creator.asyncActions.syncDataframe()+ expect(api.notebooks.sqlV2Run).not.toHaveBeenCalled()+ expect(api.notebooks.sqlV2RunResult).toHaveBeenCalledWith('insight-dataframes', 'cached-run')+ expect(attributes.returnVariable).toBe('renamed_df')+ })++ it('exposes saved and inline insights as SQL references and widget frames', () => {+ const content = buildMarkdownNotebookContent(+ '<Insight nodeId="saved" id="example" returnVariable="daily_df" dataframeQuery="SELECT 1" result={{"columns":["count"],"types":[["count","Int64"]],"row_count":1}} />\n\n' ++ `<Query nodeId="inline" query={${JSON.stringify(insightProps.query)}} returnVariable="inline_df" />`+ )+ expect(collectSqlV2Refs(content, 'consumer')).toMatchObject({+ daily_df: { node_id: 'saved', kind: 'hogql' },+ })+ expect(collectNotebookFrameNodes(content)).toEqual([+ expect.objectContaining({ name: 'daily_df', hasRun: true, columns: [['count', 'Int64']] }),+ ])+ })++ it('retries a failed preparation without creating another cell', async () => {+ jest.mocked(api.notebooks.sqlV2Run).mockRejectedValueOnce(new Error('Temporary query failure'))+ mountCreator()+ await expectLogic(creator).toFinishAllListeners()+ await creator.asyncActions.syncDataframe()+ expect(creator.values.error).toBeTruthy()+ creator.actions.retry()+ await expectLogic(creator).toFinishAllListeners()+ expect(api.notebooks.sqlV2Run).toHaveBeenCalledTimes(2)+ expect(attributes.runId).toBe('insight-run')+ })++ it.each(['', 'invalid-name'])('does not prepare a dataframe named %p', async (returnVariable) => {+ attributes = { returnVariable }+ notebook.actions.setLocalContent(+ buildMarkdownNotebookContent(+ `<Insight nodeId="source" id="example" returnVariable=${JSON.stringify(returnVariable)} />`+ )+ )+ mountCreator()+ await expectLogic(creator).toFinishAllListeners()+ await creator.asyncActions.syncDataframe()+ expect(api.notebooks.sqlV2Run).not.toHaveBeenCalled()+ })++ it.each(['edited', 'removed'])(+ 'discards a completed run when its insight was %s during preparation',+ async (change) => {+ const completedResult = await api.notebooks.sqlV2RunResult('insight-dataframes', 'insight-run')+ jest.mocked(api.notebooks.sqlV2RunResult).mockImplementationOnce(async () => {+ notebook.actions.setLocalContent(+ buildMarkdownNotebookContent(+ change === 'removed'+ ? ''+ : '<Query nodeId="source" query={{"kind":"HogQLQuery","query":"SELECT 2"}} />'+ )+ )+ return completedResult+ })+ mountCreator()+ await creator.asyncActions.syncDataframe()+ expect(attributes).toEqual({})+ expect(creator.values.error).toBe('The insight changed while preparing its dataframe. Try again.')+ expect(creator.values.isPreparing).toBe(false)+ expect(creator.values.isBusy).toBe(false)+ }+ )++ it('shares a preparation between simultaneous consumers', async () => {+ mountCreator()+ await Promise.all([creator.asyncActions.syncDataframe(), creator.asyncActions.syncDataframe()])+ expect(api.notebooks.sqlV2Run).toHaveBeenCalledTimes(1)+ expect(attributes.runId).toBe('insight-run')+ expect(creator.values.error).toBeNull()+ })++ it('prepares an insight on first reference before dispatching the consuming SQL cell', async () => {+ jest.spyOn(queries, 'performQuery').mockResolvedValue(response)+ const consumer = notebookCodeCellLogic('consumer', notebook, {}, jest.fn())+ const unmount = consumer.mount()+ try {+ await consumer.asyncActions.runQuery('SELECT * FROM insight_df', {})+ await expectLogic(consumer).toFinishAllListeners()+ expect(api.notebooks.sqlV2Run).toHaveBeenNthCalledWith(+ 1,+ 'insight-dataframes',+ expect.objectContaining({ node_id: 'source', reuse_results: true })+ )+ expect(api.notebooks.sqlV2Run).toHaveBeenNthCalledWith(+ 2,+ 'insight-dataframes',+ expect.objectContaining({+ node_id: 'consumer',+ refs: { insight_df: { node_id: 'source', kind: 'hogql' } },+ })+ )+ expect(collectNotebookFrameNodes(notebook.values.content)).toEqual([+ expect.objectContaining({ name: 'insight_df', hasRun: true }),+ ])+ } finally {+ unmount()+ }+ })++ it.each(['failed', 'interrupted'] as const)('does not cache a %s run and retries it', async (status) => {+ jest.mocked(api.notebooks.sqlV2RunResult).mockResolvedValueOnce({+ status,+ result: null,+ error: 'Query did not finish',+ })+ mountCreator()+ await creator.asyncActions.syncDataframe()+ expect(attributes).toEqual({})+ expect(creator.values.error).toBe('Query did not finish')+ await creator.asyncActions.syncDataframe()+ expect(attributes.runId).toBe('insight-run')+ expect(api.notebooks.sqlV2Run).toHaveBeenCalledTimes(2)+ })+})diff --git a/products/notebooks/frontend/notebookInsightDataframeLogic.ts b/products/notebooks/frontend/notebookInsightDataframeLogic.tsnew file mode 100644index 000000000000..56fbc50ac00a--- /dev/null+++ b/products/notebooks/frontend/notebookInsightDataframeLogic.ts@@ -0,0 +1,310 @@+import {+ BuiltLogic,+ MakeLogicType,+ actions,+ connect,+ isBreakpoint,+ kea,+ key,+ listeners,+ path,+ props,+ reducers,+ selectors,+} from 'kea'++import api from 'lib/api'+import { insightDataLogic } from 'scenes/insights/insightDataLogic'+import { insightsApi } from 'scenes/insights/utils/api'+import {+ collectNotebookDataframeNodes,+ isReferenceableSqlV2FrameName,+} from 'scenes/notebooks/Nodes/notebookNodeContent'+import type { NotebookNodeSQLV2Result } from 'scenes/notebooks/Nodes/NotebookNodeSQLV2'+import { sqlV2RunErrorMessage } from 'scenes/notebooks/Nodes/notebookNodeSQLV2Logic'+import type { notebookLogicType } from 'scenes/notebooks/Notebook/notebookLogic'+import type { NotebookNodeRunTerminalStatus } from 'scenes/notebooks/Notebook/notebookNodeStalenessLogic'+import { notebookOperationsLogic } from 'scenes/notebooks/Notebook/notebookOperationsLogic'++import { performQuery } from '~/queries/query'+import { DataNode, NodeKind, QuerySchema } from '~/queries/schema/schema-general'+import type { InsightLogicProps, InsightShortId } from '~/types'++import type { JSONContent } from '../../../frontend/src/lib/components/RichContentEditor/types'++export interface InsightDataframeAttributes {+ nodeId?: string+ id?: InsightShortId+ query?: QuerySchema+ returnVariable?: string+ dataframeSource?: string+ dataframeQuery?: string+ runId?: string | null+ result?: NotebookNodeSQLV2Result | null+ runStatus?: NotebookNodeRunTerminalStatus | null+}++export interface NotebookInsightDataframeLogicProps {+ notebookLogic: BuiltLogic<notebookLogicType>+ nodeId: string+ insightProps: InsightLogicProps+ attributes: InsightDataframeAttributes+ updateAttributes: (attributes: Partial<InsightDataframeAttributes>) => void+ enabled: boolean+}++// Generated by kea-typegen. Update if you're an agent, ignore if you're human.+export interface notebookInsightDataframeLogicValues {+ isBusy: boolean // notebookOperationsLogic+ content: JSONContent // props.notebookLogic+ error: string | null+ isPreparing: boolean+ returnVariable: string+ unsupported: boolean+}++// Generated by kea-typegen. Update if you're an agent, ignore if you're human.+export interface notebookInsightDataframeLogicActions {+ prepareDataframe: (force: boolean) => {+ force: boolean+ }+ retry: () => {+ value: true+ }+ setError: (+ error: string | null,+ unsupported?: boolean+ ) => {+ error: string | null+ unsupported: boolean+ }+ setReturnVariable: (returnVariable: string) => {+ returnVariable: string+ }+ setSyncing: (syncing: boolean) => {+ syncing: boolean+ }+ syncDataframe: (force?: boolean) => {+ force: boolean+ }+}++// Generated by kea-typegen. Update if you're an agent, ignore if you're human.+export interface notebookInsightDataframeLogicMeta {+ key: string+ __keaTypeGenInternalSelectorTypes: {+ returnVariable: (content: JSONContent, arg: string, arg2: string | undefined) => string+ }+}++export type notebookInsightDataframeLogicType = MakeLogicType<+ notebookInsightDataframeLogicValues,+ notebookInsightDataframeLogicActions,+ NotebookInsightDataframeLogicProps,+ notebookInsightDataframeLogicMeta+>++export const notebookInsightDataframeLogic = kea<notebookInsightDataframeLogicType>([+ props({} as NotebookInsightDataframeLogicProps),+ key((props) => `${props.notebookLogic.key}-${props.nodeId}`),+ path((key) => ['products', 'notebooks', 'notebookInsightDataframeLogic', key]),+ connect((props: NotebookInsightDataframeLogicProps) => ({+ values: [+ props.notebookLogic,+ ['content'],+ notebookOperationsLogic({ shortId: props.notebookLogic.props.shortId }),+ ['isBusy'],+ ],+ })),+ actions({+ syncDataframe: (force: boolean = false) => ({ force }),+ prepareDataframe: (force: boolean) => ({ force }),+ retry: true,+ setReturnVariable: (returnVariable: string) => ({ returnVariable }),+ setSyncing: (syncing: boolean) => ({ syncing }),+ setError: (error: string | null, unsupported: boolean = false) => ({ error, unsupported }),+ }),+ reducers({+ isPreparing: [false, { setSyncing: (_, { syncing }) => syncing }],+ error: [null as string | null, { setError: (_, { error }) => error }],+ unsupported: [false, { setError: (_, { unsupported }) => unsupported }],+ }),+ selectors({+ returnVariable: [+ (s) => [+ s.content,+ (_, p: NotebookInsightDataframeLogicProps) => p.nodeId,+ (_, p: NotebookInsightDataframeLogicProps) => p.attributes.returnVariable,+ ],+ (content: JSONContent | null, nodeId: string, name: string | undefined): string =>+ collectNotebookDataframeNodes(content).find((node) => node.nodeId === nodeId)?.returnVariable ??+ name ??+ 'insight_df',+ ],+ }),+ listeners(({ actions, asyncActions, values, props, cache }) => ({+ setReturnVariable: ({ returnVariable }) => props.updateAttributes({ nodeId: props.nodeId, returnVariable }),+ retry: () => actions.syncDataframe(true),+ syncDataframe: async ({ force }) => {+ if (!cache.preparation) {+ cache.preparation = asyncActions.prepareDataframe(force)+ }+ try {+ await cache.preparation+ } finally {+ cache.preparation = null+ }+ },+ prepareDataframe: async ({ force }, breakpoint) => {+ if (!props.enabled || props.notebookLogic.values.isShared || !props.notebookLogic.values.canEditNotebook) {+ return+ }+ if (!isReferenceableSqlV2FrameName(values.returnVariable)) {+ actions.setError('Enter a valid dataframe name before using this insight.')+ return+ }+ if (values.isBusy) {+ actions.setError('Wait for the current notebook operation to finish, then try again.')+ return+ }+ const prepare = async (): Promise<void> => {+ actions.setSyncing(true)+ actions.setError(null)+ const operations = notebookOperationsLogic({ shortId: props.notebookLogic.props.shortId })+ const operationId = `${props.nodeId}:prepare`+ operations.actions.startOperation({+ id: operationId,+ nodeId: props.nodeId,+ kind: 'run',+ label: `Preparing ${values.returnVariable}`,+ })+ try {+ const mounted = insightDataLogic.findMounted(props.insightProps)+ const nodeSource = (): string => {+ const attributes = collectNotebookDataframeNodes(values.content).find(+ (node) => node.nodeId === props.nodeId+ )?.node.attrs+ return JSON.stringify([attributes?.id, attributes?.query])+ }+ const originalNodeSource = nodeSource()+ const originalMountedQuery = JSON.stringify(mounted?.values.query)+ let query = (mounted?.values.query ?? props.insightProps.query ?? props.attributes.query) as+ | QuerySchema+ | undefined+ const shortId =+ props.attributes.id ?? (query?.kind === NodeKind.SavedInsightNode ? query.shortId : undefined)+ if (shortId) {+ const insight = await insightsApi.getByShortId(shortId as InsightShortId)+ query = (insight?.query ?? undefined) as QuerySchema | undefined+ }+ if (!query) {+ actions.setError('The insight query is unavailable. Try again after the insight loads.')+ return+ }+ const source = JSON.stringify(query)+ const attributes = props.attributes+ if (+ !force &&+ attributes.runId &&+ attributes.dataframeQuery &&+ attributes.dataframeSource === source+ ) {+ if (cache.completedRunId === attributes.runId) {+ return+ }+ try {+ const saved = await api.notebooks.sqlV2RunResult(+ props.notebookLogic.props.shortId,+ attributes.runId+ )+ if (saved.status === 'done') {+ cache.completedRunId = attributes.runId+ return+ }+ } catch {+ /* An expired result can be prepared again on demand. */+ }+ }+ let code =+ mounted?.values.query && JSON.stringify(mounted.values.query) === source+ ? mounted.values.hogQL+ : null+ if (!code) {+ const sourceQuery = ('source' in query ? query.source : query) as DataNode+ const response = await performQuery(sourceQuery, undefined, 'async')+ code =+ response && 'hogql' in response && typeof response.hogql === 'string'+ ? response.hogql+ : null+ }+ if (!code) {+ actions.setError("This insight can't be used as a dataframe.", true)+ return+ }+ const run = await api.notebooks.sqlV2Run(props.notebookLogic.props.shortId, {+ node_id: props.nodeId,+ code,+ refs: {},+ reuse_results: !force,+ })+ for (let attempt = 0; attempt < 600; attempt++) {+ breakpoint()+ const response = await api.notebooks.sqlV2RunResult(+ props.notebookLogic.props.shortId,+ run.run_id+ )+ breakpoint()+ if (response.status === 'done') {+ const savedQuery = shortId+ ? (await insightsApi.getByShortId(shortId as InsightShortId))?.query+ : query+ breakpoint()+ if (+ nodeSource() !== originalNodeSource ||+ JSON.stringify(mounted?.values.query) !== originalMountedQuery ||+ JSON.stringify(savedQuery) !== source+ ) {+ actions.setError('The insight changed while preparing its dataframe. Try again.')+ return+ }+ const result = response.result+ props.updateAttributes({+ nodeId: props.nodeId,+ returnVariable: values.returnVariable,+ runId: run.run_id,+ runStatus: 'done',+ dataframeSource: source,+ dataframeQuery: code,+ result: result+ ? {+ columns: result.columns ?? [],+ types: result.types ?? [],+ row_count: result.row_count ?? 0,+ has_more: result.has_more ?? false,+ }+ : null,+ })+ cache.completedRunId = run.run_id+ return+ }+ if (response.status === 'failed' || response.status === 'interrupted') {+ actions.setError(response.error || 'The dataframe query did not finish. Try again.')+ return+ }+ await breakpoint(1000)+ }+ actions.setError('The dataframe is taking too long to prepare. Try again.')+ } catch (error) {+ if (error instanceof Error && isBreakpoint(error)) {+ throw error+ }+ actions.setError(sqlV2RunErrorMessage(error, 'Could not prepare this dataframe'))+ } finally {+ actions.setSyncing(false)+ operations.actions.finishOperation(operationId)+ }+ }+ await prepare()+ },+ })),+])diff --git a/products/notebooks/frontend/prepareNotebookInsightDataframes.ts b/products/notebooks/frontend/prepareNotebookInsightDataframes.tsnew file mode 100644index 000000000000..cf03e52f7711--- /dev/null+++ b/products/notebooks/frontend/prepareNotebookInsightDataframes.ts@@ -0,0 +1,84 @@+import type { BuiltLogic } from 'kea'++import { parseMarkdownNotebook, serializeMarkdownNotebook } from 'lib/components/MarkdownNotebook/markdown'+import { getSerializableProps } from 'lib/components/MarkdownNotebook/utils'+import {+ collectNotebookDataframeNodes,+ isReferenceableSqlV2FrameName,+} from 'scenes/notebooks/Nodes/notebookNodeContent'+import {+ buildMarkdownNotebookContent,+ getMarkdownNotebookMarkdown,+ getMarkdownNotebookNodeId,+} from 'scenes/notebooks/Notebook/markdownNotebookV2'+import type { notebookLogicType } from 'scenes/notebooks/Notebook/notebookLogic'+import { NotebookNodeType } from 'scenes/notebooks/types'++import { NodeKind } from '~/queries/schema/schema-general'++import { notebookInsightDataframeLogic } from './notebookInsightDataframeLogic'++export async function prepareNotebookInsightDataframes(+ notebook: BuiltLogic<notebookLogicType>,+ names?: string[]+): Promise<void> {+ if (notebook.values.isShared || !notebook.values.canEditNotebook) {+ return+ }+ const candidates = collectNotebookDataframeNodes(notebook.values.content).filter(+ ({ node, returnVariable }) =>+ node.type === NotebookNodeType.Query &&+ isReferenceableSqlV2FrameName(returnVariable) &&+ (!names || names.includes(returnVariable))+ )+ for (const { node, nodeId } of candidates) {+ const attributes = node.attrs ?? {}+ const savedId =+ attributes.id ??+ (attributes.query?.kind === NodeKind.SavedInsightNode ? attributes.query.shortId : undefined)+ const logic = notebookInsightDataframeLogic({+ notebookLogic: notebook,+ nodeId,+ attributes,+ enabled: true,+ insightProps: savedId+ ? { dashboardItemId: savedId }+ : {+ dashboardItemId: `new-AdHoc.notebook.${notebook.props.shortId}.${nodeId}`,+ query: attributes.query,+ },+ updateAttributes: (patch) => {+ const mountedNode = notebook.values.findNodeLogicById(nodeId)+ if (mountedNode) {+ mountedNode.props.updateAttributes(patch)+ return+ }+ const content = notebook.values.content+ const document = parseMarkdownNotebook(getMarkdownNotebookMarkdown(content))+ const index = document.nodes.findIndex(+ (block) => block.type === 'component' && (block.props.nodeId || block.id) === nodeId+ )+ const block = document.nodes[index]+ if (!block || block.type !== 'component') {+ throw new Error('The insight was removed from this notebook.')+ }+ document.nodes[index] = { ...block, props: { ...block.props, ...getSerializableProps(patch) } }+ notebook.actions.setLocalContent(+ buildMarkdownNotebookContent(+ serializeMarkdownNotebook(document),+ getMarkdownNotebookNodeId(content)+ )+ )+ },+ })+ const unmount = logic.mount()+ try {+ await logic.asyncActions.syncDataframe()+ if (logic.values.error && (!logic.values.unsupported || names)) {+ throw new Error(logic.values.error)+ }+ } finally {+ unmount()+ }+ }+}diff --git a/products/notebooks/notebookResultPreview.ts b/products/notebooks/notebookResultPreview.tsnew file mode 100644index 000000000000..f9d0ee5dc1bb--- /dev/null+++ b/products/notebooks/notebookResultPreview.ts@@ -0,0 +1,40 @@+export interface NotebookResultPreviewSource<Row extends unknown[]> {+ columns?: string[]+ types?: string[][]+ row_count?: number+ first_page?: Row[]+ has_more?: boolean+ stdout?: string+ stderr?: string+}++export function notebookResultPreview<Row extends unknown[]>(+ result: NotebookResultPreviewSource<Row>+): {+ columns: string[]+ types: [string, string][]+ row_count: number+ first_page: Row[]+ has_more: boolean+ stdout: string+ stderr: string+ previewOnly: true+} {+ const rows: Row[] = []+ for (const row of (result.first_page ?? []).slice(0, 5)) {+ if (new TextEncoder().encode(JSON.stringify([...rows, row])).length > 8192) {+ break+ }+ rows.push(row)+ }+ return {+ columns: result.columns ?? [],+ types: (result.types ?? []).map(([name, type]) => [name ?? '', type ?? '']),+ row_count: result.row_count ?? 0,+ first_page: rows,+ has_more: !!result.has_more || (result.row_count ?? 0) > rows.length,+ stdout: (result.stdout ?? '').slice(0, 2048),+ stderr: (result.stderr ?? '').slice(0, 2048),+ previewOnly: true,+ }+}diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.tsindex 72f826f185b2..9ef9772bdaca 100644--- a/services/mcp/src/api/generated.ts+++ b/services/mcp/src/api/generated.ts@@ -55013,7 +55013,7 @@ export namespace Schemas {export interface NotebookCellState {/** Durable cell identity, used by the cell run and edit endpoints. */node_id: string;- /** Cell kind: 'sql', 'python', 'saved_insight' (embedded insight, never runs), or 'markdown' (prose, a heading, or a fenced block; never runs and joins no dependency graph). */+ /** Cell kind: 'sql', 'python', 'saved_insight' (an insight with an optional prepared dataframe), or 'markdown' (prose, a heading, or a fenced block; never runs and joins no dependency graph). */cell_type: string;/** Name other cells reference this cell's result by; blank means display-only. */dataframe_name: string;@@ -55395,6 +55395,8 @@ export namespace Schemas {export type NotebookSQLV2RunRequestRefs = {[key: string]: NotebookSQLV2Ref};export interface NotebookSQLV2RunRequest {+ /** Reuse the requesting user's running or completed HogQL run with the same cell and resolved query from the last hour. Does not apply to token-only callers, kernel runs, or connection runs. */+ reuse_results?: boolean;/** ProseMirror node id of the SQLV2 node being run. */node_id: string;/** Execution kind. 'hogql' is a SQL node — pushed to ClickHouse, or rerouted to the sandbox's DuckDB when it references a local frame; 'python' runs the code in the sandbox kernel, materializing referenced upstream nodes as pandas frames first.diff --git a/services/mcp/src/generated/notebooks/api.ts b/services/mcp/src/generated/notebooks/api.tsindex 90662e83c0a7..c1309ff5b907 100644--- a/services/mcp/src/generated/notebooks/api.ts+++ b/services/mcp/src/generated/notebooks/api.ts@@ -265,7 +265,7 @@ export const NotebooksKernelStatusRetrieveParams = () => zod.object({})/**- * Read a run's durable state: its status, and — once done or interrupted — the result envelope (columns, first rows, stdout/stderr, media, error). Poll until terminal. Flag-gated (revamped-py-notebooks).+ * Read a run's durable state: its status, and — once done or interrupted — the result envelope (columns, first rows, stdout/stderr, media, error). Poll until terminal. Requires notebook and query read access, including after a notebook feature flag is disabled.*/export const NotebooksSqlV2RunsRetrieveParams = () => zod.object({project_id: zod@@ -367,7 +367,7 @@ export const NotebooksWidgetGenerateParams = () => zod.object({export const notebooksWidgetGenerateBodyPromptMax = 50000-export const notebooksWidgetGenerateBodyModelDefault = `claude-sonnet-4-6`+export const notebooksWidgetGenerateBodyModelDefault = `claude-sonnet-5`export const notebooksWidgetGenerateBodyGenerationOperationDefault = `regenerate`export const NotebooksWidgetGenerateBody = () => zod.object({diff --git a/services/mcp/src/tools/notebooks/cellRuns.ts b/services/mcp/src/tools/notebooks/cellRuns.tsindex b76c0671e268..80d0be8e33d0 100644--- a/services/mcp/src/tools/notebooks/cellRuns.ts+++ b/services/mcp/src/tools/notebooks/cellRuns.ts@@ -156,14 +156,6 @@ export function wrapRunResultAsInformational<T extends object>(result: T): WithI* identically to cells run in the editor.*/export function buildResultProp(envelope: Schemas.NotebookSQLV2Envelope): Record<string, unknown> {- return {- columns: envelope.columns ?? [],- types: envelope.types ?? [],- row_count: envelope.row_count ?? 0,- first_page: envelope.first_page ?? [],- has_more: envelope.has_more ?? false,- stdout: envelope.stdout ?? '',- stderr: envelope.stderr ?? '',- media: envelope.media ?? [],- }+ return notebookResultPreview(envelope)}+import { notebookResultPreview } from 'products/notebooks/notebookResultPreview'diff --git a/services/mcp/tests/unit/notebook-cell-tools.test.ts b/services/mcp/tests/unit/notebook-cell-tools.test.tsindex 695fa90371ee..a3aa0dd4419c 100644--- a/services/mcp/tests/unit/notebook-cell-tools.test.ts+++ b/services/mcp/tests/unit/notebook-cell-tools.test.ts@@ -207,6 +207,28 @@ describe('notebook cell tools', () => {expect(catalogPrompt).toContain('groupTypeIndex: Numeric group type index.')})+ it.each([+ { name: 'many rows', rows: Array.from({ length: 100 }, (_, i) => [i]), preview: [[0], [1], [2], [3], [4]] },+ { name: 'an oversized row', rows: [['x'.repeat(10000)]], preview: [] },+ ])('bounds the persisted result preview for $name', async ({ rows, preview }) => {+ const state = makeState('# Notebook')+ state.runStatusResponses.push({+ ...DONE_STATUS,+ result: { ...DONE_STATUS.result, first_page: rows, row_count: rows.length, stdout: 'x'.repeat(20000) },+ })+ await addCellHandler(createMockContext(state), {+ notebook_id: 'aBcD1234',+ cell_type: 'sql',+ code: 'select 1',+ })+ const markdown = state.saveBodies[1].content.content[0].attrs.markdown+ expect(markdown.length).toBeLessThan(12000)+ expect(markdown).toContain('"previewOnly":true')+ expect(markdown).toContain(`"first_page":${JSON.stringify(preview)}`)+ expect(markdown).not.toContain('aGVsbG8=')+ expect(markdown).not.toContain('x'.repeat(2049))+ })+it('add sql cell inserts the tag, runs with sibling refs and variables, and writes the result back', async () => {const country = { name: 'country', type: 'string', value: 'US' }const state = makeState('# Doc\n\n<SQLV2 nodeId="up" code="select 1" returnVariable="events_df" />\n', [