: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
feat(notebooks): add notebook-level variables (#83090)
Sinan Kucukkoseler86dc890f30e4
diff --git a/frontend/src/lib/api.ts b/frontend/src/lib/api.tsindex 3361e0c87b3b..70f7089b5ed7 100644--- a/frontend/src/lib/api.ts+++ b/frontend/src/lib/api.ts@@ -4772,7 +4772,9 @@ const api = {},async update(notebookId: NotebookType['short_id'],- data: Partial<Pick<NotebookType, 'version' | 'content' | 'text_content' | 'title' | '_create_in_folder'>>+ data: Partial<+ Pick<NotebookType, 'version' | 'content' | 'text_content' | 'title' | 'variables' | '_create_in_folder'>+ >): Promise<NotebookType> {return await new ApiRequest().notebook(notebookId).update({ data })},@@ -4920,6 +4922,7 @@ const api = {node_id: stringcode: stringrefs?: Record<string, { node_id: string; kind: 'hogql' | 'local' }>+ variables?: { name: string; type: 'string' | 'number' | 'boolean' | 'date'; value: unknown }[]node_type?: 'hogql' | 'python'output_name?: stringconnection_id?: string | nulldiff --git a/frontend/src/scenes/notebooks/Nodes/NotebookNodePythonV2.tsx b/frontend/src/scenes/notebooks/Nodes/NotebookNodePythonV2.tsxindex f3d1c61dc205..fdf21e0d8d08 100644--- a/frontend/src/scenes/notebooks/Nodes/NotebookNodePythonV2.tsx+++ b/frontend/src/scenes/notebooks/Nodes/NotebookNodePythonV2.tsx@@ -64,6 +64,7 @@ const Component = ({runId: attributes.runId ?? null,hasResult: !!attributes.result,getContent: () => notebookLogic.values.content ?? null,+ getVariables: () => notebookLogic.values.runnableVariables,})const {isRunning,@@ -74,6 +75,7 @@ const Component = ({pageLoading,operationBlockReason,isStale,+ staleReason,isChainRunning,staleDownstreamCount,pendingKernelStart,@@ -139,7 +141,7 @@ const Component = ({>{isStale ? (<div className="shrink-0 pb-2" onClick={(event) => event.stopPropagation()}>- <NotebookStaleCellBanner />+ <NotebookStaleCellBanner reason={staleReason ?? undefined} /></div>) : staleDownstreamCount > 0 && !isChainRunning ? (<div className="shrink-0 pb-2" onClick={(event) => event.stopPropagation()}>@@ -246,6 +248,7 @@ const Settings = ({runId: attributes.runId ?? null,hasResult: !!attributes.result,getContent: () => notebookLogic.values.content ?? null,+ getVariables: () => notebookLogic.values.runnableVariables,})const { runNode } = useActions(dataLogic)diff --git a/frontend/src/scenes/notebooks/Nodes/NotebookNodeSQLV2.tsx b/frontend/src/scenes/notebooks/Nodes/NotebookNodeSQLV2.tsxindex 1d833649b59d..70cbb6c9f2af 100644--- a/frontend/src/scenes/notebooks/Nodes/NotebookNodeSQLV2.tsx+++ b/frontend/src/scenes/notebooks/Nodes/NotebookNodeSQLV2.tsx@@ -152,6 +152,7 @@ const Component = ({runId: attributes.runId ?? null,hasResult: !!attributes.result,getContent: () => notebookLogic.values.content ?? null,+ getVariables: () => notebookLogic.values.runnableVariables,})const {isRunning,@@ -162,6 +163,7 @@ const Component = ({pageLoading,operationBlockReason,isStale,+ staleReason,isChainRunning,staleDownstreamCount,pendingKernelStart,@@ -245,7 +247,7 @@ const Component = ({>{isStale ? (<div className="shrink-0 pb-2" onClick={(event) => event.stopPropagation()}>- <NotebookStaleCellBanner />+ <NotebookStaleCellBanner reason={staleReason ?? undefined} /></div>) : staleDownstreamCount > 0 && !isChainRunning ? (<div className="shrink-0 pb-2" onClick={(event) => event.stopPropagation()}>@@ -397,6 +399,7 @@ const Settings = ({runId: attributes.runId ?? null,hasResult: !!attributes.result,getContent: () => notebookLogic.values.content ?? null,+ getVariables: () => notebookLogic.values.runnableVariables,})const { isRunning } = useValues(dataLogic)const { runNode } = useActions(dataLogic)diff --git a/frontend/src/scenes/notebooks/Nodes/components/NotebookStaleCellBanner.tsx b/frontend/src/scenes/notebooks/Nodes/components/NotebookStaleCellBanner.tsxindex 12aa971677ef..1bda41402f2e 100644--- a/frontend/src/scenes/notebooks/Nodes/components/NotebookStaleCellBanner.tsx+++ b/frontend/src/scenes/notebooks/Nodes/components/NotebookStaleCellBanner.tsx@@ -1,12 +1,18 @@import { LemonBanner } from 'lib/lemon-ui/LemonBanner'-// Journey 10: shown on a V2 cell whose upstream re-ran after it. Identification only: the-// action to re-run lives on the cell that caused the staleness (NotebookRunDownstreamBanner).-export function NotebookStaleCellBanner(): JSX.Element {+import type { NotebookStaleReason } from '../../Notebook/notebookNodeStalenessLogic'++const REASON_CAUSE: Record<NotebookStaleReason, string> = {+ upstream: 'an upstream cell has re-run',+ variable: 'a notebook variable changed',+}++// Journey 10: shown on a V2 cell whose inputs moved on after it last ran. Identification only:+// the action to re-run lives on the cell that caused the staleness (NotebookRunDownstreamBanner).+export function NotebookStaleCellBanner({ reason = 'upstream' }: { reason?: NotebookStaleReason }): JSX.Element {return (<LemonBanner type="warning" className="mx-2 mt-1 p-2 text-xs" hideIcon>- These results may be out of date because an upstream cell has re-run. Run this cell to refresh its output- data.+ These results may be out of date because {REASON_CAUSE[reason]}. Run this cell to refresh its output data.</LemonBanner>)}diff --git a/frontend/src/scenes/notebooks/Nodes/notebookNodeSQLV2Logic.ts b/frontend/src/scenes/notebooks/Nodes/notebookNodeSQLV2Logic.tsindex 9020762e5264..94a5fdfe7f29 100644--- a/frontend/src/scenes/notebooks/Nodes/notebookNodeSQLV2Logic.ts+++ b/frontend/src/scenes/notebooks/Nodes/notebookNodeSQLV2Logic.ts@@ -19,9 +19,14 @@ import { JSONContent } from 'lib/components/RichContentEditor/types'import { lemonToast } from 'lib/lemon-ui/LemonToast/LemonToast'import { notebookKernelInfoLogic } from '../Notebook/notebookKernelInfoLogic'-import { NotebookNodeRunTerminalStatus, notebookNodeStalenessLogic } from '../Notebook/notebookNodeStalenessLogic'+import {+ NotebookNodeRunTerminalStatus,+ NotebookStaleReason,+ notebookNodeStalenessLogic,+} from '../Notebook/notebookNodeStalenessLogic'import { NotebookOperation, notebookOperationsLogic } from '../Notebook/notebookOperationsLogic'import { notebookSettingsLogic } from '../Notebook/notebookSettingsLogic'+import { NotebookVariable } from '../Notebook/notebookVariables'import { NotebookNodeType } from '../types'import {buildNotebookDependencyGraph,@@ -150,6 +155,9 @@ export interface NotebookNodeSQLV2LogicProps {}) => void// The live notebook document, for staleness marking and chain-dispatched runs (Journey 10).getContent?: () => JSONContent | null+ // The notebook's variables, already filtered to the valid ones. A notebook property rather+ // than document content, so it does not come out of getContent.+ getVariables?: () => NotebookVariable[]}// Generated by kea-typegen. Update if you're an agent, ignore if you're human.@@ -158,7 +166,7 @@ export interface notebookNodeSQLV2LogicValues {isChainRunning: boolean // notebookNodeStalenessLogiclastRunNodeId: string | null // notebookNodeStalenessLogiclastRunStaleDownstreamNodeIds: string[] // notebookNodeStalenessLogic- staleNodeIds: Record<string, true> // notebookNodeStalenessLogic+ staleNodeIds: Record<string, NotebookStaleReason> // notebookNodeStalenessLogicactiveOperation: NotebookOperation | null // notebookOperationsLogicisBusy: boolean // notebookOperationsLogicdirectRows: NotebookNodeSQLV2DirectRows | null@@ -173,6 +181,7 @@ export interface notebookNodeSQLV2LogicValues {pendingKernelStart: booleanrunError: string | nullstaleDownstreamCount: number+ staleReason: NotebookStaleReason | null}// Generated by kea-typegen. Update if you're an agent, ignore if you're human.@@ -275,7 +284,8 @@ export interface notebookNodeSQLV2LogicMeta {key: string__keaTypeGenInternalSelectorTypes: {operationBlockReason: (activeOperation: NotebookOperation | null) => string | null- isStale: (staleNodeIds: Record<string, true>) => boolean+ isStale: (staleNodeIds: Record<string, NotebookStaleReason>) => boolean+ staleReason: (staleNodeIds: Record<string, NotebookStaleReason>) => NotebookStaleReason | nullstaleDownstreamCount: (lastRunNodeId: string | null, lastRunStaleDownstreamNodeIds: string[]) => number}}@@ -545,12 +555,18 @@ export const notebookNodeSQLV2Logic = kea<notebookNodeSQLV2LogicType>([lemonToast.info('Starting a compute sandbox. The cell will run once it’s ready.')}}+ // Read from the notebook rather than the caller: every run path (Run button,+ // Cmd+Enter, chain dispatch) needs the same notebook-level values.+ const variables = props.getVariables?.() ?? []actions.startOperation(runOperation)try {const { run_id } = await api.notebooks.sqlV2Run(props.notebookShortId, {node_id: props.nodeId,code,refs,+ // Omitted when the notebook declares none, so an unchanged notebook's+ // run body stays byte-identical to before.+ ...(variables.length ? { variables } : {}),node_type: opts.nodeType,output_name: opts.outputName,// Omitted entirely for a PostHog cell — the backend's defaults say the same@@ -771,7 +787,13 @@ export const notebookNodeSQLV2Logic = kea<notebookNodeSQLV2LogicType>([// An upstream cell's run landed after this cell last ran (Journey 10).isStale: [(s) => [s.staleNodeIds],- (staleNodeIds: Record<string, true>): boolean => !!staleNodeIds[props.nodeId],+ (staleNodeIds: Record<string, NotebookStaleReason>): boolean => !!staleNodeIds[props.nodeId],+ ],+ // What made it stale, so the banner names the actual cause.+ staleReason: [+ (s) => [s.staleNodeIds],+ (staleNodeIds: Record<string, NotebookStaleReason>): NotebookStaleReason | null =>+ staleNodeIds[props.nodeId] ?? null,],// Non-zero only on the cell whose run most recently landed: how many of its// downstream cells are still stale. Drives the "run downstream cells" button.diff --git a/frontend/src/scenes/notebooks/Notebook/Notebook.tsx b/frontend/src/scenes/notebooks/Notebook/Notebook.tsxindex 1e929d1b111c..0754be4af4f5 100644--- a/frontend/src/scenes/notebooks/Notebook/Notebook.tsx+++ b/frontend/src/scenes/notebooks/Notebook/Notebook.tsx@@ -21,6 +21,7 @@ import { NotebookHistoryWarning } from './NotebookHistory'import { NotebookLoadingState } from './NotebookLoadingState'import { NotebookMergeConflictDetails } from './NotebookMergeConflictDetails'import { notebookSettingsLogic } from './notebookSettingsLogic'+import { NotebookVariablesBar } from './NotebookVariablesBar'// Counts mounted notebooks so the <body> marker class survives overlapping mounts// (e.g. one in the scene and one in the side panel)@@ -145,6 +146,8 @@ export function Notebook({</LemonBanner>) : null}+ <NotebookVariablesBar />+<div className="Notebook_content"><NotebookColumnLeft /><ErrorBoundary>diff --git a/frontend/src/scenes/notebooks/Notebook/NotebookMeta.tsx b/frontend/src/scenes/notebooks/Notebook/NotebookMeta.tsxindex 4465721f9ffc..d5d5ad45f988 100644--- a/frontend/src/scenes/notebooks/Notebook/NotebookMeta.tsx+++ b/frontend/src/scenes/notebooks/Notebook/NotebookMeta.tsx@@ -1,7 +1,7 @@import { useActions, useValues } from 'kea'import { useCallback, useEffect, useState } from 'react'-import { IconSparkles, IconTerminal } from '@posthog/icons'+import { IconBrackets, IconSparkles, IconTerminal } from '@posthog/icons'import { LemonButton, LemonButtonProps, LemonTag } from '@posthog/lemon-ui'import { IconDocumentExpand } from 'lib/lemon-ui/icons'@@ -207,6 +207,32 @@ export const NotebookExpandButton = ({ inPanel, ...buttonProps }: NotebookExpand)}+export const NotebookVariablesButton = (+ props: Pick<LemonButtonProps, 'children' | 'size' | 'type'>+): JSX.Element | null => {+ const { featureFlags } = useValues(featureFlagLogic)+ const { content, variables, showVariables } = useValues(notebookLogic)+ const { setShowVariables } = useActions(notebookSettingsLogic)++ // Only the revamped cells read variables, so the toggle stays out of other notebooks.+ if (!isKernelUiEnabled(featureFlags) || !isMarkdownNotebookContent(content)) {+ return null+ }++ return (+ <LemonButton+ {...props}+ onClick={() => setShowVariables(!showVariables)}+ active={showVariables}+ icon={<IconBrackets />}+ tooltip={showVariables ? 'Hide variables' : 'Show variables'}+ data-attr="notebook-variables-toggle"+ >+ {variables.length ? `Variables (${variables.length})` : 'Variables'}+ </LemonButton>+ )+}+type NotebookKernelInfoButtonProps = Pick<LemonButtonProps, 'children' | 'size' | 'type'> & {onBeforeShowKernelInfo?: () => void}diff --git a/frontend/src/scenes/notebooks/Notebook/NotebookVariablesBar.test.tsx b/frontend/src/scenes/notebooks/Notebook/NotebookVariablesBar.test.tsxnew file mode 100644index 000000000000..0030691945fe--- /dev/null+++ b/frontend/src/scenes/notebooks/Notebook/NotebookVariablesBar.test.tsx@@ -0,0 +1,103 @@+import { cleanup, fireEvent, render, within } from '@testing-library/react'++import { MAX_NOTEBOOK_VARIABLES, NotebookVariable, getNotebookVariableErrors } from './notebookVariables'+import { NotebookVariablesPanel } from './NotebookVariablesBar'++describe('NotebookVariablesPanel', () => {+ const country: NotebookVariable = { name: 'country', type: 'string', value: 'US' }+ const days: NotebookVariable = { name: 'lookback_days', type: 'number', value: 30 }++ // This suite runs without RTL auto-cleanup, so an earlier test's DOM would otherwise stay+ // mounted and its label and control ids would resolve ahead of the ones under test.+ afterEach(cleanup)++ const renderPanel = (+ variables: NotebookVariable[],+ disabled = false+ ): { panel: ReturnType<typeof within>; onChange: jest.Mock } => {+ const onChange = jest.fn()+ const { container } = render(+ <NotebookVariablesPanel+ variables={variables}+ errors={getNotebookVariableErrors(variables)}+ disabled={disabled}+ onChange={onChange}+ />+ )+ return { panel: within(container), onChange }+ }++ it('renders one row per variable, with name, type and value together', () => {+ const { panel } = renderPanel([country, days])++ expect(panel.getByLabelText('Name of variable 1')).toHaveProperty('value', 'country')+ expect(panel.getByLabelText('Name of variable 2')).toHaveProperty('value', 'lookback_days')+ expect(panel.getByLabelText('Value of country')).toHaveProperty('value', 'US')+ expect(panel.getByLabelText('Value of lookback_days')).toHaveProperty('value', '30')+ })++ it('editing a value reports the whole updated set', () => {+ // The bar persists all of its declarations at once, so a single edit must not drop the+ // variables it did not touch.+ const { panel, onChange } = renderPanel([country, days])++ fireEvent.change(panel.getByLabelText('Value of country'), { target: { value: 'DE' } })++ expect(onChange).toHaveBeenCalledWith([{ ...country, value: 'DE' }, days])+ })++ it('a boolean renders a checkbox rather than a text field', () => {+ const { panel } = renderPanel([{ name: 'include_bots', type: 'boolean', value: false }])++ expect(panel.getByLabelText('Value of include_bots')).toHaveProperty('checked', false)+ })++ it('surfaces a duplicate name as an error on the second row', () => {+ // Uniqueness is the rule the whole feature rests on — a duplicate that only failed at+ // dispatch would leave the user guessing which value bound.+ const { panel } = renderPanel([country, { ...country, value: 'DE' }])++ expect(panel.getByText(/already declared/)).toBeTruthy()+ })++ it('tells a reader with no variables how to use one', () => {+ const { panel } = renderPanel([])++ expect(panel.getByText(/No variables yet/)).toBeTruthy()+ })++ it('adding a variable appends an empty row', () => {+ const { panel, onChange } = renderPanel([country])++ fireEvent.click(panel.getByText('Add variable'))++ expect(onChange).toHaveBeenCalledWith([country, { name: '', type: 'string', value: '' }])+ })++ it('removing a variable drops only that one', () => {+ const { panel, onChange } = renderPanel([country, days])++ fireEvent.click(panel.getByLabelText('Remove country', { selector: 'button' }))++ expect(onChange).toHaveBeenCalledWith([days])+ })++ it('stops offering to add past the limit', () => {+ // The API rejects an eleventh variable, so the bar must not let someone type one and+ // then lose the save.+ const many = Array.from({ length: MAX_NOTEBOOK_VARIABLES }, (_, index) => ({+ name: `v${index}`,+ type: 'string' as const,+ value: '',+ }))+ const { panel } = renderPanel(many)++ expect(panel.getByText('Add variable').closest('button')?.getAttribute('aria-disabled')).toEqual('true')+ })++ it('a read-only notebook cannot change a value', () => {+ const { panel } = renderPanel([country], true)++ expect(panel.getByLabelText('Value of country')).toHaveProperty('disabled', true)+ })+})diff --git a/frontend/src/scenes/notebooks/Notebook/NotebookVariablesBar.tsx b/frontend/src/scenes/notebooks/Notebook/NotebookVariablesBar.tsxnew file mode 100644index 000000000000..307662357934--- /dev/null+++ b/frontend/src/scenes/notebooks/Notebook/NotebookVariablesBar.tsx@@ -0,0 +1,230 @@+import { useActions, useValues } from 'kea'+import { useId } from 'react'++import { IconPlus, IconTrash } from '@posthog/icons'+import { LemonButton, LemonCheckbox, LemonInput, LemonSelect } from '@posthog/lemon-ui'++import { dayjs } from 'lib/dayjs'+import { LemonCalendarSelectInput } from 'lib/lemon-ui/LemonCalendar/LemonCalendarSelect'++import { notebookLogic } from './notebookLogic'+import {+ MAX_NOTEBOOK_VARIABLES,+ MAX_NOTEBOOK_VARIABLE_VALUE_CHARS,+ NOTEBOOK_VARIABLE_TYPES,+ NotebookVariable,+ NotebookVariableType,+ NotebookVariableValue,+ coerceNotebookVariableValue,+} from './notebookVariables'++const TYPE_LABELS: Record<NotebookVariableType, string> = {+ string: 'String',+ number: 'Number',+ boolean: 'Boolean',+ date: 'Date',+}++const DEFAULT_VALUE_BY_TYPE: Record<NotebookVariableType, NotebookVariableValue> = {+ string: '',+ number: 0,+ boolean: false,+ date: '',+}++function NotebookVariableValueInput({+ variable,+ controlId,+ disabled,+ onChange,+}: {+ variable: NotebookVariable+ controlId: string+ disabled: boolean+ onChange: (value: NotebookVariableValue) => void+}): JSX.Element {+ if (variable.type === 'boolean') {+ return (+ <LemonCheckbox id={controlId} checked={variable.value === true} disabled={disabled} onChange={onChange} />+ )+ }++ if (variable.type === 'number') {+ return (+ <LemonInput+ id={controlId}+ type="number"+ size="small"+ fullWidth+ disabled={disabled}+ value={typeof variable.value === 'number' ? variable.value : undefined}+ onChange={(value) => onChange(value ?? null)}+ />+ )+ }++ if (variable.type === 'date') {+ const value = typeof variable.value === 'string' && variable.value ? dayjs(variable.value) : null+ return (+ <LemonCalendarSelectInput+ value={value?.isValid() ? value : null}+ onChange={(date) => onChange(date ? date.format('YYYY-MM-DD') : '')}+ buttonProps={{+ id: controlId,+ size: 'small',+ disabledReason: disabled ? 'This notebook is read-only' : undefined,+ }}+ placeholder="Select a date"+ />+ )+ }++ return (+ <LemonInput+ id={controlId}+ size="small"+ fullWidth+ disabled={disabled}+ maxLength={MAX_NOTEBOOK_VARIABLE_VALUE_CHARS}+ value={typeof variable.value === 'string' ? variable.value : ''}+ onChange={(value) => onChange(value)}+ />+ )+}++/**+ * The notebook's variables, one row each: name, type, value, delete. A property of the notebook+ * rather than a block in the document, so it hangs under the header and cannot be reordered,+ * duplicated, or deleted as content.+ */+export function NotebookVariablesPanel({+ variables,+ errors,+ disabled,+ onChange,+}: {+ variables: NotebookVariable[]+ errors: (string | null)[]+ disabled: boolean+ onChange: (next: NotebookVariable[]) => void+}): JSX.Element {+ // Scoped to this panel: two panels on one page would otherwise point their labels at each+ // other's inputs.+ const idPrefix = useId()++ const update = (index: number, patch: Partial<NotebookVariable>): void =>+ onChange(variables.map((variable, i) => (i === index ? { ...variable, ...patch } : variable)))++ return (+ <div className="NotebookVariables mx-auto flex w-[70%] min-w-0 flex-col gap-2 rounded border border-primary bg-surface-secondary p-2">+ {variables.length === 0 ? (+ <p className="m-0 text-xs text-secondary">+ No variables yet. Add one, then read it as <code>{'{name}'}</code> in a SQL cell or as a plain+ variable in a Python cell.+ </p>+ ) : (+ variables.map((variable, index) => (+ <div key={index} className="flex flex-col gap-1">+ {/* A grid, not a flex row: the type select sizes to its label, so on a flex+ row every value input would start at a different x. Fixed tracks line+ the values up down the column. */}+ <div className="grid grid-cols-[minmax(6rem,10rem)_7rem_minmax(0,1fr)_auto] items-center gap-x-2">+ <LemonInput+ size="small"+ className="font-mono"+ placeholder="variable_name"+ value={variable.name}+ disabled={disabled}+ onChange={(name) => update(index, { name })}+ aria-label={`Name of variable ${index + 1}`}+ />+ <LemonSelect+ size="small"+ fullWidth+ value={variable.type}+ disabled={disabled}+ onChange={(type) =>+ update(index, {+ type,+ // A value left over from the previous type would serialize+ // as the wrong shape, so refit it.+ value:+ coerceNotebookVariableValue(type, variable.value) ??+ DEFAULT_VALUE_BY_TYPE[type],+ })+ }+ options={NOTEBOOK_VARIABLE_TYPES.map((type) => ({+ value: type,+ label: TYPE_LABELS[type],+ }))}+ aria-label={`Type of ${variable.name || `variable ${index + 1}`}`}+ />+ {/* Wider gap here than between name and type: it separates what the+ variable is from what it currently holds. */}+ <div className="ml-4">+ {/* The name sits in an editable field, so it cannot label the+ value. A hidden label gives the control its own name. */}+ <label htmlFor={`${idPrefix}-${index}`} className="sr-only">+ {`Value of ${variable.name || `variable ${index + 1}`}`}+ </label>+ <NotebookVariableValueInput+ variable={variable}+ controlId={`${idPrefix}-${index}`}+ disabled={disabled}+ onChange={(value) => update(index, { value })}+ />+ </div>+ <LemonButton+ size="small"+ icon={<IconTrash />}+ tooltip="Remove variable"+ disabledReason={disabled ? 'This notebook is read-only' : undefined}+ onClick={() => onChange(variables.filter((_, i) => i !== index))}+ aria-label={`Remove ${variable.name || `variable ${index + 1}`}`}+ />+ </div>+ {errors[index] ? <span className="text-xs text-danger">{errors[index]}</span> : null}+ </div>+ ))+ )}+ <div>+ <LemonButton+ size="small"+ type="secondary"+ icon={<IconPlus />}+ disabledReason={+ disabled+ ? 'This notebook is read-only'+ : variables.length >= MAX_NOTEBOOK_VARIABLES+ ? `A notebook can have up to ${MAX_NOTEBOOK_VARIABLES} variables`+ : undefined+ }+ onClick={() => onChange([...variables, { name: '', type: 'string', value: '' }])}+ >+ Add variable+ </LemonButton>+ </div>+ </div>+ )+}++/** The panel bound to the notebook it belongs to. Renders nothing unless the bar is open. */+export function NotebookVariablesBar(): JSX.Element | null {+ const { variables, variableErrors, showVariables, isEditable } = useValues(notebookLogic)+ const { setVariables } = useActions(notebookLogic)++ if (!showVariables) {+ return null+ }++ return (+ <div className="mb-2">+ <NotebookVariablesPanel+ variables={variables}+ errors={variableErrors}+ disabled={!isEditable}+ onChange={setVariables}+ />+ </div>+ )+}diff --git a/frontend/src/scenes/notebooks/Notebook/markdownNotebookRunStatus.test.ts b/frontend/src/scenes/notebooks/Notebook/markdownNotebookRunStatus.test.tsindex af937bd5ba15..0e3c94cfc9d9 100644--- a/frontend/src/scenes/notebooks/Notebook/markdownNotebookRunStatus.test.ts+++ b/frontend/src/scenes/notebooks/Notebook/markdownNotebookRunStatus.test.ts@@ -2,7 +2,7 @@ import type { NotebookComponentRunStatus } from 'lib/components/MarkdownNotebookimport type { NotebookComponentBlockNode, NotebookComponentProps } from 'lib/components/MarkdownNotebook/types'import { resolveNotebookComponentRunStatus } from './markdownNotebookRunStatus'-import type { NotebookNodeRunTerminalStatus } from './notebookNodeStalenessLogic'+import type { NotebookNodeRunTerminalStatus, NotebookStaleReason } from './notebookNodeStalenessLogic'describe('markdownNotebookRunStatus', () => {const sqlCell = (props: NotebookComponentProps = {}, tagName = 'SQLV2'): NotebookComponentBlockNode => ({@@ -15,7 +15,7 @@ describe('markdownNotebookRunStatus', () => {const cases: {label: stringnode: NotebookComponentBlockNode- staleNodeIds?: Record<string, true>+ staleNodeIds?: Record<string, NotebookStaleReason>nodeRunStatuses?: Record<string, NotebookNodeRunTerminalStatus>expected: NotebookComponentRunStatus}[] = [@@ -42,7 +42,7 @@ describe('markdownNotebookRunStatus', () => {{label: 'a cell an upstream re-run outdated',node: sqlCell({ nodeId: 'node-1' }),- staleNodeIds: { 'node-1': true },+ staleNodeIds: { 'node-1': 'upstream' },nodeRunStatuses: { 'node-1': 'done' },expected: 'stale',},@@ -50,7 +50,7 @@ describe('markdownNotebookRunStatus', () => {// The failure, not the staleness, is what the user has to act on.label: 'a stale cell whose last run failed',node: sqlCell({ nodeId: 'node-1' }),- staleNodeIds: { 'node-1': true },+ staleNodeIds: { 'node-1': 'upstream' },nodeRunStatuses: { 'node-1': 'failed' },expected: 'error',},diff --git a/frontend/src/scenes/notebooks/Notebook/markdownNotebookRunStatus.ts b/frontend/src/scenes/notebooks/Notebook/markdownNotebookRunStatus.tsindex 54bac2c780bc..a04479e7887f 100644--- a/frontend/src/scenes/notebooks/Notebook/markdownNotebookRunStatus.ts+++ b/frontend/src/scenes/notebooks/Notebook/markdownNotebookRunStatus.ts@@ -6,7 +6,11 @@ import type { NotebookComponentBlockNode } from 'lib/components/MarkdownNotebookimport { NotebookNodeType } from '../types'import { MARKDOWN_TAG_TO_NOTEBOOK_NODE_TYPE } from './markdownNotebookRegistry'-import { NotebookNodeRunTerminalStatus, notebookNodeStalenessLogic } from './notebookNodeStalenessLogic'+import {+ NotebookNodeRunTerminalStatus,+ notebookNodeStalenessLogic,+ NotebookStaleReason,+} from './notebookNodeStalenessLogic'// Only the revamped code cells report run state. Every other block — markdown, insights, images —// has nothing to run, so it stays grey.@@ -19,7 +23,7 @@ const persistedRunStatus = (value: unknown): NotebookNodeRunTerminalStatus | undexport function resolveNotebookComponentRunStatus(node: NotebookComponentBlockNode,- staleNodeIds: Record<string, true>,+ staleNodeIds: Record<string, NotebookStaleReason>,nodeRunStatuses: Record<string, NotebookNodeRunTerminalStatus>): NotebookComponentRunStatus {if (!RUNNABLE_NODE_TYPES.includes(MARKDOWN_TAG_TO_NOTEBOOK_NODE_TYPE[node.tagName])) {diff --git a/frontend/src/scenes/notebooks/Notebook/notebookLogic.ts b/frontend/src/scenes/notebooks/Notebook/notebookLogic.tsindex 15b58e951155..bab8e3c4e2ac 100644--- a/frontend/src/scenes/notebooks/Notebook/notebookLogic.ts+++ b/frontend/src/scenes/notebooks/Notebook/notebookLogic.ts@@ -107,6 +107,7 @@ import { buildNotebookOpenedEvent } from './notebookAnalytics'import { shouldWarnBeforeLeavingNotebook } from './notebookBeforeUnload'import { notebookKernelInfoLogic } from './notebookKernelInfoLogic'import type { NotebookKernelInfo } from './notebookKernelInfoLogic'+import { notebookNodeStalenessLogic } from './notebookNodeStalenessLogic'import {NOTEBOOK_AI_PRESENCE_CLIENT_ID,NOTEBOOK_AI_PRESENCE_NAME,@@ -120,6 +121,13 @@ import {pruneNotebookRemotePresence,} from './notebookPresence'import { notebookSettingsLogic } from './notebookSettingsLogic'+import {+ NotebookVariable,+ getNotebookVariableConflictNames,+ getNotebookVariableErrors,+ getRunnableNotebookVariables,+ parseNotebookVariables,+} from './notebookVariables'/** Save debounce for local-only notebooks (scratchpad, canvas), which don't sync to the server. */export const SYNC_DELAY = 1000@@ -285,6 +293,7 @@ export interface notebookLogicValues {selectedCommentId: string | null // commentsLogickernelInfo: NotebookKernelInfo | null // notebookKernelInfoLogicshowKernelInfo: boolean // notebookSettingsLogic+ showVariablesOverride: boolean | null // notebookSettingsLogicnotebookTemplates: NotebookType[] // notebooksModelscratchpadNotebook: NotebookListItemType // notebooksModeluser: UserType | null // userLogic@@ -316,6 +325,7 @@ export interface notebookLogicValues {isShowingLeftColumn: booleanisTemplate: booleanlocalContent: JSONContent | null+ localVariables: NotebookVariable[] | nullmarkdownAIPresenceActive: booleanmarkdownEditorBuffer: string | nullmarkdownEditorDraft: string | null@@ -341,13 +351,17 @@ export interface notebookLogicValues {previewContent: JSONContent | nullpythonNodeIndices: Map<string, number>pythonNodeSummaries: PythonNodeSummary[]+ runnableVariables: NotebookVariable[]shortId: stringshouldBeEditable: booleanshowHistory: boolean+ showVariables: booleansqlNodeIndices: Map<string, number>sqlV2NodeSummaries: SqlV2NodeSummary[]syncStatus: NotebookSyncStatustitle: string+ variableErrors: (string | null)[]+ variables: NotebookVariable[]}// Generated by kea-typegen. Update if you're an agent, ignore if you're human.@@ -362,6 +376,9 @@ export interface notebookLogicActions {callback: ((event: { sent: boolean }) => void) | undefinedcontext: Record<string, any> | null} // commentsLogic+ setShowVariables: (showVariables: boolean | null) => {+ showVariables: boolean | null+ } // notebookSettingsLogicreceiveNotebookUpdate: (notebook: NotebookListItemType) => {notebook: NotebookListItemType} // notebooksModel@@ -391,6 +408,9 @@ export interface notebookLogicActions {clearLocalContent: () => {value: true}+ clearLocalVariables: () => {+ value: true+ }clearPreviewContent: () => {value: true}@@ -584,6 +604,9 @@ export interface notebookLogicActions {setShowHistory: (showHistory: boolean) => {showHistory: boolean}+ setVariables: (variables: NotebookVariable[]) => {+ variables: NotebookVariable[]+ }showMarkdownMergeConflictDetails: (conflicts: NotebookCollaborationConflict[]) => {conflicts: NotebookCollaborationConflict[]}@@ -633,7 +656,8 @@ export interface notebookLogicMeta {notebookLoading: boolean,localContent: JSONContent | null,isLocalOnly: boolean,- previewContent: JSONContent | null+ previewContent: JSONContent | null,+ localVariables: NotebookVariable[] | null) => NotebookSyncStatuseditingNodeLogics: (editingNodeIds: Record<string, true>,@@ -661,6 +685,10 @@ export interface notebookLogicMeta {duckSqlNodeIndices: (content: JSONContent) => Map<string, number>hogqlSqlNodeIndices: (content: JSONContent) => Map<string, number>isShowingLeftColumn: (showHistory: boolean) => boolean+ variables: (localVariables: NotebookVariable[] | null, notebook: NotebookType | null) => NotebookVariable[]+ variableErrors: (variables: NotebookVariable[], content: JSONContent) => (string | null)[]+ runnableVariables: (variables: NotebookVariable[], content: JSONContent) => NotebookVariable[]+ showVariables: (showVariablesOverride: boolean | null, variables: NotebookVariable[]) => booleancanEditNotebook: (previewContent: JSONContent | null,notebook: NotebookType | null,@@ -707,11 +735,13 @@ export const notebookLogic = kea<notebookLogicType>([notebookKernelInfoLogic({ shortId: props.shortId, mode: props.mode }),['kernelInfo'],notebookSettingsLogic,- ['showKernelInfo'],+ ['showKernelInfo', 'showVariablesOverride'],userLogic,['user'],],actions: [+ notebookSettingsLogic,+ ['setShowVariables'],notebooksModel,['receiveNotebookUpdate'],sidePanelStateLogic,@@ -740,6 +770,8 @@ export const notebookLogic = kea<notebookLogicType>([skipCapture,}),clearLocalContent: true,+ setVariables: (variables: NotebookVariable[]) => ({ variables }),+ clearLocalVariables: true,setPreviewContent: (jsonContent: JSONContent) => ({ jsonContent }),clearPreviewContent: true,loadNotebook: true,@@ -800,6 +832,16 @@ export const notebookLogic = kea<notebookLogicType>([clearLocalContent: () => null,},],+ // Local edits ahead of the saved notebook; null means "nothing edited yet, use the server's".+ localVariables: [+ null as NotebookVariable[] | null,+ {+ setVariables: (_, { variables }) => variables,+ // Dropped once the save round-trips, so `variables` falls back to the server's+ // copy and the bar stops reporting an unsaved edit that already landed.+ clearLocalVariables: () => null,+ },+ ],previewContent: [null as JSONContent | null,{@@ -1132,6 +1174,9 @@ export const notebookLogic = kea<notebookLogicType>([content,text_content: textContent,title,+ // The copied cells keep their `{name}` references, so a duplicate without+ // the variables fails every SQL cell that reads one.+ ...(values.variables.length ? { variables: values.variables } : {}),})posthog.capture(`notebook duplicated`, {@@ -1266,13 +1311,14 @@ export const notebookLogic = kea<notebookLogicType>([},],syncStatus: [- (s) => [s.notebook, s.notebookLoading, s.localContent, s.isLocalOnly, s.previewContent],+ (s) => [s.notebook, s.notebookLoading, s.localContent, s.isLocalOnly, s.previewContent, s.localVariables],(notebook: NotebookType | null,notebookLoading: boolean,localContent: JSONContent | null,isLocalOnly: boolean,- previewContent: JSONContent | null+ previewContent: JSONContent | null,+ localVariables: NotebookVariable[] | null): NotebookSyncStatus => {if (previewContent || notebook?.is_template) {return 'synced'@@ -1281,7 +1327,9 @@ export const notebookLogic = kea<notebookLogicType>([if (isLocalOnly) {return 'local'}- if (!notebook || !localContent) {+ // Variables save on their own PATCH, so an edit to them is unsaved work even+ // when the document itself is clean.+ if (!notebook || (!localContent && !localVariables)) {return 'synced'}@@ -1378,6 +1426,31 @@ export const notebookLogic = kea<notebookLogicType>([isShowingLeftColumn: [(s) => [s.showHistory], (showHistory: boolean) => showHistory],+ // Local edits win while they exist; otherwise the saved notebook is the source.+ variables: [+ (s) => [s.localVariables, s.notebook],+ (localVariables: NotebookVariable[] | null, notebook: NotebookType | null): NotebookVariable[] =>+ localVariables ?? parseNotebookVariables(notebook?.variables),+ ],+ variableErrors: [+ (s) => [s.variables, s.content],+ (variables: NotebookVariable[], content: JSONContent): (string | null)[] =>+ getNotebookVariableErrors(variables, getNotebookVariableConflictNames(content)),+ ],+ // Only valid, unique declarations are safe to bind into a run.+ runnableVariables: [+ (s) => [s.variables, s.content],+ (variables: NotebookVariable[], content: JSONContent): NotebookVariable[] =>+ getRunnableNotebookVariables(variables, getNotebookVariableConflictNames(content)),+ ],+ // Open by default only once the notebook has variables — an empty bar is noise on a+ // notebook that does not use them. The toggle overrides in both directions.+ showVariables: [+ (s) => [s.showVariablesOverride, s.variables],+ (showVariablesOverride: boolean | null, variables: NotebookVariable[]): boolean =>+ showVariablesOverride ?? variables.length > 0,+ ],+// Whether this reader may change the notebook at all, independent of the view/edit toggle.// A canvas is local to the reader, so it always qualifies. A history preview never does,// because it shows a version the reader is not editing. Gate a control that has to work in@@ -1457,7 +1530,51 @@ export const notebookLogic = kea<notebookLogicType>([},],}),- listeners(({ values, actions, cache }) => ({+ listeners(({ values, actions, cache, props, selectors }) => ({+ // Variables save on their own PATCH rather than through the markdown save path: they are+ // a notebook property, not document content. Debounced so typing a name is one request.+ setVariables: async ({ variables }, breakpoint, _action, previousState) => {+ // Every cell that reads a changed variable now shows a result computed from the old+ // value, so mark it (and its downstream) stale — the same contract as an upstream+ // cell's run landing. Diffed against the pre-reducer state so a rename counts as+ // both halves: the old name disappeared and the new one appeared.+ const previous = selectors.variables(previousState)+ const previousByName = new Map(previous.map((variable) => [variable.name, variable.value]))+ const nextByName = new Map(variables.map((variable) => [variable.name, variable.value]))+ const affected = new Set<string>()+ for (const [name, value] of nextByName) {+ if (!previousByName.has(name) || previousByName.get(name) !== value) {+ affected.add(name)+ }+ }+ for (const name of previousByName.keys()) {+ if (!nextByName.has(name)) {+ affected.add(name)+ }+ }+ notebookNodeStalenessLogic+ .findMounted({ shortId: props.shortId })+ ?.actions.variablesChanged([...affected].filter(Boolean), values.content)++ if (values.isLocalOnly || !values.notebook) {+ return+ }+ await breakpoint(500)+ try {+ const response = await api.notebooks.update(props.shortId, { variables: values.variables })+ actions.receiveNotebookUpdate(response)+ // Only drop the local copy when it still matches what we just saved — a keystroke+ // that landed during the request is newer and must survive to its own save.+ if (values.localVariables === variables) {+ actions.clearLocalVariables()+ }+ } catch (error) {+ // The bar keeps the edit, so the next change retries it. Losing a value silently+ // would be worse than an error the user can act on.+ lemonToast.error('Could not save notebook variables')+ posthog.captureException(error)+ }+ },connectMarkdownUpdateStream: () => {if (!values.markdownRealtimeEnabled) {returndiff --git a/frontend/src/scenes/notebooks/Notebook/notebookNodeStalenessLogic.test.ts b/frontend/src/scenes/notebooks/Notebook/notebookNodeStalenessLogic.test.tsindex 565e7e7ef71b..175c8ec85642 100644--- a/frontend/src/scenes/notebooks/Notebook/notebookNodeStalenessLogic.test.ts+++ b/frontend/src/scenes/notebooks/Notebook/notebookNodeStalenessLogic.test.ts@@ -78,7 +78,7 @@ describe('notebookNodeStalenessLogic', () => {stalenessLogic.actions.nodeRunFinished('a', 'done', content)await expectLogic(stalenessLogic).toFinishAllListeners()// b reads a directly; c reads b, so staleness must propagate transitively.- expect(stalenessLogic.values.staleNodeIds).toEqual({ b: true, c: true })+ expect(stalenessLogic.values.staleNodeIds).toEqual({ b: 'upstream', c: 'upstream' })// The finished cell is remembered as the last run with its still-stale downstream,// which is what surfaces the "run downstream cells" button on it.expect(stalenessLogic.values.lastRunNodeId).toEqual('a')@@ -97,7 +97,7 @@ describe('notebookNodeStalenessLogic', () => {await expectLogic(stalenessLogic).toFinishAllListeners()expect(runSpy.mock.calls.map((call) => call[1].node_id)).toEqual(['b', 'c'])- expect(stalenessLogic.values.staleNodeIds).toEqual({ x: true })+ expect(stalenessLogic.values.staleNodeIds).toEqual({ x: 'upstream' })expect(stalenessLogic.values.chainQueue).toEqual([])})@@ -151,7 +151,7 @@ describe('notebookNodeStalenessLogic', () => {expect(runSpy.mock.calls.map((call) => call[1].node_id)).toEqual(['b'])expect(stalenessLogic.values.chainQueue).toEqual([])// The unmounted cell keeps its flag — it was never re-run.- expect(stalenessLogic.values.staleNodeIds).toEqual({ c: true })+ expect(stalenessLogic.values.staleNodeIds).toEqual({ c: 'upstream' })})it('the chain stops when a cell does not finish successfully', async () => {@@ -167,7 +167,41 @@ describe('notebookNodeStalenessLogic', () => {expect(runSpy).toHaveBeenCalledTimes(1)expect(stalenessLogic.values.chainQueue).toEqual([])// The failed cell stays stale so the user can see what still needs a successful run.- expect(stalenessLogic.values.staleNodeIds).toEqual({ b: true, c: true })+ expect(stalenessLogic.values.staleNodeIds).toEqual({ b: 'upstream', c: 'upstream' })+ })++ it('changing a variable marks the cells that read it, and their downstream, stale', async () => {+ // Without this the cell keeps showing a result computed from the old value, with+ // nothing on screen saying so. `b` reads {threshold}; `c` reads b's frame.+ const variableContent: JSONContent = {+ type: 'doc',+ content: [+ { type: NotebookNodeType.SQLV2, attrs: { nodeId: 'a', returnVariable: 'sql_df', code: 'select 1' } },+ {+ type: NotebookNodeType.PythonV2,+ attrs: { nodeId: 'b', returnVariable: 'new_events', code: 'new_events = sql_df.head(threshold)' },+ },+ {+ type: NotebookNodeType.SQLV2,+ attrs: { nodeId: 'c', returnVariable: 'joined', code: 'select * from new_events' },+ },+ { type: NotebookNodeType.SQLV2, attrs: { nodeId: 'x', returnVariable: 'other_df', code: 'select 2' } },+ ],+ }++ stalenessLogic.actions.variablesChanged(['threshold'], variableContent)+ await expectLogic(stalenessLogic).toFinishAllListeners()++ // `a` does not read it and `x` is unrelated, so neither is disturbed. The reason rides+ // along so the cell's banner names the variable rather than an upstream re-run.+ expect(stalenessLogic.values.staleNodeIds).toEqual({ b: 'variable', c: 'variable' })+ })++ it('changing a variable no cell reads marks nothing stale', async () => {+ stalenessLogic.actions.variablesChanged(['unused'], content)+ await expectLogic(stalenessLogic).toFinishAllListeners()++ expect(stalenessLogic.values.staleNodeIds).toEqual({})})it('a second runStaleChain while one is active is refused', async () => {diff --git a/frontend/src/scenes/notebooks/Notebook/notebookNodeStalenessLogic.ts b/frontend/src/scenes/notebooks/Notebook/notebookNodeStalenessLogic.tsindex 98dc5ceb83a5..20c4e5ae98b2 100644--- a/frontend/src/scenes/notebooks/Notebook/notebookNodeStalenessLogic.ts+++ b/frontend/src/scenes/notebooks/Notebook/notebookNodeStalenessLogic.ts@@ -9,15 +9,41 @@ import {collectDependencyNodeIds,} from '../Nodes/notebookNodeContent'import { NotebookNodeType } from '../types'+import { cellReadsNotebookVariable } from './notebookVariables'export type NotebookNodeRunTerminalStatus = 'done' | 'failed' | 'interrupted'+/** Why a cell's stored result no longer reflects the notebook — drives the stale banner's wording. */+export type NotebookStaleReason = 'upstream' | 'variable'+export interface NotebookNodeStalenessLogicProps {shortId: string}const V2_NODE_TYPES: string[] = [NotebookNodeType.SQLV2, NotebookNodeType.PythonV2]+/**+ * Cells whose last result no longer reflects the notebook's variables: the ones that read a+ * changed variable, plus everything transitively downstream of them (their inputs are now stale+ * too). Same shape as `staleDownstreamNodeIds`, but rooted in a variable rather than a run.+ */+const variableDependentNodeIds = (graph: NotebookDependencyGraph, variableNames: string[]): string[] => {+ const readers = graph.nodes.filter(+ (node) =>+ V2_NODE_TYPES.includes(node.nodeType) &&+ variableNames.some((name) => cellReadsNotebookVariable(node.code ?? '', node.nodeType, name))+ )+ const affected = new Set<string>()+ for (const reader of readers) {+ for (const nodeId of collectDependencyNodeIds(graph, reader.nodeId, 'downstream')) {+ affected.add(nodeId)+ }+ }+ return graph.nodes+ .filter((node) => affected.has(node.nodeId) && V2_NODE_TYPES.includes(node.nodeType))+ .map((node) => node.nodeId)+}+const staleDownstreamNodeIds = (graph: NotebookDependencyGraph, nodeId: string): string[] => {const downstream = collectDependencyNodeIds(graph, nodeId, 'downstream')downstream.delete(nodeId)@@ -33,7 +59,7 @@ const staleDownstreamNodeIds = (graph: NotebookDependencyGraph, nodeId: string):// up by nobody, which would leave the chain queue wedged forever.const runnableStaleNodeIds = (graph: NotebookDependencyGraph,- staleNodeIds: Record<string, true>,+ staleNodeIds: Record<string, NotebookStaleReason>,mountedNodeIds: Record<string, true>): string[] =>graph.nodes@@ -53,7 +79,7 @@ export interface notebookNodeStalenessLogicValues {mountedNodeIds: Record<string, true>nodeRunStatuses: Record<string, NotebookNodeRunTerminalStatus>staleCount: number- staleNodeIds: Record<string, true>+ staleNodeIds: Record<string, NotebookStaleReason>}// Generated by kea-typegen. Update if you're an agent, ignore if you're human.@@ -67,8 +93,12 @@ export interface notebookNodeStalenessLogicActions {dispatchChainRun: (nodeId: string) => {nodeId: string}- markStaleNodeIds: (nodeIds: string[]) => {+ markStaleNodeIds: (+ nodeIds: string[],+ reason?: NotebookStaleReason+ ) => {nodeIds: string[]+ reason: NotebookStaleReason}nodeRunFinished: (nodeId: string,@@ -105,17 +135,24 @@ export interface notebookNodeStalenessLogicActions {unregisterChainNode: (nodeId: string) => {nodeId: string}+ variablesChanged: (+ variableNames: string[],+ content: JSONContent | null+ ) => {+ content: JSONContent | null+ variableNames: string[]+ }}// Generated by kea-typegen. Update if you're an agent, ignore if you're human.export interface notebookNodeStalenessLogicMeta {key: string__keaTypeGenInternalSelectorTypes: {- staleCount: (staleNodeIds: Record<string, true>) => number+ staleCount: (staleNodeIds: Record<string, NotebookStaleReason>) => numberisChainRunning: (chainQueue: string[]) => booleanlastRunStaleDownstreamNodeIds: (lastRunDownstreamNodeIds: string[],- staleNodeIds: Record<string, true>+ staleNodeIds: Record<string, NotebookStaleReason>) => string[]}}@@ -150,7 +187,7 @@ export const notebookNodeStalenessLogic = kea<notebookNodeStalenessLogicType>([status,content,}),- markStaleNodeIds: (nodeIds: string[]) => ({ nodeIds }),+ markStaleNodeIds: (nodeIds: string[], reason: NotebookStaleReason = 'upstream') => ({ nodeIds, reason }),clearNodeStale: (nodeId: string) => ({ nodeId }),// With a rootNodeId the chain is scoped to that cell's transitive downstream (the// "run downstream cells" button on the cell that just ran); without one it runs@@ -166,18 +203,21 @@ export const notebookNodeStalenessLogic = kea<notebookNodeStalenessLogicType>([// to a cell whose logic is mounted and listening.registerChainNode: (nodeId: string) => ({ nodeId }),unregisterChainNode: (nodeId: string) => ({ nodeId }),+ // A notebook variable was added, renamed, retyped, given a new value, or deleted.+ // Reported by the Variables block; `content` is the document the change produced.+ variablesChanged: (variableNames: string[], content: JSONContent | null) => ({ variableNames, content }),}),reducers({staleNodeIds: [- {} as Record<string, true>,+ {} as Record<string, NotebookStaleReason>,{- markStaleNodeIds: (state, { nodeIds }) => {+ markStaleNodeIds: (state, { nodeIds, reason }) => {if (!nodeIds.length) {return state}const next = { ...state }nodeIds.forEach((nodeId) => {- next[nodeId] = true+ next[nodeId] = reason})return next},@@ -248,14 +288,14 @@ export const notebookNodeStalenessLogic = kea<notebookNodeStalenessLogicType>([selectors({staleCount: [(s) => [s.staleNodeIds],- (staleNodeIds: Record<string, true>): number => Object.keys(staleNodeIds).length,+ (staleNodeIds: Record<string, NotebookStaleReason>): number => Object.keys(staleNodeIds).length,],isChainRunning: [(s) => [s.chainQueue], (chainQueue: string[]): boolean => chainQueue.length > 0],// The still-stale part of the last run's downstream; empties as cells re-run, which// is what hides the "run downstream cells" button once everything is fresh again.lastRunStaleDownstreamNodeIds: [(s) => [s.lastRunDownstreamNodeIds, s.staleNodeIds],- (lastRunDownstreamNodeIds: string[], staleNodeIds: Record<string, true>): string[] =>+ (lastRunDownstreamNodeIds: string[], staleNodeIds: Record<string, NotebookStaleReason>): string[] =>lastRunDownstreamNodeIds.filter((nodeId) => staleNodeIds[nodeId]),],}),@@ -316,6 +356,15 @@ export const notebookNodeStalenessLogic = kea<notebookNodeStalenessLogicType>([actions.setChainQueue(queue)actions.dispatchChainRun(queue[0])},+ variablesChanged: ({ variableNames, content }) => {+ if (!variableNames.length || !content) {+ return+ }+ actions.markStaleNodeIds(+ variableDependentNodeIds(buildNotebookDependencyGraph(content), variableNames),+ 'variable'+ )+ },abortChain: ({ reason }) => {if (reason) {lemonToast.warning('Stopped re-running stale cells: a cell did not finish successfully.')diff --git a/frontend/src/scenes/notebooks/Notebook/notebookSettingsLogic.ts b/frontend/src/scenes/notebooks/Notebook/notebookSettingsLogic.tsindex 975409c720c9..3cc0f21f08a0 100644--- a/frontend/src/scenes/notebooks/Notebook/notebookSettingsLogic.ts+++ b/frontend/src/scenes/notebooks/Notebook/notebookSettingsLogic.ts@@ -4,6 +4,7 @@ import { MakeLogicType, actions, kea, path, reducers } from 'kea'export interface notebookSettingsLogicValues {isMarkdownExpanded: booleanshowKernelInfo: boolean+ showVariablesOverride: boolean | null}// Generated by kea-typegen. Update if you're an agent, ignore if you're human.@@ -14,6 +15,9 @@ export interface notebookSettingsLogicActions {setShowKernelInfo: (showKernelInfo: boolean) => {showKernelInfo: boolean}+ setShowVariables: (showVariables: boolean | null) => {+ showVariables: boolean | null+ }}export type notebookSettingsLogicType = MakeLogicType<notebookSettingsLogicValues, notebookSettingsLogicActions>@@ -24,6 +28,8 @@ export const notebookSettingsLogic = kea<notebookSettingsLogicType>([actions({setIsMarkdownExpanded: (expanded: boolean) => ({ expanded }),setShowKernelInfo: (showKernelInfo: boolean) => ({ showKernelInfo }),+ // null restores the default: open when the notebook declares variables, closed when not.+ setShowVariables: (showVariables: boolean | null) => ({ showVariables }),}),reducers(() => ({isMarkdownExpanded: [@@ -39,5 +45,11 @@ export const notebookSettingsLogic = kea<notebookSettingsLogicType>([setShowKernelInfo: (_, { showKernelInfo }) => showKernelInfo,},],+ showVariablesOverride: [+ null as boolean | null,+ {+ setShowVariables: (_, { showVariables }) => showVariables,+ },+ ],})),])diff --git a/frontend/src/scenes/notebooks/Notebook/notebookVariables.test.ts b/frontend/src/scenes/notebooks/Notebook/notebookVariables.test.tsnew file mode 100644index 000000000000..5c67b00058ae--- /dev/null+++ b/frontend/src/scenes/notebooks/Notebook/notebookVariables.test.ts@@ -0,0 +1,122 @@+import { JSONContent } from 'lib/components/RichContentEditor/types'++import { NotebookNodeType } from '../types'+import {+ NotebookVariable,+ extractSqlVariableReferences,+ getNotebookVariableConflictNames,+ getNotebookVariableErrors,+ getRunnableNotebookVariables,+ parseNotebookVariables,+} from './notebookVariables'++describe('notebookVariables', () => {+ const country: NotebookVariable = { name: 'country', type: 'string', value: 'US' }++ describe('extractSqlVariableReferences', () => {+ it.each([+ ['a placeholder', 'select 1 where c = {country}', ['country']],+ ['each name once', 'select {a}, {a}, {b}', ['a', 'b']],+ // A name mentioned in prose or an example must not mark the cell stale, nor bind.+ ['not inside a line comment', '-- see {country}\nselect 1', []],+ ['not inside a string literal', "select '{country}' as label", []],+ ['not a dotted chain', 'select {variables.country}', []],+ ['not a struct literal', "select {'a': 1}", []],+ ])('finds %s', (_name, sql, expected) => {+ expect(extractSqlVariableReferences(sql)).toEqual(expected)+ })+ })++ describe('parseNotebookVariables', () => {+ it('reads the notebook column', () => {+ expect(+ parseNotebookVariables([+ { name: 'country', type: 'string', value: 'US' },+ { name: 'lookback_days', type: 'number', value: 30 },+ ])+ ).toEqual([+ { name: 'country', type: 'string', value: 'US' },+ { name: 'lookback_days', type: 'number', value: 30 },+ ])+ })++ it.each([+ ['null', null],+ ['a non-array', { name: 'country' }],+ ])('returns nothing for %s', (_name, value) => {+ expect(parseNotebookVariables(value)).toEqual([])+ })++ it('drops a malformed entry without losing its neighbours', () => {+ // The column is plain JSON the API can write, so one bad entry must not blank the bar.+ expect(parseNotebookVariables(['nonsense', { name: 'country', type: 'string', value: 'US' }])).toEqual([+ country,+ ])+ })++ it('coerces a value that does not match its declared type', () => {+ expect(parseNotebookVariables([{ name: 'days', type: 'number', value: '30' }])).toEqual([+ { name: 'days', type: 'number', value: 30 },+ ])+ })+ })++ describe('getNotebookVariableErrors', () => {+ it.each([+ ['an empty name', '', 'Give the variable a name.'],+ ['a hyphen', 'look-back', 'Use letters, numbers, and underscores.'],+ ['a leading digit', '7days', "The name can't start with a number."],+ // HogQL injects its own {filters}, so a variable could never be read under that name.+ ['the reserved filters name', 'filters', 'reserved'],+ ])('rejects %s', (_name, variableName, expected) => {+ const [error] = getNotebookVariableErrors([{ name: variableName, type: 'string', value: '' }])+ expect(error).toContain(expected)+ })++ it('rejects the second of two declarations sharing a name', () => {+ const errors = getNotebookVariableErrors([country, { ...country, value: 'DE' }])+ expect(errors[0]).toBeNull()+ expect(errors[1]).toContain('already declared')+ })++ it("rejects a name a cell's output dataframe already uses", () => {+ // Both land in one kernel namespace, so sharing a name means one clobbers the other.+ const errors = getNotebookVariableErrors(+ [{ name: 'sql_df', type: 'string', value: 'US' }],+ new Set(['sql_df'])+ )+ expect(errors[0]).toContain('output dataframe')+ })++ it('accepts a plain identifier', () => {+ expect(getNotebookVariableErrors([{ name: 'lookback_days', type: 'number', value: 30 }])).toEqual([null])+ })+ })++ describe('getNotebookVariableConflictNames', () => {+ it('collects the dataframe names of the revamped cells', () => {+ const content: JSONContent = {+ type: 'doc',+ content: [+ { type: NotebookNodeType.SQLV2, attrs: { nodeId: 'a', returnVariable: 'sql_df', code: '' } },+ { type: NotebookNodeType.PythonV2, attrs: { nodeId: 'b', returnVariable: 'frame', code: '' } },+ ],+ }+ expect(getNotebookVariableConflictNames(content)).toEqual(new Set(['sql_df', 'frame']))+ })+ })++ describe('getRunnableNotebookVariables', () => {+ it('sends only the declarations that pass validation', () => {+ // An invalid name would reach the backend as a variable no cell can read, and a+ // duplicate would make which value binds depend on ordering.+ expect(+ getRunnableNotebookVariables([+ country,+ { name: 'look-back', type: 'number', value: 7 },+ { ...country, value: 'DE' },+ ])+ ).toEqual([country])+ })+ })+})diff --git a/frontend/src/scenes/notebooks/Notebook/notebookVariables.ts b/frontend/src/scenes/notebooks/Notebook/notebookVariables.tsnew file mode 100644index 000000000000..13bac2f9d979--- /dev/null+++ b/frontend/src/scenes/notebooks/Notebook/notebookVariables.ts@@ -0,0 +1,190 @@+import { JSONContent } from 'lib/components/RichContentEditor/types'++import { collectNotebookFrameNodes, extractPythonIdentifiers } from '../Nodes/notebookNodeContent'+import { NotebookNodeType } from '../types'++export type NotebookVariableType = 'string' | 'number' | 'boolean' | 'date'++export const NOTEBOOK_VARIABLE_TYPES: NotebookVariableType[] = ['string', 'number', 'boolean', 'date']++/** Mirrors MAX_VARIABLES_PER_NOTEBOOK / MAX_VARIABLE_VALUE_CHARS in sql_v2_serializers.py,+ * so the bar stops at the limit instead of letting a save fail. */+export const MAX_NOTEBOOK_VARIABLES = 10+export const MAX_NOTEBOOK_VARIABLE_VALUE_CHARS = 1000++export type NotebookVariableValue = string | number | boolean | null++export type NotebookVariable = {+ name: string+ type: NotebookVariableType+ value: NotebookVariableValue+}++/**+ * HogQL injects its own `{filters}` placeholder into notebook queries, so a variable of that+ * name could never be read — the filter injection wins. Rejected at declaration rather than+ * silently shadowed.+ */+export const RESERVED_NOTEBOOK_VARIABLE_NAMES = new Set(['filters'])++/**+ * A variable is referenced as a bare `{name}` placeholder in SQL and as a plain global in+ * Python, so only a plain identifier can ever be resolved. Same rule as a cell's dataframe name.+ */+const VALID_VARIABLE_NAME = /^[A-Za-z_][A-Za-z0-9_]*$/++const stripSqlComments = (sql: string): string => sql.replace(/--.*$/gm, '').replace(/\/\*[\s\S]*?\*\//g, '')++/** String literals, blanked before scanning so a `'{country}'` inside a literal is not a reference. */+const SQL_STRING_LITERAL = /'(?:[^'\\]|\\.|'')*'/g++/**+ * The bare `{name}` placeholders a SQL cell reads. Comments and string literals are blanked+ * first, so only a real placeholder position counts.+ *+ * Deliberately the same single-brace form the legacy HogQLSQL cell uses for kernel globals:+ * that cell type is no longer insertable, and one syntax beats two in the cells people write now.+ */+export function extractSqlVariableReferences(sql: string): string[] {+ const scannable = stripSqlComments(sql || '').replace(SQL_STRING_LITERAL, ' ')+ const names: string[] = []+ const pattern = /\{([A-Za-z_][A-Za-z0-9_]*)\}/g+ let match = pattern.exec(scannable)+ while (match) {+ if (!names.includes(match[1])) {+ names.push(match[1])+ }+ match = pattern.exec(scannable)+ }+ return names+}++function toVariableType(value: unknown): NotebookVariableType {+ return typeof value === 'string' && (NOTEBOOK_VARIABLE_TYPES as string[]).includes(value)+ ? (value as NotebookVariableType)+ : 'string'+}++function toVariableValue(value: unknown): NotebookVariableValue {+ if (value === undefined || value === null) {+ return null+ }+ return typeof value === 'string' || typeof value === 'number' || typeof value === 'boolean' ? value : null+}++/**+ * Read the declarations off a notebook. Tolerant on purpose: the column is plain JSON that+ * older clients and the API can write, and one malformed entry must not blank the rest.+ */+export function parseNotebookVariables(value: unknown): NotebookVariable[] {+ if (!Array.isArray(value)) {+ return []+ }+ return value.flatMap((item): NotebookVariable[] => {+ if (!item || typeof item !== 'object' || Array.isArray(item)) {+ return []+ }+ const entry = item as Record<string, unknown>+ const type = toVariableType(entry.type)+ return [+ {+ name: typeof entry.name === 'string' ? entry.name.trim() : '',+ type,+ value: coerceNotebookVariableValue(type, toVariableValue(entry.value)),+ },+ ]+ })+}++/** Fit a value to its declared type, so a type switch in the editor never leaves a stale shape behind. */+export function coerceNotebookVariableValue(+ type: NotebookVariableType,+ value: NotebookVariableValue+): NotebookVariableValue {+ if (value === null) {+ return null+ }+ if (type === 'number') {+ const numeric = typeof value === 'number' ? value : Number(String(value).trim())+ return Number.isFinite(numeric) ? numeric : null+ }+ if (type === 'boolean') {+ return typeof value === 'boolean' ? value : String(value).trim().toLowerCase() === 'true'+ }+ return typeof value === 'string' ? value : String(value)+}++/** Names a variable must not take: every cell's output dataframe, which shares the kernel namespace. */+export function getNotebookVariableConflictNames(content?: JSONContent | null): Set<string> {+ return new Set(collectNotebookFrameNodes(content).map((node) => node.name))+}++/**+ * Per-declaration validation error, keyed by the variable's index, or null when the declaration+ * is usable. Uniqueness is checked against the other declarations and against cell dataframe+ * names: a Python cell reads both out of one kernel namespace, so a shared name means one+ * silently clobbers the other.+ */+export function getNotebookVariableErrors(+ variables: NotebookVariable[],+ conflictNames: Set<string> = new Set()+): (string | null)[] {+ const countsByName = variables.reduce<Record<string, number>>((counts, variable) => {+ counts[variable.name] = (counts[variable.name] ?? 0) + 1+ return counts+ }, {})++ return variables.map((variable, index) => {+ if (!variable.name) {+ return 'Give the variable a name.'+ }+ if (!VALID_VARIABLE_NAME.test(variable.name)) {+ const suggestion = variable.name.replace(/[^A-Za-z0-9_]/g, '_').replace(/^(?=\d)/, '_')+ const hint = VALID_VARIABLE_NAME.test(suggestion) ? ` Try ${suggestion}.` : ''+ // Name only the rule that was actually broken, so `look-back` isn't told it starts+ // with a number.+ const startsWithDigit = /^\d/.test(variable.name)+ const hasInvalidChars = /[^A-Za-z0-9_]/.test(variable.name)+ const reason =+ startsWithDigit && hasInvalidChars+ ? "Use letters, numbers, and underscores, and don't start with a number."+ : startsWithDigit+ ? "The name can't start with a number."+ : 'Use letters, numbers, and underscores.'+ return `${reason}${hint}`+ }+ if (RESERVED_NOTEBOOK_VARIABLE_NAMES.has(variable.name)) {+ return `${variable.name} is reserved by PostHog. Pick another name.`+ }+ if (countsByName[variable.name] > 1 && variables.findIndex((other) => other.name === variable.name) !== index) {+ return `${variable.name} is already declared. Names must be unique.`+ }+ if (conflictNames.has(variable.name)) {+ return `${variable.name} is already a cell's output dataframe. Names must be unique.`+ }+ return null+ })+}++/** Declarations that are safe to send to a run: named, valid, and unique. */+export function getRunnableNotebookVariables(+ variables: NotebookVariable[],+ conflictNames: Set<string> = new Set()+): NotebookVariable[] {+ const errors = getNotebookVariableErrors(variables, conflictNames)+ return variables.filter((_, index) => errors[index] === null)+}++/**+ * Whether a cell's code reads `variableName`. SQL reads it as a `{name}` placeholder; Python reads+ * it as a plain global, so the rough identifier scan is reused (a false positive only marks an+ * extra cell stale).+ */+export function cellReadsNotebookVariable(code: string, nodeType: NotebookNodeType, variableName: string): boolean {+ if (!variableName) {+ return false+ }+ return nodeType === NotebookNodeType.PythonV2+ ? extractPythonIdentifiers(code).includes(variableName)+ : extractSqlVariableReferences(code).includes(variableName)+}diff --git a/frontend/src/scenes/notebooks/Notebook/notebookVariablesWiring.test.ts b/frontend/src/scenes/notebooks/Notebook/notebookVariablesWiring.test.tsnew file mode 100644index 000000000000..98f0fe65a5f3--- /dev/null+++ b/frontend/src/scenes/notebooks/Notebook/notebookVariablesWiring.test.ts@@ -0,0 +1,100 @@+import { expectLogic } from 'kea-test-utils'++import api from 'lib/api'++import { useMocks } from '~/mocks/jest'+import { initKeaTests } from '~/test/init'+import { AccessControlLevel } from '~/types'++import { NotebookType } from '../types'+import { buildMarkdownNotebookContent } from './markdownNotebookV2'+import { notebookLogic } from './notebookLogic'+import { notebookNodeStalenessLogic } from './notebookNodeStalenessLogic'++jest.mock('./migrations/migrate', () => {+ const actual = jest.requireActual('./migrations/migrate')+ return { ...actual, migrate: jest.fn(async (notebook: unknown) => notebook) }+})++const SHORT_ID = 'vars-wiring'++// `sql_cell` reads {country}; `py_cell` reads sql_cell's frame, so it is downstream.+const MARKDOWN = [+ '<SQLV2 nodeId="sql_cell" returnVariable="sql_df" code="select {country} as c" />',+ '<PythonV2 nodeId="py_cell" returnVariable="py_df" code="out = sql_df.head()" />',+].join('\n\n')++const notebookFixture = {+ id: 'notebook-id',+ short_id: SHORT_ID,+ title: 'Variables wiring',+ content: buildMarkdownNotebookContent(MARKDOWN),+ text_content: '',+ version: 1,+ deleted: false,+ is_template: false,+ user_access_level: AccessControlLevel.Editor,+ created_at: '2025-01-01T00:00:00Z',+ created_by: null,+ last_modified_at: '2025-01-01T00:00:00Z',+ last_modified_by: null,+ variables: [{ name: 'country', type: 'string', value: 'US' }],+} as unknown as NotebookType++describe('notebook variables wiring', () => {+ let logic: ReturnType<typeof notebookLogic.build>+ let stalenessLogic: ReturnType<typeof notebookNodeStalenessLogic.build>++ beforeEach(() => {+ localStorage.clear()+ useMocks({+ get: {+ [`/api/projects/@current/notebooks/${SHORT_ID}/`]: () => [200, notebookFixture],+ [`/api/projects/:project_id/notebooks/${SHORT_ID}/`]: () => [200, notebookFixture],+ [`/api/projects/:project_id/notebooks/${SHORT_ID}/kernel/status/`]: () => [200, { backend: null }],+ },+ })+ initKeaTests()+ jest.spyOn(api.notebooks, 'collabStream').mockResolvedValue(undefined as any)+ jest.spyOn(api.notebooks, 'update').mockResolvedValue({ ...notebookFixture, version: 2 })++ stalenessLogic = notebookNodeStalenessLogic({ shortId: SHORT_ID })+ stalenessLogic.mount()+ logic = notebookLogic({ shortId: SHORT_ID, mode: 'notebook', cachedNotebook: notebookFixture })+ logic.mount()+ logic.actions.loadNotebook()+ })++ afterEach(() => {+ logic?.unmount()+ stalenessLogic?.unmount()+ jest.restoreAllMocks()+ })++ it('changing a value through the bar marks the reading cell and its downstream stale', async () => {+ await expectLogic(logic).toFinishAllListeners()+ // Goes through the action the bar actually dispatches. Asserting `variablesChanged`+ // directly would pass even with the listener unwired, which is how this regressed.+ logic.actions.setVariables([{ name: 'country', type: 'string', value: 'DE' }])+ await expectLogic(logic).toFinishAllListeners()++ expect(stalenessLogic.values.staleNodeIds).toEqual({ sql_cell: 'variable', py_cell: 'variable' })+ })++ it('reads the saved variables off the notebook', async () => {+ await expectLogic(logic).toFinishAllListeners()+ expect(logic.values.variables).toEqual([{ name: 'country', type: 'string', value: 'US' }])+ })++ it('an edit counts as unsaved work until the save lands', async () => {+ // Variables save on their own PATCH, so the document being clean must not report+ // "synced" while a variable edit is still pending — that also drives the+ // navigate-away warning.+ await expectLogic(logic).toFinishAllListeners()+ logic.actions.setVariables([{ name: 'country', type: 'string', value: 'DE' }])+ expect(logic.values.syncStatus).toEqual('unsaved')++ await expectLogic(logic).toFinishAllListeners()+ expect(logic.values.localVariables).toBeNull()+ })+})diff --git a/frontend/src/scenes/notebooks/NotebookScene.tsx b/frontend/src/scenes/notebooks/NotebookScene.tsxindex f62ce4bb4ce3..8c59ff3f8cf3 100644--- a/frontend/src/scenes/notebooks/NotebookScene.tsx+++ b/frontend/src/scenes/notebooks/NotebookScene.tsx@@ -23,6 +23,7 @@ import { notebookLogic } from './Notebook/notebookLogic'import {NotebookExpandButton,NotebookKernelInfoButton,+ NotebookVariablesButton,NotebookPresence,NotebookSyncInfo,} from './Notebook/NotebookMeta'@@ -132,6 +133,9 @@ export function NotebookScene(): JSX.Element {<SceneBreadcrumbBackButton />{isTemplate && <LemonTag type="highlight">TEMPLATE</LemonTag>}<UserActivityIndicator at={notebook?.last_modified_at} by={notebook?.last_modified_by} />+ <BindLogic logic={notebookLogic} props={{ shortId: notebookId, target: NotebookTarget.Scene }}>+ <NotebookVariablesButton type="tertiary" size="small" />+ </BindLogic></div><div className="flex gap-2 items-center">diff --git a/frontend/src/scenes/notebooks/NotebookSceneMenuBar.tsx b/frontend/src/scenes/notebooks/NotebookSceneMenuBar.tsxindex c014134dfa12..2c0be41895a1 100644--- a/frontend/src/scenes/notebooks/NotebookSceneMenuBar.tsx+++ b/frontend/src/scenes/notebooks/NotebookSceneMenuBar.tsx@@ -37,11 +37,11 @@ export function NotebookSceneMenuBar({ shortId }: { shortId: string }): JSX.Elemfunction NotebookSceneMenuBarInner({ shortId }: { shortId: string }): JSX.Element {const logic = notebookLogic({ shortId })- const { notebook, showHistory, isLocalOnly, content } = useValues(logic)+ const { notebook, showHistory, isLocalOnly, content, showVariables } = useValues(logic)const { openShareModal, duplicateNotebook, downloadMarkdown, copyMarkdown, setShowHistory } = useActions(logic)const { featureFlags } = useValues(featureFlagLogic)const { isMarkdownExpanded, showKernelInfo } = useValues(notebookSettingsLogic)- const { setIsMarkdownExpanded, setShowKernelInfo } = useActions(notebookSettingsLogic)+ const { setIsMarkdownExpanded, setShowKernelInfo, setShowVariables } = useActions(notebookSettingsLogic)const { selectNotebook } = useActions(notebookPanelLogic)const canDelete = !isLocalOnly && !notebook?.is_template// The kernel info panel only renders for markdown (V2) notebooks, so hide the toggle elsewhere@@ -128,6 +128,15 @@ function NotebookSceneMenuBarInner({ shortId }: { shortId: string }): JSX.ElemenKernel info</SceneMenuBarCheckboxItem>)}+ {showKernelToggle && (+ <SceneMenuBarCheckboxItem+ checked={showVariables}+ onCheckedChange={(checked) => setShowVariables(checked)}+ data-attr={`${RESOURCE_TYPE}-menubar-variables`}+ >+ Variables+ </SceneMenuBarCheckboxItem>+ )}<SceneMenuBarSeparator /><SceneMenuBarItemopensFloatingUidiff --git a/frontend/src/scenes/notebooks/types.ts b/frontend/src/scenes/notebooks/types.tsindex f7ea65d558fe..0a60b369065c 100644--- a/frontend/src/scenes/notebooks/types.ts+++ b/frontend/src/scenes/notebooks/types.ts@@ -18,6 +18,12 @@ export type NotebookListItemType = {_create_in_folder?: string}+export type NotebookVariableApi = {+ name: string+ type: string+ value?: unknown+}+export type NotebookParentResource = {type: 'account'id: string@@ -32,6 +38,9 @@ export type NotebookType = NotebookListItemType &// null when the notebook is standalone; set when it belongs to a resource (e.g. an// account note) so the scene can route breadcrumbs back to that resource's listparent_resource?: NotebookParentResource | null+ // Notebook-level variables a SQL cell reads as `{name}` and a Python cell as a global.+ // A notebook property rather than document content, so editing prose cannot delete it.+ variables?: NotebookVariableApi[] | null}export enum NotebookNodeType {diff --git a/posthog/api/test/notebooks/__snapshots__/test_notebook.ambr b/posthog/api/test/notebooks/__snapshots__/test_notebook.ambrindex 9b2a64ba6ae8..fca32a9abf8a 100644--- a/posthog/api/test/notebooks/__snapshots__/test_notebook.ambr+++ b/posthog/api/test/notebooks/__snapshots__/test_notebook.ambr@@ -485,6 +485,7 @@"posthog_notebook"."kernel_cpu_cores","posthog_notebook"."kernel_memory_gb","posthog_notebook"."kernel_idle_timeout_seconds",+ "posthog_notebook"."variables","posthog_team"."id","posthog_team"."uuid","posthog_team"."organization_id",@@ -694,7 +695,8 @@"posthog_notebook"."last_modified_by_id","posthog_notebook"."kernel_cpu_cores","posthog_notebook"."kernel_memory_gb",- "posthog_notebook"."kernel_idle_timeout_seconds"+ "posthog_notebook"."kernel_idle_timeout_seconds",+ "posthog_notebook"."variables"FROM "posthog_notebook"WHERE "posthog_notebook"."id" = '00000000-0000-0000-0000-000000000000'::uuidLIMIT 21@@ -717,7 +719,8 @@"posthog_notebook"."last_modified_by_id","posthog_notebook"."kernel_cpu_cores","posthog_notebook"."kernel_memory_gb",- "posthog_notebook"."kernel_idle_timeout_seconds"+ "posthog_notebook"."kernel_idle_timeout_seconds",+ "posthog_notebook"."variables"FROM "posthog_notebook"WHERE "posthog_notebook"."id" = '00000000-0000-0000-0000-000000000000'::uuidLIMIT 21diff --git a/posthog/api/test/notebooks/test_notebook.py b/posthog/api/test/notebooks/test_notebook.pyindex b9dfd5d98607..0d11796a17f2 100644--- a/posthog/api/test/notebooks/test_notebook.py+++ b/posthog/api/test/notebooks/test_notebook.py@@ -117,6 +117,7 @@ class TestNotebooks(APIBaseTest, QueryMatchingTest):"last_modified_by": response_json["last_modified_by"],"user_access_level": "manager","parent_resource": None,+ "variables": None,}self.assert_notebook_activity(@@ -505,3 +506,56 @@ class TestNotebooks(APIBaseTest, QueryMatchingTest):format="json",)assert response.status_code == status.HTTP_400_BAD_REQUEST+++class TestNotebookVariables(APIBaseTest):+ def setUp(self):+ super().setUp()+ response = self.client.post(f"/api/projects/{self.team.id}/notebooks/", {"content": None})+ self.short_id = response.json()["short_id"]+ self.url = f"/api/projects/{self.team.id}/notebooks/{self.short_id}"++ def test_variables_round_trip(self):+ # The bar reads what it saved, so a shape the serializer drops on the way out would show+ # the user an empty bar after a reload.+ variables = [+ {"name": "country", "type": "string", "value": "US"},+ {"name": "lookback_days", "type": "number", "value": 30},+ ]+ response = self.client.patch(self.url, {"variables": variables})+ assert response.status_code == status.HTTP_200_OK, response.json()+ assert response.json()["variables"] == variables+ assert self.client.get(self.url).json()["variables"] == variables++ def test_a_notebook_without_variables_reads_as_null(self):+ assert self.client.get(self.url).json()["variables"] is None++ @parameterized.expand(+ [+ # A SQL cell reads the name as `{name}` and a Python cell as a global, so only a+ # plain identifier can ever resolve.+ ("a hyphen", "look-back"),+ ("a leading digit", "7days"),+ ("a space", "look back"),+ # HogQL injects its own {filters}, so a variable of that name could never be read.+ ("the reserved filters name", "filters"),+ ]+ )+ def test_rejects_an_unusable_name(self, _name: str, variable_name: str) -> None:+ response = self.client.patch(self.url, {"variables": [{"name": variable_name, "type": "string", "value": "x"}]})+ assert response.status_code == status.HTTP_400_BAD_REQUEST, response.json()++ def test_rejects_duplicate_names(self):+ # A Python cell reads variables out of one namespace, so a duplicate would make which+ # value binds depend on ordering.+ response = self.client.patch(+ self.url,+ {+ "variables": [+ {"name": "country", "type": "string", "value": "US"},+ {"name": "country", "type": "string", "value": "DE"},+ ]+ },+ )+ assert response.status_code == status.HTTP_400_BAD_REQUEST+ assert "unique" in str(response.json())diff --git a/products/notebooks/backend/migrations/0014_notebook_variables.py b/products/notebooks/backend/migrations/0014_notebook_variables.pynew file mode 100644index 000000000000..44975b25f76d--- /dev/null+++ b/products/notebooks/backend/migrations/0014_notebook_variables.py@@ -0,0 +1,17 @@+# Generated by Django 5.2.17 on 2026-08-14 10:55++from django.db import migrations, models+++class Migration(migrations.Migration):+ dependencies = [+ ("notebooks", "0013_notebooknoderun_connection_id_and_more"),+ ]++ operations = [+ migrations.AddField(+ model_name="notebook",+ name="variables",+ field=models.JSONField(blank=True, default=None, null=True),+ ),+ ]diff --git a/products/notebooks/backend/migrations/max_migration.txt b/products/notebooks/backend/migrations/max_migration.txtindex ba8c194f5704..279eace4c7e0 100644--- a/products/notebooks/backend/migrations/max_migration.txt+++ b/products/notebooks/backend/migrations/max_migration.txt@@ -1 +1 @@-0013_notebooknoderun_connection_id_and_more+0014_notebook_variablesdiff --git a/products/notebooks/backend/models.py b/products/notebooks/backend/models.pyindex 01cabda34e11..84dd33098bae 100644--- a/products/notebooks/backend/models.py+++ b/products/notebooks/backend/models.py@@ -44,6 +44,10 @@ class Notebook(FileSystemSyncMixin, RootTeamMixin, UUIDTModel):kernel_cpu_cores = models.FloatField(null=True, blank=True)kernel_memory_gb = models.FloatField(null=True, blank=True)kernel_idle_timeout_seconds = models.IntegerField(null=True, blank=True)+ # Notebook-level variables, as [{name, type, value}]: a SQL cell reads one as a `{name}`+ # placeholder and a Python cell as a global. A property of the notebook rather than a block+ # in `content`, so editing prose can never delete it. Null until the notebook declares one.+ variables: JSONField = JSONField(default=None, null=True, blank=True)class Meta:unique_together = ("team", "short_id")diff --git a/products/notebooks/backend/presentation/views/notebook.py b/products/notebooks/backend/presentation/views/notebook.pyindex ba3b03b3a7b8..a99cfb06cd25 100644--- a/products/notebooks/backend/presentation/views/notebook.py+++ b/products/notebooks/backend/presentation/views/notebook.py@@ -1,5 +1,6 @@import mathimport hashlib+from collections import Counterfrom datetime import timedeltafrom typing import Any, cast@@ -79,11 +80,13 @@ from products.notebooks.backend.sql_v2_direct import cancel_direct_run, enqueue_from products.notebooks.backend.sql_v2_references import (SQLV2Ref,SQLV2ReferenceError,+ SQLV2RunPlan,resolve_python_node_inputs,resolve_sql_node_run,)from products.notebooks.backend.sql_v2_runs import expire_stale_kernel_run, finish_node_runfrom products.notebooks.backend.sql_v2_serializers import (+ MAX_VARIABLES_PER_NOTEBOOK,NotebookKernelConfigResponseSerializer,NotebookKernelStatusResponseSerializer,NotebookSQLV2InterruptResponseSerializer,@@ -92,12 +95,19 @@ from products.notebooks.backend.sql_v2_serializers import (NotebookSQLV2RunResponseSerializer,NotebookSQLV2RunStatusResponseSerializer,NotebookSQLV2StateResponseSerializer,+ NotebookVariableSerializer,)from products.notebooks.backend.sql_v2_state import (NotebookCellLimitExceeded,build_notebook_cell_state,validate_cell_count,)+from products.notebooks.backend.sql_v2_variables import (+ NotebookVariableError,+ build_notebook_variables,+ python_variable_bindings,+ reject_variables_in_raw_query,+)from products.notebooks.backend.temporal.client import start_sql_v2_run_workflowfrom products.notebooks.backend.temporal.sql_v2 import SQLV2RunInputfrom products.tasks.backend.facade.exceptions import SandboxProvisionError@@ -202,6 +212,17 @@ class NotebookMinimalSerializer(serializers.ModelSerializer, UserAccessControlSeclass NotebookSerializer(NotebookMinimalSerializer):+ variables = NotebookVariableSerializer(+ many=True,+ required=False,+ # DRF forwards this to the ListSerializer (LIST_SERIALIZER_KWARGS); the stubs only+ # type Serializer.__init__, so mypy cannot see it.+ max_length=MAX_VARIABLES_PER_NOTEBOOK, # type: ignore[call-arg]+ help_text=(+ "Notebook-level variables, in display order. A SQL cell reads one as a `{name}` "+ "placeholder and a Python cell as a global. Names must be unique."+ ),+ )parent_resource = serializers.SerializerMethodField(help_text=("Parent resource this notebook is attached to, or `null`. Returns "@@ -226,6 +247,7 @@ class NotebookSerializer(NotebookMinimalSerializer):"last_modified_by","user_access_level","parent_resource",+ "variables","_create_in_folder",]read_only_fields = [@@ -247,6 +269,18 @@ class NotebookSerializer(NotebookMinimalSerializer):},}+ def validate_variables(self, value: list[dict]) -> list[dict]:+ # A Python cell reads variables and cell dataframes out of one namespace, so a duplicate+ # would make which value binds depend on ordering. Dataframe names live in `content` and+ # are checked in the editor; this guards the notebook's own list.+ # Counted in one pass: `list.count` per entry is quadratic, and the 20 MB body cap+ # admits enough names for that to tie up a worker.+ counts = Counter(variable["name"] for variable in value)+ duplicates = sorted(name for name, count in counts.items() if count > 1)+ if duplicates:+ raise serializers.ValidationError(f"Variable names must be unique. Repeated: {', '.join(duplicates)}.")+ return value+@extend_schema_field(_PARENT_RESOURCE_SCHEMA)def get_parent_resource(self, obj: Notebook) -> dict | None:# Group parents are skipped: ResourceNotebook stores group PK but personhog has no get-by-pk RPC.@@ -1237,22 +1271,27 @@ class NotebookViewSet(TeamAndOrgViewSetMixin, AccessControlViewSetMixin, ForbidDcross_engine_error.format(name=name) if spec["node_id"] in other_engine_nodes else None),)+ # The notebook's variables as of this run. A SQL node has them bound into its code+ # below; a python node carries them to the kernel, which binds them as globals.+ variables = build_notebook_variables(serializer.validated_data.get("variables") or [], self.team.timezone_info)try:if node_type == "python":# A python node stores its code as-is; referenced frames become kernel inputs,# keyed by the upstream run_id so a re-run yields a fresh (not stale) frame.- run_code, inputs = code, resolve_python_node_inputs(code, refs)+ plan = SQLV2RunPlan(node_type="python", code=code, inputs=resolve_python_node_inputs(code, refs))elif send_raw_query:# Raw SQL is the connection's own dialect, so the HogQL parser can't read it and- # there is nothing to inline: it reaches the engine exactly as written.- run_code, inputs = code, []+ # there is nothing to inline: it reaches the engine exactly as written. Variables+ # are refused here rather than escaped by hand — see reject_variables_in_raw_query.+ reject_variables_in_raw_query(code, variables)+ plan = SQLV2RunPlan(node_type="hogql", code=code, inputs=[])else:# A SQL node pushes to ClickHouse — unless it references a local frame, which# reroutes it to the sandbox's DuckDB (Journey 5).- node_type, run_code, inputs = resolve_sql_node_run(code, refs)+ plan = resolve_sql_node_run(code, refs, variables)# ExposedHogQLError: with refs present the user's own code is parsed at dispatch, so a# plain typo raises here — it's a bad query (400 with the parse message), not a 500.- except (SQLV2ReferenceError, ExposedHogQLError) as e:+ except (SQLV2ReferenceError, NotebookVariableError, ExposedHogQLError) as e:return Response({"detail": str(e)}, status=400)run = NotebookNodeRun.objects.create(@@ -1262,15 +1301,15 @@ class NotebookViewSet(TeamAndOrgViewSetMixin, AccessControlViewSetMixin, ForbidD# frame snapshot to that kernel. A token user has no kernel of its own, hence None.user=user if isinstance(user, User) else None,node_id=serializer.validated_data["node_id"],- code=run_code,- node_type=node_type,+ code=plan.code,+ node_type=plan.node_type,connection_id=connection_id,send_raw_query=send_raw_query,status=NotebookNodeRun.Status.RUNNING,)try:- if node_type == NotebookNodeRun.NodeType.HOGQL:+ if plan.node_type == "hogql":# Direct lane: a pure-HogQL run never touches the sandbox — it rides the# async query manager, and the run-result poll advances the row.enqueue_direct_run(self.team, user if isinstance(user, User) else None, run)@@ -1281,10 +1320,15 @@ class NotebookViewSet(TeamAndOrgViewSetMixin, AccessControlViewSetMixin, ForbidDnotebook_short_id=notebook.short_id,team_id=self.team_id,user_id=user.id if isinstance(user, User) else None,- code=run_code,- node_type=node_type,+ code=plan.code,+ node_type=plan.node_type,output_name=output_name,- inputs=inputs,+ inputs=plan.inputs,+ # A python node reads these as globals; a duckdb node binds them as+ # `$name` query parameters, so it carries only the ones its SQL uses.+ variables=(+ python_variable_bindings(variables) if plan.node_type == "python" else plan.variables+ ),))except Exception:diff --git a/products/notebooks/backend/sandbox/kernel/bootstrap.py b/products/notebooks/backend/sandbox/kernel/bootstrap.pyindex 5ea94d975e98..a7bf7bb86534 100644--- a/products/notebooks/backend/sandbox/kernel/bootstrap.py+++ b/products/notebooks/backend/sandbox/kernel/bootstrap.py@@ -162,6 +162,9 @@ class KernelSession:# and can tell an output from a run input. DuckDB holds its own reference to each# registered object, so tracking them here adds no lifetime.self._registered: dict[str, _Registration] = {}+ # Notebook variables this session bound, so a name the notebook no longer declares+ # can be removed instead of lingering as a stale global.+ self._bound_variables: set[str] = set()# Agg backend set now, before any user `import matplotlib.pyplot`, so plots stay headless.self._plt = _load_headless_pyplot()@@ -309,6 +312,12 @@ class KernelSession:node = payload.get("node") or {}node_type = str(node.get("type") or "python")preview_rows = int(payload.get("page_limit") or _DEFAULT_PREVIEW_ROWS)+ # Python only: a duckdb node's `variables` are `$name` query parameters the driver+ # binds, not globals. Bound before the inputs, so a dataframe still wins a name+ # collision: the notebook forbids one, but a shadowed variable degrades better than a+ # join that can't find its frame.+ if node_type == "python":+ self._bind_variables(node.get("variables") or {})try:self._register_inputs(payload.get("inputs") or [], node_type=node_type)except Exception as exc: # noqa: BLE001 — a bad input must still produce an envelope@@ -383,6 +392,24 @@ class KernelSession:result_id=result_id,)+ def _bind_variables(self, variables: dict[str, Any]) -> None:+ """Bind the notebook's variables as globals, fresh on every run.++ Rebinding each run is the point: the notebook is the authority on what a name holds,+ so a value a previous cell happened to assign must not survive into this one — and a+ name the notebook stopped declaring must not either. A deleted or renamed variable+ would otherwise keep answering from the kernel namespace, so a cell reading it looks+ like it still works while the notebook says the variable is gone.+ """+ bound: set[str] = set()+ for name, value in variables.items():+ if isinstance(name, str) and name.isidentifier():+ self.shell.user_ns[name] = value+ bound.add(name)+ for stale in self._bound_variables - bound:+ self.shell.user_ns.pop(stale, None)+ self._bound_variables = bound+def _register_inputs(self, inputs: list[dict[str, Any]], node_type: str) -> None:bind_pandas = node_type == "python"for spec in inputs:@@ -433,8 +460,12 @@ class KernelSession:def _run_duckdb_node(self, node: dict[str, Any], preview_rows: int) -> dict[str, Any]:output_name = node.get("output_name") or ""+ # Notebook variables arrive as `$name` parameters the driver binds, never as SQL text,+ # so a value can't close a literal and run as a statement of its own.+ params = node.get("variables") or {}try:- relation = self.duck.sql(node.get("code") or "")+ code = node.get("code") or ""+ relation = self.duck.sql(code, params=params) if params else self.duck.sql(code)# Non-SELECT statements (DDL etc.) yield no relation — a valid, frameless run.result_df = relation.df() if relation is not None else Noneexcept Exception as exc: # noqa: BLE001 — any DuckDB failure must still produce an envelopediff --git a/products/notebooks/backend/sql_v2.py b/products/notebooks/backend/sql_v2.pyindex 8ca5dcdeb35f..dcb49e6edd3b 100644--- a/products/notebooks/backend/sql_v2.py+++ b/products/notebooks/backend/sql_v2.py@@ -405,12 +405,16 @@ def dispatch_sql_v2_run(node_type: str = "hogql",output_name: str = "",inputs: list[dict] | None = None,+ variables: dict | None = None,) -> None:"""Dispatch a run to the in-sandbox kernel-server with a single authed HTTP POST.Returns as soon as the server accepts (202); the result arrives via the callback. Akernel node (python or duckdb) carries the `node`/`inputs` shape the executor consumes;a hogql node keeps the flat `code` the capped-fetch path reads — the paths stay additive.++ `variables` are notebook-level values a python node reads as globals; the executor passes+ the whole `node` object through, so they need no handling of their own on the way in."""runtime = ensure_sql_v2_server(notebook, user)assert runtime.server_url # ensure_sql_v2_server always returns a runtime with a live server_url@@ -431,7 +435,12 @@ def dispatch_sql_v2_run("cache_limit": RESULT_CACHE_ROWS,}if node_type in ("python", "duckdb"):- payload["node"] = {"type": node_type, "code": code, "output_name": output_name}+ payload["node"] = {+ "type": node_type,+ "code": code,+ "output_name": output_name,+ "variables": variables or {},+ }payload["inputs"] = inputs or []else:payload["code"] = codediff --git a/products/notebooks/backend/sql_v2_kernel_architecture.md b/products/notebooks/backend/sql_v2_kernel_architecture.mdindex fae8fb712ffa..d187afc9ca86 100644--- a/products/notebooks/backend/sql_v2_kernel_architecture.md+++ b/products/notebooks/backend/sql_v2_kernel_architecture.md@@ -111,6 +111,16 @@ For each run, the server sends the kernel a single execute request — `_ph.run_Python node execution uses `get_ipython().run_cell(code)` inside a capture context: full IPython semantics (last-expression value, tracebacks), stdout/stderr capture, and matplotlib figures arrive as `display_data` PNG — straight into `envelope.media`.+### Notebook variables++A notebook's `<Variables>` block declares named values the whole document shares. They reach a run by lane, and only one of the two lanes involves the kernel:++- a **SQL** node has each `{name}` resolved at dispatch (`sql_v2_variables.py`). The ClickHouse lane substitutes through the HogQL AST; the DuckDB lane rewrites the placeholder to DuckDB's own `$name` parameter and carries the values on the node, so the driver binds them and no value is ever written into the SQL. Only placeholders in executable positions are rewritten — one inside a string, quoted identifier, dollar-quoted block, or comment is left as written;+- a **raw connection** query refuses variables outright. Escaping is engine- and setting-specific — MySQL treats a backslash as an escape unless `NO_BACKSLASH_ESCAPES` is set — so binding there needs the driver's own parameter binding, which the direct-query path does not carry yet;+- a **Python** node carries the values on `node.variables` and the kernel binds them into the user namespace before `run_cell`, ahead of input registration, so a dataframe still wins a name collision.++Variables are rebound every run: the block is the authority on what a name holds, so a value a previous cell assigned must not survive into the next one.+## Local DuckDB (capability 4)**DuckDB nodes always execute inside the kernel process.** This is forced by DuckDB's replacement scans: `duckdb.sql("select * from my_pandas_df")` only resolves `my_pandas_df` if the frame lives in the same process. Since DuckDB nodes exist precisely to query local frames (decision 3), they run where the frames are.diff --git a/products/notebooks/backend/sql_v2_references.py b/products/notebooks/backend/sql_v2_references.pyindex b386dee11cd6..a9603cfc2da3 100644--- a/products/notebooks/backend/sql_v2_references.py+++ b/products/notebooks/backend/sql_v2_references.py@@ -19,7 +19,7 @@ whatever HogQL refs it also reads — the same input shape Python nodes use."""import re-from dataclasses import dataclass+from dataclasses import dataclass, fieldfrom typing import Any, Literalfrom posthog.hogql import ast@@ -29,7 +29,15 @@ from posthog.hogql.parser import parse_selectfrom posthog.hogql.printer import print_prepared_astfrom posthog.hogql.visitor import TraversingVisitor+from posthog.dataclasses import frozen+from products.notebooks.backend.python_analysis import analyze_python_globals+from products.notebooks.backend.sql_v2_variables import (+ NotebookVariable,+ NotebookVariableValue,+ substitute_duckdb_variables,+ substitute_hogql_variables,+)# String literals ('' or backslash escapes) and comments, for the routing fallback to blank# out before scanning: a frame name mentioned in a literal or comment must not trigger DuckDB@@ -63,6 +71,25 @@ class SQLV2Ref:unavailable_reason: str | None = None+@frozen+class SQLV2RunPlan:+ """How one node run should execute, once its refs and variables are resolved.++ `node_type` picks the engine and `code` only means anything on that engine, so the two+ travel together rather than as a pair of bare strings a call site could swap. The+ dispatch view builds one for the python and raw-connection lanes too, so every lane+ reaches the run row the same way.+ """++ node_type: Literal["hogql", "duckdb", "python"]+ code: str+ # Frames the kernel must materialize first; always empty on the ClickHouse lane.+ inputs: list[dict[str, Any]]+ # DuckDB lane only: values for the `$name` parameters `code` now carries, bound by the+ # driver rather than written into the SQL. Empty on every other lane.+ variables: dict[str, NotebookVariableValue] = field(default_factory=dict)++class _ReferenceCollector(TraversingVisitor):"""Base for the two scans below: both gather the names of `candidates` a query reaches."""@@ -270,19 +297,28 @@ def resolve_python_node_inputs(code: str, refs: dict[str, SQLV2Ref]) -> list[dicreturn inputs-def resolve_sql_node_run(code: str, refs: dict[str, SQLV2Ref]) -> tuple[str, str, list[dict[str, Any]]]:- """Route a SQL node run to its engine; return (node_type, run_code, inputs).+def resolve_sql_node_run(+ code: str, refs: dict[str, SQLV2Ref], variables: list[NotebookVariable] | None = None+) -> SQLV2RunPlan:+ """Route a SQL node run to its engine and return the plan for executing it.The routing rule from the journey walkthroughs (decision 1): a query whose referencedinputs are all HogQL definitions pushes to ClickHouse with the refs inlined as CTEs —- `("hogql", inlined_code, [])`. A query that references any **local** frame (made by a- Python node) cannot run in ClickHouse, so it runs in the sandbox's DuckDB instead —- `("duckdb", code_as_written, inputs)`, where inputs materialize the HogQL refs it also- reads (Journey 5: the join forces `df2` into the sandbox) and assert the local ones.+ a `hogql` plan carrying the inlined code and no inputs. A query that references any+ **local** frame (made by a Python node) cannot run in ClickHouse, so it runs in the+ sandbox's DuckDB instead — a `duckdb` plan carrying the code as written, whose inputs+ materialize the HogQL refs it also reads (Journey 5: the join forces `df2` into the+ sandbox) and assert the local ones.++ Notebook variables are bound per lane, once the lane is known: the ClickHouse query gets+ AST substitution, while the DuckDB query keeps `$name` parameters for the driver to bind+ (see sql_v2_variables). Raises NotebookVariableError when the query reads an undeclared+ `{name}`.Raises SQLV2ReferenceError for unrunnable refs, and lets the HogQL parser's own errorsurface for a malformed query that doesn't touch any local frame."""+ variables = variables or []local_names = {name for name, ref in refs.items() if name and ref.kind == "local"}hogql_refs = {name: ref for name, ref in refs.items() if name and ref.kind == "hogql"}hogql_codes = {name: None if ref.unavailable_reason else ref.last_run_code for name, ref in hogql_refs.items()}@@ -306,7 +342,14 @@ def resolve_sql_node_run(code: str, refs: dict[str, SQLV2Ref]) -> tuple[str, strreferenced_hogql = found - local_namesif not referenced_locals:- return "hogql", resolve_sql_v2_references(code, hogql_codes, unavailable), []+ # Variables bind before inlining: the CTE merge prints its AST, and the printer rejects a+ # placeholder that is still unresolved by then. An inlined definition never carries one —+ # it is a previous run's stored code, which was substituted the same way at its own dispatch.+ return SQLV2RunPlan(+ node_type="hogql",+ code=resolve_sql_v2_references(substitute_hogql_variables(code, variables), hogql_codes, unavailable),+ inputs=[],+ )inputs: list[dict[str, Any]] = []for name in sorted(referenced_locals | referenced_hogql):@@ -314,4 +357,5 @@ def resolve_sql_node_run(code: str, refs: dict[str, SQLV2Ref]) -> tuple[str, strinputs.append({"name": name, "kind": "local"})else:inputs.append(_hogql_input(name, hogql_refs[name]))- return "duckdb", code, inputs+ duckdb_code, duckdb_params = substitute_duckdb_variables(code, variables)+ return SQLV2RunPlan(node_type="duckdb", code=duckdb_code, inputs=inputs, variables=duckdb_params)diff --git a/products/notebooks/backend/sql_v2_serializers.py b/products/notebooks/backend/sql_v2_serializers.pyindex 65cc5311bb09..cf8c5b8445a9 100644--- a/products/notebooks/backend/sql_v2_serializers.py+++ b/products/notebooks/backend/sql_v2_serializers.py@@ -1,6 +1,10 @@+from typing import Any+from drf_spectacular.utils import extend_schema_fieldfrom rest_framework import serializers+from products.notebooks.backend.sql_v2_variables import RESERVED_VARIABLE_NAMES+@extend_schema_field(serializers.DictField(child=serializers.FloatField()))class LenientTimingsField(serializers.JSONField):@@ -28,6 +32,53 @@ class NotebookSQLV2RefSerializer(serializers.Serializer):)+# A notebook is authored by hand, so these sit just above real use: a person types a handful+# of named values, not a data set. Keeping them tight also bounds the abuse case — values ride+# a Temporal payload (~2 MiB hard limit) to the kernel, and one placeholder repeated across a+# query multiplies its value into the SQL the engine receives.+MAX_VARIABLES_PER_NOTEBOOK = 10+MAX_VARIABLE_NAME_CHARS = 200+MAX_VARIABLE_VALUE_CHARS = 1_000+++class NotebookVariableSerializer(serializers.Serializer):+ """One notebook-level variable. Shared by the notebook's own `variables` field and a run body."""++ name = serializers.CharField(+ max_length=MAX_VARIABLE_NAME_CHARS,+ help_text="Identifier the cell reads: `{name}` in a SQL cell, a plain global in a Python cell.",+ )+ # CharField, not ChoiceField: a `type` enum collides with other generated enums under+ # --fail-on-warn (same precedent as the status fields below).+ type = serializers.CharField(+ help_text="How to coerce the value: 'string', 'number', 'boolean', or 'date'. Unknown types read as 'string'."+ )+ value = serializers.JSONField(+ required=False,+ allow_null=True,+ help_text=(+ "The variable's current value. A 'date' accepts an absolute date or a relative "+ "expression ('-7d', 'mStart'), resolved against the project timezone."+ ),+ )++ def validate_value(self, value: Any) -> Any:+ # Only scalars are ever bound, so anything longer than this is not a value someone typed.+ if isinstance(value, str) and len(value) > MAX_VARIABLE_VALUE_CHARS:+ raise serializers.ValidationError(f"A variable value can be at most {MAX_VARIABLE_VALUE_CHARS} characters.")+ return value++ def validate_name(self, value: str) -> str:+ name = value.strip()+ # A SQL cell reads the name as a `{name}` placeholder and a Python cell as a global, so+ # only a plain identifier can ever resolve.+ if not name.isidentifier():+ raise serializers.ValidationError("Use letters, numbers, and underscores, and don't start with a number.")+ if name in RESERVED_VARIABLE_NAMES:+ raise serializers.ValidationError(f"'{name}' is reserved by PostHog. Pick another name.")+ return name++class NotebookSQLV2RunRequestSerializer(serializers.Serializer):node_id = serializers.CharField(help_text="ProseMirror node id of the SQLV2 node being run.")node_type = serializers.ChoiceField(@@ -62,6 +113,19 @@ class NotebookSQLV2RunRequestSerializer(serializers.Serializer):"DuckDB; a python node materializes the hogql refs its code reads as pandas frames."),)+ variables = NotebookVariableSerializer(+ many=True,+ required=False,+ default=list,+ # DRF forwards this to the ListSerializer (LIST_SERIALIZER_KWARGS); the stubs only+ # type Serializer.__init__, so mypy cannot see it.+ max_length=MAX_VARIABLES_PER_NOTEBOOK, # type: ignore[call-arg]+ help_text=(+ "Notebook-level variables in scope for this run. A SQL node has each `{name}` bound to "+ "its value before dispatch; a Python node gets them as globals in the kernel namespace. "+ "A SQL node reading a `{name}` that is absent here fails the dispatch."+ ),+ )connection_id = serializers.UUIDField(required=False,allow_null=True,diff --git a/products/notebooks/backend/sql_v2_variables.py b/products/notebooks/backend/sql_v2_variables.pynew file mode 100644index 000000000000..875e2cd07f80--- /dev/null+++ b/products/notebooks/backend/sql_v2_variables.py@@ -0,0 +1,322 @@+"""Notebook-level variables: bind their values into a cell's code at dispatch.++A notebook declares variables in a `<Variables>` markdown block. A SQL cell reads one as a+bare ``{name}`` placeholder; a Python cell reads it as a plain global (bound in the kernel,+see `sandbox/kernel/bootstrap.py`, not here).++Substitution happens once at dispatch, like reference inlining, so the run stores a+self-contained query and paging re-queries it without re-resolving anything.++No lane ever renders a value as SQL text. Escaping rules differ by engine and by server+setting, and a hand-rolled quote is one dialect quirk away from an injection, so each lane+passes the value as data instead:++* the **hogql** lane parses the query and swaps each placeholder for an ``ast.Constant``;+* the **duckdb** lane rewrites each ``{name}`` to DuckDB's own ``$name`` parameter and hands+ the values to the driver, which binds them (`_run_duckdb_node` in the kernel);+* a **raw connection** query refuses variables outright — it is the target engine's dialect,+ and the direct-query path carries no parameter binding yet.+"""++import re+from collections.abc import Iterator+from datetime import date, datetime+from difflib import get_close_matches+from typing import Any+from zoneinfo import ZoneInfo++from posthog.hogql import ast+from posthog.hogql.context import HogQLContext+from posthog.hogql.parser import parse_select+from posthog.hogql.printer import print_prepared_ast+from posthog.hogql.variables import is_relative_date_value+from posthog.hogql.visitor import CloningVisitor++from posthog.dataclasses import frozen+from posthog.utils import relative_date_parse++# HogQL injects its own `{filters}` placeholder into notebook queries, so a variable could never+# take that name. Left untouched here rather than reported as undeclared.+RESERVED_VARIABLE_NAMES = frozenset({"filters"})++NotebookVariableValue = str | int | float | bool | datetime | date | None+++class NotebookVariableError(Exception):+ """A cell reads a `{name}` that the notebook does not declare. User-facing."""+++@frozen+class NotebookVariable:+ """One declared variable, with its value already coerced to a Python scalar."""++ name: str+ value: NotebookVariableValue+++# Bare `{name}`; a dotted chain (`{variables.x}`, `{filters.y}`) is somebody else's placeholder.+_BARE_PLACEHOLDER = re.compile(r"\{([A-Za-z_][A-Za-z0-9_]*)\}")+# String literals and comments, blanked before the textual scan so a `'{country}'` inside a+# literal is neither substituted nor reported as undeclared. Mirrors the routing scan in+# sql_v2_references.+_SQL_LITERALS_AND_COMMENTS = re.compile(r"'(?:[^'\\]|\\.|'')*'|--[^\n]*|/\*.*?\*/", re.DOTALL)+++def _undeclared_error(name: str, declared: list[str]) -> NotebookVariableError:+ if not declared:+ return NotebookVariableError(+ f"'{{{name}}}' is not a notebook variable. Add a Variables block to declare {name}."+ )+ suggestions = get_close_matches(name, declared, n=3, cutoff=0.6)+ if suggestions:+ return NotebookVariableError(+ f"'{{{name}}}' is not a notebook variable. Did you mean: {', '.join(suggestions)}?"+ )+ return NotebookVariableError(+ f"'{{{name}}}' is not a notebook variable. This notebook declares: {', '.join(sorted(declared))}."+ )+++class _ReplaceNotebookVariables(CloningVisitor):+ """Swap each `{name}` placeholder for the declared variable's value as a constant."""++ def __init__(self, values: dict[str, NotebookVariableValue]) -> None:+ super().__init__()+ self.values = values+ self.replaced: set[str] = set()++ def visit_placeholder(self, node: ast.Placeholder) -> ast.Expr:+ chain = node.chain+ # Only a bare single-segment placeholder is a notebook variable. Anything else —+ # `{filters}`, a dotted chain, an expression placeholder — belongs to another+ # resolver and must reach it untouched.+ if not chain or len(chain) != 1 or not isinstance(chain[0], str):+ return super().visit_placeholder(node)++ name = chain[0]+ if name in RESERVED_VARIABLE_NAMES:+ return super().visit_placeholder(node)+ if name not in self.values:+ raise _undeclared_error(name, list(self.values))++ self.replaced.add(name)+ return ast.Constant(value=self.values[name], start=node.start, end=node.end)+++def substitute_hogql_variables(code: str, variables: list[NotebookVariable]) -> str:+ """Bind notebook variables into a HogQL query, via the AST.++ Returns `code` untouched when it reads no `{name}` placeholder, so a query without+ variables is byte-for-byte what the user wrote. Raises NotebookVariableError when the+ query reads a name the notebook does not declare, and lets the parser's own error+ surface for a malformed query.+ """+ if not _BARE_PLACEHOLDER.search(code):+ return code++ values = {variable.name: variable.value for variable in variables}+ query = parse_select(code)+ visitor = _ReplaceNotebookVariables(values)+ substituted = visitor.visit(query)+ if not visitor.replaced:+ # Only `{filters}` (or another resolver's placeholder) was present — nothing of ours+ # changed, so don't reprint and reformat the user's query for no reason.+ return code+ return print_prepared_ast(substituted, context=HogQLContext(team_id=None), dialect="hogql")+++_TAG_CHARS = frozenset("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789_")+++def _skip_delimited(code: str, start: int, quote: str, backslash_escapes: bool) -> int:+ """Index just past the `quote`-delimited run beginning at `start`.++ Doubling the quote escapes it. An unterminated run reaches the end of the input, which is+ what a lexer does with it — the query is malformed either way, and treating the remainder+ as literal keeps a value out of it.+ """+ index = start + 1+ length = len(code)+ while index < length:+ char = code[index]+ if backslash_escapes and char == "\\":+ index += 2+ continue+ if char == quote:+ if index + 1 < length and code[index + 1] == quote:+ index += 2+ continue+ return index + 1+ index += 1+ return length+++def _skip_dollar_quoted(code: str, start: int) -> int | None:+ """Index just past the dollar-quoted run at `start`, or None if one does not begin there.++ `$tag$…$tag$` and `$$…$$` make every character between the tags literal, including a+ quote. A bare `$name` with no closing `$` is a parameter, not an opener.+ """+ index = start + 1+ length = len(code)+ while index < length and code[index] in _TAG_CHARS:+ index += 1+ if index >= length or code[index] != "$":+ return None+ tag = code[start : index + 1]+ # A tag cannot start with a digit, so `$1$` is two parameters rather than an opener.+ if len(tag) > 2 and tag[1].isdigit():+ return None+ close = code.find(tag, index + 1)+ # Unterminated: the rest of the input is inside the literal. Returning the end also keeps+ # this scan linear — a query full of unmatched openers can never re-scan the tail per tag.+ return length if close == -1 else close + len(tag)+++def _executable_placeholders(code: str) -> Iterator[re.Match[str]]:+ """Yield each `{name}` that sits in executable SQL, skipping literals and comments.++ Hand-rolled rather than one regex: matching `$tag$…$tag$` with a backreference makes the+ engine rescan the tail once per unmatched opener, which is quadratic in the input and+ reachable from a single request. Here every character is visited a bounded number of+ times — each skip either jumps past a closed region or runs to the end.+ """+ index = 0+ length = len(code)+ while index < length:+ char = code[index]+ if char == "'" or char == '"':+ index = _skip_delimited(code, index, char, backslash_escapes=False)+ elif char in "eE" and index + 1 < length and code[index + 1] == "'":+ # E'…' takes backslash escapes, so a `\'` inside it does not close the string.+ index = _skip_delimited(code, index + 1, "'", backslash_escapes=True)+ elif char == "$":+ region_end = _skip_dollar_quoted(code, index)+ index = index + 1 if region_end is None else region_end+ elif code.startswith("--", index):+ newline = code.find("\n", index)+ index = length if newline == -1 else newline + 1+ elif code.startswith("/*", index):+ closing = code.find("*/", index + 2)+ index = length if closing == -1 else closing + 2+ elif char == "{":+ placeholder = _BARE_PLACEHOLDER.match(code, index)+ if placeholder is None:+ index += 1+ else:+ yield placeholder+ index = placeholder.end()+ else:+ index += 1+++def substitute_duckdb_variables(+ code: str, variables: list[NotebookVariable]+) -> tuple[str, dict[str, NotebookVariableValue]]:+ """Rewrite each `{name}` to DuckDB's `$name` parameter; return the code and the values to bind.++ Nothing is escaped, so a value can never become SQL — DuckDB binds it through the driver+ (see `_run_duckdb_node`). Only placeholders in executable positions are rewritten: a+ `{name}` inside a string, a quoted identifier, a dollar-quoted block, or a comment is+ left exactly as written.++ Raises NotebookVariableError when an executable `{name}` is not a declared variable.+ """+ if not _BARE_PLACEHOLDER.search(code):+ return code, {}++ values = {variable.name: variable.value for variable in variables}+ used: dict[str, NotebookVariableValue] = {}+ pieces: list[str] = []+ cursor = 0++ for match in _executable_placeholders(code):+ name = match.group(1)+ if name in RESERVED_VARIABLE_NAMES:+ continue+ if name not in values:+ raise _undeclared_error(name, list(values))+ pieces.append(code[cursor : match.start()])+ pieces.append(f"${name}")+ used[name] = values[name]+ cursor = match.end()+ pieces.append(code[cursor:])+ return "".join(pieces), used+++def reject_variables_in_raw_query(code: str, variables: list[NotebookVariable]) -> None:+ """Raise if a raw-connection query reads a notebook variable.++ A raw query is the target engine's own dialect, and escaping rules differ by engine and by+ server setting — MySQL treats a backslash as an escape unless NO_BACKSLASH_ESCAPES is set,+ so a shared quote-doubling helper is not safe there. Binding these values needs the driver's+ own parameter binding, which the direct-query path does not carry yet, so the run is refused+ rather than run with a hand-rolled escape.++ Only declared names are rejected: raw SQL may use braces for its own purposes, and a query+ that reads no variable is left completely alone.+ """+ if not _BARE_PLACEHOLDER.search(code):+ return++ declared = {variable.name for variable in variables}+ scannable = _SQL_LITERALS_AND_COMMENTS.sub(lambda match: " " * len(match.group(0)), code)+ used = sorted({match.group(1) for match in _BARE_PLACEHOLDER.finditer(scannable)} & declared)+ if used:+ raise NotebookVariableError(+ f"Notebook variables ({', '.join(used)}) can't be used in a raw query. "+ "Turn off 'send raw query' to run it as HogQL, or write the value into the SQL."+ )+++def build_notebook_variables(items: list[dict[str, Any]], timezone_info: ZoneInfo) -> list[NotebookVariable]:+ """Coerce the run request's declarations into variables with Python scalar values.++ Duplicates keep the first declaration, matching what the editor treats as the valid one.+ """+ variables: list[NotebookVariable] = []+ seen: set[str] = set()+ for item in items:+ name = str(item.get("name") or "").strip()+ if not name or name in seen or name in RESERVED_VARIABLE_NAMES:+ continue+ seen.add(name)+ variables.append(+ NotebookVariable(name=name, value=_coerce_value(item.get("type"), item.get("value"), timezone_info))+ )+ return variables+++def _coerce_value(variable_type: Any, value: Any, timezone_info: ZoneInfo) -> NotebookVariableValue:+ if value is None:+ return None+ if variable_type == "number":+ if isinstance(value, bool):+ return None+ if isinstance(value, (int, float)):+ return value+ try:+ return float(str(value)) if "." in str(value) else int(str(value))+ except ValueError:+ return None+ if variable_type == "boolean":+ return value if isinstance(value, bool) else str(value).strip().lower() == "true"+ if variable_type == "date":+ text = str(value).strip()+ # A relative value ("-7d", "mStart") is resolved against the team's timezone, exactly as+ # an insight's date variable is; an absolute date stays a string the engine casts.+ return relative_date_parse(text, timezone_info) if is_relative_date_value(text) else text+ return str(value)+++def python_variable_bindings(variables: list[NotebookVariable]) -> dict[str, Any]:+ """The name -> value map a Python cell gets bound into its kernel namespace.++ Dates go over as ISO strings: the payload is JSON on its way to the sandbox, and a+ string the user can parse beats a silently dropped value.+ """+ return {+ variable.name: variable.value.isoformat() if isinstance(variable.value, datetime | date) else variable.value+ for variable in variables+ if variable.name+ }diff --git a/products/notebooks/backend/temporal/sql_v2.py b/products/notebooks/backend/temporal/sql_v2.pyindex 1b0fe6ef0141..1aead05f77a6 100644--- a/products/notebooks/backend/temporal/sql_v2.py+++ b/products/notebooks/backend/temporal/sql_v2.py@@ -10,12 +10,13 @@ its envelope in one un-retried POST, so a lost delivery would otherwise leave thRUNNING with nothing able to move it."""-from dataclasses import dataclass, field+from dataclasses import fieldfrom datetime import timedeltafrom typing import Anyfrom temporalio import activity, common, workflow+from posthog.dataclasses import frozenfrom posthog.models.user import Userfrom posthog.temporal.common.base import PostHogWorkflow@@ -35,7 +36,7 @@ from products.notebooks.backend.sql_v2_runs import (_EXPIRY_MARGIN_SECONDS = 60-@dataclass+@frozenclass SQLV2RunInput:run_id: strnotebook_short_id: str@@ -46,6 +47,9 @@ class SQLV2RunInput:output_name: str = ""# For a python node: [{name, kind, query, query_hash}] frames to materialize before running.inputs: list[dict[str, Any]] = field(default_factory=list)+ # For a python node: notebook variables to bind as globals before the cell runs. Empty for+ # every other node type — a duckdb run has its values already substituted into the SQL.+ variables: dict[str, Any] = field(default_factory=dict)def _load_notebook_and_user(team_id: int, notebook_short_id: str, user_id: int | None) -> tuple[Notebook, User | None]:@@ -67,6 +71,7 @@ def dispatch_sql_v2_run_activity(input: SQLV2RunInput) -> None:node_type=input.node_type,output_name=input.output_name,inputs=input.inputs,+ variables=input.variables,)except SQLV2KernelNotRunning:# No running kernel: provision one and dispatch again — a kernel-lane run is the@@ -82,6 +87,7 @@ def dispatch_sql_v2_run_activity(input: SQLV2RunInput) -> None:node_type=input.node_type,output_name=input.output_name,inputs=input.inputs,+ variables=input.variables,)diff --git a/products/notebooks/backend/test/test_kernel_bootstrap.py b/products/notebooks/backend/test/test_kernel_bootstrap.pyindex 3c2fcaec3d8f..6dc6672f4bf9 100644--- a/products/notebooks/backend/test/test_kernel_bootstrap.py+++ b/products/notebooks/backend/test/test_kernel_bootstrap.py@@ -187,9 +187,17 @@ class TestKernelSessionRunNode(SimpleTestCase):self.assertEqual(len(envelope["media"]), _MEDIA_MAX_FIGURES)self.assertIn("1 figure(s) omitted", envelope["stderr"])- def _run_duckdb(self, code: str, inputs=None, output_name=None) -> dict:+ def _run_duckdb(self, code: str, inputs=None, output_name=None, variables=None) -> dict:return self.session.run_node(- {"node": {"type": "duckdb", "code": code, "output_name": output_name}, "inputs": inputs or []}+ {+ "node": {+ "type": "duckdb",+ "code": code,+ "output_name": output_name,+ "variables": variables or {},+ },+ "inputs": inputs or [],+ })def test_duckdb_node_joins_a_hogql_frame_with_a_local_frame(self):@@ -339,3 +347,96 @@ class TestKernelSessionRunNode(SimpleTestCase):envelope = self._run("3 + 3")self.assertLessEqual(len(json.dumps(envelope["frames"])), 300_000)+++class TestKernelSessionNotebookVariables(SimpleTestCase):+ def setUp(self):+ self._dir = tempfile.TemporaryDirectory()+ self.addCleanup(self._dir.cleanup)+ self.session = KernelSession(data_dir=self._dir.name)++ def _run(self, code: str, variables=None, inputs=None) -> dict:+ return self.session.run_node(+ {+ "node": {"type": "python", "code": code, "output_name": None, "variables": variables or {}},+ "inputs": inputs or [],+ }+ )++ def test_variables_are_readable_as_globals(self):+ envelope = self._run("print(f'{country}-{lookback_days}')", {"country": "US", "lookback_days": 30})+ self.assertEqual(envelope["status"], "ok")+ self.assertIn("US-30", envelope["stdout"])++ def test_a_rebound_variable_is_reset_on_the_next_run(self):+ # The Variables block is the authority: a value one cell assigned must not leak into the+ # next run, or the notebook silently disagrees with what the block shows.+ self._run("country = 'DE'", {"country": "US"})+ envelope = self._run("print(country)", {"country": "US"})+ self.assertIn("US", envelope["stdout"])++ def test_an_input_frame_wins_a_name_collision(self):+ # The notebook forbids the collision, but a shadowed variable degrades better than a+ # dataframe that vanished from under the code that reads it.+ path = os.path.join(self._dir.name, "frames", "shared.arrow")+ table = pa.table({"a": [1]})+ with pa.OSFile(path, "wb") as sink:+ with pa.ipc.new_file(sink, table.schema) as writer:+ writer.write_table(table)+ envelope = self._run(+ "print(type(shared).__name__)",+ {"shared": "not-a-frame"},+ [{"name": "shared", "kind": "hogql", "path": path}],+ )+ self.assertIn("DataFrame", envelope["stdout"])++ def test_a_variable_the_notebook_stopped_declaring_is_removed(self):+ # Deleting or renaming a variable must take the global with it. Otherwise a cell that+ # reads the old name keeps working, so the notebook says the variable is gone while+ # the kernel still answers with its last value.+ self._run("print(country)", {"country": "US"})+ envelope = self._run("print('ok', 'country' in globals())", {})+ self.assertEqual(envelope["status"], "ok")+ self.assertIn("ok False", envelope["stdout"])++ def test_a_renamed_variable_leaves_no_global_under_the_old_name(self):+ self._run("pass", {"country": "US"})+ envelope = self._run("print('old' , 'country' in globals(), 'new', region)", {"region": "EU"})+ self.assertEqual(envelope["status"], "ok")+ self.assertIn("old False new EU", envelope["stdout"])++ def test_a_variable_a_cell_reassigned_is_reset_not_deleted(self):+ # Still declared, so the notebook's value wins again on the next run.+ self._run("country = 'DE'", {"country": "US"})+ envelope = self._run("print(country)", {"country": "US"})+ self.assertIn("US", envelope["stdout"])++ def test_a_run_without_variables_is_unaffected(self):+ envelope = self._run("print('no variables here')")+ self.assertEqual(envelope["status"], "ok")+ self.assertIn("no variables here", envelope["stdout"])+++class TestKernelSessionDuckdbVariables(SimpleTestCase):+ def setUp(self):+ self._dir = tempfile.TemporaryDirectory()+ self.addCleanup(self._dir.cleanup)+ self.session = KernelSession(data_dir=self._dir.name)++ def _run_duckdb(self, code: str, variables=None) -> dict:+ return self.session.run_node(+ {"node": {"type": "duckdb", "code": code, "variables": variables or {}}, "inputs": []}+ )++ def test_a_parameter_binds_as_a_value(self):+ envelope = self._run_duckdb("select $country as country", {"country": "US"})+ self.assertEqual(envelope["status"], "ok")+ self.assertEqual(envelope["first_page"], [["US"]])++ def test_a_value_carrying_sql_stays_one_value(self):+ # The whole point of binding: the driver never parses the value, so an injection+ # payload comes back as data rather than an extra result branch.+ payload = "US' UNION ALL SELECT version() --"+ envelope = self._run_duckdb("select $country as country", {"country": payload})+ self.assertEqual(envelope["status"], "ok")+ self.assertEqual(envelope["first_page"], [[payload]])diff --git a/products/notebooks/backend/test/test_sql_v2.py b/products/notebooks/backend/test/test_sql_v2.pyindex 78a96b47b921..337543c77539 100644--- a/products/notebooks/backend/test/test_sql_v2.py+++ b/products/notebooks/backend/test/test_sql_v2.py@@ -2916,3 +2916,99 @@ class TestSQLV2NodeRunMetrics(APIBaseTest):self.assertEqual(NotebookNodeRun.objects.for_team(self.team.id).get(id=run.id).status, NotebookNodeRun.Status.DONE)+++class TestSQLV2RunWithNotebookVariables(APIBaseTest):+ def setUp(self):+ super().setUp()+ self.notebook = Notebook.objects.create(team=self.team, short_id="nbvars01")+ self.run_url = f"/api/projects/{self.team.id}/notebooks/{self.notebook.short_id}/sql_v2/run/"++ @patch("products.notebooks.backend.presentation.views.notebook.enqueue_direct_run")+ @patch("products.notebooks.backend.presentation.views.notebook.is_sql_v2_enabled", return_value=True)+ def test_a_sql_run_stores_the_query_with_its_variables_bound(self, _mock_enabled, _mock_enqueue):+ # The stored code is what the direct lane executes and what paging re-queries, so an+ # unbound placeholder here reaches ClickHouse and fails the run.+ response = self.client.post(+ self.run_url,+ data={+ "node_id": "n1",+ "code": "select {country} as country",+ "variables": [{"name": "country", "type": "string", "value": "US"}],+ },+ format="json",+ )+ self.assertEqual(response.status_code, 200)+ run = NotebookNodeRun.objects.for_team(self.team.id).get(id=response.json()["run_id"])+ self.assertIn("'US'", run.code)+ self.assertNotIn("{country}", run.code)++ @patch("products.notebooks.backend.presentation.views.notebook.enqueue_direct_run")+ @patch("products.notebooks.backend.presentation.views.notebook.is_sql_v2_enabled", return_value=True)+ def test_reading_an_undeclared_variable_is_a_400(self, _mock_enabled, mock_enqueue):+ response = self.client.post(+ self.run_url,+ data={"node_id": "n1", "code": "select {country} as country", "variables": []},+ format="json",+ )+ self.assertEqual(response.status_code, 400)+ self.assertIn("not a notebook variable", response.json()["detail"])+ mock_enqueue.assert_not_called()++ @patch("products.notebooks.backend.presentation.views.notebook.start_sql_v2_run_workflow")+ @patch("products.notebooks.backend.presentation.views.notebook.is_sql_v2_enabled", return_value=True)+ def test_a_python_run_carries_the_variables_to_the_kernel_unsubstituted(self, _mock_enabled, mock_start):+ # Python reads them as globals, so the code must reach the kernel untouched with the+ # values alongside it — substituting into Python source would be a different feature.+ code = "print(country)"+ response = self.client.post(+ self.run_url,+ data={+ "node_id": "p1",+ "code": code,+ "node_type": "python",+ "variables": [+ {"name": "country", "type": "string", "value": "US"},+ {"name": "days", "type": "number", "value": 30},+ ],+ },+ format="json",+ )+ self.assertEqual(response.status_code, 200)+ run = NotebookNodeRun.objects.for_team(self.team.id).get(id=response.json()["run_id"])+ self.assertEqual(run.code, code)+ self.assertEqual(mock_start.call_args.args[0].variables, {"country": "US", "days": 30})++ @patch("products.notebooks.backend.presentation.views.notebook.enqueue_direct_run")+ @patch("products.notebooks.backend.presentation.views.notebook.is_sql_v2_enabled", return_value=True)+ def test_a_run_without_variables_is_unchanged(self, _mock_enabled, _mock_enqueue):+ response = self.client.post(self.run_url, data={"node_id": "n1", "code": "select 1"}, format="json")+ self.assertEqual(response.status_code, 200)+ run = NotebookNodeRun.objects.for_team(self.team.id).get(id=response.json()["run_id"])+ self.assertEqual(run.code, "select 1")++ @patch("products.notebooks.backend.presentation.views.notebook.get_direct_connection_source")+ @patch("products.notebooks.backend.presentation.views.notebook.start_sql_v2_run_workflow")+ @patch("products.notebooks.backend.presentation.views.notebook.enqueue_direct_run")+ @patch("products.notebooks.backend.presentation.views.notebook.is_sql_v2_enabled", return_value=True)+ def test_a_raw_connection_query_refuses_variables(+ self, _mock_enabled, mock_enqueue, mock_start, mock_source+ ) -> None:+ # Quote doubling is not a safe escape on every engine a connection can point at, so the+ # dispatch is refused rather than run with a hand-rolled literal.+ mock_source.return_value = object()+ response = self.client.post(+ self.run_url,+ data={+ "node_id": "n1",+ "code": "select * from t where c = {country}",+ "connection_id": "018e0e7a-9999-8888-7777-666666666666",+ "send_raw_query": True,+ "variables": [{"name": "country", "type": "string", "value": "US"}],+ },+ format="json",+ )+ self.assertEqual(response.status_code, 400, response.json())+ self.assertIn("raw query", response.json()["detail"])+ mock_enqueue.assert_not_called()+ mock_start.assert_not_called()diff --git a/products/notebooks/backend/test/test_sql_v2_references.py b/products/notebooks/backend/test/test_sql_v2_references.pyindex 5c1397c1e5e4..4a9c0a25fb64 100644--- a/products/notebooks/backend/test/test_sql_v2_references.py+++ b/products/notebooks/backend/test/test_sql_v2_references.py@@ -70,40 +70,38 @@ class TestResolvePythonNodeInputs(SimpleTestCase):class TestResolveSQLNodeRun(SimpleTestCase):def test_all_hogql_refs_push_to_clickhouse(self):- node_type, run_code, inputs = resolve_sql_node_run(- "select * from df1", {"df1": hogql_ref("select id from events")}- )- self.assertEqual(node_type, "hogql")- self.assertIn("WITH df1 AS (SELECT id FROM events)", run_code)- self.assertEqual(inputs, [])+ plan = resolve_sql_node_run("select * from df1", {"df1": hogql_ref("select id from events")})+ self.assertEqual(plan.node_type, "hogql")+ self.assertIn("WITH df1 AS (SELECT id FROM events)", plan.code)+ self.assertEqual(plan.inputs, [])def test_unreferenced_local_frame_does_not_reroute(self):# The local frame exists in the notebook but this query never touches it.- node_type, run_code, inputs = resolve_sql_node_run(+ plan = resolve_sql_node_run("select * from df1", {"df1": hogql_ref("select id from events"), "new_events": LOCAL})- self.assertEqual(node_type, "hogql")- self.assertIn("WITH df1 AS", run_code)- self.assertEqual(inputs, [])+ self.assertEqual(plan.node_type, "hogql")+ self.assertIn("WITH df1 AS", plan.code)+ self.assertEqual(plan.inputs, [])def test_referenced_local_frame_reroutes_to_duckdb_and_materializes_hogql_refs(self):# Journey 5 step 4: the join runs locally, forcing df2 into the sandbox.code = "select * from df2 join new_events on df2.id = new_events.id"- node_type, run_code, inputs = resolve_sql_node_run(- code, {"df2": hogql_ref("select id from persons"), "new_events": LOCAL}+ plan = resolve_sql_node_run(code, {"df2": hogql_ref("select id from persons"), "new_events": LOCAL})+ self.assertEqual(plan.node_type, "duckdb")+ self.assertEqual(plan.code, code) # DuckDB gets the SQL as written, not a CTE rewrite+ self.assertEqual(+ [(spec["name"], spec["kind"]) for spec in plan.inputs], [("df2", "hogql"), ("new_events", "local")])- self.assertEqual(node_type, "duckdb")- self.assertEqual(run_code, code) # DuckDB gets the SQL as written, not a CTE rewrite- self.assertEqual([(spec["name"], spec["kind"]) for spec in inputs], [("df2", "hogql"), ("new_events", "local")])- self.assertEqual(inputs[0]["query"], "select id from persons")+ self.assertEqual(plan.inputs[0]["query"], "select id from persons")# DuckDB-rerouted runs key materialized frames the same way python nodes do.- self.assertEqual(inputs[0]["node_id"], "node-df1")- self.assertEqual(inputs[0]["run_id"], "run-1")+ self.assertEqual(plan.inputs[0]["node_id"], "node-df1")+ self.assertEqual(plan.inputs[0]["run_id"], "run-1")def test_local_only_query_reroutes_with_no_materialization(self):- node_type, run_code, inputs = resolve_sql_node_run("select count() from new_events", {"new_events": LOCAL})- self.assertEqual(node_type, "duckdb")- self.assertEqual(inputs, [{"name": "new_events", "kind": "local"}])+ plan = resolve_sql_node_run("select count() from new_events", {"new_events": LOCAL})+ self.assertEqual(plan.node_type, "duckdb")+ self.assertEqual(plan.inputs, [{"name": "new_events", "kind": "local"}])def test_duckdb_run_referencing_a_never_run_hogql_node_raises(self):with self.assertRaises(SQLV2ReferenceError):@@ -115,19 +113,19 @@ class TestResolveSQLNodeRun(SimpleTestCase):# DuckDB-only syntax (PIVOT isn't HogQL; QUALIFY actually parses) must still run# locally when it names a local frame — this is the regex fallback's positive path.code = "pivot new_events on category"- node_type, run_code, inputs = resolve_sql_node_run(code, {"new_events": LOCAL})- self.assertEqual(node_type, "duckdb")- self.assertEqual(run_code, code)- self.assertEqual(inputs, [{"name": "new_events", "kind": "local"}])+ plan = resolve_sql_node_run(code, {"new_events": LOCAL})+ self.assertEqual(plan.node_type, "duckdb")+ self.assertEqual(plan.code, code)+ self.assertEqual(plan.inputs, [{"name": "new_events", "kind": "local"}])def test_frame_named_only_in_a_literal_or_comment_does_not_route_to_duckdb(self):# The fallback scanner must not see the frame name inside a string or comment —# that would reroute the query to DuckDB and materialize a frame it never reads.code = "pivot events on label in ('new_events') -- new_events"- node_type, run_code, inputs = resolve_sql_node_run(code, {"new_events": LOCAL})- self.assertEqual(node_type, "hogql")- self.assertEqual(run_code, code)- self.assertEqual(inputs, [])+ plan = resolve_sql_node_run(code, {"new_events": LOCAL})+ self.assertEqual(plan.node_type, "hogql")+ self.assertEqual(plan.code, code)+ self.assertEqual(plan.inputs, [])class TestResolveSQLV2References(SimpleTestCase):diff --git a/products/notebooks/backend/test/test_sql_v2_variables.py b/products/notebooks/backend/test/test_sql_v2_variables.pynew file mode 100644index 000000000000..3815273425fb--- /dev/null+++ b/products/notebooks/backend/test/test_sql_v2_variables.py@@ -0,0 +1,271 @@+import time+from zoneinfo import ZoneInfo++from django.test import SimpleTestCase++from parameterized import parameterized++from posthog.hogql import ast+from posthog.hogql.parser import parse_select++from products.notebooks.backend.sql_v2_references import SQLV2Ref, resolve_sql_node_run+from products.notebooks.backend.sql_v2_variables import (+ NotebookVariable,+ NotebookVariableError,+ build_notebook_variables,+ python_variable_bindings,+ reject_variables_in_raw_query,+ substitute_duckdb_variables,+ substitute_hogql_variables,+)++UTC = ZoneInfo("UTC")+COUNTRY = NotebookVariable(name="country", value="US")+DAYS = NotebookVariable(name="lookback_days", value=30)+++class TestSubstituteHogqlVariables(SimpleTestCase):+ def test_binds_a_value_as_a_constant(self):+ printed = substitute_hogql_variables("select 1 where 'x' = {country}", [COUNTRY])+ self.assertIn("'US'", printed)+ self.assertNotIn("{country}", printed)++ def test_a_query_without_placeholders_is_returned_verbatim(self):+ # Byte-identical, so adding the feature cannot reformat anybody's existing query.+ code = "select count()\nfrom events -- trailing comment"+ self.assertEqual(substitute_hogql_variables(code, [COUNTRY]), code)++ def test_a_string_value_stays_one_literal(self):+ # The value is a constant in the AST, never spliced text, so SQL syntax inside it is+ # data. Re-parsing the printed query is what proves it: an escape that leaked would+ # change the shape of the tree, not just the characters.+ injected = "US' or 1=1 --"+ printed = substitute_hogql_variables(+ "select 1 where 'x' = {country}", [NotebookVariable(name="country", value=injected)]+ )+ where = parse_select(printed).where # type: ignore[union-attr]+ self.assertIsInstance(where, ast.Call)+ # Exactly two operands, the payload intact in the second — not an `or` the escape opened up.+ constants = [arg.value for arg in where.args if isinstance(arg, ast.Constant)] # type: ignore[union-attr]+ self.assertEqual(constants, ["x", injected])++ @parameterized.expand(+ [+ # Injected by HogQL itself, and resolved much later than dispatch.+ ("filters", "select 1 from events where {filters}"),+ # An insight variable, which has its own resolver and its own storage.+ ("dotted_chain", "select 1 from events where properties.x = {variables.country}"),+ ]+ )+ def test_another_resolvers_placeholder_is_left_untouched(self, _name: str, code: str) -> None:+ self.assertEqual(substitute_hogql_variables(code, [COUNTRY]), code)++ @parameterized.expand(+ [+ ("close_match_is_suggested", "{contry}", [COUNTRY], "country"),+ ("nothing_declared_says_how_to_declare", "{country}", [], "Variables block"),+ ]+ )+ def test_an_undeclared_name_is_reported(+ self, _name: str, placeholder: str, variables: list[NotebookVariable], expected: str+ ) -> None:+ with self.assertRaises(NotebookVariableError) as error:+ substitute_hogql_variables(f"select 1 where 'x' = {placeholder}", variables)+ self.assertIn(expected, str(error.exception))+++class TestSubstituteDuckdbVariables(SimpleTestCase):+ def test_a_placeholder_becomes_a_bound_parameter(self):+ # The value never enters the SQL, so nothing about it can be parsed as SQL.+ code, params = substitute_duckdb_variables("select * from t where c = {country}", [COUNTRY])+ self.assertEqual(code, "select * from t where c = $country")+ self.assertEqual(params, {"country": "US"})++ def test_only_the_names_the_query_uses_are_bound(self):+ # DuckDB rejects a parameter the query never references, so an unused declaration+ # must not be sent.+ code, params = substitute_duckdb_variables("select {country}", [COUNTRY, DAYS])+ self.assertEqual(code, "select $country")+ self.assertEqual(params, {"country": "US"})++ @parameterized.expand(+ [+ ("single_quoted", "select '{country}' as label"),+ ("double_quoted_identifier", 'select 1 as "{country}"'),+ # The region the escaping scanner missed: everything between the tags is literal,+ # so a value written here could have closed the string and run as SQL.+ ("dollar_quoted", "select $tag${country}$tag$"),+ ("dollar_quoted_bare", "select $${country}$$"),+ ("line_comment", "-- {country}\nselect 1"),+ ("block_comment", "/* {country} */ select 1"),+ ]+ )+ def test_a_placeholder_outside_executable_sql_is_left_alone(self, _name: str, code: str) -> None:+ rewritten, params = substitute_duckdb_variables(code, [COUNTRY])+ self.assertEqual(rewritten, code)+ self.assertEqual(params, {})++ def test_a_value_cannot_escape_a_dollar_quoted_string(self):+ # The reported injection: with textual escaping this produced+ # `select $tag$'$tag$ UNION ALL SELECT version() --'$tag$`, where the payload closed+ # the literal and ran. Now the placeholder is literal text and nothing is bound.+ code = "select $tag${country}$tag$"+ rewritten, params = substitute_duckdb_variables(+ code, [NotebookVariable(name="country", value="$tag$ UNION ALL SELECT version() --")]+ )+ self.assertEqual(rewritten, code)+ self.assertEqual(params, {})++ def test_a_query_without_placeholders_is_returned_verbatim(self):+ code = "select * from py_df"+ self.assertEqual(substitute_duckdb_variables(code, [COUNTRY]), (code, {}))++ @parameterized.expand(+ [+ # An unterminated literal swallows the rest of the input, exactly as a lexer reads+ # it. The query is malformed either way; what matters is that no value goes in.+ ("unterminated_dollar_quote", "select $tag$ {country}"),+ ("unterminated_string", "select ' {country}"),+ ("unterminated_block_comment", "select /* {country}"),+ # Backslash escapes apply inside E'…', so the quote here does not close the string.+ ("escaped_quote_in_e_string", "select E'\\' {country}"),+ ]+ )+ def test_an_unterminated_region_keeps_the_placeholder_literal(self, _name: str, code: str) -> None:+ rewritten, params = substitute_duckdb_variables(code, [COUNTRY])+ self.assertEqual(rewritten, code)+ self.assertEqual(params, {})++ def test_a_numbered_parameter_is_not_read_as_a_dollar_quote(self):+ # `$1$2` is two positional parameters; reading it as an opener would swallow the query.+ code = "select $1, $2, {country}"+ rewritten, params = substitute_duckdb_variables(code, [COUNTRY])+ self.assertEqual(rewritten, "select $1, $2, $country")+ self.assertEqual(params, {"country": "US"})++ def test_many_unmatched_dollar_openers_stay_linear(self):+ # Matching `$tag$…$tag$` with a backreference rescans the tail once per unmatched+ # opener, which a single 20 MB request turns into hours of CPU. The margin here is+ # three orders of magnitude: the linear scan does this in milliseconds.+ code = " ".join(f"$tag{index}$" for index in range(200_000)) + " {country}"+ started = time.monotonic()+ substitute_duckdb_variables(code, [COUNTRY])+ self.assertLess(time.monotonic() - started, 2.0)++ def test_an_undeclared_name_raises(self):+ with self.assertRaises(NotebookVariableError):+ substitute_duckdb_variables("select {nope}", [COUNTRY])+++class TestBuildNotebookVariables(SimpleTestCase):+ @parameterized.expand(+ [+ ("string", "string", "US", "US"),+ ("number_from_string", "number", "30", 30),+ ("number_float", "number", "1.5", 1.5),+ ("number_invalid", "number", "abc", None),+ ("boolean_from_string", "boolean", "true", True),+ ("boolean_false", "boolean", "nope", False),+ ("absolute_date", "date", "2026-01-31", "2026-01-31"),+ ("unknown_type_reads_as_string", "wat", 5, "5"),+ ]+ )+ def test_coerces_by_type(self, _name: str, variable_type: str, value: object, expected: object) -> None:+ built = build_notebook_variables([{"name": "v", "type": variable_type, "value": value}], UTC)+ self.assertEqual(built[0].value, expected)++ def test_a_relative_date_resolves_to_a_datetime(self):+ built = build_notebook_variables([{"name": "since", "type": "date", "value": "-7d"}], UTC)+ self.assertIsNotNone(built[0].value)+ self.assertNotEqual(built[0].value, "-7d")++ def test_duplicates_keep_the_first_declaration(self):+ # Matches the editor, which flags the second one as invalid rather than shadowing.+ built = build_notebook_variables(+ [+ {"name": "country", "type": "string", "value": "US"},+ {"name": "country", "type": "string", "value": "DE"},+ ],+ UTC,+ )+ self.assertEqual([(variable.name, variable.value) for variable in built], [("country", "US")])++ def test_unnamed_and_reserved_declarations_are_dropped(self):+ built = build_notebook_variables(+ [+ {"name": " ", "type": "string", "value": "x"},+ {"name": "filters", "type": "string", "value": "x"},+ {"name": "ok", "type": "string", "value": "x"},+ ],+ UTC,+ )+ self.assertEqual([variable.name for variable in built], ["ok"])+++class TestPythonVariableBindings(SimpleTestCase):+ def test_scalars_pass_through_and_dates_become_iso_strings(self):+ built = build_notebook_variables(+ [+ {"name": "country", "type": "string", "value": "US"},+ {"name": "days", "type": "number", "value": 30},+ {"name": "since", "type": "date", "value": "-7d"},+ ],+ UTC,+ )+ bindings = python_variable_bindings(built)+ self.assertEqual(bindings["country"], "US")+ self.assertEqual(bindings["days"], 30)+ self.assertIsInstance(bindings["since"], str)+++class TestResolveSqlNodeRunWithVariables(SimpleTestCase):+ def test_the_clickhouse_lane_binds_through_the_ast(self):+ plan = resolve_sql_node_run("select 1 where 'x' = {country}", {}, [COUNTRY])+ self.assertEqual(plan.node_type, "hogql")+ self.assertEqual(plan.inputs, [])+ self.assertIn("'US'", plan.code)++ def test_the_duckdb_lane_carries_parameters_without_reformatting(self):+ # A local ref reroutes to DuckDB, whose dialect the HogQL printer must not rewrite.+ # The value rides alongside as a bound parameter rather than inside the SQL.+ plan = resolve_sql_node_run(+ "select * from py_df where country = {country}", {"py_df": SQLV2Ref(kind="local")}, [COUNTRY]+ )+ self.assertEqual(plan.node_type, "duckdb")+ self.assertEqual(plan.code, "select * from py_df where country = $country")+ self.assertEqual(plan.variables, {"country": "US"})++ def test_a_variable_binds_in_a_query_that_also_inlines_a_reference(self):+ # Both rewrites have to survive each other: the CTE merge reprints the AST, which fails+ # on a placeholder that is still unresolved by then.+ plan = resolve_sql_node_run(+ "select * from df1 where days > {lookback_days}",+ {"df1": SQLV2Ref(kind="hogql", node_id="n1", run_id="r1", last_run_code="select 1 as days")},+ [DAYS],+ )+ self.assertEqual(plan.node_type, "hogql")+ self.assertIn("30", plan.code)+ self.assertIn("df1 AS (", plan.code)+++class TestRejectVariablesInRawQuery(SimpleTestCase):+ def test_a_raw_query_reading_a_variable_is_refused(self):+ # Escaping differs by engine and by server setting — MySQL treats a backslash as an+ # escape, so quote doubling alone would let `\' OR 1=1 -- ` close the literal and run+ # as SQL. Refusing is what keeps a hand-rolled escape out of the raw lane.+ with self.assertRaises(NotebookVariableError) as error:+ reject_variables_in_raw_query("select * from t where c = {country}", [COUNTRY])+ self.assertIn("raw query", str(error.exception))+ self.assertIn("country", str(error.exception))++ @parameterized.expand(+ [+ # Raw SQL may use braces for its own purposes, so an unknown name is not ours to reject.+ ("an undeclared name", "select {not_a_variable}"),+ ("a name inside a string literal", "select '{country}' as label"),+ ("a name inside a comment", "-- {country}\nselect 1"),+ ("no braces at all", "select * from t"),+ ]+ )+ def test_leaves_a_query_alone(self, _name: str, code: str) -> None:+ reject_variables_in_raw_query(code, [COUNTRY])diff --git a/products/notebooks/frontend/generated/api.schemas.ts b/products/notebooks/frontend/generated/api.schemas.tsindex 3721cea3d80c..c425b6cc2a24 100644--- a/products/notebooks/frontend/generated/api.schemas.ts+++ b/products/notebooks/frontend/generated/api.schemas.ts@@ -106,6 +106,21 @@ export type NotebookApiParentResource = {readonly id: string} | null+/**+ * One notebook-level variable. Shared by the notebook's own `variables` field and a run body.+ */+export interface NotebookVariableApi {+ /**+ * Identifier the cell reads: `{name}` in a SQL cell, a plain global in a Python cell.+ * @maxLength 200+ */+ name: string+ /** How to coerce the value: 'string', 'number', 'boolean', or 'date'. Unknown types read as 'string'. */+ type: string+ /** The variable's current value. A 'date' accepts an absolute date or a relative expression ('-7d', 'mStart'), resolved against the project timezone. */+ value?: unknown+}+export interface NotebookApi {/** UUID of the notebook. */readonly id: string@@ -146,6 +161,8 @@ export interface NotebookApi {* @nullable*/readonly parent_resource: NotebookApiParentResource+ /** Notebook-level variables, in display order. A SQL cell reads one as a `{name}` placeholder and a Python cell as a global. Names must be unique. */+ variables?: NotebookVariableApi[]_create_in_folder?: string}@@ -198,6 +215,8 @@ export interface PatchedNotebookApi {* @nullable*/readonly parent_resource?: PatchedNotebookApiParentResource+ /** Notebook-level variables, in display order. A SQL cell reads one as a `{name}` placeholder and a Python cell as a global. Names must be unique. */+ variables?: NotebookVariableApi[]_create_in_folder?: string}@@ -427,6 +446,8 @@ export interface NotebookSQLV2RunRequestApi {output_name?: string/** Available upstream nodes, keyed by dataframe name. A SQL node inlines referenced hogql refs as CTEs — unless it references a local ref, which reroutes the run to the sandbox's DuckDB; a python node materializes the hogql refs its code reads as pandas frames. */refs?: NotebookSQLV2RunRequestApiRefs+ /** Notebook-level variables in scope for this run. A SQL node has each `{name}` bound to its value before dispatch; a Python node gets them as globals in the kernel namespace. A SQL node reading a `{name}` that is absent here fails the dispatch. */+ variables?: NotebookVariableApi[]/*** SQL nodes only: id of a direct-query-capable external data source to run against instead of PostHog's ClickHouse. Omit to query PostHog.* @nullablediff --git a/products/notebooks/frontend/generated/api.zod.ts b/products/notebooks/frontend/generated/api.zod.tsindex 63357d4f9829..a751f1b74d57 100644--- a/products/notebooks/frontend/generated/api.zod.ts+++ b/products/notebooks/frontend/generated/api.zod.ts@@ -17,6 +17,8 @@ export const notebooksCreateBodyTitleMax = 256export const notebooksCreateBodyVersionMin = -2147483648export const notebooksCreateBodyVersionMax = 2147483647+export const notebooksCreateBodyVariablesItemNameMax = 200+export const NotebooksCreateBody = /* @__PURE__ */ zod.object({title: zod.string().max(notebooksCreateBodyTitleMax).nullish().describe('Title of the notebook.'),content: zod.unknown().optional().describe('Notebook content as a ProseMirror JSON document structure.'),@@ -30,6 +32,34 @@ export const NotebooksCreateBody = /* @__PURE__ */ zod.object({'Version number for optimistic concurrency control. Must match the current version when updating content.'),deleted: zod.boolean().optional().describe('Whether the notebook has been soft-deleted.'),+ variables: zod+ .array(+ zod+ .object({+ name: zod+ .string()+ .max(notebooksCreateBodyVariablesItemNameMax)+ .describe(+ 'Identifier the cell reads: `{name}` in a SQL cell, a plain global in a Python cell.'+ ),+ type: zod+ .string()+ .describe(+ "How to coerce the value: 'string', 'number', 'boolean', or 'date'. Unknown types read as 'string'."+ ),+ value: zod+ .unknown()+ .optional()+ .describe(+ "The variable's current value. A 'date' accepts an absolute date or a relative expression ('-7d', 'mStart'), resolved against the project timezone."+ ),+ })+ .describe("One notebook-level variable. Shared by the notebook's own `variables` field and a run body.")+ )+ .optional()+ .describe(+ 'Notebook-level variables, in display order. A SQL cell reads one as a `{name}` placeholder and a Python cell as a global. Names must be unique.'+ ),_create_in_folder: zod.string().optional(),})@@ -41,6 +71,8 @@ export const notebooksUpdateBodyTitleMax = 256export const notebooksUpdateBodyVersionMin = -2147483648export const notebooksUpdateBodyVersionMax = 2147483647+export const notebooksUpdateBodyVariablesItemNameMax = 200+export const NotebooksUpdateBody = /* @__PURE__ */ zod.object({title: zod.string().max(notebooksUpdateBodyTitleMax).nullish().describe('Title of the notebook.'),content: zod.unknown().optional().describe('Notebook content as a ProseMirror JSON document structure.'),@@ -54,6 +86,34 @@ export const NotebooksUpdateBody = /* @__PURE__ */ zod.object({'Version number for optimistic concurrency control. Must match the current version when updating content.'),deleted: zod.boolean().optional().describe('Whether the notebook has been soft-deleted.'),+ variables: zod+ .array(+ zod+ .object({+ name: zod+ .string()+ .max(notebooksUpdateBodyVariablesItemNameMax)+ .describe(+ 'Identifier the cell reads: `{name}` in a SQL cell, a plain global in a Python cell.'+ ),+ type: zod+ .string()+ .describe(+ "How to coerce the value: 'string', 'number', 'boolean', or 'date'. Unknown types read as 'string'."+ ),+ value: zod+ .unknown()+ .optional()+ .describe(+ "The variable's current value. A 'date' accepts an absolute date or a relative expression ('-7d', 'mStart'), resolved against the project timezone."+ ),+ })+ .describe("One notebook-level variable. Shared by the notebook's own `variables` field and a run body.")+ )+ .optional()+ .describe(+ 'Notebook-level variables, in display order. A SQL cell reads one as a `{name}` placeholder and a Python cell as a global. Names must be unique.'+ ),_create_in_folder: zod.string().optional(),})@@ -65,6 +125,8 @@ export const notebooksPartialUpdateBodyTitleMax = 256export const notebooksPartialUpdateBodyVersionMin = -2147483648export const notebooksPartialUpdateBodyVersionMax = 2147483647+export const notebooksPartialUpdateBodyVariablesItemNameMax = 200+export const NotebooksPartialUpdateBody = /* @__PURE__ */ zod.object({title: zod.string().max(notebooksPartialUpdateBodyTitleMax).nullish().describe('Title of the notebook.'),content: zod.unknown().optional().describe('Notebook content as a ProseMirror JSON document structure.'),@@ -78,6 +140,34 @@ export const NotebooksPartialUpdateBody = /* @__PURE__ */ zod.object({'Version number for optimistic concurrency control. Must match the current version when updating content.'),deleted: zod.boolean().optional().describe('Whether the notebook has been soft-deleted.'),+ variables: zod+ .array(+ zod+ .object({+ name: zod+ .string()+ .max(notebooksPartialUpdateBodyVariablesItemNameMax)+ .describe(+ 'Identifier the cell reads: `{name}` in a SQL cell, a plain global in a Python cell.'+ ),+ type: zod+ .string()+ .describe(+ "How to coerce the value: 'string', 'number', 'boolean', or 'date'. Unknown types read as 'string'."+ ),+ value: zod+ .unknown()+ .optional()+ .describe(+ "The variable's current value. A 'date' accepts an absolute date or a relative expression ('-7d', 'mStart'), resolved against the project timezone."+ ),+ })+ .describe("One notebook-level variable. Shared by the notebook's own `variables` field and a run body.")+ )+ .optional()+ .describe(+ 'Notebook-level variables, in display order. A SQL cell reads one as a `{name}` placeholder and a Python cell as a global. Names must be unique.'+ ),_create_in_folder: zod.string().optional(),})@@ -213,6 +303,8 @@ export const notebooksHogqlExecuteCreateBodyTitleMax = 256export const notebooksHogqlExecuteCreateBodyVersionMin = -2147483648export const notebooksHogqlExecuteCreateBodyVersionMax = 2147483647+export const notebooksHogqlExecuteCreateBodyVariablesItemNameMax = 200+export const NotebooksHogqlExecuteCreateBody = /* @__PURE__ */ zod.object({title: zod.string().max(notebooksHogqlExecuteCreateBodyTitleMax).nullish().describe('Title of the notebook.'),content: zod.unknown().optional().describe('Notebook content as a ProseMirror JSON document structure.'),@@ -226,6 +318,34 @@ export const NotebooksHogqlExecuteCreateBody = /* @__PURE__ */ zod.object({'Version number for optimistic concurrency control. Must match the current version when updating content.'),deleted: zod.boolean().optional().describe('Whether the notebook has been soft-deleted.'),+ variables: zod+ .array(+ zod+ .object({+ name: zod+ .string()+ .max(notebooksHogqlExecuteCreateBodyVariablesItemNameMax)+ .describe(+ 'Identifier the cell reads: `{name}` in a SQL cell, a plain global in a Python cell.'+ ),+ type: zod+ .string()+ .describe(+ "How to coerce the value: 'string', 'number', 'boolean', or 'date'. Unknown types read as 'string'."+ ),+ value: zod+ .unknown()+ .optional()+ .describe(+ "The variable's current value. A 'date' accepts an absolute date or a relative expression ('-7d', 'mStart'), resolved against the project timezone."+ ),+ })+ .describe("One notebook-level variable. Shared by the notebook's own `variables` field and a run body.")+ )+ .optional()+ .describe(+ 'Notebook-level variables, in display order. A SQL cell reads one as a `{name}` placeholder and a Python cell as a global. Names must be unique.'+ ),_create_in_folder: zod.string().optional(),})@@ -255,6 +375,8 @@ export const notebooksKernelExecuteCreateBodyTitleMax = 256export const notebooksKernelExecuteCreateBodyVersionMin = -2147483648export const notebooksKernelExecuteCreateBodyVersionMax = 2147483647+export const notebooksKernelExecuteCreateBodyVariablesItemNameMax = 200+export const NotebooksKernelExecuteCreateBody = /* @__PURE__ */ zod.object({title: zod.string().max(notebooksKernelExecuteCreateBodyTitleMax).nullish().describe('Title of the notebook.'),content: zod.unknown().optional().describe('Notebook content as a ProseMirror JSON document structure.'),@@ -268,6 +390,34 @@ export const NotebooksKernelExecuteCreateBody = /* @__PURE__ */ zod.object({'Version number for optimistic concurrency control. Must match the current version when updating content.'),deleted: zod.boolean().optional().describe('Whether the notebook has been soft-deleted.'),+ variables: zod+ .array(+ zod+ .object({+ name: zod+ .string()+ .max(notebooksKernelExecuteCreateBodyVariablesItemNameMax)+ .describe(+ 'Identifier the cell reads: `{name}` in a SQL cell, a plain global in a Python cell.'+ ),+ type: zod+ .string()+ .describe(+ "How to coerce the value: 'string', 'number', 'boolean', or 'date'. Unknown types read as 'string'."+ ),+ value: zod+ .unknown()+ .optional()+ .describe(+ "The variable's current value. A 'date' accepts an absolute date or a relative expression ('-7d', 'mStart'), resolved against the project timezone."+ ),+ })+ .describe("One notebook-level variable. Shared by the notebook's own `variables` field and a run body.")+ )+ .optional()+ .describe(+ 'Notebook-level variables, in display order. A SQL cell reads one as a `{name}` placeholder and a Python cell as a global. Names must be unique.'+ ),_create_in_folder: zod.string().optional(),})@@ -279,6 +429,8 @@ export const notebooksKernelExecuteStreamCreateBodyTitleMax = 256export const notebooksKernelExecuteStreamCreateBodyVersionMin = -2147483648export const notebooksKernelExecuteStreamCreateBodyVersionMax = 2147483647+export const notebooksKernelExecuteStreamCreateBodyVariablesItemNameMax = 200+export const NotebooksKernelExecuteStreamCreateBody = /* @__PURE__ */ zod.object({title: zod.string()@@ -296,6 +448,34 @@ export const NotebooksKernelExecuteStreamCreateBody = /* @__PURE__ */ zod.object'Version number for optimistic concurrency control. Must match the current version when updating content.'),deleted: zod.boolean().optional().describe('Whether the notebook has been soft-deleted.'),+ variables: zod+ .array(+ zod+ .object({+ name: zod+ .string()+ .max(notebooksKernelExecuteStreamCreateBodyVariablesItemNameMax)+ .describe(+ 'Identifier the cell reads: `{name}` in a SQL cell, a plain global in a Python cell.'+ ),+ type: zod+ .string()+ .describe(+ "How to coerce the value: 'string', 'number', 'boolean', or 'date'. Unknown types read as 'string'."+ ),+ value: zod+ .unknown()+ .optional()+ .describe(+ "The variable's current value. A 'date' accepts an absolute date or a relative expression ('-7d', 'mStart'), resolved against the project timezone."+ ),+ })+ .describe("One notebook-level variable. Shared by the notebook's own `variables` field and a run body.")+ )+ .optional()+ .describe(+ 'Notebook-level variables, in display order. A SQL cell reads one as a `{name}` placeholder and a Python cell as a global. Names must be unique.'+ ),_create_in_folder: zod.string().optional(),})@@ -307,6 +487,8 @@ export const notebooksKernelRestartCreateBodyTitleMax = 256export const notebooksKernelRestartCreateBodyVersionMin = -2147483648export const notebooksKernelRestartCreateBodyVersionMax = 2147483647+export const notebooksKernelRestartCreateBodyVariablesItemNameMax = 200+export const NotebooksKernelRestartCreateBody = /* @__PURE__ */ zod.object({title: zod.string().max(notebooksKernelRestartCreateBodyTitleMax).nullish().describe('Title of the notebook.'),content: zod.unknown().optional().describe('Notebook content as a ProseMirror JSON document structure.'),@@ -320,6 +502,34 @@ export const NotebooksKernelRestartCreateBody = /* @__PURE__ */ zod.object({'Version number for optimistic concurrency control. Must match the current version when updating content.'),deleted: zod.boolean().optional().describe('Whether the notebook has been soft-deleted.'),+ variables: zod+ .array(+ zod+ .object({+ name: zod+ .string()+ .max(notebooksKernelRestartCreateBodyVariablesItemNameMax)+ .describe(+ 'Identifier the cell reads: `{name}` in a SQL cell, a plain global in a Python cell.'+ ),+ type: zod+ .string()+ .describe(+ "How to coerce the value: 'string', 'number', 'boolean', or 'date'. Unknown types read as 'string'."+ ),+ value: zod+ .unknown()+ .optional()+ .describe(+ "The variable's current value. A 'date' accepts an absolute date or a relative expression ('-7d', 'mStart'), resolved against the project timezone."+ ),+ })+ .describe("One notebook-level variable. Shared by the notebook's own `variables` field and a run body.")+ )+ .optional()+ .describe(+ 'Notebook-level variables, in display order. A SQL cell reads one as a `{name}` placeholder and a Python cell as a global. Names must be unique.'+ ),_create_in_folder: zod.string().optional(),})@@ -331,6 +541,8 @@ export const notebooksKernelStartCreateBodyTitleMax = 256export const notebooksKernelStartCreateBodyVersionMin = -2147483648export const notebooksKernelStartCreateBodyVersionMax = 2147483647+export const notebooksKernelStartCreateBodyVariablesItemNameMax = 200+export const NotebooksKernelStartCreateBody = /* @__PURE__ */ zod.object({title: zod.string().max(notebooksKernelStartCreateBodyTitleMax).nullish().describe('Title of the notebook.'),content: zod.unknown().optional().describe('Notebook content as a ProseMirror JSON document structure.'),@@ -344,6 +556,34 @@ export const NotebooksKernelStartCreateBody = /* @__PURE__ */ zod.object({'Version number for optimistic concurrency control. Must match the current version when updating content.'),deleted: zod.boolean().optional().describe('Whether the notebook has been soft-deleted.'),+ variables: zod+ .array(+ zod+ .object({+ name: zod+ .string()+ .max(notebooksKernelStartCreateBodyVariablesItemNameMax)+ .describe(+ 'Identifier the cell reads: `{name}` in a SQL cell, a plain global in a Python cell.'+ ),+ type: zod+ .string()+ .describe(+ "How to coerce the value: 'string', 'number', 'boolean', or 'date'. Unknown types read as 'string'."+ ),+ value: zod+ .unknown()+ .optional()+ .describe(+ "The variable's current value. A 'date' accepts an absolute date or a relative expression ('-7d', 'mStart'), resolved against the project timezone."+ ),+ })+ .describe("One notebook-level variable. Shared by the notebook's own `variables` field and a run body.")+ )+ .optional()+ .describe(+ 'Notebook-level variables, in display order. A SQL cell reads one as a `{name}` placeholder and a Python cell as a global. Names must be unique.'+ ),_create_in_folder: zod.string().optional(),})@@ -355,6 +595,8 @@ export const notebooksKernelStopCreateBodyTitleMax = 256export const notebooksKernelStopCreateBodyVersionMin = -2147483648export const notebooksKernelStopCreateBodyVersionMax = 2147483647+export const notebooksKernelStopCreateBodyVariablesItemNameMax = 200+export const NotebooksKernelStopCreateBody = /* @__PURE__ */ zod.object({title: zod.string().max(notebooksKernelStopCreateBodyTitleMax).nullish().describe('Title of the notebook.'),content: zod.unknown().optional().describe('Notebook content as a ProseMirror JSON document structure.'),@@ -368,6 +610,34 @@ export const NotebooksKernelStopCreateBody = /* @__PURE__ */ zod.object({'Version number for optimistic concurrency control. Must match the current version when updating content.'),deleted: zod.boolean().optional().describe('Whether the notebook has been soft-deleted.'),+ variables: zod+ .array(+ zod+ .object({+ name: zod+ .string()+ .max(notebooksKernelStopCreateBodyVariablesItemNameMax)+ .describe(+ 'Identifier the cell reads: `{name}` in a SQL cell, a plain global in a Python cell.'+ ),+ type: zod+ .string()+ .describe(+ "How to coerce the value: 'string', 'number', 'boolean', or 'date'. Unknown types read as 'string'."+ ),+ value: zod+ .unknown()+ .optional()+ .describe(+ "The variable's current value. A 'date' accepts an absolute date or a relative expression ('-7d', 'mStart'), resolved against the project timezone."+ ),+ })+ .describe("One notebook-level variable. Shared by the notebook's own `variables` field and a run body.")+ )+ .optional()+ .describe(+ 'Notebook-level variables, in display order. A SQL cell reads one as a `{name}` placeholder and a Python cell as a global. Names must be unique.'+ ),_create_in_folder: zod.string().optional(),})@@ -377,6 +647,8 @@ export const NotebooksKernelStopCreateBody = /* @__PURE__ */ zod.object({export const notebooksSqlV2RunCreateBodyNodeTypeDefault = `hogql`export const notebooksSqlV2RunCreateBodyOutputNameDefault = ``export const notebooksSqlV2RunCreateBodyRefsKindDefault = `hogql`+export const notebooksSqlV2RunCreateBodyVariablesItemNameMax = 200+export const notebooksSqlV2RunCreateBodySendRawQueryDefault = falseexport const NotebooksSqlV2RunCreateBody = /* @__PURE__ */ zod.object({@@ -415,6 +687,34 @@ export const NotebooksSqlV2RunCreateBody = /* @__PURE__ */ zod.object({.describe("Available upstream nodes, keyed by dataframe name. A SQL node inlines referenced hogql refs as CTEs — unless it references a local ref, which reroutes the run to the sandbox's DuckDB; a python node materializes the hogql refs its code reads as pandas frames."),+ variables: zod+ .array(+ zod+ .object({+ name: zod+ .string()+ .max(notebooksSqlV2RunCreateBodyVariablesItemNameMax)+ .describe(+ 'Identifier the cell reads: `{name}` in a SQL cell, a plain global in a Python cell.'+ ),+ type: zod+ .string()+ .describe(+ "How to coerce the value: 'string', 'number', 'boolean', or 'date'. Unknown types read as 'string'."+ ),+ value: zod+ .unknown()+ .optional()+ .describe(+ "The variable's current value. A 'date' accepts an absolute date or a relative expression ('-7d', 'mStart'), resolved against the project timezone."+ ),+ })+ .describe("One notebook-level variable. Shared by the notebook's own `variables` field and a run body.")+ )+ .optional()+ .describe(+ 'Notebook-level variables in scope for this run. A SQL node has each `{name}` bound to its value before dispatch; a Python node gets them as globals in the kernel namespace. A SQL node reading a `{name}` that is absent here fails the dispatch.'+ ),connection_id: zod.uuid().nullish()diff --git a/pyproject.toml b/pyproject.tomlindex 8e458df44e6d..17976189d006 100644--- a/pyproject.toml+++ b/pyproject.toml@@ -633,6 +633,7 @@ ignore_imports = ["products.notebooks.backend.presentation.views.notebook -> products.notebooks.backend.sql_v2_runs","products.notebooks.backend.presentation.views.notebook -> products.notebooks.backend.sql_v2_serializers","products.notebooks.backend.presentation.views.notebook -> products.notebooks.backend.sql_v2_state",+ "products.notebooks.backend.presentation.views.notebook -> products.notebooks.backend.sql_v2_variables","products.notebooks.backend.presentation.views.notebook -> products.notebooks.backend.temporal.client","products.notebooks.backend.presentation.views.notebook -> products.notebooks.backend.temporal.sql_v2",# TODO: experiments presentation wave — these were invisible to import-linter untildiff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.tsindex c90e9055e08c..e8b3d8ce864d 100644--- a/services/mcp/src/api/generated.ts+++ b/services/mcp/src/api/generated.ts@@ -50398,6 +50398,21 @@ export namespace Schemas {readonly id: string;} | null;+ /**+ * One notebook-level variable. Shared by the notebook's own `variables` field and a run body.+ */+ export interface NotebookVariable {+ /**+ * Identifier the cell reads: `{name}` in a SQL cell, a plain global in a Python cell.+ * @maxLength 200+ */+ name: string;+ /** How to coerce the value: 'string', 'number', 'boolean', or 'date'. Unknown types read as 'string'. */+ type: string;+ /** The variable's current value. A 'date' accepts an absolute date or a relative expression ('-7d', 'mStart'), resolved against the project timezone. */+ value?: unknown;+ }+export interface Notebook {/** UUID of the notebook. */readonly id: string;@@ -50438,6 +50453,8 @@ export namespace Schemas {* @nullable*/readonly parent_resource: NotebookParentResource;+ /** Notebook-level variables, in display order. A SQL cell reads one as a `{name}` placeholder and a Python cell as a global. Names must be unique. */+ variables?: NotebookVariable[];_create_in_folder?: string;}@@ -50809,6 +50826,8 @@ export namespace Schemas {output_name?: string;/** Available upstream nodes, keyed by dataframe name. A SQL node inlines referenced hogql refs as CTEs — unless it references a local ref, which reroutes the run to the sandbox's DuckDB; a python node materializes the hogql refs its code reads as pandas frames. */refs?: NotebookSQLV2RunRequestRefs;+ /** Notebook-level variables in scope for this run. A SQL node has each `{name}` bound to its value before dispatch; a Python node gets them as globals in the kernel namespace. A SQL node reading a `{name}` that is absent here fails the dispatch. */+ variables?: NotebookVariable[];/*** SQL nodes only: id of a direct-query-capable external data source to run against instead of PostHog's ClickHouse. Omit to query PostHog.* @nullable@@ -62644,6 +62663,8 @@ export namespace Schemas {* @nullable*/readonly parent_resource?: PatchedNotebookParentResource;+ /** Notebook-level variables, in display order. A SQL cell reads one as a `{name}` placeholder and a Python cell as a global. Names must be unique. */+ variables?: NotebookVariable[];_create_in_folder?: string;}diff --git a/services/mcp/src/generated/notebooks/api.ts b/services/mcp/src/generated/notebooks/api.tsindex fabfc9a96e4e..52b795f2aede 100644--- a/services/mcp/src/generated/notebooks/api.ts+++ b/services/mcp/src/generated/notebooks/api.ts@@ -59,6 +59,8 @@ export const notebooksCreateBodyTitleMax = 256export const notebooksCreateBodyVersionMin = -2147483648export const notebooksCreateBodyVersionMax = 2147483647+export const notebooksCreateBodyVariablesItemNameMax = 200+export const NotebooksCreateBody = /* @__PURE__ */ zod.object({title: zod.string().max(notebooksCreateBodyTitleMax).nullish().describe('Title of the notebook.'),content: zod.unknown().optional().describe('Notebook content as a ProseMirror JSON document structure.'),@@ -72,6 +74,34 @@ export const NotebooksCreateBody = /* @__PURE__ */ zod.object({'Version number for optimistic concurrency control. Must match the current version when updating content.'),deleted: zod.boolean().optional().describe('Whether the notebook has been soft-deleted.'),+ variables: zod+ .array(+ zod+ .object({+ name: zod+ .string()+ .max(notebooksCreateBodyVariablesItemNameMax)+ .describe(+ 'Identifier the cell reads: `{name}` in a SQL cell, a plain global in a Python cell.'+ ),+ type: zod+ .string()+ .describe(+ "How to coerce the value: 'string', 'number', 'boolean', or 'date'. Unknown types read as 'string'."+ ),+ value: zod+ .unknown()+ .optional()+ .describe(+ "The variable's current value. A 'date' accepts an absolute date or a relative expression ('-7d', 'mStart'), resolved against the project timezone."+ ),+ })+ .describe("One notebook-level variable. Shared by the notebook's own `variables` field and a run body.")+ )+ .optional()+ .describe(+ 'Notebook-level variables, in display order. A SQL cell reads one as a `{name}` placeholder and a Python cell as a global. Names must be unique.'+ ),})/**@@ -103,6 +133,8 @@ export const notebooksPartialUpdateBodyTitleMax = 256export const notebooksPartialUpdateBodyVersionMin = -2147483648export const notebooksPartialUpdateBodyVersionMax = 2147483647+export const notebooksPartialUpdateBodyVariablesItemNameMax = 200+export const NotebooksPartialUpdateBody = /* @__PURE__ */ zod.object({title: zod.string().max(notebooksPartialUpdateBodyTitleMax).nullish().describe('Title of the notebook.'),content: zod.unknown().optional().describe('Notebook content as a ProseMirror JSON document structure.'),@@ -116,6 +148,34 @@ export const NotebooksPartialUpdateBody = /* @__PURE__ */ zod.object({'Version number for optimistic concurrency control. Must match the current version when updating content.'),deleted: zod.boolean().optional().describe('Whether the notebook has been soft-deleted.'),+ variables: zod+ .array(+ zod+ .object({+ name: zod+ .string()+ .max(notebooksPartialUpdateBodyVariablesItemNameMax)+ .describe(+ 'Identifier the cell reads: `{name}` in a SQL cell, a plain global in a Python cell.'+ ),+ type: zod+ .string()+ .describe(+ "How to coerce the value: 'string', 'number', 'boolean', or 'date'. Unknown types read as 'string'."+ ),+ value: zod+ .unknown()+ .optional()+ .describe(+ "The variable's current value. A 'date' accepts an absolute date or a relative expression ('-7d', 'mStart'), resolved against the project timezone."+ ),+ })+ .describe("One notebook-level variable. Shared by the notebook's own `variables` field and a run body.")+ )+ .optional()+ .describe(+ 'Notebook-level variables, in display order. A SQL cell reads one as a `{name}` placeholder and a Python cell as a global. Names must be unique.'+ ),})/**diff --git a/services/mcp/src/tools/generated/notebooks.ts b/services/mcp/src/tools/generated/notebooks.tsindex cada79d9d642..c0b4cbd49733 100644--- a/services/mcp/src/tools/generated/notebooks.ts+++ b/services/mcp/src/tools/generated/notebooks.ts@@ -80,6 +80,9 @@ const notebooksCreate = (): ToolBase<typeof NotebooksCreateSchema, WithPostHogUrif (params.deleted !== undefined) {body['deleted'] = params.deleted}+ if (params.variables !== undefined) {+ body['variables'] = params.variables+ }const result = await context.api.request<Schemas.Notebook>({method: 'POST',path: `/api/projects/${encodeURIComponent(String(projectId))}/notebooks/`,@@ -208,6 +211,9 @@ const notebooksPartialUpdate = (): ToolBase<typeof NotebooksPartialUpdateSchema,if (params.deleted !== undefined) {body['deleted'] = params.deleted}+ if (params.variables !== undefined) {+ body['variables'] = params.variables+ }const result = await context.api.request<Schemas.Notebook>({method: 'PATCH',path: `/api/projects/${encodeURIComponent(String(projectId))}/notebooks/${encodeURIComponent(String(params.short_id))}/`,diff --git a/services/mcp/tests/unit/__snapshots__/tool-schemas/notebooks-create.json b/services/mcp/tests/unit/__snapshots__/tool-schemas/notebooks-create.jsonindex 6cf009269402..b7b264d7741b 100644--- a/services/mcp/tests/unit/__snapshots__/tool-schemas/notebooks-create.json+++ b/services/mcp/tests/unit/__snapshots__/tool-schemas/notebooks-create.json@@ -31,6 +31,29 @@],"description": "Title of the notebook."},+ "variables": {+ "description": "Notebook-level variables, in display order. A SQL cell reads one as a `{name}` placeholder and a Python cell as a global. Names must be unique.",+ "items": {+ "description": "One notebook-level variable. Shared by the notebook's own `variables` field and a run body.",+ "properties": {+ "name": {+ "description": "Identifier the cell reads: `{name}` in a SQL cell, a plain global in a Python cell.",+ "maxLength": 200,+ "type": "string"+ },+ "type": {+ "description": "How to coerce the value: 'string', 'number', 'boolean', or 'date'. Unknown types read as 'string'.",+ "type": "string"+ },+ "value": {+ "description": "The variable's current value. A 'date' accepts an absolute date or a relative expression ('-7d', 'mStart'), resolved against the project timezone."+ }+ },+ "required": ["name", "type"],+ "type": "object"+ },+ "type": "array"+ },"version": {"description": "Version number for optimistic concurrency control. Must match the current version when updating content.","maximum": 2147483647,diff --git a/services/mcp/tests/unit/__snapshots__/tool-schemas/notebooks-partial-update.json b/services/mcp/tests/unit/__snapshots__/tool-schemas/notebooks-partial-update.jsonindex 58e0b11cd23b..be617fc35e79 100644--- a/services/mcp/tests/unit/__snapshots__/tool-schemas/notebooks-partial-update.json+++ b/services/mcp/tests/unit/__snapshots__/tool-schemas/notebooks-partial-update.json@@ -34,6 +34,29 @@],"description": "Title of the notebook."},+ "variables": {+ "description": "Notebook-level variables, in display order. A SQL cell reads one as a `{name}` placeholder and a Python cell as a global. Names must be unique.",+ "items": {+ "description": "One notebook-level variable. Shared by the notebook's own `variables` field and a run body.",+ "properties": {+ "name": {+ "description": "Identifier the cell reads: `{name}` in a SQL cell, a plain global in a Python cell.",+ "maxLength": 200,+ "type": "string"+ },+ "type": {+ "description": "How to coerce the value: 'string', 'number', 'boolean', or 'date'. Unknown types read as 'string'.",+ "type": "string"+ },+ "value": {+ "description": "The variable's current value. A 'date' accepts an absolute date or a relative expression ('-7d', 'mStart'), resolved against the project timezone."+ }+ },+ "required": ["name", "type"],+ "type": "object"+ },+ "type": "array"+ },"version": {"description": "Version number for optimistic concurrency control. Must match the current version when updating content.","maximum": 2147483647,