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): fail a kernel run whose callback never arrives (#88304)

Sinan Kucukkoseler4d0c0275a6da
diff --git a/products/notebooks/backend/presentation/views/notebook.py b/products/notebooks/backend/presentation/views/notebook.py
index c876cc03e723..5b1b8969b04f 100644
--- a/products/notebooks/backend/presentation/views/notebook.py
+++ b/products/notebooks/backend/presentation/views/notebook.py
@@ -80,7 +80,7 @@ from products.notebooks.backend.sql_v2_references import (
resolve_python_node_inputs,
resolve_sql_node_run,
)
-from products.notebooks.backend.sql_v2_runs import finish_node_run
+from products.notebooks.backend.sql_v2_runs import expire_stale_kernel_run, finish_node_run
from products.notebooks.backend.sql_v2_serializers import (
NotebookKernelConfigResponseSerializer,
NotebookKernelStatusResponseSerializer,
@@ -1336,6 +1336,10 @@ class NotebookViewSet(TeamAndOrgViewSetMixin, AccessControlViewSetMixin, ForbidD
# caller lost access mid-query. Advancing the row leaks nothing — the gate below still
# decides whether any of it is returned.
rows = sync_direct_run(run)
+ # The kernel lane's equivalent, and here for the same reason: the sandbox delivers its
+ # envelope once with no retry, so a lost delivery leaves a run nothing else can move.
+ # The two are mutually exclusive — each is a no-op for the other's node types.
+ expire_stale_kernel_run(run)
self._require_run_connection_access(run, user)
# Interrupted runs keep their envelope too: the walkthrough (Journey 9) promises the
diff --git a/products/notebooks/backend/sql_v2.py b/products/notebooks/backend/sql_v2.py
index 8af4d5ac97c1..8ca5dcdeb35f 100644
--- a/products/notebooks/backend/sql_v2.py
+++ b/products/notebooks/backend/sql_v2.py
@@ -195,9 +195,16 @@ def build_data_plane_url() -> str:
return f"{_backend_base_url()}/internal/notebooks/data_plane/query/"
-def mint_data_plane_token(notebook_short_id: str, team_id: int, user_id: int | None) -> str:
+def mint_data_plane_token(notebook_short_id: str, team_id: int, user_id: int | None, run_id: str | None = None) -> str:
+ """Sign a data-plane token for the sandbox.
+
+ `run_id` names the run the fetch belongs to, so a data-plane query counts as observable
+ progress on it (see `touch_run_progress`). It rides the signed token rather than the
+ request body because the sandbox must not be able to name a different run than the one
+ the backend dispatched to it.
+ """
return signing.dumps(
- {"notebook_short_id": notebook_short_id, "team_id": team_id, "user_id": user_id},
+ {"notebook_short_id": notebook_short_id, "team_id": team_id, "user_id": user_id, "run_id": run_id},
salt=_DATA_PLANE_TOKEN_SALT,
)
@@ -207,16 +214,21 @@ class DataPlaneClaims:
notebook_short_id: str
team_id: int
user_id: int | None
+ # Absent on a token minted before the run-progress claim existed, so it stays optional:
+ # such a token still fetches data, it just cannot advance its run's watchdog clock.
+ run_id: str | None = None
def verify_data_plane_token(token: str) -> DataPlaneClaims:
"""Return the claims from a valid token, else raise signing.BadSignature."""
data = signing.loads(token, salt=_DATA_PLANE_TOKEN_SALT, max_age=_DATA_PLANE_TOKEN_MAX_AGE_SECONDS)
user_id = data.get("user_id")
+ run_id = data.get("run_id")
return DataPlaneClaims(
notebook_short_id=str(data["notebook_short_id"]),
team_id=int(data["team_id"]),
user_id=int(user_id) if user_id is not None else None,
+ run_id=str(run_id) if run_id else None,
)
@@ -414,7 +426,7 @@ def dispatch_sql_v2_run(
"callback_url": build_callback_url(str(run.id)),
"callback_token": mint_callback_token(str(run.id), notebook.team_id),
"data_plane_url": build_data_plane_url(),
- "data_plane_token": mint_data_plane_token(notebook.short_id, notebook.team_id, user_id),
+ "data_plane_token": mint_data_plane_token(notebook.short_id, notebook.team_id, user_id, str(run.id)),
"page_limit": DISPLAY_PAGE_LIMIT,
"cache_limit": RESULT_CACHE_ROWS,
}
@@ -455,7 +467,7 @@ def fetch_sql_v2_page(notebook: Notebook, user: User | None, run: NotebookNodeRu
if run.node_type == NotebookNodeRun.NodeType.HOGQL:
payload["code"] = run.code
payload["data_plane_url"] = build_data_plane_url()
- payload["data_plane_token"] = mint_data_plane_token(notebook.short_id, notebook.team_id, user_id)
+ payload["data_plane_token"] = mint_data_plane_token(notebook.short_id, notebook.team_id, user_id, str(run.id))
else:
payload["result_id"] = str(run.result_id)
try:
diff --git a/products/notebooks/backend/sql_v2_data_plane.py b/products/notebooks/backend/sql_v2_data_plane.py
index 70de6969becc..b08397a14ce0 100644
--- a/products/notebooks/backend/sql_v2_data_plane.py
+++ b/products/notebooks/backend/sql_v2_data_plane.py
@@ -45,6 +45,7 @@ from products.notebooks.backend.sql_v2 import (
verify_data_plane_token,
)
from products.notebooks.backend.sql_v2_direct import apply_page_bounds
+from products.notebooks.backend.sql_v2_runs import touch_run_progress
from products.notebooks.backend.sql_v2_serializers import NotebookSQLV2DataPlaneRequestSerializer
logger = structlog.get_logger(__name__)
@@ -138,6 +139,13 @@ def notebook_sql_v2_data_plane(request: HttpRequest) -> HttpResponse:
if not Notebook.objects.filter(team_id=claims.team_id, short_id=claims.notebook_short_id).exists():
return JsonResponse({"error": "Notebook not found"}, status=404)
+
+ # This request is the kernel's only observable sign of life during a run, so it resets the
+ # run's watchdog clock. A python cell materializes one input per upstream node, one after
+ # another, and without this the watchdog would count that whole sequence against a single
+ # budget and fail a cell that is working correctly.
+ if claims.run_id:
+ touch_run_progress(claims.team_id, claims.run_id)
team = Team.objects.get(id=claims.team_id)
user = User.objects.filter(id=claims.user_id).first() if claims.user_id else None
diff --git a/products/notebooks/backend/sql_v2_direct.py b/products/notebooks/backend/sql_v2_direct.py
index 0323048063d5..3cd61b4633da 100644
--- a/products/notebooks/backend/sql_v2_direct.py
+++ b/products/notebooks/backend/sql_v2_direct.py
@@ -273,8 +273,8 @@ def sync_direct_run(run: NotebookNodeRun) -> list[list[Any]] | None:
except QueryNotFoundError:
age_seconds = (timezone.now() - run.created_at).total_seconds()
if run.status == NotebookNodeRun.Status.RUNNING and age_seconds > DIRECT_RUN_RESULT_GRACE_SECONDS:
- # The watchdog the kernel lane never had: with no status left to complete
- # this run, waiting longer cannot help.
+ # With no status left to complete this run, waiting longer cannot help.
+ # `expire_stale_kernel_run` is the kernel lane's counterpart.
finish_node_run(
run,
NotebookNodeRun.Status.FAILED,
diff --git a/products/notebooks/backend/sql_v2_runs.py b/products/notebooks/backend/sql_v2_runs.py
index 18689582cba6..44b5a84b8ec9 100644
--- a/products/notebooks/backend/sql_v2_runs.py
+++ b/products/notebooks/backend/sql_v2_runs.py
@@ -1,18 +1,37 @@
"""Claim a NotebookNodeRun's RUNNING -> terminal transition and report it exactly once.
Every lane that finishes a run funnels through `finish_node_run`: the direct (hogql)
-lane's pollers and grace-expiry watchdog, dispatch failures (the run view and the
-Temporal mark-failed activity), and the interrupt endpoints. The sandbox callback is
-the one deliberate exception — it upserts losing deliveries too, so a late real result
-can overwrite an interrupt placeholder — and keeps its own block in sql_v2_callback.py.
+lane's pollers and grace-expiry watchdog, the kernel lane's watchdog below, dispatch
+failures (the run view and the Temporal mark-failed activity), and the interrupt
+endpoints. The sandbox callback is the one deliberate exception — it upserts losing
+deliveries too, so a late real result can overwrite an interrupt placeholder — and keeps
+its own block in sql_v2_callback.py.
"""
from typing import Any
+from django.core.exceptions import ValidationError as DjangoValidationError
from django.utils import timezone
+import structlog
+
from products.notebooks.backend.models import NotebookNodeRun
-from products.notebooks.backend.sql_v2_metrics import outcome_for_status, record_node_run_terminal
+from products.notebooks.backend.sql_v2_metrics import OUTCOME_TIMED_OUT, outcome_for_status, record_node_run_terminal
+
+logger = structlog.get_logger(__name__)
+
+# How long a RUNNING kernel run may go **without observable progress** before a watchdog
+# fails it. The kernel lane's analogue of DIRECT_RUN_RESULT_GRACE_SECONDS, and necessarily
+# wider, because one cell can spend a long time in the kernel before it reports anything.
+#
+# This is a gap budget, not a total-runtime budget, and the distinction is load-bearing. A
+# python node materializes one input per referenced upstream node, one after another, each
+# with its own 11 minute data-plane deadline, and only then executes for up to 5 minutes. No
+# fixed total-runtime budget can hold: two inputs already outrun 20 minutes while the cell is
+# working correctly. `touch_run_progress` re-anchors the clock on every input the kernel
+# fetches, so what must fit here is the longest gap between two signs of life — one input's
+# wait plus the execute cap — rather than their sum over N inputs.
+KERNEL_RUN_RESULT_GRACE_SECONDS = 20 * 60
def finish_node_run(
@@ -47,3 +66,62 @@ def finish_node_run(
if updated:
record_node_run_terminal(run, outcome or outcome_for_status(status))
return bool(updated)
+
+
+def touch_run_progress(team_id: int, run_id: str) -> None:
+ """Record that the kernel is still working on `run_id`, resetting its watchdog clock.
+
+ Called from the data plane, which is the kernel's only way back to PostHog during a run:
+ every uncached HogQL input it materializes lands there. Without this the watchdog would
+ measure total runtime from dispatch, and a cell with several inputs would outrun the
+ budget while working correctly.
+
+ Guarded on RUNNING so a late fetch cannot revive the clock of a run a callback or the
+ watchdog already finished. Best effort: the run's progress matters less than the query
+ the sandbox is waiting on, so a failure here must never fail the fetch.
+ """
+ try:
+ NotebookNodeRun.objects.for_team(team_id).filter(id=run_id, status=NotebookNodeRun.Status.RUNNING).update(
+ updated_at=timezone.now()
+ )
+ except (DjangoValidationError, ValueError):
+ # The id comes out of a signed token, so a malformed one means the minting side has a
+ # bug. Swallow it here rather than failing the sandbox's fetch over it.
+ logger.warning("notebook_run_progress_touch_invalid_run_id", run_id=run_id, team_id=team_id)
+
+
+def expire_stale_kernel_run(run: NotebookNodeRun) -> bool:
+ """Fail a kernel (python/duckdb) run whose callback never arrived; return whether it did.
+
+ The sandbox POSTs its envelope exactly once, with no retry, so a lost delivery leaves
+ the row RUNNING with nothing left to complete it. The dispatch workflow's mark-failed
+ activity does not cover this: it fires when dispatch never landed, not when a run landed
+ and then went quiet. This is the watchdog the kernel lane never had, mirroring
+ `sync_direct_run`'s grace expiry for the lane that already has one.
+
+ Anchored on `updated_at`, which dispatch writes when it records the kernel that took the
+ run and `touch_run_progress` re-writes on every data-plane fetch, so the budget measures
+ the gap since the kernel was last seen working rather than the run's total time.
+
+ One gap stays uncovered: a run queued in the kernel behind another cell makes no fetches
+ of its own, so its clock runs while it waits. That needs several runs dispatched to one
+ kernel at once, which the editor never does (a chain waits for each cell), so it takes an
+ API caller running cells in parallel.
+
+ Safe to call from any reader: it is a no-op for a hogql run, for a run that already
+ reached a terminal state, and for one still inside its budget.
+ """
+ if run.node_type == NotebookNodeRun.NodeType.HOGQL:
+ return False
+ if run.status != NotebookNodeRun.Status.RUNNING:
+ return False
+ if (timezone.now() - run.updated_at).total_seconds() <= KERNEL_RUN_RESULT_GRACE_SECONDS:
+ return False
+ return finish_node_run(
+ run,
+ NotebookNodeRun.Status.FAILED,
+ error="The kernel never reported a result. Re-run the cell.",
+ # A lost callback is a timeout, not a user error — the status alone would file it
+ # under the same bucket as a failed query.
+ outcome=OUTCOME_TIMED_OUT,
+ )
diff --git a/products/notebooks/backend/temporal/__init__.py b/products/notebooks/backend/temporal/__init__.py
index 4b7808a9e400..5b4258011857 100644
--- a/products/notebooks/backend/temporal/__init__.py
+++ b/products/notebooks/backend/temporal/__init__.py
@@ -6,6 +6,7 @@ from products.notebooks.backend.temporal.frame_materialize import (
from products.notebooks.backend.temporal.sql_v2 import (
NotebookSQLV2RunWorkflow,
dispatch_sql_v2_run_activity,
+ expire_sql_v2_run_activity,
mark_sql_v2_run_failed_activity,
)
@@ -16,6 +17,7 @@ WORKFLOWS = [
ACTIVITIES = [
dispatch_sql_v2_run_activity,
+ expire_sql_v2_run_activity,
mark_sql_v2_run_failed_activity,
materialize_frame_activity,
mark_frame_materialize_failed_activity,
diff --git a/products/notebooks/backend/temporal/sql_v2.py b/products/notebooks/backend/temporal/sql_v2.py
index 8ad8bd48a133..1b0fe6ef0141 100644
--- a/products/notebooks/backend/temporal/sql_v2.py
+++ b/products/notebooks/backend/temporal/sql_v2.py
@@ -4,6 +4,10 @@ The run endpoint kicks this off fire-and-forget so the sandbox I/O (kernel-serve
bootstrap on first run, the /run POST) runs on a Temporal worker with retries —
never on a web worker. Instance lifecycle is owned by the Kernel info panel
(kernel/start); dispatch lazily ensures the SQLV2 server on the running kernel.
+
+After dispatch lands, the workflow stays open as the run's watchdog: the sandbox delivers
+its envelope in one un-retried POST, so a lost delivery would otherwise leave the run row
+RUNNING with nothing able to move it.
"""
from dataclasses import dataclass, field
@@ -18,7 +22,17 @@ from posthog.temporal.common.base import PostHogWorkflow
from products.notebooks.backend.kernel_runtime import get_kernel_runtime
from products.notebooks.backend.models import Notebook, NotebookNodeRun
from products.notebooks.backend.sql_v2 import SQLV2KernelNotRunning, dispatch_sql_v2_run
-from products.notebooks.backend.sql_v2_runs import finish_node_run
+from products.notebooks.backend.sql_v2_runs import (
+ KERNEL_RUN_RESULT_GRACE_SECONDS,
+ expire_stale_kernel_run,
+ finish_node_run,
+)
+
+# Margin on top of the run budget before the workflow applies the watchdog. The budget is
+# measured from `updated_at` in the database and the sleep is measured by Temporal, so a
+# sleep of exactly the budget can land a moment early and find the run still inside it,
+# which would leave the row stuck with nobody left to check it again.
+_EXPIRY_MARGIN_SECONDS = 60
@dataclass
@@ -81,6 +95,16 @@ def mark_sql_v2_run_failed_activity(input: SQLV2RunInput) -> None:
finish_node_run(run, NotebookNodeRun.Status.FAILED, error="Run failed to dispatch to the kernel.")
[email protected](name="notebook-sandbox-cmd-expire")
+def expire_sql_v2_run_activity(input: SQLV2RunInput) -> None:
+ # The watchdog for a run the kernel accepted but never reported on. Guarded inside
+ # expire_stale_kernel_run on both status and elapsed time, so a run whose callback
+ # landed keeps its real outcome and this call does nothing.
+ run = NotebookNodeRun.objects.for_team(input.team_id).filter(id=input.run_id).first()
+ if run is not None:
+ expire_stale_kernel_run(run)
+
+
@workflow.defn(name="notebook-sandbox-cmd-run")
class NotebookSQLV2RunWorkflow(PostHogWorkflow):
inputs_cls = SQLV2RunInput
@@ -106,3 +130,22 @@ class NotebookSQLV2RunWorkflow(PostHogWorkflow):
retry_policy=common.RetryPolicy(maximum_attempts=3),
)
raise
+
+ # Dispatch landed, so the kernel owns the run. Its envelope POST is a single attempt
+ # with no retry, and losing it would strand the row RUNNING forever: the poll's
+ # watchdog only fires for a run somebody is still watching, and an abandoned tab or a
+ # finished agent means nobody is. Waiting here is a Temporal timer rather than a
+ # worker slot, and this workflow already exists one-per-kernel-run, so the cost is a
+ # longer-lived execution rather than a new one.
+ await workflow.sleep(timedelta(seconds=KERNEL_RUN_RESULT_GRACE_SECONDS + _EXPIRY_MARGIN_SECONDS))
+ # The watchdog is the run's last resort. A brief database outage while it fires must
+ # not burn a three-attempt budget and leave the row RUNNING with nothing left to move
+ # it. The activity is idempotent (guarded on status and elapsed time), so retry until
+ # it lands, bounded by schedule_to_close rather than a fixed attempt count.
+ await workflow.execute_activity(
+ expire_sql_v2_run_activity,
+ input,
+ start_to_close_timeout=timedelta(seconds=30),
+ schedule_to_close_timeout=timedelta(hours=1),
+ retry_policy=common.RetryPolicy(maximum_attempts=0),
+ )
diff --git a/products/notebooks/backend/test/test_sql_v2.py b/products/notebooks/backend/test/test_sql_v2.py
index f788868fa3ce..6a04cc1afd2d 100644
--- a/products/notebooks/backend/test/test_sql_v2.py
+++ b/products/notebooks/backend/test/test_sql_v2.py
@@ -1275,10 +1275,16 @@ class TestSQLV2RunResult(APIBaseTest):
def _url(self, run_id: str) -> str:
return f"/api/projects/{self.team.id}/notebooks/{self.notebook.short_id}/sql_v2/runs/{run_id}/"
- def _create_run(self, status, envelope=None, error="") -> NotebookNodeRun:
+ def _create_run(self, status, envelope=None, error="", node_type=NotebookNodeRun.NodeType.HOGQL) -> NotebookNodeRun:
with team_scope(self.team.id):
return NotebookNodeRun.objects.create(
- team=self.team, notebook=self.notebook, node_id="n1", status=status, envelope=envelope, error=error
+ team=self.team,
+ notebook=self.notebook,
+ node_id="n1",
+ status=status,
+ envelope=envelope,
+ error=error,
+ node_type=node_type,
)
@parameterized.expand(
@@ -1330,18 +1336,26 @@ class TestSQLV2RunResult(APIBaseTest):
_restrict_query_access(self)
self.assertEqual(self.client.get(self._url(str(run.id))).status_code, 403)
+ @parameterized.expand(
+ [
+ # hogql: no query status left, so the run can never complete.
+ ("direct", NotebookNodeRun.NodeType.HOGQL, "expired"),
+ # python: the sandbox delivers its envelope once with no retry, so a lost
+ # delivery leaves nothing able to move the row.
+ ("kernel", NotebookNodeRun.NodeType.PYTHON, "never reported"),
+ ]
+ )
@patch("products.notebooks.backend.presentation.views.notebook.is_sql_v2_enabled", return_value=True)
- def test_running_direct_run_expires_to_failed_after_grace(self, _mock_enabled):
- # A RUNNING hogql run with no query status left can never complete — this poll is
- # its watchdog. Within the grace window it keeps waiting (covers pre-deploy
- # kernel-executed hogql runs whose callback is still due).
+ def test_running_run_expires_to_failed_after_grace(self, _name, node_type, expected_error, _mock_enabled):
+ # This poll is the watchdog for both lanes. Within the grace window it keeps waiting,
+ # which for hogql also covers pre-deploy kernel-executed runs whose callback is due.
with freeze_time("2026-07-01T00:00:00Z"):
- expired = self._create_run(NotebookNodeRun.Status.RUNNING)
+ expired = self._create_run(NotebookNodeRun.Status.RUNNING, node_type=node_type)
body = self.client.get(self._url(str(expired.id))).json()
self.assertEqual(body["status"], NotebookNodeRun.Status.FAILED)
- self.assertIn("expired", body["error"])
+ self.assertIn(expected_error, body["error"])
- young = self._create_run(NotebookNodeRun.Status.RUNNING)
+ young = self._create_run(NotebookNodeRun.Status.RUNNING, node_type=node_type)
body = self.client.get(self._url(str(young.id))).json()
self.assertEqual(body["status"], NotebookNodeRun.Status.RUNNING)
@@ -1734,6 +1748,57 @@ class TestSQLV2DataPlaneEndpoint(APIBaseTest):
self.assertEqual(types[0][0], "answer")
self.assertIn("Int", types[0][1])
+ @parameterized.expand(
+ [
+ # The reviewer's case on #88304: a python cell materializes one input per upstream
+ # node, in sequence, each with its own 11 minute data-plane deadline. Measured from
+ # dispatch, a two-input cell outruns the 20 minute budget while working correctly,
+ # and the watchdog fails it. A fetch is the kernel's only sign of life mid-run, so
+ # it has to move the clock.
+ ("running_run_stays_alive", NotebookNodeRun.Status.RUNNING, False, NotebookNodeRun.Status.RUNNING),
+ # And the guard on the other side: a fetch arriving after the run already finished
+ # must not revive its clock, or a late straggler would resurrect a settled row.
+ ("finished_run_is_not_revived", NotebookNodeRun.Status.DONE, False, NotebookNodeRun.Status.DONE),
+ ]
+ )
+ def test_a_data_plane_fetch_resets_the_run_watchdog_clock(
+ self, _name, initial_status, expect_expired, expected_status
+ ):
+ with freeze_time("2026-07-01T00:00:00Z"), team_scope(self.team.id):
+ run = NotebookNodeRun.objects.create(
+ team=self.team,
+ notebook=self.notebook,
+ node_id="n1",
+ node_type=NotebookNodeRun.NodeType.PYTHON,
+ status=initial_status,
+ )
+ token = mint_data_plane_token(self.notebook.short_id, self.team.id, self.user.id, str(run.id))
+ self.assertEqual(self._post({"query": "select 1"}, token=token).status_code, 202)
+
+ from products.notebooks.backend.sql_v2_runs import expire_stale_kernel_run
+
+ run.refresh_from_db()
+ self.assertEqual(expire_stale_kernel_run(run), expect_expired)
+ self.assertEqual(run.status, expected_status)
+
+ def test_a_fetch_without_a_run_claim_touches_no_run(self):
+ # Tokens minted before the run claim existed stay valid across the deploy that adds
+ # it. They fetch data as before; they just cannot advance any run's clock.
+ with freeze_time("2026-07-01T00:00:00Z"), team_scope(self.team.id):
+ run = NotebookNodeRun.objects.create(
+ team=self.team,
+ notebook=self.notebook,
+ node_id="n1",
+ node_type=NotebookNodeRun.NodeType.PYTHON,
+ status=NotebookNodeRun.Status.RUNNING,
+ )
+ self.assertEqual(self._post({"query": "select 1"}, token=self._token()).status_code, 202)
+
+ from products.notebooks.backend.sql_v2_runs import expire_stale_kernel_run
+
+ run.refresh_from_db()
+ self.assertTrue(expire_stale_kernel_run(run))
+
def test_outer_limit_and_offset_cap_the_page(self):
response = self._run_to_completion({"query": "select number from numbers(10)", "limit": 3, "offset": 2})
self.assertEqual(response.status_code, 200, response.content)