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): mark dependent cells stale and re-run the chain (#70176)

Sinan Kucukkoseler337d39d768ef
diff --git a/frontend/src/scenes/notebooks/Nodes/NotebookNodePythonV2.tsx b/frontend/src/scenes/notebooks/Nodes/NotebookNodePythonV2.tsx
index 2c4fe7955da7..7a14e5215d28 100644
--- a/frontend/src/scenes/notebooks/Nodes/NotebookNodePythonV2.tsx
+++ b/frontend/src/scenes/notebooks/Nodes/NotebookNodePythonV2.tsx
@@ -10,6 +10,8 @@ import { createPostHogWidgetNode } from 'scenes/notebooks/Nodes/NodeWrapper'
import { NotebookNodeAttributeProperties, NotebookNodeProps, NotebookNodeType } from '../types'
import { NotebookDataframeTable } from './components/NotebookDataframeTable'
+import { NotebookRunDownstreamBanner } from './components/NotebookRunDownstreamBanner'
+import { NotebookStaleCellBanner } from './components/NotebookStaleCellBanner'
import { notebookNodeLogic } from './notebookNodeLogic'
import type { NotebookNodeSQLV2Result } from './NotebookNodeSQLV2'
import { SQL_V2_DEFAULT_PAGE_SIZE, collectSqlV2Refs, notebookNodeSQLV2Logic } from './notebookNodeSQLV2Logic'
@@ -51,9 +53,21 @@ const Component = ({
updateAttributes,
runId: attributes.runId ?? null,
hasResult: !!attributes.result,
+ getContent: () => notebookLogic.values.content ?? null,
})
- const { isRunning, runError, page, pageSize, pageResult, pageLoading, operationBlockReason } = useValues(dataLogic)
- const { setPage, setPageSize } = useActions(dataLogic)
+ const {
+ isRunning,
+ runError,
+ page,
+ pageSize,
+ pageResult,
+ pageLoading,
+ operationBlockReason,
+ isStale,
+ isChainRunning,
+ staleDownstreamCount,
+ } = useValues(dataLogic)
+ const { setPage, setPageSize, runStaleChain } = useActions(dataLogic)
const result = attributes.result ?? null
const dataframeResult = useMemo(() => {
@@ -83,6 +97,19 @@ const Component = ({
onMouseDown={(event) => event.stopPropagation()}
onDragStart={(event) => event.stopPropagation()}
>
+ {isStale ? (
+ <div className="shrink-0" onClick={(event) => event.stopPropagation()}>
+ <NotebookStaleCellBanner />
+ </div>
+ ) : staleDownstreamCount > 0 && !isChainRunning ? (
+ <div className="shrink-0" onClick={(event) => event.stopPropagation()}>
+ <NotebookRunDownstreamBanner
+ count={staleDownstreamCount}
+ onRun={() => runStaleChain(notebookLogic.values.content ?? null, nodeId)}
+ disabledReason={isRunning ? 'This cell is running' : (operationBlockReason ?? undefined)}
+ />
+ </div>
+ ) : null}
{hasStreamOutput ? (
<div className="shrink-0 space-y-2 px-2 pt-1" onClick={(event) => event.stopPropagation()}>
{result?.stdout ? (
@@ -169,6 +196,7 @@ const Settings = ({
updateAttributes,
runId: attributes.runId ?? null,
hasResult: !!attributes.result,
+ getContent: () => notebookLogic.values.content ?? null,
})
const { isRunning, isInterrupting, operationBlockReason } = useValues(dataLogic)
const { runQuery, interruptRun } = useActions(dataLogic)
diff --git a/frontend/src/scenes/notebooks/Nodes/NotebookNodeSQLV2.tsx b/frontend/src/scenes/notebooks/Nodes/NotebookNodeSQLV2.tsx
index 8d6f0a84af83..02756b35a24e 100644
--- a/frontend/src/scenes/notebooks/Nodes/NotebookNodeSQLV2.tsx
+++ b/frontend/src/scenes/notebooks/Nodes/NotebookNodeSQLV2.tsx
@@ -14,7 +14,9 @@ import { ChartDisplayType } from '~/types'
import { NotebookNodeAttributeProperties, NotebookNodeProps, NotebookNodeType } from '../types'
import { NotebookDataframeTable } from './components/NotebookDataframeTable'
import { getCellLabel } from './components/NotebookNodeTitle'
+import { NotebookRunDownstreamBanner } from './components/NotebookRunDownstreamBanner'
import { NotebookCodeSQLEditorSettings } from './components/NotebookSQLEditor'
+import { NotebookStaleCellBanner } from './components/NotebookStaleCellBanner'
import { notebookNodeLogic } from './notebookNodeLogic'
import { SQL_V2_DEFAULT_PAGE_SIZE, collectSqlV2Refs, notebookNodeSQLV2Logic } from './notebookNodeSQLV2Logic'
import { NotebookDataframeResult } from './pythonExecution'
@@ -86,9 +88,21 @@ const Component = ({
updateAttributes,
runId: attributes.runId ?? null,
hasResult: !!attributes.result,
+ getContent: () => notebookLogic.values.content ?? null,
})
- const { isRunning, runError, page, pageSize, pageResult, pageLoading, operationBlockReason } = useValues(dataLogic)
- const { setPage, setPageSize } = useActions(dataLogic)
+ const {
+ isRunning,
+ runError,
+ page,
+ pageSize,
+ pageResult,
+ pageLoading,
+ operationBlockReason,
+ isStale,
+ isChainRunning,
+ staleDownstreamCount,
+ } = useValues(dataLogic)
+ const { setPage, setPageSize, runStaleChain } = useActions(dataLogic)
const usageLabel = (nodeType: NotebookNodeType, nodeIndex: number | undefined, title: string): string =>
title.trim() || getCellLabel(nodeIndex, nodeType) || 'SQL'
@@ -133,6 +147,19 @@ const Component = ({
onMouseDown={(event) => event.stopPropagation()}
onDragStart={(event) => event.stopPropagation()}
>
+ {isStale ? (
+ <div className="shrink-0" onClick={(event) => event.stopPropagation()}>
+ <NotebookStaleCellBanner />
+ </div>
+ ) : staleDownstreamCount > 0 && !isChainRunning ? (
+ <div className="shrink-0" onClick={(event) => event.stopPropagation()}>
+ <NotebookRunDownstreamBanner
+ count={staleDownstreamCount}
+ onRun={() => runStaleChain(notebookLogic.values.content ?? null, nodeId)}
+ disabledReason={isRunning ? 'This cell is running' : (operationBlockReason ?? undefined)}
+ />
+ </div>
+ ) : null}
{runError ? (
<div className="p-2 text-xs font-mono text-danger whitespace-pre-wrap">{runError}</div>
) : dataframeResult && cachedResults ? (
@@ -262,6 +289,7 @@ const Settings = ({
updateAttributes,
runId: attributes.runId ?? null,
hasResult: !!attributes.result,
+ getContent: () => notebookLogic.values.content ?? null,
})
const { isRunning, isInterrupting, operationBlockReason } = useValues(dataLogic)
const { runQuery, interruptRun } = useActions(dataLogic)
diff --git a/frontend/src/scenes/notebooks/Nodes/components/NotebookRunDownstreamBanner.tsx b/frontend/src/scenes/notebooks/Nodes/components/NotebookRunDownstreamBanner.tsx
new file mode 100644
index 000000000000..375aa685d341
--- /dev/null
+++ b/frontend/src/scenes/notebooks/Nodes/components/NotebookRunDownstreamBanner.tsx
@@ -0,0 +1,31 @@
+import { IconInfo } from '@posthog/icons'
+
+import { LemonButton } from 'lib/lemon-ui/LemonButton'
+
+// Journey 10: shown on the cell whose run most recently landed, while any of its downstream
+// cells are still stale. The action re-runs that downstream set in document order via the
+// staleness logic's rooted chain; unrelated stale cells keep their warning but are not run.
+// Accent styling on purpose: this is a nudge to keep results consistent, not an error state.
+export function NotebookRunDownstreamBanner({
+ count,
+ onRun,
+ disabledReason,
+}: {
+ count: number
+ onRun: () => void
+ disabledReason?: string
+}): JSX.Element {
+ return (
+ <div className="mx-2 mt-1 flex items-center gap-2 rounded border border-accent bg-accent-highlight-secondary p-2 text-xs">
+ <LemonButton type="primary" size="xsmall" onClick={onRun} disabledReason={disabledReason}>
+ {count === 1 ? 'Run downstream cell' : `Run downstream cells (${count})`}
+ </LemonButton>
+ <IconInfo className="shrink-0 text-sm text-accent" />
+ <span>
+ {count === 1
+ ? '1 downstream cell may be showing outdated data'
+ : `${count} downstream cells may be showing outdated data`}
+ </span>
+ </div>
+ )
+}
diff --git a/frontend/src/scenes/notebooks/Nodes/components/NotebookStaleCellBanner.tsx b/frontend/src/scenes/notebooks/Nodes/components/NotebookStaleCellBanner.tsx
new file mode 100644
index 000000000000..12aa971677ef
--- /dev/null
+++ b/frontend/src/scenes/notebooks/Nodes/components/NotebookStaleCellBanner.tsx
@@ -0,0 +1,12 @@
+import { LemonBanner } from 'lib/lemon-ui/LemonBanner'
+
+// Journey 10: shown on a V2 cell whose upstream re-ran after it. Identification only: the
+// action to re-run lives on the cell that caused the staleness (NotebookRunDownstreamBanner).
+export function NotebookStaleCellBanner(): JSX.Element {
+ return (
+ <LemonBanner type="warning" className="mx-2 mt-1 p-2 text-xs" hideIcon>
+ These results may be out of date because an upstream cell has re-run. Run this cell to refresh its output
+ data.
+ </LemonBanner>
+ )
+}
diff --git a/frontend/src/scenes/notebooks/Nodes/notebookNodeContent.test.ts b/frontend/src/scenes/notebooks/Nodes/notebookNodeContent.test.ts
index 9f806fe562bb..dda8182ba2f3 100644
--- a/frontend/src/scenes/notebooks/Nodes/notebookNodeContent.test.ts
+++ b/frontend/src/scenes/notebooks/Nodes/notebookNodeContent.test.ts
@@ -1,6 +1,6 @@
import { buildMarkdownNotebookContent, serializeMarkdownNotebookComponent } from '../Notebook/markdownNotebookV2'
import { NotebookNodeType } from '../types'
-import { buildNotebookDependencyGraph } from './notebookNodeContent'
+import { buildNotebookDependencyGraph, extractPythonIdentifiers } from './notebookNodeContent'
describe('buildNotebookDependencyGraph', () => {
const sqlV2Node = (nodeId: string, returnVariable: string, code: string): Record<string, unknown> => ({
@@ -8,6 +8,11 @@ describe('buildNotebookDependencyGraph', () => {
attrs: { nodeId, returnVariable, code },
})
+ const pythonV2Node = (nodeId: string, returnVariable: string, code: string): Record<string, unknown> => ({
+ type: NotebookNodeType.PythonV2,
+ attrs: { nodeId, returnVariable, code },
+ })
+
it('links a SQLV2 node to a downstream SQLV2 node that references it by table name', () => {
// The "Used in" back-links depend on SQLV2 producing an export and its reader listing it as a use.
const content = {
@@ -36,6 +41,53 @@ describe('buildNotebookDependencyGraph', () => {
expect(graph.upstreamSourcesByNode['c'].sql_df.nodeId).toEqual('a')
})
+ it('links PythonV2 cells in both directions (python reads sql, sql joins the python frame)', () => {
+ // Journey 10 staleness walks these edges: without PythonV2 in the graph, running a
+ // SQL cell never marks its Python dependents stale, and vice versa.
+ const content = {
+ type: 'doc',
+ content: [
+ sqlV2Node('a', 'sql_df', 'select id from events'),
+ pythonV2Node('py', 'new_events', 'new_events = sql_df.head(50)'),
+ sqlV2Node('c', 'joined', 'select * from new_events'),
+ ],
+ }
+ const graph = buildNotebookDependencyGraph(content)
+ expect(graph.downstreamUsageByNode['a'].sql_df.map((usage) => usage.nodeId)).toEqual(['py'])
+ expect(graph.upstreamSourcesByNode['py'].sql_df.nodeId).toEqual('a')
+ expect(graph.downstreamUsageByNode['py'].new_events.map((usage) => usage.nodeId)).toEqual(['c'])
+ })
+
+ it('links PythonV2 cells held inside a markdown notebook', () => {
+ // Markdown notebooks are the only V2 surface; without expanding PythonV2 tags the
+ // graph misses every real-world Python cell.
+ 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 graph = buildNotebookDependencyGraph(buildMarkdownNotebookContent(markdown))
+ expect(graph.downstreamUsageByNode['a'].sql_df.map((usage) => usage.nodeId)).toEqual(['py'])
+ })
+
+ it('extractPythonIdentifiers ignores strings, comments, and attribute tails', () => {
+ // A frame name inside a string or after a dot is not a read; matching it would
+ // create a false dependency edge and mark unrelated cells stale.
+ const identifiers = extractPythonIdentifiers(
+ 'result = sql_df.head(10) # other_df is just a comment\nprint("other_df")\nlabel = frame.other_df'
+ )
+ expect(identifiers).toEqual(expect.arrayContaining(['result', 'sql_df', 'print', 'label', 'frame']))
+ expect(identifiers).not.toContain('other_df')
+ expect(identifiers).not.toContain('head')
+ })
+
it('links SQLV2 cells inside a markdown notebook', () => {
// Markdown notebooks hold cells as tags inside one markdown attribute; without
// expanding them the graph is empty and the "Used in" back-links never render.
diff --git a/frontend/src/scenes/notebooks/Nodes/notebookNodeContent.ts b/frontend/src/scenes/notebooks/Nodes/notebookNodeContent.ts
index 592c1e54076f..a8f445dae65a 100644
--- a/frontend/src/scenes/notebooks/Nodes/notebookNodeContent.ts
+++ b/frontend/src/scenes/notebooks/Nodes/notebookNodeContent.ts
@@ -136,6 +136,24 @@ export const extractDuckSqlTables = (sql: string): string[] => {
return Array.from(tableNames.values())
}
+// Rough by design, like the SQL extraction above: identifiers a Python cell's code mentions,
+// with string literals, comments, and attribute tails stripped. Only ever intersected with
+// sibling exports (matchesUsage), so a false positive just marks an extra cell stale.
+export const extractPythonIdentifiers = (code: string): string[] => {
+ const cleaned = (code || '')
+ .replace(/('''[\s\S]*?'''|"""[\s\S]*?""")/g, ' ')
+ .replace(/('(?:[^'\\\n]|\\.)*'|"(?:[^"\\\n]|\\.)*")/g, ' ')
+ .replace(/#.*$/gm, ' ')
+ const identifiers = new Set<string>()
+ const identifierPattern = /(?<![\w.])[A-Za-z_]\w*/g
+ let match = identifierPattern.exec(cleaned)
+ while (match) {
+ identifiers.add(match[0])
+ match = identifierPattern.exec(cleaned)
+ }
+ return Array.from(identifiers)
+}
+
export const normalizeDuckSqlIdentifier = (identifier: string): string => {
return normalizeSqlIdentifier(identifier)
}
@@ -519,6 +537,48 @@ const matchesUsage = (exportName: string, usageName: string, usageNodeType: Note
return exportName === usageName
}
+export type NotebookDependencyDirection = 'upstream' | 'downstream'
+
+/** Transitive closure of a node's dependencies (or dependents), including the start node. */
+export const collectDependencyNodeIds = (
+ dependencyGraph: NotebookDependencyGraph,
+ startNodeId: string,
+ direction: NotebookDependencyDirection
+): Set<string> => {
+ const visited = new Set<string>()
+ if (!startNodeId || !dependencyGraph.nodesById[startNodeId]) {
+ return visited
+ }
+
+ const stack = [startNodeId]
+
+ while (stack.length > 0) {
+ const currentId = stack.pop()
+ if (!currentId || visited.has(currentId)) {
+ continue
+ }
+ visited.add(currentId)
+
+ if (direction === 'upstream') {
+ const sources = Object.values(dependencyGraph.upstreamSourcesByNode[currentId] ?? {})
+ sources.forEach((source) => {
+ if (source.nodeId && !visited.has(source.nodeId)) {
+ stack.push(source.nodeId)
+ }
+ })
+ } else {
+ const downstreamGroups = Object.values(dependencyGraph.downstreamUsageByNode[currentId] ?? {})
+ downstreamGroups.flat().forEach((usage) => {
+ if (usage.nodeId && !visited.has(usage.nodeId)) {
+ stack.push(usage.nodeId)
+ }
+ })
+ }
+ }
+
+ return visited
+}
+
export const buildNotebookDependencyGraph = (content?: JSONContent | null): NotebookDependencyGraph => {
if (!content || typeof content !== 'object') {
return {
@@ -531,6 +591,7 @@ export const buildNotebookDependencyGraph = (content?: JSONContent | null): Note
const nodes: NotebookDependencyNode[] = []
let pythonIndex = 0
+ let pythonV2Index = 0
let duckSqlIndex = 0
let hogqlSqlIndex = 0
let sqlV2Index = 0
@@ -623,8 +684,33 @@ export const buildNotebookDependencyGraph = (content?: JSONContent | null): Note
})
}
+ if (node.type === NotebookNodeType.PythonV2) {
+ const attrs = node.attrs ?? {}
+ pythonV2Index += 1
+ // The returnVariable IS the kernel variable, never disambiguated — the same
+ // last-write-wins semantics as collectPythonKernelNodes.
+ const returnVariable =
+ typeof attrs.returnVariable === 'string' && attrs.returnVariable.trim()
+ ? attrs.returnVariable.trim()
+ : 'df'
+ const code = typeof attrs.code === 'string' ? attrs.code : ''
+ nodes.push({
+ nodeId: attrs.nodeId ?? '',
+ nodeType: NotebookNodeType.PythonV2,
+ nodeIndex: pythonV2Index,
+ title: typeof attrs.title === 'string' ? attrs.title : '',
+ exports: returnVariable ? [returnVariable] : [],
+ uses: extractPythonIdentifiers(code),
+ code,
+ returnVariable,
+ })
+ }
+
if (node.type === NotebookNodeType.MarkdownNotebook) {
+ // Markdown notebooks (the only V2 surface) store cells as component tags, so both
+ // V2 cell types must be expanded or the graph misses every markdown-held cell.
expandMarkdownNotebookSqlV2Nodes(node).forEach(walk)
+ expandMarkdownNotebookNodesOfType(node, NotebookNodeType.PythonV2).forEach(walk)
}
if (Array.isArray(node.content)) {
diff --git a/frontend/src/scenes/notebooks/Nodes/notebookNodeLogic.ts b/frontend/src/scenes/notebooks/Nodes/notebookNodeLogic.ts
index 6ea09064674f..4a85825678f7 100644
--- a/frontend/src/scenes/notebooks/Nodes/notebookNodeLogic.ts
+++ b/frontend/src/scenes/notebooks/Nodes/notebookNodeLogic.ts
@@ -47,6 +47,7 @@ import {
type NotebookDependencyGraph,
type NotebookDependencyNode,
type NotebookDependencyUsage,
+ collectDependencyNodeIds,
extractHogqlPlaceholders,
getUniqueDuckSqlReturnVariable,
getUniqueHogqlReturnVariable,
@@ -245,45 +246,6 @@ const buildHogqlExecutionResult = ({
type DependencyRunDirection = 'upstream' | 'downstream'
-const collectDependencyNodeIds = (
- dependencyGraph: NotebookDependencyGraph,
- startNodeId: string,
- direction: DependencyRunDirection
-): Set<string> => {
- const visited = new Set<string>()
- if (!startNodeId || !dependencyGraph.nodesById[startNodeId]) {
- return visited
- }
-
- const stack = [startNodeId]
-
- while (stack.length > 0) {
- const currentId = stack.pop()
- if (!currentId || visited.has(currentId)) {
- continue
- }
- visited.add(currentId)
-
- if (direction === 'upstream') {
- const sources = Object.values(dependencyGraph.upstreamSourcesByNode[currentId] ?? {})
- sources.forEach((source) => {
- if (source.nodeId && !visited.has(source.nodeId)) {
- stack.push(source.nodeId)
- }
- })
- } else {
- const downstreamGroups = Object.values(dependencyGraph.downstreamUsageByNode[currentId] ?? {})
- downstreamGroups.flat().forEach((usage) => {
- if (usage.nodeId && !visited.has(usage.nodeId)) {
- stack.push(usage.nodeId)
- }
- })
- }
- }
-
- return visited
-}
-
const getDependencyNodesForRun = (
dependencyGraph: NotebookDependencyGraph,
startNodeId: string,
diff --git a/frontend/src/scenes/notebooks/Nodes/notebookNodeSQLV2Logic.ts b/frontend/src/scenes/notebooks/Nodes/notebookNodeSQLV2Logic.ts
index 2f2b6c6fdc85..be1d0ec62e5e 100644
--- a/frontend/src/scenes/notebooks/Nodes/notebookNodeSQLV2Logic.ts
+++ b/frontend/src/scenes/notebooks/Nodes/notebookNodeSQLV2Logic.ts
@@ -17,8 +17,10 @@ import api from 'lib/api'
import { JSONContent } from 'lib/components/RichContentEditor/types'
import { lemonToast } from 'lib/lemon-ui/LemonToast/LemonToast'
+import { notebookNodeStalenessLogic } from '../Notebook/notebookNodeStalenessLogic'
import { NotebookOperation, notebookOperationsLogic } from '../Notebook/notebookOperationsLogic'
-import { collectPythonKernelNodes, collectSqlV2Nodes } from './notebookNodeContent'
+import { NotebookNodeType } from '../types'
+import { buildNotebookDependencyGraph, collectPythonKernelNodes, collectSqlV2Nodes } from './notebookNodeContent'
import { NotebookNodeSQLV2Result } from './NotebookNodeSQLV2'
export type SqlV2RunRef = {
@@ -82,24 +84,58 @@ export interface NotebookNodeSQLV2LogicProps {
runId?: string | null
result?: NotebookNodeSQLV2Result | null
}) => void
+ // The live notebook document, for staleness marking and chain-dispatched runs (Journey 10).
+ getContent?: () => JSONContent | null
}
// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface notebookNodeSQLV2LogicValues {
+ chainQueue: string[] // notebookNodeStalenessLogic
+ isChainRunning: boolean // notebookNodeStalenessLogic
+ lastRunNodeId: string | null // notebookNodeStalenessLogic
+ lastRunStaleDownstreamNodeIds: string[] // notebookNodeStalenessLogic
+ staleNodeIds: Record<string, true> // notebookNodeStalenessLogic
activeOperation: NotebookOperation | null // notebookOperationsLogic
isBusy: boolean // notebookOperationsLogic
isInterrupting: boolean
isRunning: boolean
+ isStale: boolean
operationBlockReason: string | null
page: number
pageLoading: boolean
pageResult: NotebookNodeSQLV2Page | null
pageSize: number
runError: string | null
+ staleDownstreamCount: number
}
// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface notebookNodeSQLV2LogicActions {
+ dispatchChainRun: (nodeId: string) => {
+ nodeId: string
+ } // notebookNodeStalenessLogic
+ nodeRunFinished: (
+ nodeId: string,
+ status: import('../Notebook/notebookNodeStalenessLogic').NotebookNodeRunTerminalStatus,
+ content: JSONContent | null
+ ) => {
+ content: JSONContent | null
+ nodeId: string
+ status: import('../Notebook/notebookNodeStalenessLogic').NotebookNodeRunTerminalStatus
+ } // notebookNodeStalenessLogic
+ registerChainNode: (nodeId: string) => {
+ nodeId: string
+ } // notebookNodeStalenessLogic
+ runStaleChain: (
+ content: JSONContent | null,
+ rootNodeId?: string | null | undefined
+ ) => {
+ content: JSONContent | null
+ rootNodeId: string | null
+ } // notebookNodeStalenessLogic
+ unregisterChainNode: (nodeId: string) => {
+ nodeId: string
+ } // notebookNodeStalenessLogic
finishNodeOperations: (nodeId: string) => {
nodeId: string
} // notebookOperationsLogic
@@ -167,10 +203,17 @@ export const notebookNodeSQLV2Logic = kea<notebookNodeSQLV2LogicType>([
props({} as NotebookNodeSQLV2LogicProps),
key((props) => props.nodeId),
connect((props: NotebookNodeSQLV2LogicProps) => ({
- values: [notebookOperationsLogic({ shortId: props.notebookShortId }), ['activeOperation', 'isBusy']],
+ values: [
+ notebookOperationsLogic({ shortId: props.notebookShortId }),
+ ['activeOperation', 'isBusy'],
+ notebookNodeStalenessLogic({ shortId: props.notebookShortId }),
+ ['staleNodeIds', 'chainQueue', 'isChainRunning', 'lastRunNodeId', 'lastRunStaleDownstreamNodeIds'],
+ ],
actions: [
notebookOperationsLogic({ shortId: props.notebookShortId }),
['startOperation', 'finishOperation', 'finishNodeOperations'],
+ notebookNodeStalenessLogic({ shortId: props.notebookShortId }),
+ ['nodeRunFinished', 'dispatchChainRun', 'runStaleChain', 'registerChainNode', 'unregisterChainNode'],
],
})),
actions({
@@ -321,6 +364,7 @@ export const notebookNodeSQLV2Logic = kea<notebookNodeSQLV2LogicType>([
if (!code.trim()) {
actions.setRunError('Nothing to run — type some code first.')
actions.setIsRunning(false)
+ actions.nodeRunFinished(props.nodeId, 'failed', null)
return
}
// The run button is disabled while the notebook is busy; this guards Cmd+Enter
@@ -328,6 +372,7 @@ export const notebookNodeSQLV2Logic = kea<notebookNodeSQLV2LogicType>([
if (values.isBusy && values.activeOperation?.nodeId !== props.nodeId) {
lemonToast.info('Another operation is running in this notebook — wait for it to finish.')
actions.setIsRunning(false)
+ actions.nodeRunFinished(props.nodeId, 'failed', null)
return
}
actions.startOperation(runOperation)
@@ -351,8 +396,27 @@ export const notebookNodeSQLV2Logic = kea<notebookNodeSQLV2LogicType>([
actions.setRunError(error instanceof Error ? error.message : 'Failed to run query')
actions.setIsRunning(false)
actions.finishOperation(runOperation.id)
+ actions.nodeRunFinished(props.nodeId, 'failed', null)
}
},
+ // A chain-dispatched run (Journey 10): only the matching node acts; it rebuilds its
+ // code and refs from the live document, exactly like its own Run button would.
+ dispatchChainRun: ({ nodeId }) => {
+ if (nodeId !== props.nodeId) {
+ return
+ }
+ const content = props.getContent?.() ?? null
+ const self = content ? buildNotebookDependencyGraph(content).nodesById[props.nodeId] : null
+ if (!content || !self) {
+ actions.nodeRunFinished(props.nodeId, 'failed', null)
+ return
+ }
+ const opts: RunQueryOptions =
+ self.nodeType === NotebookNodeType.PythonV2
+ ? { nodeType: 'python', outputName: self.returnVariable }
+ : {}
+ actions.runQuery(self.code ?? '', collectSqlV2Refs(content, props.nodeId), opts)
+ },
startPolling: ({ runId }) => {
// Idempotent re-register: also covers a remount resuming a persisted in-flight run.
actions.startOperation(runOperation)
@@ -373,6 +437,7 @@ export const notebookNodeSQLV2Logic = kea<notebookNodeSQLV2LogicType>([
if (cache.pollAttempts > MAX_POLL_ATTEMPTS) {
actions.setRunError('Timed out waiting for result')
actions.stopPolling()
+ actions.nodeRunFinished(props.nodeId, 'failed', null)
return
}
cache.pollInFlight = true
@@ -400,6 +465,9 @@ export const notebookNodeSQLV2Logic = kea<notebookNodeSQLV2LogicType>([
// A fresh envelope replaces whatever page the user had drilled into.
actions.resetPaging()
actions.stopPolling()
+ // Downstream cells now derive from outdated data — mark them stale
+ // against the document as it stands now (Journey 10).
+ actions.nodeRunFinished(props.nodeId, 'done', props.getContent?.() ?? null)
} else if (status === 'interrupted') {
// A user-requested stop: the envelope still carries whatever stdout,
// stderr, and figures the cell produced before the interrupt landed.
@@ -407,9 +475,11 @@ export const notebookNodeSQLV2Logic = kea<notebookNodeSQLV2LogicType>([
actions.setRunError(error ?? 'Run interrupted.')
actions.resetPaging()
actions.stopPolling()
+ actions.nodeRunFinished(props.nodeId, 'interrupted', null)
} else if (status === 'failed') {
actions.setRunError(error ?? 'Run failed')
actions.stopPolling()
+ actions.nodeRunFinished(props.nodeId, 'failed', null)
}
// 'running' → keep polling
} catch (error) {
@@ -418,6 +488,7 @@ export const notebookNodeSQLV2Logic = kea<notebookNodeSQLV2LogicType>([
}
actions.setRunError(error instanceof Error ? error.message : 'Failed to fetch result')
actions.stopPolling()
+ actions.nodeRunFinished(props.nodeId, 'failed', null)
} finally {
cache.pollInFlight = false
}
@@ -458,16 +529,36 @@ export const notebookNodeSQLV2Logic = kea<notebookNodeSQLV2LogicType>([
? 'Another operation is running in this notebook'
: null,
],
+ // An upstream cell's run landed after this cell last ran (Journey 10).
+ isStale: [
+ (s) => [s.staleNodeIds],
+ (staleNodeIds: Record<string, true>): boolean => !!staleNodeIds[props.nodeId],
+ ],
+ // Non-zero only on the cell whose run most recently landed: how many of its
+ // downstream cells are still stale. Drives the "run downstream cells" button.
+ staleDownstreamCount: [
+ (s) => [s.lastRunNodeId, s.lastRunStaleDownstreamNodeIds],
+ (lastRunNodeId: string | null, lastRunStaleDownstreamNodeIds: string[]): number =>
+ lastRunNodeId === props.nodeId ? lastRunStaleDownstreamNodeIds.length : 0,
+ ],
})),
afterMount(({ props, actions }) => {
+ // Only registered cells are eligible for chain dispatch — a dispatch to an unmounted
+ // cell would be picked up by nobody and wedge the chain.
+ actions.registerChainNode(props.nodeId)
// Recover after a reload/remount: a persisted runId with no result means the run may still be
// in flight or already finished — poll to catch up rather than lose the result.
if (props.runId && !props.hasResult) {
actions.startPolling(props.runId)
}
}),
- beforeUnmount(({ props, actions }) => {
+ beforeUnmount(({ props, actions, values }) => {
+ actions.unregisterChainNode(props.nodeId)
// A deleted or unmounted cell must never leave the notebook wedged as busy.
actions.finishNodeOperations(props.nodeId)
+ // Nor leave a stale-cell chain waiting forever on a run that can no longer report.
+ if (values.chainQueue[0] === props.nodeId) {
+ actions.nodeRunFinished(props.nodeId, 'failed', null)
+ }
}),
])
diff --git a/frontend/src/scenes/notebooks/Notebook/notebookNodeStalenessLogic.test.ts b/frontend/src/scenes/notebooks/Notebook/notebookNodeStalenessLogic.test.ts
new file mode 100644
index 000000000000..565e7e7ef71b
--- /dev/null
+++ b/frontend/src/scenes/notebooks/Notebook/notebookNodeStalenessLogic.test.ts
@@ -0,0 +1,186 @@
+import { expectLogic } from 'kea-test-utils'
+
+import api from 'lib/api'
+import { JSONContent } from 'lib/components/RichContentEditor/types'
+
+import { initKeaTests } from '~/test/init'
+
+import { notebookNodeSQLV2Logic } from '../Nodes/notebookNodeSQLV2Logic'
+import { NotebookNodeType } from '../types'
+import { notebookNodeStalenessLogic } from './notebookNodeStalenessLogic'
+
+describe('notebookNodeStalenessLogic', () => {
+ // A three-cell chain plus one independent cell: sql cell `a` exports sql_df, python cell
+ // `b` reads it and exports new_events, sql cell `c` joins new_events, and `x` references
+ // nothing. Document order is dependency order.
+ const content: JSONContent = {
+ type: 'doc',
+ content: [
+ { type: NotebookNodeType.SQLV2, attrs: { nodeId: 'a', returnVariable: 'sql_df', code: 'select 1' } },
+ {
+ type: NotebookNodeType.PythonV2,
+ attrs: { nodeId: 'b', returnVariable: 'new_events', code: 'new_events = sql_df.head()' },
+ },
+ {
+ type: NotebookNodeType.SQLV2,
+ attrs: { nodeId: 'c', returnVariable: 'joined', code: 'select * from new_events' },
+ },
+ { type: NotebookNodeType.SQLV2, attrs: { nodeId: 'x', returnVariable: 'other_df', code: 'select 2' } },
+ ],
+ }
+ const getContent = (): JSONContent => content
+
+ let stalenessLogic: ReturnType<typeof notebookNodeStalenessLogic.build>
+ let nodeLogics: ReturnType<typeof notebookNodeSQLV2Logic.build>[]
+ let runSpy: jest.SpyInstance
+ let resultSpy: jest.SpyInstance
+
+ const mountNode = (nodeId: string): ReturnType<typeof notebookNodeSQLV2Logic.build> => {
+ const logic = notebookNodeSQLV2Logic({
+ nodeId,
+ notebookShortId: 'nb1',
+ updateAttributes: jest.fn(),
+ getContent,
+ })
+ logic.mount()
+ nodeLogics.push(logic)
+ return logic
+ }
+
+ beforeEach(() => {
+ initKeaTests()
+ nodeLogics = []
+ stalenessLogic = notebookNodeStalenessLogic({ shortId: 'nb1' })
+ stalenessLogic.mount()
+ // Each dispatched run gets its own run id (r1, r2, …); results resolve as done unless
+ // a test overrides resultSpy.
+ let runCounter = 0
+ runSpy = jest.spyOn(api.notebooks, 'sqlV2Run').mockImplementation(() => {
+ runCounter += 1
+ return Promise.resolve({ run_id: `r${runCounter}` })
+ })
+ resultSpy = jest.spyOn(api.notebooks, 'sqlV2RunResult').mockResolvedValue({
+ status: 'done',
+ result: { columns: [], first_page: [], row_count: 0 },
+ error: null,
+ })
+ })
+
+ afterEach(() => {
+ nodeLogics.forEach((logic) => logic.unmount())
+ stalenessLogic?.unmount()
+ jest.restoreAllMocks()
+ })
+
+ it('a finished run marks transitive downstream cells stale and clears the finished cell', async () => {
+ mountNode('a')
+ stalenessLogic.actions.markStaleNodeIds(['a'])
+ stalenessLogic.actions.nodeRunFinished('a', 'done', content)
+ await expectLogic(stalenessLogic).toFinishAllListeners()
+ // b reads a directly; c reads b, so staleness must propagate transitively.
+ expect(stalenessLogic.values.staleNodeIds).toEqual({ b: true, c: true })
+ // The finished cell is remembered as the last run with its still-stale downstream,
+ // which is what surfaces the "run downstream cells" button on it.
+ expect(stalenessLogic.values.lastRunNodeId).toEqual('a')
+ expect(stalenessLogic.values.lastRunStaleDownstreamNodeIds).toEqual(['b', 'c'])
+ })
+
+ it('a rooted chain runs only cells downstream of the root, leaving unrelated stale cells flagged', async () => {
+ // The "run downstream cells" button must not run stale cells its run did not affect;
+ // without the root scope, x would be re-run by a chain rooted at a.
+ mountNode('b')
+ mountNode('c')
+ mountNode('x')
+ stalenessLogic.actions.markStaleNodeIds(['b', 'c', 'x'])
+
+ stalenessLogic.actions.runStaleChain(content, 'a')
+ await expectLogic(stalenessLogic).toFinishAllListeners()
+
+ expect(runSpy.mock.calls.map((call) => call[1].node_id)).toEqual(['b', 'c'])
+ expect(stalenessLogic.values.staleNodeIds).toEqual({ x: true })
+ expect(stalenessLogic.values.chainQueue).toEqual([])
+ })
+
+ it('runStaleChain runs stale cells in document order and clears them all', async () => {
+ mountNode('a')
+ mountNode('b')
+ mountNode('c')
+ stalenessLogic.actions.markStaleNodeIds(['b', 'c'])
+
+ stalenessLogic.actions.runStaleChain(content)
+ await expectLogic(stalenessLogic).toFinishAllListeners()
+
+ expect(runSpy).toHaveBeenCalledTimes(2)
+ // b (the python cell) must run before c (the sql cell that joins its output), and
+ // each run must carry the node's own type and output name.
+ expect(runSpy.mock.calls[0][1]).toMatchObject({
+ node_id: 'b',
+ node_type: 'python',
+ output_name: 'new_events',
+ })
+ expect(runSpy.mock.calls[1][1]).toMatchObject({ node_id: 'c' })
+ expect(stalenessLogic.values.staleNodeIds).toEqual({})
+ expect(stalenessLogic.values.chainQueue).toEqual([])
+ })
+
+ it('a chain run picks up cells its own completion marked stale', async () => {
+ // The queue must be rebuilt as the chain advances: a's run marks b and c stale, and
+ // a snapshot taken at chain start would finish "successfully" while they stay flagged.
+ mountNode('a')
+ mountNode('b')
+ mountNode('c')
+ stalenessLogic.actions.markStaleNodeIds(['a'])
+
+ stalenessLogic.actions.runStaleChain(content)
+ await expectLogic(stalenessLogic).toFinishAllListeners()
+
+ expect(runSpy.mock.calls.map((call) => call[1].node_id)).toEqual(['a', 'b', 'c'])
+ expect(stalenessLogic.values.staleNodeIds).toEqual({})
+ expect(stalenessLogic.values.chainQueue).toEqual([])
+ })
+
+ it('skips a stale cell with no mounted logic instead of wedging the chain', async () => {
+ // A dispatch to an unmounted cell is picked up by nobody: without the mounted-cell
+ // filter the queue would sit at ['c'] forever, blocking any further stale-cell run.
+ mountNode('b')
+ stalenessLogic.actions.markStaleNodeIds(['b', 'c'])
+
+ stalenessLogic.actions.runStaleChain(content)
+ await expectLogic(stalenessLogic).toFinishAllListeners()
+
+ expect(runSpy.mock.calls.map((call) => call[1].node_id)).toEqual(['b'])
+ expect(stalenessLogic.values.chainQueue).toEqual([])
+ // The unmounted cell keeps its flag — it was never re-run.
+ expect(stalenessLogic.values.staleNodeIds).toEqual({ c: true })
+ })
+
+ it('the chain stops when a cell does not finish successfully', async () => {
+ mountNode('b')
+ mountNode('c')
+ stalenessLogic.actions.markStaleNodeIds(['b', 'c'])
+ // The first chain link fails; running c anyway would join a frame that was never rebuilt.
+ resultSpy.mockResolvedValue({ status: 'failed', result: null, error: 'boom' })
+
+ stalenessLogic.actions.runStaleChain(content)
+ await expectLogic(stalenessLogic).toFinishAllListeners()
+
+ expect(runSpy).toHaveBeenCalledTimes(1)
+ expect(stalenessLogic.values.chainQueue).toEqual([])
+ // The failed cell stays stale so the user can see what still needs a successful run.
+ expect(stalenessLogic.values.staleNodeIds).toEqual({ b: true, c: true })
+ })
+
+ it('a second runStaleChain while one is active is refused', async () => {
+ mountNode('b')
+ // Keep the first link running so the chain stays active.
+ resultSpy.mockResolvedValue({ status: 'running', result: null, error: null })
+ stalenessLogic.actions.markStaleNodeIds(['b'])
+
+ stalenessLogic.actions.runStaleChain(content)
+ await expectLogic(stalenessLogic).toFinishAllListeners()
+ stalenessLogic.actions.runStaleChain(content)
+ await expectLogic(stalenessLogic).toFinishAllListeners()
+
+ expect(runSpy).toHaveBeenCalledTimes(1)
+ })
+})
diff --git a/frontend/src/scenes/notebooks/Notebook/notebookNodeStalenessLogic.ts b/frontend/src/scenes/notebooks/Notebook/notebookNodeStalenessLogic.ts
new file mode 100644
index 000000000000..2a4152a5973b
--- /dev/null
+++ b/frontend/src/scenes/notebooks/Notebook/notebookNodeStalenessLogic.ts
@@ -0,0 +1,302 @@
+import { MakeLogicType, actions, kea, key, listeners, path, props, reducers, selectors } from 'kea'
+
+import { JSONContent } from 'lib/components/RichContentEditor/types'
+import { lemonToast } from 'lib/lemon-ui/LemonToast/LemonToast'
+
+import {
+ NotebookDependencyGraph,
+ buildNotebookDependencyGraph,
+ collectDependencyNodeIds,
+} from '../Nodes/notebookNodeContent'
+import { NotebookNodeType } from '../types'
+
+export type NotebookNodeRunTerminalStatus = 'done' | 'failed' | 'interrupted'
+
+export interface NotebookNodeStalenessLogicProps {
+ shortId: string
+}
+
+const V2_NODE_TYPES: string[] = [NotebookNodeType.SQLV2, NotebookNodeType.PythonV2]
+
+const staleDownstreamNodeIds = (graph: NotebookDependencyGraph, nodeId: string): string[] => {
+ const downstream = collectDependencyNodeIds(graph, nodeId, 'downstream')
+ downstream.delete(nodeId)
+ // Only V2 cells participate: legacy cells have their own freshness system, and the
+ // chain runner only knows how to dispatch V2 runs.
+ return graph.nodes
+ .filter((node) => downstream.has(node.nodeId) && V2_NODE_TYPES.includes(node.nodeType))
+ .map((node) => node.nodeId)
+}
+
+// Stale V2 cells the chain can actually run, in document order (which is dependency order).
+// Restricting to registered (mounted) cells matters: a dispatch to an unmounted cell is picked
+// up by nobody, which would leave the chain queue wedged forever.
+const runnableStaleNodeIds = (
+ graph: NotebookDependencyGraph,
+ staleNodeIds: Record<string, true>,
+ mountedNodeIds: Record<string, true>
+): string[] =>
+ graph.nodes
+ .filter(
+ (node) => V2_NODE_TYPES.includes(node.nodeType) && staleNodeIds[node.nodeId] && mountedNodeIds[node.nodeId]
+ )
+ .map((node) => node.nodeId)
+
+// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
+export interface notebookNodeStalenessLogicValues {
+ chainQueue: string[]
+ chainRootNodeId: string | null
+ isChainRunning: boolean
+ lastRunDownstreamNodeIds: string[]
+ lastRunNodeId: string | null
+ lastRunStaleDownstreamNodeIds: string[]
+ mountedNodeIds: Record<string, true>
+ staleCount: number
+ staleNodeIds: Record<string, true>
+}
+
+// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
+export interface notebookNodeStalenessLogicActions {
+ abortChain: (reason: string | null) => {
+ reason: string | null
+ }
+ clearNodeStale: (nodeId: string) => {
+ nodeId: string
+ }
+ dispatchChainRun: (nodeId: string) => {
+ nodeId: string
+ }
+ markStaleNodeIds: (nodeIds: string[]) => {
+ nodeIds: string[]
+ }
+ nodeRunFinished: (
+ nodeId: string,
+ status: NotebookNodeRunTerminalStatus,
+ content: JSONContent | null
+ ) => {
+ content: JSONContent | null
+ nodeId: string
+ status: NotebookNodeRunTerminalStatus
+ }
+ registerChainNode: (nodeId: string) => {
+ nodeId: string
+ }
+ runStaleChain: (
+ content: JSONContent | null,
+ rootNodeId?: string | null
+ ) => {
+ content: JSONContent | null
+ rootNodeId: string | null
+ }
+ setChainQueue: (nodeIds: string[]) => {
+ nodeIds: string[]
+ }
+ setChainRoot: (nodeId: string | null) => {
+ nodeId: string | null
+ }
+ setLastRun: (
+ nodeId: string,
+ downstreamNodeIds: string[]
+ ) => {
+ downstreamNodeIds: string[]
+ nodeId: string
+ }
+ unregisterChainNode: (nodeId: string) => {
+ nodeId: string
+ }
+}
+
+export type notebookNodeStalenessLogicType = MakeLogicType<
+ notebookNodeStalenessLogicValues,
+ notebookNodeStalenessLogicActions,
+ NotebookNodeStalenessLogicProps
+>
+
+/**
+ * Journey 10: UI-only staleness for revamped (SQLV2/PythonV2) cells, plus the chain runner.
+ *
+ * When a cell's run lands, every transitive dependent is marked stale (its result now derives
+ * from outdated data). "Run stale cells" re-runs the stale set in document order — which IS
+ * dependency order, because a cell can only reference exports of earlier cells. Runs go
+ * through each cell's own notebookNodeSQLV2Logic (the node logics listen for
+ * `dispatchChainRun`), so operation serialization, polling, and interrupt all apply per link.
+ * Flags are session-local by design (walkthrough decision: UI-only, no backend call).
+ */
+export const notebookNodeStalenessLogic = kea<notebookNodeStalenessLogicType>([
+ path((key) => ['scenes', 'notebooks', 'Notebook', 'notebookNodeStalenessLogic', key]),
+ props({} as NotebookNodeStalenessLogicProps),
+ key((props) => props.shortId),
+ actions({
+ // Reported by every V2 node logic from each of its run's terminal paths, whether the
+ // run was user-clicked or chain-dispatched. `content` rides along on success so the
+ // downstream set is computed against the document as it was when the result landed.
+ nodeRunFinished: (nodeId: string, status: NotebookNodeRunTerminalStatus, content: JSONContent | null) => ({
+ nodeId,
+ status,
+ content,
+ }),
+ markStaleNodeIds: (nodeIds: string[]) => ({ nodeIds }),
+ clearNodeStale: (nodeId: string) => ({ nodeId }),
+ // With a rootNodeId the chain is scoped to that cell's transitive downstream (the
+ // "run downstream cells" button on the cell that just ran); without one it runs
+ // every stale cell in the notebook.
+ runStaleChain: (content: JSONContent | null, rootNodeId: string | null = null) => ({ content, rootNodeId }),
+ // Consumed by the matching notebookNodeSQLV2Logic, which builds refs and runs itself.
+ dispatchChainRun: (nodeId: string) => ({ nodeId }),
+ setChainQueue: (nodeIds: string[]) => ({ nodeIds }),
+ setChainRoot: (nodeId: string | null) => ({ nodeId }),
+ setLastRun: (nodeId: string, downstreamNodeIds: string[]) => ({ nodeId, downstreamNodeIds }),
+ abortChain: (reason: string | null) => ({ reason }),
+ // Called by every V2 node logic on mount/unmount so the chain only ever dispatches
+ // to a cell whose logic is mounted and listening.
+ registerChainNode: (nodeId: string) => ({ nodeId }),
+ unregisterChainNode: (nodeId: string) => ({ nodeId }),
+ }),
+ reducers({
+ staleNodeIds: [
+ {} as Record<string, true>,
+ {
+ markStaleNodeIds: (state, { nodeIds }) => {
+ if (!nodeIds.length) {
+ return state
+ }
+ const next = { ...state }
+ nodeIds.forEach((nodeId) => {
+ next[nodeId] = true
+ })
+ return next
+ },
+ clearNodeStale: (state, { nodeId }) => {
+ if (!(nodeId in state)) {
+ return state
+ }
+ const next = { ...state }
+ delete next[nodeId]
+ return next
+ },
+ },
+ ],
+ // Stale cells still to run; the head is the one currently running.
+ chainQueue: [
+ [] as string[],
+ {
+ setChainQueue: (_, { nodeIds }) => nodeIds,
+ abortChain: () => [],
+ },
+ ],
+ // The cell whose "run downstream cells" started the active chain; scopes the queue
+ // rebuild so unrelated stale cells are left alone.
+ chainRootNodeId: [
+ null as string | null,
+ {
+ setChainRoot: (_, { nodeId }) => nodeId,
+ abortChain: () => null,
+ },
+ ],
+ // The last cell whose run landed, and the downstream set that run marked stale.
+ // Drives the "run downstream cells" affordance on that cell.
+ lastRunNodeId: [
+ null as string | null,
+ {
+ setLastRun: (_, { nodeId }) => nodeId,
+ },
+ ],
+ lastRunDownstreamNodeIds: [
+ [] as string[],
+ {
+ setLastRun: (_, { downstreamNodeIds }) => downstreamNodeIds,
+ },
+ ],
+ mountedNodeIds: [
+ {} as Record<string, true>,
+ {
+ registerChainNode: (state, { nodeId }) => ({ ...state, [nodeId]: true as const }),
+ unregisterChainNode: (state, { nodeId }) => {
+ if (!(nodeId in state)) {
+ return state
+ }
+ const next = { ...state }
+ delete next[nodeId]
+ return next
+ },
+ },
+ ],
+ }),
+ selectors({
+ staleCount: [
+ (s) => [s.staleNodeIds],
+ (staleNodeIds: Record<string, true>): number => Object.keys(staleNodeIds).length,
+ ],
+ isChainRunning: [(s) => [s.chainQueue], (chainQueue: string[]): boolean => chainQueue.length > 0],
+ // The still-stale part of the last run's downstream; empties as cells re-run, which
+ // is what hides the "run downstream cells" button once everything is fresh again.
+ lastRunStaleDownstreamNodeIds: [
+ (s) => [s.lastRunDownstreamNodeIds, s.staleNodeIds],
+ (lastRunDownstreamNodeIds: string[], staleNodeIds: Record<string, true>): string[] =>
+ lastRunDownstreamNodeIds.filter((nodeId) => staleNodeIds[nodeId]),
+ ],
+ }),
+ listeners(({ actions, values }) => ({
+ nodeRunFinished: ({ nodeId, status, content }) => {
+ if (status === 'done') {
+ actions.clearNodeStale(nodeId)
+ const downstream = content ? staleDownstreamNodeIds(buildNotebookDependencyGraph(content), nodeId) : []
+ actions.markStaleNodeIds(downstream)
+ actions.setLastRun(nodeId, downstream)
+ }
+
+ if (values.chainQueue[0] !== nodeId) {
+ return
+ }
+ if (status !== 'done') {
+ actions.abortChain(nodeId)
+ return
+ }
+ // Rebuild the queue from the live stale set instead of shifting the snapshot:
+ // cells marked stale while the chain ran (including by this very run) join in,
+ // and cells deleted or unmounted while queued drop out rather than receiving a
+ // dispatch nobody picks up. A rooted chain stays scoped to the root's downstream
+ // so unrelated stale cells are never run by it.
+ const graph = content ? buildNotebookDependencyGraph(content) : null
+ let queue = graph ? runnableStaleNodeIds(graph, values.staleNodeIds, values.mountedNodeIds) : []
+ if (graph && values.chainRootNodeId) {
+ const scope = collectDependencyNodeIds(graph, values.chainRootNodeId, 'downstream')
+ queue = queue.filter((queuedNodeId) => scope.has(queuedNodeId))
+ }
+ actions.setChainQueue(queue)
+ if (queue.length) {
+ actions.dispatchChainRun(queue[0])
+ } else {
+ actions.setChainRoot(null)
+ lemonToast.success('Stale cells re-run.')
+ }
+ },
+ runStaleChain: ({ content, rootNodeId }) => {
+ if (values.isChainRunning) {
+ lemonToast.info('Stale cells are already being re-run.')
+ return
+ }
+ if (!content) {
+ return
+ }
+ const graph = buildNotebookDependencyGraph(content)
+ let queue = runnableStaleNodeIds(graph, values.staleNodeIds, values.mountedNodeIds)
+ if (rootNodeId) {
+ const scope = collectDependencyNodeIds(graph, rootNodeId, 'downstream')
+ queue = queue.filter((queuedNodeId) => scope.has(queuedNodeId))
+ }
+ if (!queue.length) {
+ lemonToast.info('No stale cells to run.')
+ return
+ }
+ actions.setChainRoot(rootNodeId)
+ actions.setChainQueue(queue)
+ actions.dispatchChainRun(queue[0])
+ },
+ abortChain: ({ reason }) => {
+ if (reason) {
+ lemonToast.warning('Stopped re-running stale cells: a cell did not finish successfully.')
+ }
+ },
+ })),
+])
diff --git a/frontend/src/scenes/notebooks/NotebookPanel/notebookPanelLogic.ts b/frontend/src/scenes/notebooks/NotebookPanel/notebookPanelLogic.ts
index ac517958a68d..f44b2d73c2ac 100644
--- a/frontend/src/scenes/notebooks/NotebookPanel/notebookPanelLogic.ts
+++ b/frontend/src/scenes/notebooks/NotebookPanel/notebookPanelLogic.ts
@@ -10,7 +10,6 @@ import { SidePanelTab } from '~/types'
import type { FocusPosition } from '../../../../../node_modules/.pnpm/@[email protected]_@[email protected]/node_modules/@tiptap/core/dist/index'
import type { FeatureFlagsSet } from '../../../lib/logic/featureFlagLogic'
import { NotebookNodeResource } from '../types'
-
// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface notebookPanelLogicValues {
featureFlags: FeatureFlagsSet // featureFlagLogic
diff --git a/frontend/src/scenes/notebooks/NotebookSelectButton/notebookSelectButtonLogic.ts b/frontend/src/scenes/notebooks/NotebookSelectButton/notebookSelectButtonLogic.ts
index ddf1798c1bec..f8850123dc92 100644
--- a/frontend/src/scenes/notebooks/NotebookSelectButton/notebookSelectButtonLogic.ts
+++ b/frontend/src/scenes/notebooks/NotebookSelectButton/notebookSelectButtonLogic.ts
@@ -4,7 +4,6 @@ import { loaders } from 'kea-loaders'
import api from 'lib/api'
import { NotebookListItemType, NotebookNodeResource, NotebookNodeType } from '../types'
-
export const NOTEBOOK_DROPDOWN_LIMIT = 50
export interface NotebookSelectButtonLogicProps {