: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): share one markdown parse across collectors (#95652)
Sinan Kucukkoseler846253e750ae
diff --git a/frontend/src/scenes/notebooks/Nodes/notebookNodeContent.test.ts b/frontend/src/scenes/notebooks/Nodes/notebookNodeContent.test.tsindex 661eca878e61..dde9f3bf4d4d 100644--- a/frontend/src/scenes/notebooks/Nodes/notebookNodeContent.test.ts+++ b/frontend/src/scenes/notebooks/Nodes/notebookNodeContent.test.ts@@ -1,3 +1,5 @@+import * as markdownNotebookParser from 'lib/components/MarkdownNotebook/markdown'+import { buildMarkdownNotebookContent, serializeMarkdownNotebookComponent } from '../Notebook/markdownNotebookV2'import { NotebookNodeType } from '../types'import {@@ -7,6 +9,10 @@ import {} from './notebookNodeContent'describe('buildNotebookDependencyGraph', () => {+ afterEach(() => {+ jest.restoreAllMocks()+ })+const sqlV2Node = (nodeId: string, returnVariable: string, code: string): Record<string, unknown> => ({type: NotebookNodeType.SQLV2,attrs: { nodeId, returnVariable, code },@@ -173,4 +179,56 @@ describe('buildNotebookDependencyGraph', () => {expect(graph.downstreamUsageByNode['a'].df1.map((usage) => usage.nodeId)).toEqual(['b'])expect(graph.upstreamSourcesByNode['b'].df1.nodeId).toEqual('a')})++ it('parses the markdown once for two collectors reading the same content', () => {+ // The parse is cached on the content node so collectors share one parse per edit. The+ // cell assertions alone would still pass with the cache gone, so count the parses too:+ // that is the per-keystroke work this guards. A cache keyed by anything other than the+ // node would also hand the second collector the wrong cells.+ const markdown = [+ serializeMarkdownNotebookComponent('SQLV2', {+ nodeId: 'a',+ returnVariable: 'sql_df',+ code: 'select id from events',+ }),+ serializeMarkdownNotebookComponent('PythonV2', {+ nodeId: 'py',+ returnVariable: 'new_events',+ code: 'new_events = sql_df.head()',+ }),+ ].join('\n\n')+ const content = buildMarkdownNotebookContent(markdown)+ const parseSpy = jest.spyOn(markdownNotebookParser, 'parseMarkdownNotebook')+ // Populate the cache from one collector, then read it from another.+ expect(collectNotebookFrameNodes(content).map((frame) => frame.name)).toEqual(['sql_df', 'new_events'])+ const graph = buildNotebookDependencyGraph(content)+ expect(graph.downstreamUsageByNode['a'].sql_df.map((usage) => usage.nodeId)).toEqual(['py'])+ expect(parseSpy).toHaveBeenCalledTimes(1)+ })++ it('does not serve one content its parse for a later content with different markdown', () => {+ // Each edit builds a new content node, so the cache must key on it and stay fresh. A+ // cache that leaked the first parse would report the first document's cells forever.+ const graphA = buildNotebookDependencyGraph(+ buildMarkdownNotebookContent(+ serializeMarkdownNotebookComponent('SQLV2', {+ nodeId: 'a',+ returnVariable: 'df_a',+ code: 'select id from events',+ })+ )+ )+ const graphB = buildNotebookDependencyGraph(+ buildMarkdownNotebookContent(+ serializeMarkdownNotebookComponent('SQLV2', {+ nodeId: 'b',+ returnVariable: 'df_b',+ code: 'select id from persons',+ })+ )+ )+ expect(Object.keys(graphA.nodesById)).toEqual(['a'])+ expect(Object.keys(graphB.nodesById)).toEqual(['b'])+ expect(graphB.nodesById['b'].exports).toEqual(['df_b'])+ })})diff --git a/frontend/src/scenes/notebooks/Nodes/notebookNodeContent.ts b/frontend/src/scenes/notebooks/Nodes/notebookNodeContent.tsindex 5068e4722fdb..aecee1a990b3 100644--- a/frontend/src/scenes/notebooks/Nodes/notebookNodeContent.ts+++ b/frontend/src/scenes/notebooks/Nodes/notebookNodeContent.ts@@ -328,6 +328,24 @@ 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.+// Each collector that expands a markdown notebook parses the same markdown string, so one edit+// parses the whole document once per collector. Cache the parse on the node object. Every+// collector in a recompute reads the same content node, so they share one parse. The next edit+// builds a new content node, so the old entry drops with it — the parse never goes stale.+const parsedMarkdownNotebookByNode = new WeakMap<object, ReturnType<typeof parseMarkdownNotebook>>()++const parseMarkdownNotebookNodeCached = (node: {+ attrs: { markdown: string }+}): ReturnType<typeof parseMarkdownNotebook> => {+ const cached = parsedMarkdownNotebookByNode.get(node)+ if (cached) {+ return cached+ }+ const parsed = parseMarkdownNotebook(node.attrs.markdown)+ parsedMarkdownNotebookByNode.set(node, parsed)+ return parsed+}+const expandMarkdownNotebookNodesOfTypes = (node: any, nodeTypes: NotebookNodeType[]): JSONContent[] => {if (typeof node?.attrs?.markdown !== 'string') {return []@@ -342,7 +360,7 @@ const expandMarkdownNotebookNodesOfTypes = (node: any, nodeTypes: NotebookNodeTynodeTypeByTag.set(tag, nodeType)}}- return parseMarkdownNotebook(node.attrs.markdown).nodes.flatMap((block): JSONContent[] => {+ return parseMarkdownNotebookNodeCached(node).nodes.flatMap((block): JSONContent[] => {if (block.type !== 'component') {return []}