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.

feat(notebooks): list kernel dataframes in the SQLV2 schema browser (#71709)

Sinan Kucukkoseler9bf9f97f3a05
diff --git a/frontend/src/layout/panel-layout/DatabaseTree/DatabaseTree.tsx b/frontend/src/layout/panel-layout/DatabaseTree/DatabaseTree.tsx
index 5f73bf2c898a..13ac3ef67e1e 100644
--- a/frontend/src/layout/panel-layout/DatabaseTree/DatabaseTree.tsx
+++ b/frontend/src/layout/panel-layout/DatabaseTree/DatabaseTree.tsx
@@ -5,6 +5,7 @@ import { IconSidebarClose } from '@posthog/icons'
import { Resizer } from 'lib/components/Resizer/Resizer'
import { ScrollableShadows } from 'lib/components/ScrollableShadows/ScrollableShadows'
+import { TreeDataItem } from 'lib/lemon-ui/LemonTree/LemonTree'
import { ButtonPrimitive } from 'lib/ui/Button/ButtonPrimitives'
import { cn } from 'lib/utils/css-classes'
import { ConnectionSelector } from 'scenes/data-warehouse/editor/ConnectionSelector'
@@ -19,9 +20,12 @@ import { SyncMoreNotice } from './SyncMoreNotice'
export const DatabaseTree = memo(function DatabaseTree({
databaseTreeRef,
tabId,
+ extraTreeSections,
}: {
databaseTreeRef: React.RefObject<HTMLDivElement>
tabId: string
+ /** Extra top-level tree sections owned by the embedding surface — see QueryDatabase. */
+ extraTreeSections?: TreeDataItem[]
}): JSX.Element | null {
const scrollContainerRef = useRef<HTMLDivElement | null>(null)
const { databaseTreeWidth, databaseTreeResizerProps, isDatabaseTreeCollapsed, databaseTreeWillCollapse } =
@@ -73,7 +77,10 @@ export const DatabaseTree = memo(function DatabaseTree({
styledScrollbars
>
<div className="grow w-full">
- <QueryDatabase virtualizationScrollContainerRef={scrollContainerRef} />
+ <QueryDatabase
+ virtualizationScrollContainerRef={scrollContainerRef}
+ extraTreeSections={extraTreeSections}
+ />
</div>
<SyncMoreNotice />
<ViewLinkModal />
diff --git a/frontend/src/scenes/data-warehouse/editor/SQLEditor.tsx b/frontend/src/scenes/data-warehouse/editor/SQLEditor.tsx
index f1d7f274d8d6..a3d5326d9100 100644
--- a/frontend/src/scenes/data-warehouse/editor/SQLEditor.tsx
+++ b/frontend/src/scenes/data-warehouse/editor/SQLEditor.tsx
@@ -11,6 +11,7 @@ import { FEATURE_FLAGS } from 'lib/constants'
import { useOnMountEffect } from 'lib/hooks/useOnMountEffect'
import { LemonButton } from 'lib/lemon-ui/LemonButton'
import { LemonMenuOverlay } from 'lib/lemon-ui/LemonMenu/LemonMenu'
+import { TreeDataItem } from 'lib/lemon-ui/LemonTree/LemonTree'
import { useAttachedLogic } from 'lib/logic/scenes/useAttachedLogic'
import { getAccessControlDisabledReason } from 'lib/utils/accessControlUtils'
@@ -61,6 +62,8 @@ interface SQLEditorProps {
mode?: SQLEditorMode
showDatabaseTree?: boolean
defaultShowDatabaseTree?: boolean
+ /** Extra top-level sections for the database tree, owned by the embedder — see QueryDatabase. */
+ extraTreeSections?: TreeDataItem[]
panel?: SQLEditorPanel
showOutputToolbar?: boolean
onRunQuery?: () => void
@@ -81,6 +84,7 @@ export function SQLEditor({
mode = SQLEditorMode.FullScene,
showDatabaseTree,
defaultShowDatabaseTree = true,
+ extraTreeSections,
panel = SQLEditorPanel.Full,
showOutputToolbar = true,
onRunQuery,
@@ -238,6 +242,7 @@ export function SQLEditor({
<DatabaseTree
databaseTreeRef={databaseTreeRef}
tabId={tabId || ''}
+ extraTreeSections={extraTreeSections}
/>
)}
<div
diff --git a/frontend/src/scenes/data-warehouse/editor/sidebar/QueryDatabase.tsx b/frontend/src/scenes/data-warehouse/editor/sidebar/QueryDatabase.tsx
index 3925c1a34bcd..2811f3bcc47d 100644
--- a/frontend/src/scenes/data-warehouse/editor/sidebar/QueryDatabase.tsx
+++ b/frontend/src/scenes/data-warehouse/editor/sidebar/QueryDatabase.tsx
@@ -2,7 +2,7 @@ import { DragEndEvent, DragOverEvent, DragStartEvent } from '@dnd-kit/core'
import { useActions, useMountedLogic, useValues } from 'kea'
import { router } from 'kea-router'
import posthog from 'posthog-js'
-import { useEffect, useRef } from 'react'
+import { useEffect, useMemo, useRef } from 'react'
import {
IconBrackets,
@@ -73,10 +73,35 @@ export function getSidebarAddJoinSourceTableName(
}
}
+/**
+ * Keep a section whose folder, or any of its children, matches the search term — the same
+ * name-and-field matching the database tree does for its own tables.
+ */
+const filterTreeSections = (sections: TreeDataItem[], searchTerm: string): TreeDataItem[] => {
+ const needle = searchTerm.trim().toLowerCase()
+ if (!needle) {
+ return sections
+ }
+ const matches = (item: TreeDataItem): boolean =>
+ item.name.toLowerCase().includes(needle) || (item.children ?? []).some(matches)
+ return sections.flatMap((section) => {
+ const children = (section.children ?? []).filter(matches)
+ return children.length ? [{ ...section, children }] : []
+ })
+}
+
export const QueryDatabase = ({
virtualizationScrollContainerRef,
+ extraTreeSections,
}: {
virtualizationScrollContainerRef?: React.RefObject<HTMLDivElement | null>
+ /**
+ * Extra top-level sections to render above the database tree, owned by the embedding surface
+ * (notebooks lists the dataframes its kernel holds). Rendered as-is: whatever builds them owns
+ * their icons, children, and search filtering. Default empty, so surfaces that pass nothing are
+ * unaffected.
+ */
+ extraTreeSections?: TreeDataItem[]
}): JSX.Element => {
const {
searchTerm,
@@ -308,10 +333,21 @@ export const QueryDatabase = ({
setTreeRef(treeRef)
}, [treeRef, setTreeRef])
+ const treeData = useMemo(() => {
+ if (!extraTreeSections?.length) {
+ return displayedTreeData
+ }
+ // Filtered here rather than by the caller: the tree swaps in its own filtered data while
+ // searching, so an unfiltered section would sit above the results still listing
+ // everything — and keeping the search term on this side means an embedder doesn't have to
+ // mount this logic just to read it.
+ return [...filterTreeSections(extraTreeSections, searchTerm), ...displayedTreeData]
+ }, [extraTreeSections, displayedTreeData, searchTerm])
+
return (
<LemonTree
ref={treeRef}
- data={displayedTreeData}
+ data={treeData}
enableDragAndDrop={!searchTerm}
isItemDraggable={(item) => !searchTerm && item.record?.type === 'view' && item.record?.isSavedQuery}
isItemDroppable={(item) =>
diff --git a/frontend/src/scenes/notebooks/Nodes/components/NotebookSQLEditor.tsx b/frontend/src/scenes/notebooks/Nodes/components/NotebookSQLEditor.tsx
index 9021f8eaab55..6ab3d76d6b3b 100644
--- a/frontend/src/scenes/notebooks/Nodes/components/NotebookSQLEditor.tsx
+++ b/frontend/src/scenes/notebooks/Nodes/components/NotebookSQLEditor.tsx
@@ -1,8 +1,9 @@
import { deepEqual as equal } from 'fast-equals'
-import { useActions, useValues } from 'kea'
+import { useActions, useMountedLogic, useValues } from 'kea'
import { type CSSProperties, useEffect, useMemo, useRef, useState } from 'react'
import { wasNotebookNodeJustInserted } from 'lib/components/MarkdownNotebook/freshlyInserted'
+import { TreeDataItem } from 'lib/lemon-ui/LemonTree/LemonTree'
import { OutputTab, outputPaneLogic } from 'scenes/data-warehouse/editor/outputPaneLogic'
import { SQLEditor, SQLEditorPanel } from 'scenes/data-warehouse/editor/SQLEditor'
import { sqlEditorLogic } from 'scenes/data-warehouse/editor/sqlEditorLogic'
@@ -12,7 +13,10 @@ import { DataVisualizationNode, HogQLQuery, NodeKind, ProductKey, QuerySchema }
import { convertDataTableNodeToDataVisualizationNode, isDataVisualizationNode, isHogQLQuery } from '~/queries/utils'
import { ChartDisplayType } from '~/types'
+import { notebookKernelInfoLogic } from '../../Notebook/notebookKernelInfoLogic'
import { NotebookNodeAttributeProperties, NotebookNodeAttributes, NotebookNodeProps } from '../../types'
+import { notebookNodeLogic } from '../notebookNodeLogic'
+import { buildDataframeTreeSection } from './notebookDataframeTree'
export const EMBEDDED_SQL_EDITOR_DEFAULT_HEIGHT = 333
export const EMBEDDED_SQL_EDITOR_EDIT_DEFAULT_HEIGHT = 150
@@ -22,6 +26,24 @@ export const EMBEDDED_SQL_EDITOR_EDIT_MIN_HEIGHT = 150
export const getNotebookSqlEditorTabId = (nodeId: string | null | undefined, suffix: string | null = null): string =>
`notebook-sql-${suffix ? `${suffix}-` : ''}${nodeId ?? 'new'}`
+/**
+ * The "Dataframes" section this node contributes to the shared database tree (Journey 7).
+ *
+ * Reads only logics notebookLogic already mounts — the document for the names its cells bind,
+ * and notebookKernelInfoLogic for the kernel's catalog — so it adds no requests. It deliberately
+ * does not read queryDatabaseLogic for the search term: reading a logic mounts it, and that one's
+ * afterMount fans out to the warehouse loaders (drafts, joins, tab state), which every notebook
+ * with a SQL cell would then pay on open even with the browser closed. QueryDatabase already
+ * holds the search term and filters these sections itself.
+ */
+function useNotebookDataframeTreeSections(): TreeDataItem[] {
+ const nodeLogic = useMountedLogic(notebookNodeLogic)
+ const { notebookLogic } = useValues(nodeLogic)
+ const { frameNodeSummaries } = useValues(notebookLogic)
+ const { localFrames } = useValues(notebookKernelInfoLogic({ shortId: notebookLogic.props.shortId }))
+ return useMemo(() => buildDataframeTreeSection(frameNodeSummaries, localFrames), [frameNodeSummaries, localFrames])
+}
+
const withNotebookHogQLTags = (query: DataVisualizationNode): DataVisualizationNode => ({
...query,
source: {
@@ -416,6 +438,7 @@ export function NotebookCodeSQLEditorSettings<T extends { code: string }>({
[attributes.nodeId, tabIdSuffix]
)
useNotebookCodeSQLEditorSync({ attributes, updateAttributes, tabId })
+ const extraTreeSections = useNotebookDataframeTreeSections()
const editorLogic = sqlEditorLogic({ tabId, mode: SQLEditorMode.Embedded })
const { queryInput } = useValues(editorLogic)
// Prefer what the user sees in the editor; fall back to the attribute before the first sync.
@@ -441,6 +464,7 @@ export function NotebookCodeSQLEditorSettings<T extends { code: string }>({
mode={SQLEditorMode.Embedded}
panel={SQLEditorPanel.Query}
defaultShowDatabaseTree={false}
+ extraTreeSections={extraTreeSections}
autoFocusQueryPane={autoFocusQueryPane}
// Read the editor's current text imperatively at run time. The Cmd+Enter keybinding
// fires a stale closure (and Monaco's keybinding value can come through empty), so a
diff --git a/frontend/src/scenes/notebooks/Nodes/components/notebookDataframeTree.test.tsx b/frontend/src/scenes/notebooks/Nodes/components/notebookDataframeTree.test.tsx
new file mode 100644
index 000000000000..de90a3455bce
--- /dev/null
+++ b/frontend/src/scenes/notebooks/Nodes/components/notebookDataframeTree.test.tsx
@@ -0,0 +1,118 @@
+import { NotebookKernelFrame } from '../../Notebook/notebookKernelInfoLogic'
+import { NotebookFrameNodeSummary } from '../notebookNodeContent'
+import { buildDataframeTreeSection } from './notebookDataframeTree'
+
+describe('buildDataframeTreeSection', () => {
+ const sqlNode = (name: string, hasRun = true, code = 'SELECT 1'): NotebookFrameNodeSummary => ({
+ nodeId: `n-${name}`,
+ name,
+ nodeType: 'sql',
+ columns: hasRun ? [['id', 'String']] : [],
+ rowCount: hasRun ? 50 : null,
+ hasRun,
+ code,
+ })
+ const pythonNode = (name: string, hasRun = true, code = 'df = 1'): NotebookFrameNodeSummary => ({
+ nodeId: `n-${name}`,
+ name,
+ nodeType: 'python',
+ columns: hasRun ? [['count', 'int64']] : [],
+ rowCount: hasRun ? 3 : null,
+ hasRun,
+ code,
+ })
+ const kernelFrame = (name: string, kind: NotebookKernelFrame['kind'] = 'frame'): NotebookKernelFrame => ({
+ name,
+ kind,
+ columns: [['a', 'BIGINT']],
+ row_count: 7,
+ })
+
+ const children = (section: ReturnType<typeof buildDataframeTreeSection>): [string, string | undefined][] =>
+ (section[0]?.children ?? []).map((child) => [child.name, child.disabledReason])
+
+ it('lists a SQL frame the kernel has never seen', () => {
+ // The bug this shipped with: a SQL cell's output lives in ClickHouse and only enters the
+ // kernel if something materializes it, but it is referenceable from SQL the whole time.
+ // Sourcing the list from the kernel alone hid it entirely.
+ expect(children(buildDataframeTreeSection([sqlNode('events_df')], []))).toEqual([['events_df', undefined]])
+ })
+
+ it('greys out a python frame the kernel no longer has, but never a SQL one', () => {
+ // A python frame only ever exists in the kernel, so absence means it is really gone. The
+ // same absence for a SQL frame means nothing, so the two must not be treated alike.
+ expect(children(buildDataframeTreeSection([sqlNode('events_df'), pythonNode('top50_people')], []))).toEqual([
+ ['events_df', undefined],
+ ['top50_people', 'Not in the kernel right now. Run the cell that creates it to make it available'],
+ ])
+ })
+
+ it.each([
+ ['sql', sqlNode('never_ran', false)],
+ ['python', pythonNode('never_ran', false)],
+ ])('greys out an un-run %s cell', (_nodeType, node) => {
+ // No successful run means nothing to reference: the backend resolves refs to the latest
+ // DONE run and treats a node without one as not-run.
+ expect(children(buildDataframeTreeSection([node], []))).toEqual([
+ ['never_ran', 'Run the cell that creates it to make it available'],
+ ])
+ })
+
+ it('shows a materialized frame once, with the kernel shape', () => {
+ // A SQL frame a python cell pulled in is both a cell output and a kernel entry. It must
+ // not double up, and the kernel's shape wins because it is the current one.
+ const section = buildDataframeTreeSection([sqlNode('people')], [kernelFrame('people')])
+ expect(children(section)).toEqual([['people', undefined]])
+ expect(section[0].children?.[0].record?.row_count).toEqual(7)
+ })
+
+ it('lists a DuckDB table no cell binds', () => {
+ // A CREATE TABLE in a DuckDB cell writes no result file and appears nowhere in the
+ // document — the kernel's catalog is the only place it exists.
+ expect(children(buildDataframeTreeSection([], [kernelFrame('agg', 'table')]))).toEqual([['agg', undefined]])
+ })
+
+ it('collapses duplicate names, keeping the last', () => {
+ // Python names are deliberately not disambiguated and default to `df`, so two un-run
+ // Python cells is enough to emit `df` twice — duplicate ids in a virtualized tree.
+ const section = buildDataframeTreeSection([pythonNode('df'), pythonNode('df')], [])
+ expect(children(section)).toHaveLength(1)
+ const ids = (section[0].children ?? []).map((c) => c.id)
+ expect(new Set(ids).size).toEqual(ids.length)
+ })
+
+ it('has no section when there is nothing to list', () => {
+ expect(buildDataframeTreeSection([], [])).toEqual([])
+ })
+
+ it('ignores an empty cell nobody has written yet', () => {
+ // A blank cell takes the default returnVariable, so it collides with the first one and is
+ // renamed sql_df_2 — listing it means every new cell adds a greyed-out row for a frame
+ // the user never conceived of.
+ const section = buildDataframeTreeSection([sqlNode('sql_df'), sqlNode('sql_df_2', false, '')], [])
+ expect(children(section)).toEqual([['sql_df', undefined]])
+ })
+
+ it('says a cell that ran but bound nothing produced no dataframe', () => {
+ // It has a result with no columns: its code binds no frame. "Run this cell" would be a
+ // lie — it ran, and running it again changes nothing.
+ const ranEmpty: NotebookFrameNodeSummary = {
+ nodeId: 'n-new-df',
+ name: 'new-df',
+ nodeType: 'python',
+ columns: [],
+ rowCount: 0,
+ hasRun: true,
+ code: 'top50 = people.value_counts()',
+ }
+ expect(children(buildDataframeTreeSection([ranEmpty], []))).toEqual([
+ ['new-df', "The last run of the cell that creates it didn't produce a dataframe"],
+ ])
+ })
+
+ it('still lists a written cell that has not run', () => {
+ // Written but un-run is a real intent to bind that name, so it stays with a nudge to run.
+ const section = buildDataframeTreeSection([sqlNode('draft', false, 'SELECT 1')], [])
+ expect(children(section)).toEqual([['draft', 'Run the cell that creates it to make it available']])
+ })
+})
diff --git a/frontend/src/scenes/notebooks/Nodes/components/notebookDataframeTree.tsx b/frontend/src/scenes/notebooks/Nodes/components/notebookDataframeTree.tsx
new file mode 100644
index 000000000000..91087cf21fe2
--- /dev/null
+++ b/frontend/src/scenes/notebooks/Nodes/components/notebookDataframeTree.tsx
@@ -0,0 +1,160 @@
+import { IconDatabase, IconDocument } from '@posthog/icons'
+
+import { TreeDataItem } from 'lib/lemon-ui/LemonTree/LemonTree'
+
+import { NotebookKernelFrame } from '../../Notebook/notebookKernelInfoLogic'
+import { NotebookFrameNodeSummary } from '../notebookNodeContent'
+
+export const DATAFRAMES_FOLDER_ID = 'notebook-dataframes'
+
+// These render as tooltips on a row in *another* cell's sidebar, so they can't say "this cell"
+// — that already means "the cell you're in" on the run controls, and would point at the wrong
+// one for every row but the current cell's own output.
+const NEVER_RAN_REASON = 'Run the cell that creates it to make it available'
+const NO_FRAME_REASON = "The last run of the cell that creates it didn't produce a dataframe"
+const NOT_IN_KERNEL_REASON = 'Not in the kernel right now. Run the cell that creates it to make it available'
+
+type DataframeEntry = {
+ name: string
+ columns: [string, string][]
+ rowCount: number | null
+ /** A DuckDB table or view reads differently from a dataframe, so they get different icons. */
+ isTable: boolean
+ /** Set when the name can't be referenced as things stand; renders greyed out with this reason. */
+ disabledReason?: string
+}
+
+/**
+ * One entry per name. Python cells deliberately don't disambiguate their names — they are the
+ * raw kernel variables, where a repeated name means last-run-wins — and they default to `df`,
+ * so two un-run Python cells is enough to produce the same name twice. Collapsing to the last
+ * matches what the kernel actually holds, and keeps the tree's item ids unique.
+ */
+const dedupeByName = (entries: DataframeEntry[]): DataframeEntry[] => {
+ const byName = new Map<string, DataframeEntry>()
+ entries.forEach((entry) => byName.set(entry.name, entry))
+ return [...byName.values()]
+}
+
+/**
+ * The tree renders `row_count` as a plain count, so an estimate can't go through it honestly —
+ * DuckDB's `estimated_size` doesn't track deletes and can read 100,000 for a table holding 10.
+ * A DDL table therefore lists without a count rather than with a confident wrong one.
+ */
+const kernelEntry = (frame: NotebookKernelFrame): DataframeEntry => ({
+ name: frame.name,
+ columns: frame.columns,
+ rowCount: frame.row_count_is_estimate ? null : frame.row_count,
+ isTable: frame.kind !== 'frame',
+})
+
+/**
+ * Drop cells that bind nothing worth showing: an empty one nobody has written yet holds no query
+ * and no result, and its name is only the default. Listing those means every blank cell you add
+ * spawns a greyed-out row (`sql_df_2`, `sql_df_3`, …) for a frame that was never conceived of.
+ * A cell with a query but no run is different — it is a real intent to bind that name.
+ */
+const listableNodes = (nodes: NotebookFrameNodeSummary[]): NotebookFrameNodeSummary[] =>
+ nodes.filter((node) => node.hasRun || node.code.trim())
+
+/**
+ * Merge what the notebook knows with what the kernel knows. Neither is sufficient alone:
+ *
+ * - The kernel's catalog is the only thing that can see a table a DuckDB cell created, and the
+ * only honest answer to whether a Python cell's frame still exists.
+ * - It cannot see a SQL cell's output, though. That output lives in ClickHouse and only enters
+ * the kernel if some cell materializes it — yet it stays referenceable from SQL the whole
+ * time, re-inlined as a CTE. Listing the kernel's view alone makes a SQL frame appear or
+ * vanish depending on whether an unrelated Python cell happens to use it.
+ */
+function mergeEntries(nodes: NotebookFrameNodeSummary[], kernelFrames: NotebookKernelFrame[]): DataframeEntry[] {
+ const kernelByName = new Map(kernelFrames.map((frame) => [frame.name, frame]))
+ const listable = listableNodes(nodes)
+ const boundByCell = new Set(listable.map((node) => node.name))
+
+ const fromNodes = listable.map((node): DataframeEntry => {
+ const kernelFrame = kernelByName.get(node.name)
+ if (kernelFrame) {
+ // The kernel holds it, so prefer its shape: that reflects the frame as it is now,
+ // while the cell's stored result is only as fresh as that cell's last run.
+ return kernelEntry(kernelFrame)
+ }
+ const base = { name: node.name, columns: node.columns, rowCount: node.rowCount, isTable: false }
+ if (!node.hasRun) {
+ return { ...base, disabledReason: NEVER_RAN_REASON }
+ }
+ if (!node.columns.length) {
+ // It ran and bound nothing — its code produces no frame, or it was DDL. Telling the
+ // user to run it would be a lie; running it again changes nothing.
+ return { ...base, disabledReason: NO_FRAME_REASON }
+ }
+ // A SQL cell that ran is referenceable with no kernel at all; a Python cell's frame only
+ // ever exists in the kernel, so its absence from the catalog means it is really gone.
+ return node.nodeType === 'sql' ? base : { ...base, disabledReason: NOT_IN_KERNEL_REASON }
+ })
+
+ // Anything the kernel has that no cell binds: a table a DuckDB cell created with DDL, which
+ // exists only in the kernel and is invisible to the notebook document.
+ const kernelOnly = kernelFrames.filter((frame) => !boundByCell.has(frame.name)).map(kernelEntry)
+
+ return dedupeByName([...fromNodes, ...kernelOnly])
+}
+
+// Frame and column ids share one namespace, so the separator must be something an identifier
+// can't contain — `-` would let a frame named `a-col-b` collide with column `b` of frame `a`.
+const frameId = (index: number): string => `nb-frame:${index}`
+
+const entryNode = (entry: DataframeEntry, index: number): TreeDataItem => ({
+ id: frameId(index),
+ name: entry.name,
+ type: 'node',
+ icon: entry.isTable ? <IconDatabase /> : <IconDocument />,
+ disabledReason: entry.disabledReason,
+ record: {
+ type: 'notebook-frame',
+ // QueryDatabase renders this natively next to the name, the same as a warehouse table's.
+ row_count: entry.rowCount ?? undefined,
+ },
+ children: entry.columns.map(([columnName, columnType], columnIndex) => ({
+ id: `${frameId(index)}:col:${columnIndex}`,
+ name: columnName,
+ type: 'node' as const,
+ // The shape QueryDatabase's renderItem expects for a column: monospaced name plus a
+ // muted type suffix, so a dataframe's columns read like a table's. Only the rendering
+ // is shared — its click handler needs `table`/`columnName`, which a kernel frame has no
+ // equivalent of, so selection is disabled rather than left as a click that does nothing.
+ record: { type: 'column', field: { name: columnName, type: columnType } },
+ disableSelect: true,
+ })),
+})
+
+/**
+ * The "Dataframes" section for the SQLV2 node's schema browser: the names this notebook's cells
+ * bind, plus anything extra its kernel holds. A name that can't be referenced as things stand
+ * renders greyed out rather than disappearing — a cell you can see in the notebook going missing
+ * from the browser is more confusing than one shown as unavailable.
+ *
+ * Unfiltered: QueryDatabase applies its own search term to these sections, so this stays out of
+ * queryDatabaseLogic (reading it would mount its warehouse loaders in every notebook).
+ */
+export function buildDataframeTreeSection(
+ nodes: NotebookFrameNodeSummary[],
+ kernelFrames: NotebookKernelFrame[]
+): TreeDataItem[] {
+ const entries = mergeEntries(nodes, kernelFrames)
+ if (!entries.length) {
+ return []
+ }
+ return [
+ {
+ id: DATAFRAMES_FOLDER_ID,
+ name: 'Dataframes',
+ // Bold like the built-in section headers, which key off record types we don't share.
+ displayName: <span className="font-semibold">Dataframes</span>,
+ type: 'node',
+ icon: <IconDatabase />,
+ record: { type: 'notebook-dataframes' },
+ children: entries.map(entryNode),
+ },
+ ]
+}
diff --git a/frontend/src/scenes/notebooks/Nodes/notebookNodeContent.ts b/frontend/src/scenes/notebooks/Nodes/notebookNodeContent.ts
index a8f445dae65a..9788afac93c3 100644
--- a/frontend/src/scenes/notebooks/Nodes/notebookNodeContent.ts
+++ b/frontend/src/scenes/notebooks/Nodes/notebookNodeContent.ts
@@ -306,31 +306,47 @@ export const getUniqueSqlV2ReturnVariable = (
// tiptap-shaped nodes so the collectors and the dependency graph see the same cells in both
// notebook formats. Scoped to the revamped-notebook cell types (SQLV2 + kernel Python):
// expanding the other node types would change their (markdown-blind) summaries and naming.
-const expandMarkdownNotebookNodesOfType = (node: any, nodeType: NotebookNodeType): JSONContent[] => {
+const expandMarkdownNotebookNodesOfTypes = (node: any, nodeTypes: NotebookNodeType[]): JSONContent[] => {
if (typeof node?.attrs?.markdown !== 'string') {
return []
}
- return parseMarkdownNotebook(node.attrs.markdown).nodes.flatMap((block) =>
- block.type === 'component' && block.tagName === NOTEBOOK_NODE_TYPE_TO_MARKDOWN_TAG[nodeType]
- ? [
- {
- type: nodeType,
- attrs: {
- ...block.props,
- // 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).
- nodeId:
- typeof block.props.nodeId === 'string' && block.props.nodeId
- ? block.props.nodeId
- : block.id,
- },
- },
- ]
- : []
- )
+ // Keyed by tag so one pass over the parsed blocks can expand several cell types at once,
+ // keeping them in document order — collecting each type separately would group all the SQL
+ // cells before all the Python ones.
+ const nodeTypeByTag = new Map<string, NotebookNodeType>()
+ for (const nodeType of nodeTypes) {
+ const tag = NOTEBOOK_NODE_TYPE_TO_MARKDOWN_TAG[nodeType]
+ if (tag) {
+ nodeTypeByTag.set(tag, nodeType)
+ }
+ }
+ return parseMarkdownNotebook(node.attrs.markdown).nodes.flatMap((block): JSONContent[] => {
+ if (block.type !== 'component') {
+ return []
+ }
+ const nodeType = nodeTypeByTag.get(block.tagName)
+ if (!nodeType) {
+ return []
+ }
+ return [
+ {
+ type: nodeType,
+ attrs: {
+ ...block.props,
+ // 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).
+ nodeId:
+ typeof block.props.nodeId === 'string' && block.props.nodeId ? block.props.nodeId : block.id,
+ },
+ },
+ ]
+ })
}
+const expandMarkdownNotebookNodesOfType = (node: any, nodeType: NotebookNodeType): JSONContent[] =>
+ expandMarkdownNotebookNodesOfTypes(node, [nodeType])
+
const expandMarkdownNotebookSqlV2Nodes = (node: any): JSONContent[] =>
expandMarkdownNotebookNodesOfType(node, NotebookNodeType.SQLV2)
@@ -405,6 +421,95 @@ export const collectPythonNodes = (content?: JSONContent | null): PythonNodeSumm
return nodes
}
+export type NotebookFrameNodeSummary = {
+ nodeId: string
+ name: string
+ /**
+ * Which cell produced it, which decides where the data lives. A SQL cell that pushed to
+ * ClickHouse can be referenced again from SQL with no kernel at all (it is re-inlined as a
+ * CTE); a Python cell's output only exists inside the kernel.
+ */
+ nodeType: 'sql' | 'python'
+ /** [column name, type] pairs from the last run, empty when the cell has never produced a frame. */
+ columns: [string, string][]
+ rowCount: number | null
+ /**
+ * The cell has a stored result. A cell that has never run can't be referenced at all — the
+ * backend resolves refs to the latest DONE run — but a cell that ran and produced no frame
+ * (its code binds nothing, or it was DDL) is a different story, and `columns` tells them apart.
+ */
+ hasRun: boolean
+ /** Empty for a cell nobody has written yet, which binds nothing worth listing. */
+ code: string
+}
+
+const frameNodeColumns = (result: any): [string, string][] => {
+ if (!result || !Array.isArray(result.types)) {
+ return []
+ }
+ return result.types
+ .filter((pair: unknown): pair is [string, string] => Array.isArray(pair) && pair.length >= 2)
+ .map(([name, type]: [string, string]) => [String(name), String(type)] as [string, string])
+}
+
+/**
+ * Every cell in a revamped notebook that binds a name other cells can reference, in document
+ * order, with the shape of its last run.
+ *
+ * This is the notebook's own record, not the kernel's: a SQL cell's output never enters the
+ * kernel unless something materializes it, so the kernel's catalog alone cannot see it.
+ * Names follow each collector's existing rules — SQL names disambiguated as the dependency
+ * graph does, Python names left as the raw kernel variables.
+ */
+export const collectNotebookFrameNodes = (content?: JSONContent | null): NotebookFrameNodeSummary[] => {
+ if (!content || typeof content !== 'object') {
+ return []
+ }
+
+ const nodes: NotebookFrameNodeSummary[] = []
+ const usedReturnVariables = new Set<string>()
+
+ const walk = (node: any): void => {
+ if (!node || typeof node !== 'object') {
+ return
+ }
+ if (node.type === NotebookNodeType.SQLV2 || node.type === NotebookNodeType.PythonV2) {
+ const attrs = node.attrs ?? {}
+ const isSql = node.type === NotebookNodeType.SQLV2
+ const rawReturnVariable = typeof attrs.returnVariable === 'string' ? attrs.returnVariable : ''
+ let name: string
+ if (isSql) {
+ name = buildUniqueSqlV2ReturnVariable(
+ resolveSqlV2ReturnVariable(rawReturnVariable),
+ usedReturnVariables
+ )
+ usedReturnVariables.add(normalizeSqlIdentifier(name))
+ } else {
+ name = rawReturnVariable.trim() || 'df'
+ }
+ const result = attrs.result ?? null
+ nodes.push({
+ nodeId: attrs.nodeId ?? '',
+ name,
+ nodeType: isSql ? 'sql' : 'python',
+ columns: frameNodeColumns(result),
+ rowCount: typeof result?.row_count === 'number' ? result.row_count : null,
+ hasRun: Boolean(result),
+ code: typeof attrs.code === 'string' ? attrs.code : '',
+ })
+ }
+ if (node.type === NotebookNodeType.MarkdownNotebook) {
+ expandMarkdownNotebookNodesOfTypes(node, [NotebookNodeType.SQLV2, NotebookNodeType.PythonV2]).forEach(walk)
+ }
+ if (Array.isArray(node.content)) {
+ node.content.forEach(walk)
+ }
+ }
+
+ walk(content)
+ return nodes
+}
+
export type PythonKernelNodeSummary = {
nodeId: string
returnVariable: string
diff --git a/frontend/src/scenes/notebooks/Notebook/notebookKernelInfoLogic.ts b/frontend/src/scenes/notebooks/Notebook/notebookKernelInfoLogic.ts
index 0cbf193e06fd..4c63aed88ab1 100644
--- a/frontend/src/scenes/notebooks/Notebook/notebookKernelInfoLogic.ts
+++ b/frontend/src/scenes/notebooks/Notebook/notebookKernelInfoLogic.ts
@@ -17,9 +17,24 @@ import api from 'lib/api'
import { PythonKernelExecuteResponse } from '../Nodes/pythonExecution'
+/** A DuckDB object a SQL node can currently SELECT from, as reported by the kernel's last run. */
+export type NotebookKernelFrame = {
+ name: string
+ /** 'frame': a dataframe a node produced. 'table'/'view': created by SQL DDL in a DuckDB node. */
+ kind: 'frame' | 'table' | 'view'
+ /** [column name, DuckDB type] pairs. */
+ columns: [string, string][]
+ /** Null when counting would need a table scan (a DDL view). */
+ row_count: number | null
+ /** True when row_count is DuckDB's estimate, which doesn't track deletes and can be wildly off. */
+ row_count_is_estimate?: boolean
+}
+
export type NotebookKernelInfo = {
backend: 'docker' | 'modal' | null
status: string
+ /** Empty unless a live kernel has run something — the backend gates this on the kernel being up. */
+ frames?: NotebookKernelFrame[]
last_used_at?: string | null
last_error?: string | null
runtime_id?: string | null
@@ -90,6 +105,7 @@ export interface notebookKernelInfoLogicValues {
isStarting: boolean
kernelInfo: NotebookKernelInfo | null
kernelInfoLoading: boolean
+ localFrames: NotebookKernelFrame[]
memoryIndex: number
selectedCpu: number
selectedMemory: number
@@ -207,6 +223,7 @@ export interface notebookKernelInfoLogicMeta {
isBusyStatus: (isStarting: boolean, actionInFlight: KernelActionInFlight) => boolean
hasActionInFlight: (actionInFlight: KernelActionInFlight) => boolean
isModalKernel: (kernelInfo: NotebookKernelInfo | null) => boolean
+ localFrames: (kernelInfo: NotebookKernelInfo | null) => NotebookKernelFrame[]
selectedCpu: (cpuIndex: number) => number
selectedMemory: (memoryIndex: number) => number
currentCpu: (kernelInfo: NotebookKernelInfo | null, selectedCpu: number) => number
@@ -419,6 +436,7 @@ export const notebookKernelInfoLogic = kea<notebookKernelInfoLogicType>([
(s) => [s.kernelInfo],
(kernelInfo: NotebookKernelInfo | null) => kernelInfo?.backend === 'modal',
],
+ localFrames: [(s) => [s.kernelInfo], (kernelInfo: NotebookKernelInfo | null) => kernelInfo?.frames ?? []],
selectedCpu: [(s) => [s.cpuIndex], (cpuIndex: number) => cpuCoreOptions[cpuIndex]],
selectedMemory: [(s) => [s.memoryIndex], (memoryIndex: number) => memoryGbOptions[memoryIndex]],
currentCpu: [
diff --git a/frontend/src/scenes/notebooks/Notebook/notebookLogic.ts b/frontend/src/scenes/notebooks/Notebook/notebookLogic.ts
index e90ec8b61828..8fefa4b1a4e9 100644
--- a/frontend/src/scenes/notebooks/Notebook/notebookLogic.ts
+++ b/frontend/src/scenes/notebooks/Notebook/notebookLogic.ts
@@ -75,6 +75,7 @@ import {
collectHogqlSqlNodes,
collectNodeIndices,
collectPythonNodes,
+ collectNotebookFrameNodes,
collectSqlV2Nodes,
} from '../Nodes/notebookNodeContent'
import type {
@@ -82,6 +83,7 @@ import type {
HogqlSqlNodeSummary,
NotebookDependencyGraph,
PythonNodeSummary,
+ NotebookFrameNodeSummary,
SqlV2NodeSummary,
} from '../Nodes/notebookNodeContent'
import type { notebookNodeLogicType } from '../Nodes/notebookNodeLogic'
@@ -301,6 +303,7 @@ export interface notebookLogicValues {
editingNodeLogics: BuiltLogic<notebookNodeLogicType>[]
findNodeLogic: (type: NotebookNodeType, attributes: Record<string, any>) => notebookNodeLogicType | null
findNodeLogicById: (id: string) => BuiltLogic<notebookNodeLogicType> | null
+ frameNodeSummaries: NotebookFrameNodeSummary[]
getSharedCachedInlineQueryResults: (nodeId: string | null | undefined) => AnyResponseType | null
getSharedCachedInsight: (shortId: string | null | undefined) => InsightModel | null
hogqlSqlNodeIndices: Map<string, number>
@@ -650,6 +653,7 @@ export interface notebookLogicMeta {
duckSqlNodeSummaries: (content: JSONContent) => DuckSqlNodeSummary[]
hogqlSqlNodeSummaries: (content: JSONContent) => HogqlSqlNodeSummary[]
sqlV2NodeSummaries: (content: JSONContent) => SqlV2NodeSummary[]
+ frameNodeSummaries: (content: JSONContent) => NotebookFrameNodeSummary[]
dependencyGraph: (content: JSONContent) => NotebookDependencyGraph
pythonNodeIndices: (content: JSONContent) => Map<string, number>
sqlNodeIndices: (content: JSONContent) => Map<string, number>
@@ -1343,6 +1347,7 @@ export const notebookLogic = kea<notebookLogicType>([
duckSqlNodeSummaries: [(s) => [s.content], (content: JSONContent) => collectDuckSqlNodes(content)],
hogqlSqlNodeSummaries: [(s) => [s.content], (content: JSONContent) => collectHogqlSqlNodes(content)],
sqlV2NodeSummaries: [(s) => [s.content], (content: JSONContent) => collectSqlV2Nodes(content)],
+ frameNodeSummaries: [(s) => [s.content], (content: JSONContent) => collectNotebookFrameNodes(content)],
dependencyGraph: [(s) => [s.content], (content: JSONContent) => buildNotebookDependencyGraph(content)],
pythonNodeIndices: [
diff --git a/products/notebooks/backend/migrations/0012_kernelruntime_frames_and_more.py b/products/notebooks/backend/migrations/0012_kernelruntime_frames_and_more.py
new file mode 100644
index 000000000000..3404354f6e26
--- /dev/null
+++ b/products/notebooks/backend/migrations/0012_kernelruntime_frames_and_more.py
@@ -0,0 +1,42 @@
+# Generated by Django 5.2.14 on 2026-07-17 10:36
+
+import django.db.models.deletion
+from django.conf import settings
+from django.db import migrations, models
+
+
+class Migration(migrations.Migration):
+ dependencies = [
+ ("notebooks", "0011_alter_notebooknoderun_status"),
+ migrations.swappable_dependency(settings.AUTH_USER_MODEL),
+ ]
+
+ operations = [
+ migrations.AddField(
+ model_name="kernelruntime",
+ name="frames",
+ field=models.JSONField(blank=True, default=None, null=True),
+ ),
+ migrations.AddField(
+ model_name="kernelruntime",
+ name="frames_run_created_at",
+ field=models.DateTimeField(blank=True, null=True),
+ ),
+ migrations.AddField(
+ model_name="notebooknoderun",
+ name="kernel_runtime_id",
+ field=models.UUIDField(blank=True, null=True),
+ ),
+ migrations.AddField(
+ model_name="notebooknoderun",
+ name="user",
+ field=models.ForeignKey(
+ blank=True,
+ db_constraint=False,
+ db_index=False,
+ null=True,
+ on_delete=django.db.models.deletion.DO_NOTHING,
+ to=settings.AUTH_USER_MODEL,
+ ),
+ ),
+ ]
diff --git a/products/notebooks/backend/migrations/max_migration.txt b/products/notebooks/backend/migrations/max_migration.txt
index 8a8c2c3c87c4..7a86ed6f9a95 100644
--- a/products/notebooks/backend/migrations/max_migration.txt
+++ b/products/notebooks/backend/migrations/max_migration.txt
@@ -1 +1 @@
-0011_alter_notebooknoderun_status
+0012_kernelruntime_frames_and_more
diff --git a/products/notebooks/backend/models.py b/products/notebooks/backend/models.py
index beeae0599c1c..c5288a03f6be 100644
--- a/products/notebooks/backend/models.py
+++ b/products/notebooks/backend/models.py
@@ -173,6 +173,16 @@ class KernelRuntime(UUIDTModel):
last_error = models.TextField(null=True, blank=True)
server_url = models.TextField(null=True, blank=True)
server_connect_token = models.TextField(null=True, blank=True)
+ # The DuckDB objects a SQL node can currently SELECT from, as of this kernel's last run
+ # (Journey 7). Kernel-scoped rather than notebook-scoped on purpose: a row is only ever
+ # reused while its sandbox is verifiably alive, so the snapshot cannot outlive the kernel
+ # that produced it and go stale — a restarted kernel gets a new row with this unset.
+ frames: JSONField = JSONField(default=None, null=True, blank=True)
+ # Which run's snapshot `frames` holds, as that run's created_at. The kernel executes runs
+ # one at a time in arrival order, but their callbacks land on different web workers and can
+ # arrive out of order, so a slow older callback must not overwrite a newer snapshot. Runs
+ # are created before dispatch, so created_at orders them the same way the kernel ran them.
+ frames_run_created_at = models.DateTimeField(null=True, blank=True)
class Meta:
db_table = "posthog_kernelruntime"
@@ -203,6 +213,17 @@ class NotebookNodeRun(TeamScopedRootMixin, UUIDModel):
# Tenant isolation is still enforced by the fail-closed TeamScopedRootMixin manager.
team = models.ForeignKey("posthog.Team", on_delete=models.CASCADE, db_constraint=False)
notebook = models.ForeignKey("notebooks.Notebook", on_delete=models.CASCADE)
+ # Who ran it. Kernels are per user, so this is the second half of a KernelRuntime's scope —
+ # the callback needs it to file the frame snapshot without a user-blind lookup by id.
+ # db_constraint=False: a real FK to the hot posthog_user table locks it on deploy.
+ # db_index=False: nothing queries runs by user — it is only ever read off a run we already
+ # hold. DO_NOTHING keeps that true: SET_NULL would have Django's collector issue an
+ # `UPDATE … WHERE user_id = …` against this unindexed column on every user delete, on the
+ # table that grows fastest. Nothing enforces referential integrity here anyway
+ # (db_constraint=False), and a dangling id already reads back as None.
+ user = models.ForeignKey(
+ "posthog.User", on_delete=models.DO_NOTHING, null=True, blank=True, db_constraint=False, db_index=False
+ )
node_id = models.CharField(max_length=128)
# How the run executed: hogql pushed to ClickHouse (pages re-query by `code`); python and
# duckdb ran in the sandbox kernel (pages slice the on-sandbox result frame by `result_id`).
@@ -213,6 +234,11 @@ class NotebookNodeRun(TeamScopedRootMixin, UUIDModel):
status = models.CharField(choices=Status, default=Status.RUNNING, max_length=20)
envelope: JSONField = JSONField(default=None, null=True, blank=True)
result_id = models.UUIDField(null=True, blank=True)
+ # Which kernel this run was dispatched to, so the callback can file the run's frame
+ # snapshot against the right KernelRuntime. A plain id rather than an FK: runtime rows
+ # are transient (starting/stopped/discarded/error) and run history must not be coupled
+ # to their churn — see sql_v2_result_delivery.md, "Related model notes".
+ kernel_runtime_id = models.UUIDField(null=True, blank=True)
error = models.TextField(null=True, blank=True)
created_at = models.DateTimeField(auto_now_add=True)
updated_at = models.DateTimeField(auto_now=True)
diff --git a/products/notebooks/backend/presentation/views/notebook.py b/products/notebooks/backend/presentation/views/notebook.py
index 61a333e872d7..15a1fc3398b6 100644
--- a/products/notebooks/backend/presentation/views/notebook.py
+++ b/products/notebooks/backend/presentation/views/notebook.py
@@ -584,12 +584,15 @@ class NotebookViewSet(TeamAndOrgViewSetMixin, AccessControlViewSetMixin, ForbidD
return self.get_object()
+ def _has_query_access(self) -> bool:
+ return bool(self.user_access_control.check_access_level_for_resource("query", "viewer"))
+
def _require_query_access(self) -> None:
# SQLV2 runs arbitrary HogQL and returns analytics rows, so notebook access alone is not
# enough — a notebook editor whose query access is denied must not read data through it.
# Mirrors ee/api/subscription.py: the query:read scope gates tokens, this gates sessions
# (which carry no scopes) and enforces real RBAC for tokens too.
- if not self.user_access_control.check_access_level_for_resource("query", "viewer"):
+ if not self._has_query_access():
raise PermissionDenied("You need query access to run SQL in a notebook.")
def _current_user(self) -> User | None:
@@ -822,6 +825,18 @@ class NotebookViewSet(TeamAndOrgViewSetMixin, AccessControlViewSetMixin, ForbidD
"kernel_id": runtime.kernel_id if runtime else None,
"kernel_pid": runtime.kernel_pid if runtime else None,
"sandbox_id": runtime.sandbox_id if runtime else None,
+ # Journey 7: what a SQL node can currently SELECT from. Gated twice. On the
+ # live-checked status, not runtime.status — the row above is the latest by
+ # last_used_at regardless of state, and a dead kernel's frames are not
+ # SELECT-able. And on query access, because these are column names and types
+ # derived from the user's data: notebook access alone gates liveness (which is
+ # all this endpoint used to return), but not schema. The rest of SQLV2 draws
+ # that line already; this keeps the endpoint's existing surface ungated.
+ "frames": (
+ (runtime.frames or [])
+ if runtime and status == KernelRuntime.Status.RUNNING and self._has_query_access()
+ else []
+ ),
"cpu_cores": cpu_cores,
"memory_gb": sandbox_config.memory_gb,
"disk_size_gb": sandbox_config.disk_size_gb,
@@ -1038,6 +1053,9 @@ class NotebookViewSet(TeamAndOrgViewSetMixin, AccessControlViewSetMixin, ForbidD
run = NotebookNodeRun.objects.create(
team_id=self.team_id,
notebook=notebook,
+ # The same user the run's kernel is resolved for, so the callback can scope the
+ # 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,
diff --git a/products/notebooks/backend/sandbox/kernel/bootstrap.py b/products/notebooks/backend/sandbox/kernel/bootstrap.py
index a904644a92a1..80ffef55cae5 100644
--- a/products/notebooks/backend/sandbox/kernel/bootstrap.py
+++ b/products/notebooks/backend/sandbox/kernel/bootstrap.py
@@ -34,7 +34,7 @@ import json
import uuid
import base64
import logging
-from typing import Any
+from typing import Any, NamedTuple
import duckdb
import pandas as pd
@@ -54,6 +54,40 @@ _STREAM_CAP_CHARS = 32_768
_CELL_CAP_CHARS = 10_000
_MEDIA_MAX_FIGURES = 8
_MEDIA_TOTAL_CAP_CHARS = 4_000_000 # base64 chars across all figures (~3 MB of PNG bytes)
+# User SQL can create unboundedly many DuckDB objects; the schema browser only ever renders
+# a list, so cap what the envelope carries rather than let the catalog size it. The byte cap
+# is the one that matters: identifiers and type strings are user-controlled and unbounded
+# (a nested struct type prints in full), so a count cap alone can still push the envelope
+# past the callback's MAX_ENVELOPE_BYTES and cost the user the run's actual result.
+_SNAPSHOT_MAX_OBJECTS = 200
+_SNAPSHOT_MAX_COLUMNS = 100
+_SNAPSHOT_MAX_IDENTIFIER_CHARS = 200
+_SNAPSHOT_MAX_BYTES = 256_000
+
+
+class _Registration(NamedTuple):
+ frame: Any
+ # "output": a node bound this name (its own output, or an upstream node's frame re-registered
+ # as an input) — a node can only reference it while it is still a frame in the namespace.
+ # "input": materialized from an upstream HogQL node's Arrow file, re-fetched on demand, so it
+ # stays referenceable regardless of the namespace (a DuckDB node never binds one there).
+ origin: str
+
+
+def _clip_identifier(value: Any) -> str:
+ # Identifiers and type strings are user-controlled and unbounded (a nested struct type
+ # prints in full), and the envelope has a hard byte ceiling.
+ text = str(value)
+ return text if len(text) <= _SNAPSHOT_MAX_IDENTIFIER_CHARS else text[:_SNAPSHOT_MAX_IDENTIFIER_CHARS] + "…"
+
+
+def _safe_len(frame: Any) -> int | None:
+ # Registered objects are pandas frames or Arrow tables (both sized in O(1)), but user code
+ # can register anything DuckDB accepts, so an unsized object lists without a count.
+ try:
+ return int(len(frame))
+ except Exception: # noqa: BLE001
+ return None
def _truncate_stream(text: str, cap: int = _STREAM_CAP_CHARS) -> str:
@@ -104,11 +138,155 @@ class KernelSession:
self.duck.execute(f"SET temp_directory = '{self._duck_dir}'") # spill big ops to disk
# In-kernel this is the ipykernel's own shell; in tests it's the process singleton.
self.shell = shell or InteractiveShell.instance()
- self._registered: set[str] = set()
+ # name -> what we registered under it. Kept so the catalog snapshot can report a row
+ # count without scanning (a registration is a DuckDB view, so it has no estimated_size)
+ # 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] = {}
# Agg backend set now, before any user `import matplotlib.pyplot`, so plots stay headless.
self._plt = _load_headless_pyplot()
def run_node(self, payload: dict[str, Any]) -> dict[str, Any]:
+ result = self._execute_node(payload)
+ # Reconciling the registry mutates kernel state, so it is its own step rather than a
+ # side effect of building a display list — a later reader who caches or skips the
+ # snapshot must not silently change what SQL can see.
+ self._reap_stale_registrations()
+ # Every envelope carries the snapshot, including error and interrupted ones: a run that
+ # failed part-way can still have changed the catalog (a CREATE TABLE before the raise),
+ # and the browser must not miss it until the next successful run. A failed snapshot
+ # omits the key entirely — absent means "leave the stored one alone", where an empty
+ # list would mean "the kernel has nothing" and wipe the browser.
+ frames = self._catalog_snapshot()
+ if frames is not None:
+ result["frames"] = frames
+ return result
+
+ def _reap_stale_registrations(self) -> None:
+ """Drop registrations the node layer would already reject.
+
+ DuckDB keeps its own reference to a registered object, so `del df` leaves the catalog
+ entry behind while `_register_inputs` would now refuse the name. Follow the node layer
+ rather than the raw catalog, so a later DuckDB node can't read a deleted frame's rows.
+ """
+ for name, registration in list(self._registered.items()):
+ if registration.origin == "output" and not self._is_referenceable(name):
+ self._unregister_duck(name)
+
+ def _catalog_snapshot(self) -> list[dict[str, Any]] | None:
+ """The objects a SQL node can currently SELECT from, read from DuckDB's own catalog.
+
+ A pure read: returns None if the catalog can't be read, which the callback treats as
+ "unchanged" rather than "empty".
+
+ The catalog is authoritative rather than an approximation: `register`/`unregister`
+ keep it in step with the namespace on every path that invalidates a name, and DDL
+ objects live in duck.db for exactly as long as they stay queryable — including across
+ a kernel restart, which drops registrations (in-memory) but keeps tables (on disk).
+ """
+ try:
+ # duckdb_columns() covers tables and views alike, so names/columns/types come in
+ # one pass; duckdb_tables() is only needed to tell a table from a view and to pick
+ # up its free estimated_size. `NOT internal` excludes the system catalog. Both are
+ # keyed by the qualified triple: a bare name is ambiguous across schemas, and
+ # merging two objects that share one invents a schema matching neither.
+ columns_by_ref: dict[tuple[str, str, str], list[list[str]]] = {}
+ for database_name, schema_name, table_name, column_name, data_type in self.duck.execute(
+ "SELECT database_name, schema_name, table_name, column_name, data_type "
+ "FROM duckdb_columns() WHERE NOT internal ORDER BY table_name, column_index"
+ ).fetchall():
+ columns = columns_by_ref.setdefault((str(database_name), str(schema_name), str(table_name)), [])
+ if len(columns) < _SNAPSHOT_MAX_COLUMNS:
+ columns.append([_clip_identifier(column_name), _clip_identifier(data_type)])
+ table_sizes: dict[tuple[str, str, str], int | None] = {
+ (str(database_name), str(schema_name), str(table_name)): (
+ int(estimated_size) if estimated_size is not None else None
+ )
+ for database_name, schema_name, table_name, estimated_size in self.duck.execute(
+ "SELECT database_name, schema_name, table_name, estimated_size "
+ "FROM duckdb_tables() WHERE NOT internal"
+ ).fetchall()
+ }
+ except BaseException: # noqa: BLE001 — incl. KeyboardInterrupt: a stop must not turn an
+ # interrupted envelope into a generic failure, and the browser is display-only.
+ logger.exception("nb_kernel catalog snapshot failed")
+ return None
+
+ frames: list[dict[str, Any]] = []
+ budget = _SNAPSHOT_MAX_BYTES
+ for ref in self._resolvable_refs(columns_by_ref):
+ entry = self._catalog_entry(ref, columns_by_ref[ref], table_sizes)
+ cost = len(json.dumps(entry))
+ if cost > budget:
+ # Over budget: stop rather than ship an envelope the callback would reject,
+ # which would cost the user the run's real result over a sidebar list.
+ logger.warning("nb_kernel catalog snapshot truncated at %d objects", len(frames))
+ break
+ budget -= cost
+ frames.append(entry)
+ if len(frames) >= _SNAPSHOT_MAX_OBJECTS:
+ break
+ return frames
+
+ def _resolvable_refs(
+ self, columns_by_ref: dict[tuple[str, str, str], list[list[str]]]
+ ) -> list[tuple[str, str, str]]:
+ """One ref per bare name: the one an unqualified `FROM <name>` actually reaches.
+
+ Users write bare names, and only one object per name is reachable that way, so listing
+ both would advertise a table their SQL will never read. A registration always shadows
+ (DuckDB puts it in `temp`, which its search path resolves first).
+ """
+ by_name: dict[str, tuple[str, str, str]] = {}
+ for ref in sorted(columns_by_ref):
+ name = ref[2]
+ incumbent = by_name.get(name)
+ if incumbent is None or self._shadow_rank(ref) > self._shadow_rank(incumbent):
+ by_name[name] = ref
+ return [by_name[name] for name in sorted(by_name)]
+
+ def _shadow_rank(self, ref: tuple[str, str, str]) -> int:
+ database, _schema, name = ref
+ # Verified against DuckDB: `register()` creates the view in `temp.main`, and its search
+ # path resolves temp first — a bare `FROM x` reaches the registration even when a table
+ # `x` exists in another schema. Rank by where the object lives, not by name alone: both
+ # refs share the name, so only the database tells the registration from its shadow.
+ if database == "temp":
+ return 2 if name in self._registered else 1
+ return 0
+
+ def _catalog_entry(
+ self,
+ ref: tuple[str, str, str],
+ columns: list[list[str]],
+ table_sizes: dict[tuple[str, str, str], int | None],
+ ) -> dict[str, Any]:
+ name = ref[2]
+ registration = self._registered.get(name)
+ if registration is not None and self._shadow_rank(ref) == 2:
+ # A DuckDB view over an object we hold, so len() is free and exact.
+ return {"name": name, "columns": columns, "kind": "frame", "row_count": _safe_len(registration.frame)}
+ if ref in table_sizes:
+ # estimated_size is the optimizer's cardinality estimate, not a count: it does not
+ # track deletes. Flagged approximate so the UI never presents it as fact, and a
+ # missing estimate stays unknown rather than becoming a confident zero.
+ return {
+ "name": name,
+ "columns": columns,
+ "kind": "table",
+ "row_count": table_sizes[ref],
+ "row_count_is_estimate": True,
+ }
+ # A view the user created with DDL. Counting it means scanning the base table, which
+ # browsing must never do — so it lists without a row count.
+ return {"name": name, "columns": columns, "kind": "view", "row_count": None}
+
+ def _is_referenceable(self, name: str) -> bool:
+ # The same rule _register_inputs applies to a `local` input, so the browser lists a name
+ # exactly when a node could actually reference it.
+ return isinstance(self.shell.user_ns.get(name), pd.DataFrame)
+
+ def _execute_node(self, payload: dict[str, Any]) -> dict[str, Any]:
node = payload.get("node") or {}
node_type = str(node.get("type") or "python")
preview_rows = int(payload.get("page_limit") or _DEFAULT_PREVIEW_ROWS)
@@ -197,7 +375,7 @@ class KernelSession:
# node additionally bind pandas (the one step that materializes in RAM).
with pa.memory_map(spec["path"]) as source:
table = pa.ipc.open_file(source).read_all()
- self._register_duck(name, table)
+ self._register_duck(name, table, origin="input")
if bind_pandas:
self.shell.user_ns[name] = table.to_pandas()
elif kind == "local":
@@ -222,17 +400,17 @@ class KernelSession:
else:
raise ValueError(f"unknown input kind '{kind}' for '{name}'")
- def _register_duck(self, name: str, frame: Any) -> None:
+ def _register_duck(self, name: str, frame: Any, origin: str = "output") -> None:
self._unregister_duck(name) # replace cleanly when a frame was registered before
self.duck.register(name, frame)
- self._registered.add(name)
+ self._registered[name] = _Registration(frame=frame, origin=origin)
def _unregister_duck(self, name: str) -> None:
try:
self.duck.unregister(name)
except Exception: # noqa: BLE001 — nothing registered under this name yet
pass
- self._registered.discard(name)
+ self._registered.pop(name, None)
def _run_duckdb_node(self, node: dict[str, Any], preview_rows: int) -> dict[str, Any]:
output_name = node.get("output_name") or ""
diff --git a/products/notebooks/backend/sql_v2.py b/products/notebooks/backend/sql_v2.py
index 8d8981f2c50e..d6b5991f1d0e 100644
--- a/products/notebooks/backend/sql_v2.py
+++ b/products/notebooks/backend/sql_v2.py
@@ -267,7 +267,12 @@ def ensure_sql_v2_server(notebook: Notebook, user: User | None) -> KernelRuntime
runtime.server_url = credentials.url
runtime.server_connect_token = credentials.token
- runtime.save(update_fields=["server_url", "server_connect_token"])
+ # A redeploy relaunches the kernel inside a live sandbox and keeps this row, so the frame
+ # snapshot would outlive the kernel that produced it — the one path where the row's
+ # lifetime stops tracking the kernel's. Its registrations are gone with the namespace, so
+ # drop the snapshot; the next run repopulates it from the new kernel's catalog.
+ runtime.frames = None
+ runtime.save(update_fields=["server_url", "server_connect_token", "frames"])
return runtime
@@ -288,6 +293,11 @@ def dispatch_sql_v2_run(
"""
runtime = ensure_sql_v2_server(notebook, user)
assert runtime.server_url # ensure_sql_v2_server always returns a runtime with a live server_url
+ # Record which kernel took the run: the sandbox can't name it (its secret is a one-way
+ # derivation of the runtime id, not the id), and letting it name one would let a sandbox
+ # write over another kernel's state. So the backend decides here and the callback follows.
+ run.kernel_runtime_id = runtime.id
+ run.save(update_fields=["kernel_runtime_id", "updated_at"])
command_token = mint_command_token(kernel_server_secret(str(runtime.id)), str(run.id))
user_id = user.id if isinstance(user, User) else None
payload: dict = {
diff --git a/products/notebooks/backend/sql_v2_callback.py b/products/notebooks/backend/sql_v2_callback.py
index dc77474171c5..44233129bcf8 100644
--- a/products/notebooks/backend/sql_v2_callback.py
+++ b/products/notebooks/backend/sql_v2_callback.py
@@ -8,12 +8,13 @@ posthog/urls.py at internal/notebooks/runs/<run_id>/result/.
import json
from django.core import signing
+from django.db.models import Q
from django.http import JsonResponse
import structlog
from drf_spectacular.utils import OpenApiResponse, extend_schema
-from products.notebooks.backend.models import NotebookNodeRun
+from products.notebooks.backend.models import KernelRuntime, NotebookNodeRun
from products.notebooks.backend.sql_v2 import verify_callback_token
from products.notebooks.backend.sql_v2_serializers import NotebookSQLV2CallbackRequestSerializer
@@ -76,9 +77,15 @@ def notebook_sql_v2_callback(request, run_id: str) -> JsonResponse:
# Store the raw JSON envelope (JSON-native types) — the serializer's validated_data
# would coerce result_id to a uuid.UUID, which the JSONField can't serialize.
envelope = body["envelope"]
+ # The snapshot is kernel state, read only off KernelRuntime. Keeping a copy on every run
+ # row would park a duplicate catalog forever on the table that grows fastest (one row per
+ # cell execution), so it rides the envelope to get here and is then dropped.
+ frames = envelope.pop("frames", None)
try:
- run = NotebookNodeRun.objects.for_team(team_id).get(id=run_id)
+ # select_related: the frame snapshot below scopes to the run's user, so fetch it up front
+ # rather than lazy-loading it on attribute access.
+ run = NotebookNodeRun.objects.for_team(team_id).select_related("user").get(id=run_id)
except NotebookNodeRun.DoesNotExist:
return JsonResponse({"error": "Run not found"}, status=404)
@@ -92,4 +99,34 @@ def notebook_sql_v2_callback(request, run_id: str) -> JsonResponse:
run.error = envelope.get("error")
run.save(update_fields=["status", "envelope", "result_id", "error", "updated_at"])
+ _store_frame_snapshot(run, frames, team_id)
+
return JsonResponse({"ok": True})
+
+
+def _store_frame_snapshot(run: NotebookNodeRun, frames: list | None, team_id: int) -> None:
+ """File the run's DuckDB catalog snapshot against the kernel that produced it (Journey 7).
+
+ `frames` is absent for a hogql run (it never enters the kernel) and for a kernel whose
+ catalog read failed. Both mean "leave the stored snapshot alone" — a hogql run changes no
+ local state, and a failed read knows nothing. Only an actual empty list means "the kernel
+ has nothing", so absent must never be coerced to empty here.
+ """
+ if frames is None or not run.kernel_runtime_id:
+ return
+ # Scoped to the dispatch-time kernel rather than "the notebook's current kernel": if the
+ # kernel was replaced mid-run, this snapshot describes the dead one and must not overwrite
+ # the live one. Team AND user because a KernelRuntime is scoped to both — kernels are per
+ # user, so a notebook's collaborators each have their own, and a snapshot must never land
+ # on someone else's row. Both come from the run, which was itself looked up team-scoped.
+ #
+ # The created_at guard makes the write last-run-wins rather than last-callback-wins. The
+ # kernel runs cells one at a time in arrival order, but callbacks land on separate web
+ # workers and can arrive out of order, so without it a slow older callback would overwrite
+ # a newer catalog and leave deleted frames on show until the next run. Done as a
+ # conditional UPDATE rather than read-then-write so concurrent callbacks can't interleave.
+ (
+ KernelRuntime.objects.filter(id=run.kernel_runtime_id, team_id=team_id, user=run.user)
+ .filter(Q(frames_run_created_at__isnull=True) | Q(frames_run_created_at__lt=run.created_at))
+ .update(frames=frames, frames_run_created_at=run.created_at)
+ )
diff --git a/products/notebooks/backend/sql_v2_serializers.py b/products/notebooks/backend/sql_v2_serializers.py
index 1011c89ae7f9..109005227c0b 100644
--- a/products/notebooks/backend/sql_v2_serializers.py
+++ b/products/notebooks/backend/sql_v2_serializers.py
@@ -106,8 +106,48 @@ class NotebookSQLV2MediaSerializer(serializers.Serializer):
data = serializers.CharField(help_text="Base64-encoded media bytes.") # type: ignore[assignment]
+class NotebookSQLV2FrameSerializer(serializers.Serializer):
+ name = serializers.CharField(help_text="Name a SQL node can SELECT from.")
+ # CharField, not ChoiceField: a `kind` enum collides with other generated enums under
+ # --fail-on-warn, and `status` above sets the same precedent.
+ kind = serializers.CharField(
+ help_text=(
+ "Where the object came from: 'frame' (a dataframe a node produced), "
+ "or 'table'/'view' (created by SQL DDL in a DuckDB node)."
+ )
+ )
+ columns = serializers.ListField(
+ child=serializers.ListField(child=serializers.CharField(), help_text="A [column name, DuckDB type] pair."),
+ required=False,
+ default=list,
+ help_text="DuckDB type per column, as [name, type] pairs.",
+ )
+ row_count = serializers.IntegerField(
+ required=False,
+ allow_null=True,
+ help_text="Rows available, or null when counting would require a table scan (a DDL view).",
+ )
+ row_count_is_estimate = serializers.BooleanField(
+ required=False,
+ default=False,
+ help_text=(
+ "True when row_count is DuckDB's optimizer estimate rather than a count. The estimate "
+ "does not track deletes, so it must never be presented as exact."
+ ),
+ )
+
+
class NotebookSQLV2EnvelopeSerializer(serializers.Serializer):
status = serializers.CharField(help_text="Run outcome: 'ok', 'error', or 'interrupted' (user-requested stop).")
+ frames = NotebookSQLV2FrameSerializer(
+ many=True,
+ required=False,
+ default=list,
+ help_text=(
+ "DuckDB objects a SQL node can SELECT from as of this run, for the schema browser. "
+ "Only kernel runs (python/duckdb) report these; a hogql run never enters the kernel."
+ ),
+ )
stdout = serializers.CharField(
required=False,
default="",
diff --git a/products/notebooks/backend/test/test_kernel_bootstrap.py b/products/notebooks/backend/test/test_kernel_bootstrap.py
index acdb44835a3d..3a668cc6fecf 100644
--- a/products/notebooks/backend/test/test_kernel_bootstrap.py
+++ b/products/notebooks/backend/test/test_kernel_bootstrap.py
@@ -1,4 +1,5 @@
import os
+import json
import tempfile
from django.test import SimpleTestCase
@@ -251,3 +252,73 @@ class TestKernelSessionRunNode(SimpleTestCase):
envelope = self._run_duckdb("select * from out", inputs=[{"name": "out", "kind": "local"}])
self.assertEqual(envelope["status"], "error")
self.assertIn("out", envelope["error"])
+
+ def test_snapshot_lists_only_what_sql_can_select_from(self):
+ # The browser's contract is "things you can SELECT from", so the snapshot is read from
+ # DuckDB's catalog rather than the namespace. Walking user_ns for DataFrames instead —
+ # the tempting shortcut — would leak `raw` in and miss `agg`, which has no result file
+ # at all (a frameless DDL run writes none) and is invisible to anything document-derived.
+ self._run("import pandas as pd\npd.DataFrame({'a': [1, 2, 3]})", output_name="sql_df")
+ self._run("raw = pd.DataFrame({'zz': [1]})\nNone")
+ envelope = self._run_duckdb("create table agg as select a from sql_df")
+
+ by_name = {frame["name"]: frame for frame in envelope["frames"]}
+ self.assertEqual(sorted(by_name), ["agg", "sql_df"])
+ self.assertEqual(by_name["sql_df"]["kind"], "frame")
+ self.assertEqual(by_name["sql_df"]["row_count"], 3)
+ self.assertEqual(by_name["sql_df"]["columns"], [["a", "BIGINT"]])
+ self.assertEqual(by_name["agg"]["kind"], "table")
+
+ def test_snapshot_rides_a_failed_run(self):
+ # A run that raises part-way can still have changed the catalog, so snapshotting only
+ # successful runs would hide `scratch` until some later run happened to succeed.
+ self._run_duckdb("create table scratch as select 1 as n")
+ envelope = self._run("raise ValueError('boom')")
+
+ self.assertEqual(envelope["status"], "error")
+ self.assertEqual([frame["name"] for frame in envelope["frames"]], ["scratch"])
+
+ def test_snapshot_drops_a_deleted_frame(self):
+ # `del df` unregisters it, so it stops being SELECT-able and must stop being listed —
+ # this is the phantom-frame case that sank deriving the list from the document.
+ self._run("import pandas as pd\npd.DataFrame({'a': [1]})", output_name="doomed")
+ self._run("del doomed")
+ envelope = self._run("1 + 1")
+
+ self.assertEqual([frame["name"] for frame in envelope["frames"]], [])
+
+ def test_snapshot_keeps_same_named_objects_apart(self):
+ # Keyed on the bare name, a registered frame and a same-named table in another schema
+ # merge into one entry whose columns and row count match neither — a schema the user's
+ # SQL will never see. Only one object is reachable from a bare `FROM`, and DuckDB
+ # resolves the registration first, so that is the one to report.
+ self._run("import pandas as pd\npd.DataFrame({'a': [1, 2, 3]})", output_name="sql_df")
+ self.session.duck.execute("CREATE SCHEMA IF NOT EXISTS other")
+ self.session.duck.execute("CREATE TABLE other.sql_df AS SELECT 99 AS totally_different")
+ envelope = self._run("1 + 1")
+
+ entries = [frame for frame in envelope["frames"] if frame["name"] == "sql_df"]
+ self.assertEqual(len(entries), 1)
+ self.assertEqual(entries[0]["kind"], "frame")
+ self.assertEqual(entries[0]["row_count"], 3)
+ self.assertEqual(entries[0]["columns"], [["a", "BIGINT"]])
+
+ def test_snapshot_is_omitted_when_the_catalog_cannot_be_read(self):
+ # An empty list means "the kernel has nothing" and overwrites the stored snapshot; a
+ # failed read knows nothing and must leave it alone. The two must not look alike.
+ self._run("import pandas as pd\npd.DataFrame({'a': [1]})", output_name="kept")
+ self.session.duck.close()
+ envelope = self._run("2 + 2")
+
+ self.assertNotIn("frames", envelope)
+
+ def test_snapshot_stays_within_the_envelope_budget(self):
+ # Column names and type strings are user-controlled and unbounded, so a count cap alone
+ # can still push the envelope past the callback's byte limit — which drops the whole
+ # result, costing the user their run over a sidebar list.
+ wide = ", ".join(f"1 AS {'x' * 300}_{index}" for index in range(60))
+ for table in range(30):
+ self.session.duck.execute(f"CREATE TABLE wide_{table} AS SELECT {wide}")
+ envelope = self._run("3 + 3")
+
+ self.assertLessEqual(len(json.dumps(envelope["frames"])), 300_000)
diff --git a/products/notebooks/backend/test/test_sql_v2.py b/products/notebooks/backend/test/test_sql_v2.py
index b38f54f0f278..404c254cb842 100644
--- a/products/notebooks/backend/test/test_sql_v2.py
+++ b/products/notebooks/backend/test/test_sql_v2.py
@@ -23,6 +23,7 @@ from parameterized import parameterized
from posthog.constants import AvailableFeature
from posthog.models.organization import OrganizationMembership
from posthog.models.scoping import team_scope
+from posthog.models.user import User
from products.notebooks.backend.kernel_package import kernel_package_bytes_and_hash
from products.notebooks.backend.models import KernelRuntime, Notebook, NotebookNodeRun
@@ -87,6 +88,7 @@ class TestSQLV2Callback(APIBaseTest):
self.node_run = NotebookNodeRun.objects.create(
team=self.team,
notebook=self.notebook,
+ user=self.user,
node_id="node-1",
status=NotebookNodeRun.Status.RUNNING,
)
@@ -168,6 +170,115 @@ class TestSQLV2Callback(APIBaseTest):
self.assertEqual(response.status_code, 400)
self.assertEqual(self._reload_run().status, NotebookNodeRun.Status.RUNNING)
+ def _create_runtime(self, status: str, user: User | None = None) -> KernelRuntime:
+ return KernelRuntime.objects.create(
+ team=self.team,
+ notebook=self.notebook,
+ notebook_short_id=self.notebook.short_id,
+ user=user or self.user,
+ status=status,
+ backend=KernelRuntime.Backend.DOCKER,
+ )
+
+ def test_frame_snapshot_never_lands_on_another_users_kernel(self):
+ # Kernels are per user, so collaborators on one notebook each have their own. A snapshot
+ # filed by runtime id alone would write this user's frame names onto a teammate's kernel
+ # row, surfacing them in that teammate's schema browser.
+ collaborator = User.objects.create_and_join(self.organization, "[email protected]", None)
+ theirs = self._create_runtime(KernelRuntime.Status.RUNNING, user=collaborator)
+ with team_scope(self.team.id):
+ self.node_run.kernel_runtime_id = theirs.id
+ self.node_run.save(update_fields=["kernel_runtime_id"])
+
+ token = mint_callback_token(str(self.node_run.id), self.team.id)
+ response = self._post(
+ token,
+ envelope={
+ **self.envelope,
+ "frames": [{"name": "secret_df", "kind": "frame", "columns": [], "row_count": 1}],
+ },
+ )
+
+ self.assertEqual(response.status_code, 200)
+ theirs.refresh_from_db()
+ self.assertIsNone(theirs.frames)
+
+ def test_frame_snapshot_lands_on_the_kernel_that_ran_it(self):
+ # A snapshot describes one kernel's state, so it must follow the run's dispatch-time
+ # kernel. Resolving "the notebook's current kernel" at callback time instead would let a
+ # kernel that died mid-run overwrite the frames of the live one that replaced it.
+ ran_on = self._create_runtime(KernelRuntime.Status.STOPPED)
+ replaced_by = self._create_runtime(KernelRuntime.Status.RUNNING)
+ with team_scope(self.team.id):
+ self.node_run.kernel_runtime_id = ran_on.id
+ self.node_run.save(update_fields=["kernel_runtime_id"])
+ frames = [{"name": "sql_df", "kind": "frame", "columns": [["a", "BIGINT"]], "row_count": 3}]
+
+ token = mint_callback_token(str(self.node_run.id), self.team.id)
+ response = self._post(token, envelope={**self.envelope, "frames": frames})
+
+ self.assertEqual(response.status_code, 200)
+ ran_on.refresh_from_db()
+ replaced_by.refresh_from_db()
+ self.assertEqual(ran_on.frames, frames)
+ self.assertIsNone(replaced_by.frames)
+
+ def test_a_late_callback_cannot_overwrite_a_newer_snapshot(self):
+ # The kernel runs cells one at a time, but their callbacks land on separate web workers
+ # and can arrive out of order. Without a guard the slow older one wins, leaving frames
+ # it has since dropped on show until some later run happens to refresh them.
+ ran_on = self._create_runtime(KernelRuntime.Status.RUNNING)
+ with team_scope(self.team.id):
+ older = NotebookNodeRun.objects.create(
+ team=self.team,
+ notebook=self.notebook,
+ user=self.user,
+ node_id="n-old",
+ status=NotebookNodeRun.Status.RUNNING,
+ kernel_runtime_id=ran_on.id,
+ )
+ newer = NotebookNodeRun.objects.create(
+ team=self.team,
+ notebook=self.notebook,
+ user=self.user,
+ node_id="n-new",
+ status=NotebookNodeRun.Status.RUNNING,
+ kernel_runtime_id=ran_on.id,
+ )
+ fresh = [{"name": "after", "kind": "frame", "columns": [], "row_count": 1}]
+ stale = [{"name": "before", "kind": "frame", "columns": [], "row_count": 1}]
+
+ # Newer run's callback lands first, then the older one's arrives late.
+ for run, frames in ((newer, fresh), (older, stale)):
+ response = self.client.post(
+ f"/internal/notebooks/runs/{run.id}/result/",
+ data=json.dumps({"envelope": {**self.envelope, "frames": frames}}),
+ content_type="application/json",
+ HTTP_AUTHORIZATION=f"Bearer {mint_callback_token(str(run.id), self.team.id)}",
+ )
+ self.assertEqual(response.status_code, 200)
+
+ ran_on.refresh_from_db()
+ self.assertEqual(ran_on.frames, fresh)
+
+ def test_hogql_envelope_leaves_the_previous_snapshot_standing(self):
+ # A hogql run never enters the kernel, so it reports no frames and must not be read as
+ # "the kernel now has none" — that would blank the browser on every SQL run.
+ ran_on = self._create_runtime(KernelRuntime.Status.RUNNING)
+ existing = [{"name": "sql_df", "kind": "frame", "columns": [["a", "BIGINT"]], "row_count": 3}]
+ ran_on.frames = existing
+ ran_on.save(update_fields=["frames"])
+ with team_scope(self.team.id):
+ self.node_run.kernel_runtime_id = ran_on.id
+ self.node_run.save(update_fields=["kernel_runtime_id"])
+
+ token = mint_callback_token(str(self.node_run.id), self.team.id)
+ response = self._post(token)
+
+ self.assertEqual(response.status_code, 200)
+ ran_on.refresh_from_db()
+ self.assertEqual(ran_on.frames, existing)
+
def test_unknown_run_returns_404(self):
other_id = "00000000-0000-0000-0000-000000000000"
token = mint_callback_token(other_id, self.team.id)