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.

fix(notebooks): fix fetching stale data on re-runs, make Cmd+Enter work, and more efficient dataframe cache (#70068)

Sinan Kucukkoselerc8f629d8bff0
diff --git a/frontend/src/scenes/notebooks/Nodes/NotebookNodePythonV2.tsx b/frontend/src/scenes/notebooks/Nodes/NotebookNodePythonV2.tsx
index 253fe3281de9..d5a724566389 100644
--- a/frontend/src/scenes/notebooks/Nodes/NotebookNodePythonV2.tsx
+++ b/frontend/src/scenes/notebooks/Nodes/NotebookNodePythonV2.tsx
@@ -1,5 +1,5 @@
import { useActions, useMountedLogic, useValues } from 'kea'
-import { useMemo } from 'react'
+import { useMemo, useRef } from 'react'
import { IconCornerDownRight, IconPlayFilled } from '@posthog/icons'
@@ -173,12 +173,22 @@ const Settings = ({
const { runQuery } = useActions(dataLogic)
const run = (): void => {
+ // Guard here (not just on the button) so Cmd+Enter can't fire a second run mid-flight —
+ // overlapping runs race the poller and can strand the spinner.
+ if (isRunning) {
+ return
+ }
// The refs map sibling SQLV2 frames; the backend materializes only the ones the code reads.
runQuery(attributes.code ?? '', collectSqlV2Refs(notebookLogic.values.content, nodeId), {
nodeType: 'python',
outputName: attributes.returnVariable,
})
}
+ // Monaco binds Cmd+Enter once at editor mount, so a plain `run` closure would capture the
+ // initial (empty) code and the guard would drop the run. Route through a ref that always
+ // points at the latest run so the keybinding sees the current code, output name, and run state.
+ const runRef = useRef(run)
+ runRef.current = run
return (
<div className="flex h-full min-h-0 flex-col">
@@ -192,11 +202,7 @@ const Settings = ({
size="small"
type="primary"
icon={<IconPlayFilled color="var(--success)" />}
- onClick={() => {
- if (!isRunning) {
- run()
- }
- }}
+ onClick={() => run()}
loading={isRunning}
disabledReason={operationBlockReason ?? undefined}
tooltip="Run Python (⌘⏎)"
@@ -209,7 +215,7 @@ const Settings = ({
language="python"
value={typeof attributes.code === 'string' ? attributes.code : ''}
onChange={(value) => updateAttributes({ code: value ?? '' })}
- onPressCmdEnter={run}
+ onPressCmdEnter={() => runRef.current()}
allowManualResize={false}
minHeight={160}
embedded
diff --git a/products/notebooks/backend/presentation/views/notebook.py b/products/notebooks/backend/presentation/views/notebook.py
index 15cefe7530a0..0c3c60d945f5 100644
--- a/products/notebooks/backend/presentation/views/notebook.py
+++ b/products/notebooks/backend/presentation/views/notebook.py
@@ -69,6 +69,7 @@ from products.notebooks.backend.sql_v2 import (
sql_v2_page_lock_key,
)
from products.notebooks.backend.sql_v2_references import (
+ PythonNodeRef,
SQLV2ReferenceError,
resolve_python_node_inputs,
resolve_sql_v2_references,
@@ -984,25 +985,36 @@ class NotebookViewSet(TeamAndOrgViewSetMixin, AccessControlViewSetMixin, ForbidD
# happens once here, so the run stores a self-contained query and paging re-queries it
# without re-resolving refs.
ref_node_ids: dict[str, str] = serializer.validated_data.get("refs") or {}
- # One DISTINCT ON query fetches the latest DONE run for every referenced node at once.
- code_by_node_id: dict[str, str] = dict(
- NotebookNodeRun.objects.for_team(self.team_id)
- .filter(notebook=notebook, node_id__in=set(ref_node_ids.values()), status=NotebookNodeRun.Status.DONE)
- .order_by("node_id", "-created_at")
- .distinct("node_id")
- .values_list("node_id", "code")
- )
- last_run_code: dict[str, str | None] = {
- name: code_by_node_id.get(node_id) for name, node_id in ref_node_ids.items()
+ # One DISTINCT ON query fetches the latest DONE run (id + code) for every referenced node.
+ latest_by_node: dict[str, tuple[str, str]] = {
+ node_id: (str(run_id), code)
+ for node_id, run_id, code in (
+ NotebookNodeRun.objects.for_team(self.team_id)
+ .filter(notebook=notebook, node_id__in=set(ref_node_ids.values()), status=NotebookNodeRun.Status.DONE)
+ .order_by("node_id", "-created_at")
+ .distinct("node_id")
+ .values_list("node_id", "id", "code")
+ )
}
node_type = serializer.validated_data["node_type"]
code = serializer.validated_data["code"]
output_name = serializer.validated_data["output_name"]
try:
if node_type == "python":
- # A python node stores its code as-is; referenced frames become materialization inputs.
- run_code, inputs = code, resolve_python_node_inputs(code, last_run_code)
+ # A python node stores its code as-is; referenced frames become materialization inputs,
+ # keyed by the upstream run_id so a re-run yields a fresh (not stale) frame.
+ python_refs: dict[str, PythonNodeRef | None] = {
+ name: (PythonNodeRef(node_id, *latest_by_node[node_id]) if node_id in latest_by_node else None)
+ for name, node_id in ref_node_ids.items()
+ }
+ run_code, inputs = code, resolve_python_node_inputs(code, python_refs)
else:
+ # A join recomputes against each ref's last-run query (not its live editor text), so
+ # inlining happens once here and paging re-queries the stored self-contained query.
+ last_run_code: dict[str, str | None] = {
+ name: (latest_by_node[node_id][1] if node_id in latest_by_node else None)
+ for name, node_id in ref_node_ids.items()
+ }
run_code, inputs = resolve_sql_v2_references(code, last_run_code), []
except SQLV2ReferenceError as e:
return Response({"detail": str(e)}, status=400)
diff --git a/products/notebooks/backend/python_analysis.py b/products/notebooks/backend/python_analysis.py
index f739b5f3d6b2..94c304269c00 100644
--- a/products/notebooks/backend/python_analysis.py
+++ b/products/notebooks/backend/python_analysis.py
@@ -93,6 +93,11 @@ class GlobalAnalyzer(ast.NodeVisitor):
self.builtins = builtins
self.used: set[str] = set()
self.scopes: list[Scope] = [Scope(kind="module", locals=module_locals)]
+ # Module names bound so far in execution order. At module (exec) scope a name is a
+ # local *from the point it is bound onwards* — reading it before that reads the injected
+ # namespace, so a read-before-bind name (df.columns = ...; df = df.assign(...)) is a
+ # genuine external input, unlike function scope where any assignment makes the name local.
+ self.module_assigned: set[str] = set()
def is_global_name(self, name: str) -> bool:
current_scope = self.scopes[-1]
@@ -107,9 +112,92 @@ class GlobalAnalyzer(ast.NodeVisitor):
def visit_Name(self, node: ast.Name) -> None:
if isinstance(node.ctx, ast.Load):
- if self.is_global_name(node.id) and node.id not in self.builtins and node.id not in self.module_locals:
+ # A module-scope name already bound before this read is a local, not an input.
+ if self.is_global_name(node.id) and node.id not in self.builtins and node.id not in self.module_assigned:
self.used.add(node.id)
+ def visit_Module(self, node: ast.Module) -> None:
+ for statement in node.body:
+ self._visit_module_statement(statement)
+
+ def _visit_module_statement(self, statement: ast.stmt) -> None:
+ # Walk top-level statements in execution order, visiting reads before recording the
+ # bindings they introduce, so a name read before it is bound counts as an input.
+ if isinstance(statement, ast.Assign):
+ self.visit(statement.value)
+ for target in statement.targets:
+ self.visit(target) # attribute/subscript targets still *read* their base object
+ self._record_bindings(statement.targets)
+ elif isinstance(statement, ast.AnnAssign):
+ if statement.value is not None:
+ self.visit(statement.value)
+ self.visit(statement.annotation)
+ self.visit(statement.target)
+ if statement.value is not None:
+ self._record_bindings([statement.target])
+ elif isinstance(statement, ast.AugAssign):
+ self.visit(statement.value)
+ self.visit(statement.target)
+ self._record_bindings([statement.target])
+ elif isinstance(statement, ast.Import):
+ self.module_assigned.update(alias.asname or alias.name.split(".")[0] for alias in statement.names)
+ elif isinstance(statement, ast.ImportFrom):
+ self.module_assigned.update(alias.asname or alias.name for alias in statement.names)
+ elif isinstance(statement, ast.FunctionDef | ast.AsyncFunctionDef | ast.ClassDef):
+ self.visit(statement)
+ self.module_assigned.add(statement.name)
+ elif isinstance(statement, ast.For | ast.AsyncFor):
+ self.visit(statement.iter)
+ self._record_bindings([statement.target]) # loop var is bound before the body runs
+ for child in [*statement.body, *statement.orelse]:
+ self._visit_module_statement(child)
+ elif isinstance(statement, ast.With | ast.AsyncWith):
+ for item in statement.items:
+ self.visit(item.context_expr)
+ if item.optional_vars is not None:
+ self._record_bindings([item.optional_vars])
+ for child in statement.body:
+ self._visit_module_statement(child)
+ elif isinstance(statement, ast.If | ast.While):
+ self.visit(statement.test)
+ for child in [*statement.body, *statement.orelse]:
+ self._visit_module_statement(child)
+ elif isinstance(statement, ast.Try):
+ for child in statement.body:
+ self._visit_module_statement(child)
+ for handler in statement.handlers:
+ if handler.type is not None:
+ self.visit(handler.type)
+ if handler.name is not None:
+ self.module_assigned.add(handler.name)
+ for child in handler.body:
+ self._visit_module_statement(child)
+ for child in [*statement.orelse, *statement.finalbody]:
+ self._visit_module_statement(child)
+ elif isinstance(statement, ast.Match):
+ self.visit(statement.subject)
+ for case in statement.cases:
+ # Capture patterns bind their names before the case body runs.
+ self.module_assigned.update(match_capture_names(case.pattern))
+ if case.guard is not None:
+ self.visit(case.guard)
+ for child in case.body:
+ self._visit_module_statement(child)
+ else:
+ self.visit(statement)
+
+ def visit_NamedExpr(self, node: ast.NamedExpr) -> None:
+ # A walrus binds its target in the enclosing scope; at module scope record it so a later
+ # read (print(rows) after `if (rows := ...)`) isn't mistaken for an external input.
+ self.visit(node.value)
+ if len(self.scopes) == 1:
+ self.module_assigned.update(extract_target_names(node.target))
+ self.visit(node.target)
+
+ def _record_bindings(self, targets: list[ast.expr]) -> None:
+ for target in targets:
+ self.module_assigned.update(extract_target_names(target))
+
def visit_FunctionDef(self, node: ast.FunctionDef) -> None:
self._visit_function_like(node, "function")
@@ -210,6 +298,31 @@ def extract_target_names(target: ast.AST) -> set[str]:
return names
+def match_capture_names(pattern: ast.pattern) -> set[str]:
+ """Names a match-case pattern binds — captures are locals, not external frames."""
+ names: set[str] = set()
+ if isinstance(pattern, ast.MatchAs):
+ if pattern.name is not None:
+ names.add(pattern.name)
+ if pattern.pattern is not None:
+ names |= match_capture_names(pattern.pattern)
+ elif isinstance(pattern, ast.MatchStar):
+ if pattern.name is not None:
+ names.add(pattern.name)
+ elif isinstance(pattern, ast.MatchMapping):
+ if pattern.rest is not None:
+ names.add(pattern.rest)
+ for sub in pattern.patterns:
+ names |= match_capture_names(sub)
+ elif isinstance(pattern, ast.MatchSequence | ast.MatchOr):
+ for sub in pattern.patterns:
+ names |= match_capture_names(sub)
+ elif isinstance(pattern, ast.MatchClass):
+ for sub in [*pattern.patterns, *pattern.kwd_patterns]:
+ names |= match_capture_names(sub)
+ return names
+
+
def annotation_to_string(annotation: ast.AST) -> str:
if hasattr(ast, "unparse"):
return ast.unparse(annotation)
diff --git a/products/notebooks/backend/sandbox/kernel/executor.py b/products/notebooks/backend/sandbox/kernel/executor.py
index 35b46a1d7bcc..aa9c8ef62a62 100644
--- a/products/notebooks/backend/sandbox/kernel/executor.py
+++ b/products/notebooks/backend/sandbox/kernel/executor.py
@@ -15,10 +15,12 @@ Flow for a Python node:
"""
import os
+import glob
import json
import time
import queue
import shutil
+import hashlib
import threading
from typing import Any
@@ -104,8 +106,15 @@ class KernelExecutor:
if spec.get("kind") == "local":
kernel_inputs.append({"name": name, "kind": "local"})
continue
- frame_path = os.path.join(self._frames_dir, f"{spec['query_hash']}.arrow")
- if not os.path.exists(frame_path): # unchanged upstream query → reuse the frame
+ # Keyed by the upstream run_id, so the same run reuses its frame while a re-run (new
+ # run_id) fetches fresh data instead of the stale cached rows. node_id comes from
+ # user-controlled notebook content, so hash it to a filesystem-safe token — a raw
+ # "../x" id would otherwise escape the frames dir on write and in the eviction glob.
+ # run_id is a server-generated UUID.
+ node_token = hashlib.sha256(spec["node_id"].encode()).hexdigest()
+ frame_path = os.path.join(self._frames_dir, f"{node_token}.{spec['run_id']}.arrow")
+ if not os.path.exists(frame_path):
+ self._evict_superseded_frames(node_token, keep=frame_path)
data_plane.materialize_query_to_file(
payload["data_plane_url"],
payload["data_plane_token"],
@@ -116,6 +125,15 @@ class KernelExecutor:
kernel_inputs.append({"name": name, "kind": "hogql", "path": frame_path})
return kernel_inputs
+ def _evict_superseded_frames(self, node_token: str, keep: str) -> None:
+ """Drop this upstream node's older frames so iterating a query doesn't pile up unread frames."""
+ for stale in glob.glob(os.path.join(self._frames_dir, f"{node_token}.*.arrow")):
+ if stale != keep:
+ try:
+ os.remove(stale)
+ except OSError:
+ pass # best-effort: a concurrent run or teardown may have removed it already
+
def _invoke_run_node(self, payload: dict[str, Any], inputs: list[dict[str, Any]]) -> dict[str, Any]:
run_id = str(payload.get("run_id") or "run")
run_dir = os.path.join(self._runs_dir, run_id)
diff --git a/products/notebooks/backend/sql_v2_references.py b/products/notebooks/backend/sql_v2_references.py
index 9017889d380d..c9d4903a7d02 100644
--- a/products/notebooks/backend/sql_v2_references.py
+++ b/products/notebooks/backend/sql_v2_references.py
@@ -13,7 +13,7 @@ own ``WITH`` is left alone. Broken definitions that nothing references are never
so an unrelated malformed node can't fail a run.
"""
-import hashlib
+from dataclasses import dataclass
from typing import Any
from posthog.hogql import ast
@@ -131,30 +131,41 @@ def resolve_sql_v2_references(code: str, refs: dict[str, str | None]) -> str:
return print_prepared_ast(root, context=HogQLContext(team_id=None), dialect="hogql")
-def resolve_python_node_inputs(code: str, refs: dict[str, str | None]) -> list[dict[str, Any]]:
+@dataclass(frozen=True)
+class PythonNodeRef:
+ """The latest completed run of an upstream node a Python frame can materialize from."""
+
+ node_id: str
+ run_id: str
+ query: str
+
+
+def resolve_python_node_inputs(code: str, refs: dict[str, PythonNodeRef | None]) -> list[dict[str, Any]]:
"""Return the materialization specs for the upstream frames a Python node reads.
- `refs` maps each named upstream node's dataframe name to its **last-run** HogQL (or None
- if it has never completed a run). A Python node references frames as plain variables, so
- we materialize only the names its code actually reads — each becomes a HogQL input the
- executor fetches to a local Arrow file, keyed by `query_hash` so an unchanged upstream
- query reuses its frame.
+ `refs` maps each named upstream node's dataframe name to its **latest completed run**
+ (or None if it has never completed a run). A Python node references frames as plain
+ variables, so we materialize only the names its code actually reads — each becomes a
+ HogQL input the executor fetches to a local Arrow file, keyed by the upstream `run_id`
+ so a re-run of that node yields a fresh frame (not stale data) and the executor can
+ evict the node's superseded frames.
Raises SQLV2ReferenceError if the code reads a known node that has not been run yet.
"""
used = set(analyze_python_globals(code).used)
inputs: list[dict[str, Any]] = []
- for name, last_run_code in refs.items():
+ for name, ref in refs.items():
if not name or name not in used:
continue
- if last_run_code is None or not last_run_code.strip():
+ if ref is None or not ref.query.strip():
raise SQLV2ReferenceError(f"Referenced node '{name}' has not been run yet — run it first.")
inputs.append(
{
"name": name,
"kind": "hogql",
- "query": last_run_code,
- "query_hash": hashlib.sha256(last_run_code.encode()).hexdigest(),
+ "node_id": ref.node_id,
+ "run_id": ref.run_id,
+ "query": ref.query,
}
)
return inputs
diff --git a/products/notebooks/backend/test/test_python_analysis.py b/products/notebooks/backend/test/test_python_analysis.py
new file mode 100644
index 000000000000..b37a5ab317b5
--- /dev/null
+++ b/products/notebooks/backend/test/test_python_analysis.py
@@ -0,0 +1,26 @@
+from django.test import SimpleTestCase
+
+from parameterized import parameterized
+
+from products.notebooks.backend.python_analysis import analyze_python_globals
+
+
+class TestAnalyzePythonGlobalsUsed(SimpleTestCase):
+ @parameterized.expand(
+ [
+ # A ref read before it is reassigned is still an input: `df` must be re-materialized
+ # every run, else the node runs against the mutated frame left by its previous run.
+ ("reassigned_after_read", "df.columns = ['a', 'b']\ndf = df.assign(x=1)", ["df"]),
+ ("read_then_reassigned_via_call", "out = df.agg('sum')\ndf = df.head()", ["df"]),
+ # A name created before it is read is a genuine local, not an input — materializing it
+ # would clobber the user's own frame.
+ ("assigned_before_read", "import pandas as pd\ndf = pd.DataFrame()\ndf.head()", []),
+ # Loop, function, walrus, and match-capture locals must not leak in as phantom inputs.
+ ("loop_variable", "for col in df.columns:\n print(df[col].sum())", ["df"]),
+ ("function_local", "def f():\n x = 1\n return x + df.iloc[0]", ["df"]),
+ ("walrus_local", "if (rows := len(df)):\n print(rows)", ["df"]),
+ ("match_capture", "match df.shape:\n case (rows, cols):\n print(rows, cols)", ["df"]),
+ ]
+ )
+ def test_used_globals(self, _name: str, code: str, expected: list[str]) -> None:
+ self.assertEqual(analyze_python_globals(code).used, expected)
diff --git a/products/notebooks/backend/test/test_sql_v2_references.py b/products/notebooks/backend/test/test_sql_v2_references.py
index 6e6dfff031ef..b0fb27977d72 100644
--- a/products/notebooks/backend/test/test_sql_v2_references.py
+++ b/products/notebooks/backend/test/test_sql_v2_references.py
@@ -1,30 +1,45 @@
from django.test import SimpleTestCase
from products.notebooks.backend.sql_v2_references import (
+ PythonNodeRef,
SQLV2ReferenceError,
resolve_python_node_inputs,
resolve_sql_v2_references,
)
+def _ref(query: str, node_id: str = "node-df1", run_id: str = "run-1") -> PythonNodeRef:
+ return PythonNodeRef(node_id=node_id, run_id=run_id, query=query)
+
+
class TestResolvePythonNodeInputs(SimpleTestCase):
def test_only_referenced_frames_are_materialized(self):
# A python node reads frames as variables; materialize only the ones its code uses.
- inputs = resolve_python_node_inputs("df1.head()", {"df1": "select id from events", "df2": "select 1"})
+ inputs = resolve_python_node_inputs(
+ "df1.head()", {"df1": _ref("select id from events"), "df2": _ref("select 1", node_id="node-df2")}
+ )
self.assertEqual(len(inputs), 1)
self.assertEqual(inputs[0]["name"], "df1")
self.assertEqual(inputs[0]["kind"], "hogql")
self.assertEqual(inputs[0]["query"], "select id from events")
- self.assertTrue(inputs[0]["query_hash"])
def test_unused_refs_are_ignored(self):
- self.assertEqual(resolve_python_node_inputs("import pandas as pd\npd.DataFrame()", {"df1": "select 1"}), [])
+ self.assertEqual(
+ resolve_python_node_inputs("import pandas as pd\npd.DataFrame()", {"df1": _ref("select 1")}), []
+ )
- def test_query_hash_is_stable_for_the_same_query(self):
- # The executor reuses a frame file keyed by hash, so identical queries must hash identically.
- a = resolve_python_node_inputs("df1", {"df1": "select 1"})[0]["query_hash"]
- b = resolve_python_node_inputs("df1", {"df1": "select 1"})[0]["query_hash"]
- self.assertEqual(a, b)
+ def test_reassigned_ref_is_still_materialized(self):
+ # Reassigning a ref (df1 = df1.assign(...)) must not drop it from the inputs — otherwise it
+ # is never re-fetched and the node runs against the mutated frame from its previous run.
+ inputs = resolve_python_node_inputs("df1.columns = ['a']\ndf1 = df1.assign(x=1)", {"df1": _ref("select 1")})
+ self.assertEqual([i["name"] for i in inputs], ["df1"])
+
+ def test_frame_is_keyed_on_the_upstream_run_id(self):
+ # The executor caches/evicts frames by (node_id, run_id), so both must reach the spec — a
+ # new run of the same node must key a fresh frame rather than reuse the stale one.
+ inputs = resolve_python_node_inputs("df1.head()", {"df1": _ref("select 1", node_id="n1", run_id="r2")})
+ self.assertEqual(inputs[0]["node_id"], "n1")
+ self.assertEqual(inputs[0]["run_id"], "r2")
def test_referencing_a_never_run_node_raises(self):
with self.assertRaises(SQLV2ReferenceError):