: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
perf(notebooks): rebuild the dependency graph on run, not per keystroke (#96326)
Sinan Kucukkoselerfd02d0ea482d
diff --git a/frontend/src/scenes/notebooks/Notebook/notebookDependencyGraphRunState.test.ts b/frontend/src/scenes/notebooks/Notebook/notebookDependencyGraphRunState.test.tsnew file mode 100644index 000000000000..7283ccaaa35f--- /dev/null+++ b/frontend/src/scenes/notebooks/Notebook/notebookDependencyGraphRunState.test.ts@@ -0,0 +1,104 @@+import { expectLogic } from 'kea-test-utils'++import api from 'lib/api'++import { useMocks } from '~/mocks/jest'+import { initKeaTests } from '~/test/init'+import { AccessControlLevel } from '~/types'++import { NotebookType } from '../types'+import { buildMarkdownNotebookContent } from './markdownNotebookV2'+import { notebookLogic } from './notebookLogic'+import { notebookNodeStalenessLogic } from './notebookNodeStalenessLogic'++jest.mock('./migrations/migrate', () => {+ const actual = jest.requireActual('./migrations/migrate')+ return { ...actual, migrate: jest.fn(async (notebook: unknown) => notebook) }+})++const SHORT_ID = 'dep-graph-run-state'++// `a` exports sql_df; `b` reads it, so the loaded notebook has one edge a -> b.+const LOADED_MARKDOWN = [+ '<SQLV2 nodeId="a" returnVariable="sql_df" code="select id from events" />',+ '<SQLV2 nodeId="b" returnVariable="joined" code="select * from sql_df" />',+].join('\n\n')++// The same two cells, but `b` no longer reads sql_df, so a live graph would drop the edge.+const EDITED_MARKDOWN = [+ '<SQLV2 nodeId="a" returnVariable="sql_df" code="select id from events" />',+ '<SQLV2 nodeId="b" returnVariable="joined" code="select 1" />',+].join('\n\n')++const notebookFixture: NotebookType = {+ id: 'notebook-id',+ short_id: SHORT_ID,+ title: 'Dependency graph run state',+ content: buildMarkdownNotebookContent(LOADED_MARKDOWN),+ text_content: '',+ version: 1,+ is_template: false,+ user_access_level: AccessControlLevel.Editor,+ created_at: '2025-01-01T00:00:00Z',+ created_by: null,+ last_modified_at: '2025-01-01T00:00:00Z',+ last_modified_by: null,+ variables: [],+}++describe('notebook dependency graph run state', () => {+ let logic: ReturnType<typeof notebookLogic.build>+ let stalenessLogic: ReturnType<typeof notebookNodeStalenessLogic.build>++ beforeEach(() => {+ localStorage.clear()+ useMocks({+ get: {+ [`/api/projects/@current/notebooks/${SHORT_ID}/`]: () => [200, notebookFixture],+ [`/api/projects/:project_id/notebooks/${SHORT_ID}/`]: () => [200, notebookFixture],+ [`/api/projects/:project_id/notebooks/${SHORT_ID}/kernel/status/`]: () => [200, { backend: null }],+ },+ })+ initKeaTests()+ jest.spyOn(api.notebooks, 'collabStream').mockResolvedValue(undefined as any)+ jest.spyOn(api.notebooks, 'update').mockImplementation(async (_shortId: string, data: Record<string, any>) => ({+ ...notebookFixture,+ ...data,+ }))++ stalenessLogic = notebookNodeStalenessLogic({ shortId: SHORT_ID })+ stalenessLogic.mount()+ logic = notebookLogic({ shortId: SHORT_ID, mode: 'notebook', cachedNotebook: notebookFixture })+ logic.mount()+ logic.actions.loadNotebook()+ })++ afterEach(() => {+ logic?.unmount()+ stalenessLogic?.unmount()+ jest.restoreAllMocks()+ })++ const edgeTargets = (): string[] =>+ logic.values.dependencyGraph.downstreamUsageByNode['a']?.sql_df?.map((usage) => usage.nodeId) ?? []++ it('freezes the dependency graph to run state: seeded on load, held on edit, refreshed on run', async () => {+ await expectLogic(logic).toFinishAllListeners()+ expect(edgeTargets()).toEqual(['b'])++ // The edit drops b's reference; the edge must hold until a run, or the graph tracks live text.+ logic.actions.setLocalContent(buildMarkdownNotebookContent(EDITED_MARKDOWN))+ await expectLogic(logic).toFinishAllListeners()+ expect(edgeTargets()).toEqual(['b'])++ // A failed run carries no executed document, so it must not advance the snapshot.+ stalenessLogic.actions.nodeRunFinished('b', 'failed', null)+ await expectLogic(logic).toFinishAllListeners()+ expect(edgeTargets()).toEqual(['b'])++ // A successful run reports the executed document, so the snapshot refreshes and the edge drops.+ stalenessLogic.actions.nodeRunFinished('b', 'done', buildMarkdownNotebookContent(EDITED_MARKDOWN))+ await expectLogic(logic).toFinishAllListeners()+ expect(edgeTargets()).toEqual([])+ })+})diff --git a/frontend/src/scenes/notebooks/Notebook/notebookLogic.ts b/frontend/src/scenes/notebooks/Notebook/notebookLogic.tsindex 370d22f5848d..7e3a598bfd5b 100644--- a/frontend/src/scenes/notebooks/Notebook/notebookLogic.ts+++ b/frontend/src/scenes/notebooks/Notebook/notebookLogic.ts@@ -107,7 +107,7 @@ import { buildNotebookOpenedEvent } from './notebookAnalytics'import { shouldWarnBeforeLeavingNotebook } from './notebookBeforeUnload'import { notebookKernelInfoLogic } from './notebookKernelInfoLogic'import type { NotebookKernelInfo } from './notebookKernelInfoLogic'-import { notebookNodeStalenessLogic } from './notebookNodeStalenessLogic'+import { notebookNodeStalenessLogic, NotebookNodeRunTerminalStatus } from './notebookNodeStalenessLogic'import {NOTEBOOK_AI_PRESENCE_CLIENT_ID,NOTEBOOK_AI_PRESENCE_NAME,@@ -310,6 +310,7 @@ export interface notebookLogicValues {canvasFiltersOverride: anycontainerSize: 'medium' | 'small'content: JSONContent+ contentAtLastRun: JSONContent | nulldependencyGraph: NotebookDependencyGraphduckSqlNodeIndices: Map<string, number>duckSqlNodeSummaries: DuckSqlNodeSummary[]@@ -381,6 +382,15 @@ export interface notebookLogicActions {callback: ((event: { sent: boolean }) => void) | undefinedcontext: Record<string, any> | null} // commentsLogic+ nodeRunFinished: (+ nodeId: string,+ status: NotebookNodeRunTerminalStatus,+ content: JSONContent | null+ ) => {+ content: JSONContent | null+ nodeId: string+ status: NotebookNodeRunTerminalStatus+ } // notebookNodeStalenessLogicsetShowVariables: (showVariables: boolean | null) => {showVariables: boolean | null} // notebookSettingsLogic@@ -577,6 +587,9 @@ export interface notebookLogicActions {setContainerSize: (containerSize: 'medium' | 'small') => {containerSize: 'medium' | 'small'}+ setContentAtLastRun: (content: JSONContent | null) => {+ content: JSONContent | null+ }setEditable: (editable: boolean) => {editable: boolean}@@ -688,7 +701,7 @@ export interface notebookLogicMeta {hogqlSqlNodeSummaries: (content: JSONContent) => HogqlSqlNodeSummary[]sqlV2NodeSummaries: (content: JSONContent) => SqlV2NodeSummary[]frameNodeSummaries: (content: JSONContent) => NotebookFrameNodeSummary[]- dependencyGraph: (content: JSONContent) => NotebookDependencyGraph+ dependencyGraph: (contentAtLastRun: JSONContent | null) => NotebookDependencyGraphpythonNodeIndices: (content: JSONContent) => Map<string, number>sqlNodeIndices: (content: JSONContent) => Map<string, number>duckSqlNodeIndices: (content: JSONContent) => Map<string, number>@@ -767,6 +780,9 @@ export const notebookLogic = kea<notebookLogicType>([item_id: props.shortId,}),['setItemContext', 'maybeLoadComments'],+ // Connected so the dependency-graph snapshot can refresh when a cell run finishes.+ notebookNodeStalenessLogic({ shortId: props.shortId }),+ ['nodeRunFinished'],],})),actions({@@ -826,6 +842,7 @@ export const notebookLogic = kea<notebookLogicType>([}),setShowHistory: (showHistory: boolean) => ({ showHistory }),setContainerSize: (containerSize: 'small' | 'medium') => ({ containerSize }),+ setContentAtLastRun: (content: JSONContent | null) => ({ content }),insertComment: (context: Record<string, any>) => ({ context }),selectComment: (itemContextId: string) => ({ itemContextId }),openShareModal: true,@@ -849,6 +866,13 @@ export const notebookLogic = kea<notebookLogicType>([clearLocalContent: () => null,},],+ // The document as of the last run: a cell output exists only after its cell has run.+ contentAtLastRun: [+ null as JSONContent | null,+ {+ setContentAtLastRun: (_, { content }) => content,+ },+ ],// Local edits ahead of the saved notebook; null means "nothing edited yet, use the server's".localVariables: [null as NotebookVariable[] | null,@@ -1441,7 +1465,11 @@ export const notebookLogic = kea<notebookLogicType>([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)],+ dependencyGraph: [+ // Keyed on the last-run snapshot, not live content, so typing does not rebuild it.+ (s) => [s.contentAtLastRun],+ (contentAtLastRun: JSONContent | null) => buildNotebookDependencyGraph(contentAtLastRun),+ ],pythonNodeIndices: [(s) => [s.content],@@ -2087,6 +2115,9 @@ export const notebookLogic = kea<notebookLogicType>([actions.maybeLoadComments()actions.processPendingMarkdownStreamEvents()+ // Seed the snapshot so an opened notebook shows its links before any rerun.+ actions.setContentAtLastRun(values.content)+// `notebook opened` is a human/browser open — capture once per mount. This listener// also runs on every polling refresh (scheduleNotebookRefresh above), so gate on a// per-instance flag; the flag resets on remount, so revisiting counts as a new open.@@ -2102,6 +2133,15 @@ export const notebookLogic = kea<notebookLogicType>([actions.processPendingMarkdownStreamEvents()},+ // Only a successful run carries the executed document; failed and interrupted runs pass+ // null and leave the snapshot, so the links keep matching what the kernel last ran. This is+ // the document the staleness logic records too, so the two stay consistent.+ nodeRunFinished: ({ content }) => {+ if (content) {+ actions.setContentAtLastRun(content)+ }+ },+exportJSON: () => {const file = new File([JSON.stringify(values.content, null, 2)],