Skip to content

: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.

fix(notebooks): show the SQL in a cell written with a query prop (#81848)

Marius Andra5f7f720ac5bc
diff --git a/ee/hogai/context/context.py b/ee/hogai/context/context.py
index d0283679427b..5e7bceb30e11 100644
--- a/ee/hogai/context/context.py
+++ b/ee/hogai/context/context.py
@@ -460,6 +460,11 @@ class AssistantContextManager(AssistantContextMixin):
"prop in their block header. Keep the titles already there, and give any tag you add a short "
"one saying what it shows, so a reader can skim the notebook without opening each block."
),
+ (
+ "- `<SQLV2 />` and `<PythonV2 />` carry their body in a `code` prop holding the SQL or Python "
+ "as a string. Only `<Query />` takes a `query` prop holding a query object, so never give a "
+ "code cell a `query` prop."
+ ),
(
"When the current user asks you to change broad notebook content, use notebook tools against "
"the current notebook instead of explaining how the user could do it. "
diff --git a/ee/hogai/tools/create_notebook/tool.py b/ee/hogai/tools/create_notebook/tool.py
index 9b0af055204a..10150ec716d8 100644
--- a/ee/hogai/tools/create_notebook/tool.py
+++ b/ee/hogai/tools/create_notebook/tool.py
@@ -89,6 +89,7 @@ Our signup funnel shows the following conversion rates:
- Do not include the inline placeholder text, empty `<Prompt question="" />` blocks, or the user's instruction prompt in the final markdown unless the user explicitly asks to keep them
- Use a direct assistant markdown response instead of this tool only for local answers or small insertions that should replace the inline response placeholder
- Component tags such as `<Query … />`, `<SQLV2 … />`, and `<PythonV2 … />` render a `title` prop in their block header. Keep the titles already there, and give any tag you add a short one saying what it shows, so a reader can skim the notebook without opening each block
+- `<SQLV2 />` and `<PythonV2 />` carry their body in a `code` prop holding the SQL or Python as a string. Only `<Query />` takes a `query` prop holding a query object, so never give a code cell a `query` prop
# Transient vs saved notebooks:
- By default, notebooks are created as transient artifacts visible only in this conversation. Do NOT share URLs or references to notebook pages for transient artifacts.
diff --git a/frontend/src/scenes/notebooks/Nodes/notebookNodeContent.test.ts b/frontend/src/scenes/notebooks/Nodes/notebookNodeContent.test.ts
index 8e6da593fd17..661eca878e61 100644
--- a/frontend/src/scenes/notebooks/Nodes/notebookNodeContent.test.ts
+++ b/frontend/src/scenes/notebooks/Nodes/notebookNodeContent.test.ts
@@ -135,6 +135,25 @@ describe('buildNotebookDependencyGraph', () => {
expect(identifiers).not.toContain('head')
})
+ it('links a SQLV2 cell that carries its SQL in a query prop', () => {
+ // Cells authored with the `<Query query={…} />` prop shape have no `code` attr, so
+ // without recovering the SQL they read as empty and reference no upstream frame.
+ const markdown = [
+ serializeMarkdownNotebookComponent('SQLV2', {
+ nodeId: 'a',
+ returnVariable: 'df1',
+ code: 'select id from events',
+ }),
+ serializeMarkdownNotebookComponent('SQLV2', {
+ nodeId: 'b',
+ returnVariable: 'joined',
+ query: { kind: 'HogQLQuery', query: 'select * from df1' },
+ }),
+ ].join('\n\n')
+ const graph = buildNotebookDependencyGraph(buildMarkdownNotebookContent(markdown))
+ expect(graph.downstreamUsageByNode['a'].df1.map((usage) => usage.nodeId)).toEqual(['b'])
+ })
+
it('links SQLV2 cells inside a markdown notebook', () => {
// Markdown notebooks hold cells as tags inside one markdown attribute; without
// expanding them the graph is empty and the "Used in" back-links never render.
diff --git a/frontend/src/scenes/notebooks/Nodes/notebookNodeContent.ts b/frontend/src/scenes/notebooks/Nodes/notebookNodeContent.ts
index 74c2f5d111a9..89fdcfb2bab8 100644
--- a/frontend/src/scenes/notebooks/Nodes/notebookNodeContent.ts
+++ b/frontend/src/scenes/notebooks/Nodes/notebookNodeContent.ts
@@ -1,7 +1,7 @@
import { parseMarkdownNotebook } from 'lib/components/MarkdownNotebook/markdown'
import { JSONContent } from 'lib/components/RichContentEditor/types'
-import { NOTEBOOK_NODE_TYPE_TO_MARKDOWN_TAG } from '../Notebook/markdownNotebookV2'
+import { NOTEBOOK_NODE_TYPE_TO_MARKDOWN_TAG, getSqlV2PropsFromQueryProp } from '../Notebook/markdownNotebookV2'
import { NotebookNodeType } from '../types'
export type PythonNodeSummary = {
@@ -355,6 +355,7 @@ const expandMarkdownNotebookNodesOfTypes = (node: any, nodeTypes: NotebookNodeTy
type: nodeType,
attrs: {
...block.props,
+ ...(nodeType === NotebookNodeType.SQLV2 ? getSqlV2PropsFromQueryProp(block.props) : null),
// Prefer the persisted nodeId prop: the parsed block id is a content
// fingerprint, which drifts from the live cell id as soon as any prop
// changes (running a cell writes runId/result into its props).
diff --git a/frontend/src/scenes/notebooks/Notebook/markdownNotebookRegistry.test.tsx b/frontend/src/scenes/notebooks/Notebook/markdownNotebookRegistry.test.tsx
index 3bbc8181be52..8fbe6291fe78 100644
--- a/frontend/src/scenes/notebooks/Notebook/markdownNotebookRegistry.test.tsx
+++ b/frontend/src/scenes/notebooks/Notebook/markdownNotebookRegistry.test.tsx
@@ -18,6 +18,7 @@ import {
getHiddenInsertCommandKeysForFeatureFlags,
getMarkdownNodeAttributeLabel,
getMarkdownRegistryForFeatureFlags,
+ getNodeAttributes,
getQueryTitle,
getSerializableAttributeInputValue,
getSerializableProps,
@@ -268,6 +269,27 @@ describe('markdownNotebookRegistry', () => {
)
})
+ it('renders a SQL cell whose query arrived as a query prop', () => {
+ // Regression: a `<SQLV2 query={…} />` cell (the shape AI-authored notebooks use) has no
+ // `code` prop, so the editor rendered blank with no way to see or run the query.
+ const attributes = getNodeAttributes(
+ {
+ query: {
+ kind: 'DataVisualizationNode',
+ source: { kind: 'HogQLQuery', query: 'select event from events' },
+ display: 'ActionsBar',
+ },
+ },
+ 'block-1',
+ KNOWN_NODES[NotebookNodeType.SQLV2],
+ NotebookNodeType.SQLV2,
+ false
+ )
+
+ expect(attributes.code).toEqual('select event from events')
+ expect(attributes.vizQuery).toMatchObject({ display: 'ActionsBar' })
+ })
+
describe('getQueryTitle', () => {
it.each([
[
diff --git a/frontend/src/scenes/notebooks/Notebook/markdownNotebookRegistry.tsx b/frontend/src/scenes/notebooks/Notebook/markdownNotebookRegistry.tsx
index 6ba65d2161c3..420a6f71bc23 100644
--- a/frontend/src/scenes/notebooks/Notebook/markdownNotebookRegistry.tsx
+++ b/frontend/src/scenes/notebooks/Notebook/markdownNotebookRegistry.tsx
@@ -79,6 +79,7 @@ import { CreatePostHogWidgetNodeOptions, NotebookNodeAttributes, NotebookNodeTyp
import { KNOWN_NODES } from '../utils'
import { NotebookDiscussionComment, getNotebookDiscussionCommentTitle } from './MarkdownNotebookDiscussionComment'
import { MarkdownNotebookNodeAttributeInput } from './MarkdownNotebookNodeAttributeInput'
+import { getSqlV2PropsFromQueryProp } from './markdownNotebookV2'
import { notebookLogic } from './notebookLogic'
const INTERNAL_MARKDOWN_NODE_ATTRIBUTE_KEYS = new Set([
@@ -935,6 +936,7 @@ export function getNodeAttributes(
const attributes = {
...getDefaultProps(options),
...attributeProps,
+ ...(nodeType === NotebookNodeType.SQLV2 ? getSqlV2PropsFromQueryProp(props) : null),
nodeId: typeof props.nodeId === 'string' ? props.nodeId : fallbackNodeId,
} as NotebookNodeAttributes<any>
diff --git a/frontend/src/scenes/notebooks/Notebook/markdownNotebookV2.test.ts b/frontend/src/scenes/notebooks/Notebook/markdownNotebookV2.test.ts
index 07a18b59fdce..aed5b450dd32 100644
--- a/frontend/src/scenes/notebooks/Notebook/markdownNotebookV2.test.ts
+++ b/frontend/src/scenes/notebooks/Notebook/markdownNotebookV2.test.ts
@@ -1,5 +1,7 @@
import { parseMarkdownNotebook } from 'lib/components/MarkdownNotebook/markdown'
+import { NotebookComponentProps } from 'lib/components/MarkdownNotebook/types'
import { JSONContent } from 'lib/components/RichContentEditor/types'
+import { OutputTab } from 'scenes/data-warehouse/editor/outputPaneLogic'
import {
ArtifactContentType,
@@ -7,6 +9,7 @@ import {
VisualizationArtifactContent,
} from '~/queries/schema/schema-assistant-messages'
import { NodeKind } from '~/queries/schema/schema-general'
+import { ChartDisplayType } from '~/types'
import { NotebookNodeType } from '../types'
import {
@@ -17,6 +20,7 @@ import {
convertNotebookContentToMarkdown,
getMarkdownNotebookMarkdown,
getMarkdownNotebookTitle,
+ getSqlV2PropsFromQueryProp,
insertMarkdownNotebookBlockAfterNode,
isMarkdownNotebookContent,
notebookArtifactContentToMarkdown,
@@ -902,6 +906,59 @@ Body`)
})
})
+ describe('getSqlV2PropsFromQueryProp', () => {
+ const hogqlQuery = { kind: NodeKind.HogQLQuery, query: 'select event from events' }
+ const visualizationQuery = {
+ kind: NodeKind.DataVisualizationNode,
+ source: hogqlQuery,
+ display: ChartDisplayType.ActionsBar,
+ }
+
+ it.each<[string, NotebookComponentProps, NotebookComponentProps]>([
+ [
+ 'a visualization query',
+ { query: visualizationQuery },
+ {
+ code: 'select event from events',
+ vizQuery: visualizationQuery,
+ outputTab: OutputTab.Visualization,
+ },
+ ],
+ [
+ 'a data table query',
+ { query: { kind: NodeKind.DataTableNode, source: hogqlQuery } },
+ { code: 'select event from events' },
+ ],
+ ['a bare HogQL query', { query: hogqlQuery }, { code: 'select event from events' }],
+ ['a plain SQL string', { query: 'select event from events' }, { code: 'select event from events' }],
+ [
+ 'a query serialized to a JSON string',
+ { query: JSON.stringify(visualizationQuery) },
+ {
+ code: 'select event from events',
+ vizQuery: visualizationQuery,
+ outputTab: OutputTab.Visualization,
+ },
+ ],
+ ])('recovers the SQL from a cell written with %s', (_case, props, expected) => {
+ expect(getSqlV2PropsFromQueryProp(props)).toEqual(expected)
+ })
+
+ it.each<[string, NotebookComponentProps]>([
+ ['the cell already has code', { code: 'select 1', query: hogqlQuery }],
+ ['there is no query prop', { title: 'Events' }],
+ [
+ 'the query holds no SQL',
+ { query: { kind: NodeKind.DataTableNode, source: { kind: NodeKind.EventsQuery, select: ['event'] } } },
+ ],
+ // Never fall through to the plain-SQL reading here: the editor would show JSON and run it.
+ ['a JSON string does not parse', { query: '{"kind":"HogQLQuery",' }],
+ ['a JSON string carries no SQL', { query: JSON.stringify({ kind: NodeKind.EventsQuery }) }],
+ ])('leaves the cell untouched when %s', (_case, props) => {
+ expect(getSqlV2PropsFromQueryProp(props)).toBeNull()
+ })
+ })
+
describe('convertDroppedRichContentNodeToMarkdownNode', () => {
it('maps a dragged recording payload to its markdown component', () => {
const node = convertDroppedRichContentNodeToMarkdownNode(NotebookNodeType.Recording, {
diff --git a/frontend/src/scenes/notebooks/Notebook/markdownNotebookV2.ts b/frontend/src/scenes/notebooks/Notebook/markdownNotebookV2.ts
index 163dcd6076d6..1addb9a6f315 100644
--- a/frontend/src/scenes/notebooks/Notebook/markdownNotebookV2.ts
+++ b/frontend/src/scenes/notebooks/Notebook/markdownNotebookV2.ts
@@ -18,6 +18,7 @@ import {
import { getInlineText, isNotebookPropValue, toSerializablePropValue } from 'lib/components/MarkdownNotebook/utils'
import { JSONContent } from 'lib/components/RichContentEditor/types'
import { removeProjectIdIfPresent } from 'lib/utils/kea-router'
+import { OutputTab } from 'scenes/data-warehouse/editor/outputPaneLogic'
import { urlToResource } from 'scenes/urls'
import { DocumentBlock, VisualizationBlock } from '~/queries/schema/schema-assistant-artifacts'
@@ -265,6 +266,57 @@ export function buildDroppedLinkParagraphNode(url: string): NotebookBlockNode {
}
}
+/** A SQL cell keeps its query in `code`, but authors (the AI especially) reach for the
+ * `<Query query={…} />` prop shape instead, which leaves the editor blank and unrunnable. Read the
+ * HogQL back out of such a query so the cell shows what it was written with. Returns the props to
+ * merge over the cell's own, or null when there is nothing to recover. */
+export function getSqlV2PropsFromQueryProp(props: NotebookComponentProps): NotebookComponentProps | null {
+ if (typeof props.code === 'string' && props.code.trim()) {
+ return null
+ }
+
+ const query = toQueryPropObject(props.query)
+ if (!query) {
+ // Everything else a string prop can hold is the SQL itself.
+ return typeof props.query === 'string' && props.query.trim() && !looksLikeJsonObject(props.query)
+ ? { code: props.query }
+ : null
+ }
+
+ // Both the wrapped shapes (data table, visualization) and a bare HogQL query show up.
+ const source = (isHogQLQuery(query) ? query : query.source) as Record<string, NotebookPropValue> | undefined
+ const code = source?.kind === NodeKind.HogQLQuery && typeof source.query === 'string' ? source.query : null
+ if (!code?.trim()) {
+ return null
+ }
+
+ // A visualization query also carries the chart the author picked. The node rewrites the source
+ // from its own code on render, so keeping the whole query here costs nothing.
+ return isDataVisualizationNode(query) ? { code, vizQuery: query, outputTab: OutputTab.Visualization } : { code }
+}
+
+function looksLikeJsonObject(value: string): boolean {
+ return value.trim().startsWith('{')
+}
+
+/** A `query="{…}"` attribute parses back as a JSON string rather than an object (v1 nodes
+ * round-trip their attrs as JSON), so decode that form before reading the query. */
+function toQueryPropObject(value: NotebookPropValue | undefined): Record<string, NotebookPropValue> | null {
+ if (typeof value === 'string') {
+ if (!looksLikeJsonObject(value)) {
+ return null
+ }
+ try {
+ return toQueryPropObject(JSON.parse(value))
+ } catch {
+ return null
+ }
+ }
+ return value && typeof value === 'object' && !Array.isArray(value)
+ ? (value as Record<string, NotebookPropValue>)
+ : null
+}
+
export function serializeMarkdownNotebookComponent(tagName: string, props: NotebookComponentProps): string {
return serializeNode({
id: '',