: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): size sql/python cells to the output they return (#73358)
Sinan Kucukkoseler967e56be0612
diff --git a/frontend/src/scenes/notebooks/Nodes/NotebookNodePythonV2.tsx b/frontend/src/scenes/notebooks/Nodes/NotebookNodePythonV2.tsxindex bca9eeeb872b..f9345d7160cc 100644--- a/frontend/src/scenes/notebooks/Nodes/NotebookNodePythonV2.tsx+++ b/frontend/src/scenes/notebooks/Nodes/NotebookNodePythonV2.tsx@@ -13,6 +13,7 @@ import { NotebookDataframeTable } from './components/NotebookDataframeTable'import { NotebookRunDownstreamBanner } from './components/NotebookRunDownstreamBanner'import { NotebookStaleCellBanner } from './components/NotebookStaleCellBanner'import { notebookNodeLogic } from './notebookNodeLogic'+import { countTextLines, outputHeightForShape } from './notebookNodeOutputHeight'import type { NotebookNodeSQLV2Result } from './NotebookNodeSQLV2'import { SQL_V2_DEFAULT_PAGE_SIZE, collectSqlV2Refs, notebookNodeSQLV2Logic } from './notebookNodeSQLV2Logic'import { NotebookDataframeResult } from './pythonExecution'@@ -21,10 +22,6 @@ import { NotebookDataframeResult } from './pythonExecution'// path, with sibling SQLV2 frames materialized as pandas frames. A separate node type from// the legacy ph-python cell (in-browser kernel) so the two flows never share run wiring.-// The default node height only fits a couple of table rows; grow to this once output lands-// so results and figures aren't clipped and the user doesn't have to resize by hand to read them.-const RESULT_MIN_HEIGHT = 300-export type NotebookNodePythonV2Attributes = {code: string// The dataframe name this cell's result is exposed as to later cells.@@ -91,20 +88,27 @@ const Component = ({const hasStreamOutput = !!(result?.stdout || result?.stderr || result?.media?.length)- // Grow a still-default (too-short) node the first time output lands so it's readable without- // a manual resize. Only grows below the target and only on fresh output, so a deliberate- // resize (or a taller reload) is left untouched.- const hadOutputRef = useRef(hasStreamOutput || !!dataframeResult)+ // Grow a still-too-short node to fit the output each run lands, so it's readable without a+ // manual resize. Sized to what came back — a printed value stays compact, a table or figure+ // grows up to a cap. Only grows, and only for a run we haven't sized yet, so a deliberate+ // resize (or a reload of an already-sized cell) is left untouched.+ const sizedRunIdRef = useRef<string | null | undefined>(result ? (attributes.runId ?? null) : undefined)useEffect(() => {- const hasOutput = hasStreamOutput || !!dataframeResult- if (hasOutput && !hadOutputRef.current) {- if (typeof attributes.height !== 'number' || attributes.height < RESULT_MIN_HEIGHT) {- updateAttributes({ height: RESULT_MIN_HEIGHT })- }+ const runId = attributes.runId ?? null+ if (!result || runId === sizedRunIdRef.current) {+ return+ }+ sizedRunIdRef.current = runId+ const target = outputHeightForShape({+ rowCount: result.columns?.length ? (result.first_page ?? []).length : 0,+ textLines: countTextLines(result.stdout, result.stderr),+ hasMedia: !!result.media?.length,+ })+ if (target !== null && (typeof attributes.height !== 'number' || attributes.height < target)) {+ updateAttributes({ height: target })}- hadOutputRef.current = hasOutput// oxlint-disable-next-line exhaustive-deps- }, [dataframeResult, hasStreamOutput])+ }, [result, attributes.runId])if (!expanded) {return nulldiff --git a/frontend/src/scenes/notebooks/Nodes/NotebookNodeSQLV2.tsx b/frontend/src/scenes/notebooks/Nodes/NotebookNodeSQLV2.tsxindex 6b57e36db779..520e92a2fa92 100644--- a/frontend/src/scenes/notebooks/Nodes/NotebookNodeSQLV2.tsx+++ b/frontend/src/scenes/notebooks/Nodes/NotebookNodeSQLV2.tsx@@ -18,6 +18,7 @@ import { NotebookRunDownstreamBanner } from './components/NotebookRunDownstreamBimport { NotebookCodeSQLEditorSettings } from './components/NotebookSQLEditor'import { NotebookStaleCellBanner } from './components/NotebookStaleCellBanner'import { notebookNodeLogic } from './notebookNodeLogic'+import { outputHeightForShape } from './notebookNodeOutputHeight'import { SQL_V2_DEFAULT_PAGE_SIZE, collectSqlV2Refs, notebookNodeSQLV2Logic } from './notebookNodeSQLV2Logic'import { NotebookDataframeResult } from './pythonExecution'@@ -47,9 +48,6 @@ export type NotebookNodeSQLV2Attributes = {// Matches the SQL editor output pane's default so charts land at v1-node size.const VIZ_MIN_HEIGHT = 350-// The default node height only fits a couple of table rows; grow to this once a result lands-// so the output isn't clipped and the user doesn't have to resize by hand to read it.-const RESULT_MIN_HEIGHT = 300// The dataframe name is referenced as a bare SQL table name and becomes a Python variable// when a python cell reads the frame, so it must be a plain identifier. Empty is fine —@@ -164,21 +162,26 @@ const Component = ({[attributes.vizQuery, attributes.code])- // Grow a still-default (too-short) node the first time a result lands so it's readable- // without a manual resize. Only grows below the target and only on a fresh result, so a- // deliberate resize (or a taller reload) is left untouched.- const hadResultRef = useRef(!!result)+ // Grow a still-too-short node to fit the result each run lands, so output is readable without+ // a manual resize. Sized to the rows that came back — a scalar stays compact, a wide result+ // grows up to a cap. Only grows, and only for a run we haven't sized yet, so a deliberate+ // resize (or a reload of an already-sized cell) is left untouched.+ const sizedRunIdRef = useRef<string | null | undefined>(result ? (attributes.runId ?? null) : undefined)useEffect(() => {- const hasResult = !!dataframeResult- if (hasResult && !hadResultRef.current) {- const target = activeTab === OutputTab.Visualization ? VIZ_MIN_HEIGHT : RESULT_MIN_HEIGHT- if (typeof attributes.height !== 'number' || attributes.height < target) {- updateAttributes({ height: target })- }+ const runId = attributes.runId ?? null+ if (!result || runId === sizedRunIdRef.current) {+ return+ }+ sizedRunIdRef.current = runId+ const target =+ activeTab === OutputTab.Visualization+ ? VIZ_MIN_HEIGHT+ : outputHeightForShape({ rowCount: (result.first_page ?? []).length })+ if (target !== null && (typeof attributes.height !== 'number' || attributes.height < target)) {+ updateAttributes({ height: target })}- hadResultRef.current = hasResult// oxlint-disable-next-line exhaustive-deps- }, [dataframeResult])+ }, [result, attributes.runId])if (!expanded) {return nulldiff --git a/frontend/src/scenes/notebooks/Nodes/notebookNodeOutputHeight.test.ts b/frontend/src/scenes/notebooks/Nodes/notebookNodeOutputHeight.test.tsnew file mode 100644index 000000000000..e43cbcd1b1ab--- /dev/null+++ b/frontend/src/scenes/notebooks/Nodes/notebookNodeOutputHeight.test.ts@@ -0,0 +1,34 @@+import { countTextLines, outputHeightForShape } from './notebookNodeOutputHeight'++describe('notebookNodeOutputHeight', () => {+ it('returns null when there is nothing to show', () => {+ expect(outputHeightForShape({})).toBeNull()+ expect(outputHeightForShape({ rowCount: 0, textLines: 0, hasMedia: false })).toBeNull()+ })++ it('keeps a single-value result compact', () => {+ const oneRow = outputHeightForShape({ rowCount: 1 })+ const fiveRows = outputHeightForShape({ rowCount: 5 })+ expect(oneRow).toBeLessThan(fiveRows!)+ expect(oneRow).toBeLessThan(250)+ })++ it('grows with the row count and caps out', () => {+ const heights = [1, 5, 10, 50, 1000].map((rowCount) => outputHeightForShape({ rowCount })!)+ expect(heights).toEqual([...heights].sort((a, b) => a - b))+ expect(heights.at(-1)).toEqual(outputHeightForShape({ rowCount: 50 }))+ })++ it('caps long text output so a traceback cannot swallow the notebook', () => {+ expect(outputHeightForShape({ textLines: 500 })).toEqual(outputHeightForShape({ textLines: 1000 }))+ })++ it('leaves room for a figure', () => {+ expect(outputHeightForShape({ hasMedia: true })!).toBeGreaterThan(outputHeightForShape({ textLines: 1 })!)+ })++ it('counts text lines across streams, ignoring a trailing newline', () => {+ expect(countTextLines('a\nb\n', 'c')).toEqual(3)+ expect(countTextLines(null, undefined, '')).toEqual(0)+ })+})diff --git a/frontend/src/scenes/notebooks/Nodes/notebookNodeOutputHeight.ts b/frontend/src/scenes/notebooks/Nodes/notebookNodeOutputHeight.tsnew file mode 100644index 000000000000..116bc43ca43f--- /dev/null+++ b/frontend/src/scenes/notebooks/Nodes/notebookNodeOutputHeight.ts@@ -0,0 +1,52 @@+// Height for a SQL/Python V2 cell once its output lands. The default node height only fits a+// couple of table rows, but a scalar result doesn't need a tall cell either — so size to what+// actually came back and cap it, instead of snapping every result to one large default.++/** Tab bar, dataframe-name footer, and the padding around the output area. */+const NODE_CHROME_HEIGHT = 80+/** Table header plus the pagination bar under it. */+const TABLE_CHROME_HEIGHT = 68+const ROW_HEIGHT = 28+const TEXT_LINE_HEIGHT = 18+/** Beyond this the text scrolls — a long traceback shouldn't swallow the notebook. */+const MAX_TEXT_LINES = 12+/** Enough for a default-size matplotlib figure. */+const MEDIA_HEIGHT = 300+const MIN_OUTPUT_HEIGHT = 160+const MAX_OUTPUT_HEIGHT = 460++export type NotebookNodeOutputShape = {+ /** Rows in the returned page, not the total row count — only the page is rendered. */+ rowCount?: number+ textLines?: number+ hasMedia?: boolean+}++export const countTextLines = (...texts: (string | null | undefined)[]): number =>+ texts.reduce((lines: number, text) => lines + (text ? text.replace(/\n$/, '').split('\n').length : 0), 0)++/**+ * Height that fits the given output, clamped so a single value stays compact and a large+ * result grows to a readable — but still bounded — size. Returns null when there's nothing+ * to show, so callers leave the node's height alone.+ */+export const outputHeightForShape = ({+ rowCount = 0,+ textLines = 0,+ hasMedia = false,+}: NotebookNodeOutputShape): number | null => {+ let content = 0+ if (rowCount > 0) {+ content += TABLE_CHROME_HEIGHT + rowCount * ROW_HEIGHT+ }+ if (textLines > 0) {+ content += Math.min(textLines, MAX_TEXT_LINES) * TEXT_LINE_HEIGHT+ }+ if (hasMedia) {+ content += MEDIA_HEIGHT+ }+ if (content === 0) {+ return null+ }+ return Math.min(MAX_OUTPUT_HEIGHT, Math.max(MIN_OUTPUT_HEIGHT, NODE_CHROME_HEIGHT + content))+}