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): add node-run observability (#72849)

Sinan Kucukkoselerf9ffbc3c2566
diff --git a/products/notebooks/backend/presentation/views/notebook.py b/products/notebooks/backend/presentation/views/notebook.py
index 043b6b1e5634..a6577bbe0bfa 100644
--- a/products/notebooks/backend/presentation/views/notebook.py
+++ b/products/notebooks/backend/presentation/views/notebook.py
@@ -79,6 +79,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_serializers import (
NotebookSQLV2PageRequestSerializer,
NotebookSQLV2RunRequestSerializer,
@@ -1106,9 +1107,9 @@ class NotebookViewSet(TeamAndOrgViewSetMixin, AccessControlViewSetMixin, ForbidD
)
except Exception:
logger.exception("notebook_sql_v2_run_start_failed", notebook_short_id=notebook.short_id)
- run.status = NotebookNodeRun.Status.FAILED
- run.error = "Failed to start run."
- run.save(update_fields=["status", "error", "updated_at"])
+ # Status-guarded: a dispatch that partially started before raising could still
+ # deliver a callback, which must keep the row and stay the only reporter.
+ finish_node_run(run, NotebookNodeRun.Status.FAILED, error="Failed to start run.")
return Response({"detail": "Failed to start run."}, status=503)
return Response({"run_id": str(run.id)})
@@ -1271,14 +1272,7 @@ class NotebookViewSet(TeamAndOrgViewSetMixin, AccessControlViewSetMixin, ForbidD
# runs to its bounded completion. Mark the row abandoned; the guarded update
# yields to a completion that already landed, and sync_direct_run's own guard
# can never overwrite this interrupt afterwards.
- NotebookNodeRun.objects.for_team(self.team_id).filter(
- id=run.id, status=NotebookNodeRun.Status.RUNNING
- ).update(
- status=NotebookNodeRun.Status.INTERRUPTED,
- error="Run stopped.",
- updated_at=now(),
- )
- run.refresh_from_db()
+ finish_node_run(run, NotebookNodeRun.Status.INTERRUPTED, error="Run stopped.")
return Response({"status": run.status})
try:
@@ -1306,9 +1300,9 @@ class NotebookViewSet(TeamAndOrgViewSetMixin, AccessControlViewSetMixin, ForbidD
# No reachable kernel anywhere: the callback can never arrive, so this is the
# user's escape hatch out of a stuck RUNNING row. A late callback (e.g. the
# sandbox comes back) simply overwrites with the real outcome.
- run.status = NotebookNodeRun.Status.INTERRUPTED
- run.error = "Kernel is not reachable, so the run was stopped."
- run.save(update_fields=["status", "error", "updated_at"])
+ finish_node_run(
+ run, NotebookNodeRun.Status.INTERRUPTED, error="Kernel is not reachable, so the run was stopped."
+ )
return Response({"status": run.status})
if not known:
diff --git a/products/notebooks/backend/sandbox/kernel/data_plane.py b/products/notebooks/backend/sandbox/kernel/data_plane.py
index b78c2be55401..074482c5362e 100644
--- a/products/notebooks/backend/sandbox/kernel/data_plane.py
+++ b/products/notebooks/backend/sandbox/kernel/data_plane.py
@@ -73,7 +73,7 @@ def fetch_query_page(
cancel_event: "threading.Event | None" = None,
) -> tuple[list[str], list[tuple[Any, ...]], list[list[str]]]:
"""Run `query` through the data plane; return (columns, rows, types) of the capped page."""
- table, _source = _request_table(url, token, query, limit, offset, cancel_event=cancel_event)
+ table, _source, _download_s = _request_table(url, token, query, limit, offset, cancel_event=cancel_event)
return _table_to_rows_and_types(table)
@@ -85,24 +85,27 @@ def materialize_query_to_file(
limit: int,
offset: int = 0,
cancel_event: "threading.Event | None" = None,
-) -> tuple[int, str | None]:
+) -> tuple[int, str | None, float]:
"""Fetch the full result of `query` and write it as a local Arrow IPC file for a Python/DuckDB node.
- Returns (row count, truncated frame-store URL preview) — the preview is set only when
- the frame actually came from a presigned object download (None on the inline fallback),
- so callers can surface which store served the frame. Requests object delivery: the poll
- answers with a 302 to a presigned object-store URL carrying the same Arrow bytes
- (falling back to the inline body when the backend's frame store is unavailable). The
- file is written to a temp name and renamed on success so a torn write (e.g. a
- mid-stream failure) never leaves a half-frame the kernel could read.
+ Returns (row count, truncated frame-store URL preview, presigned download seconds) —
+ the preview is set only when the frame actually came from a presigned object download
+ (None on the inline fallback, with 0.0 download seconds), so callers can surface which
+ store served the frame. Requests object delivery: the poll answers with a 302 to a
+ presigned object-store URL carrying the same Arrow bytes (falling back to the inline
+ body when the backend's frame store is unavailable). The file is written to a temp
+ name and renamed on success so a torn write (e.g. a mid-stream failure) never leaves
+ a half-frame the kernel could read.
"""
- table, source = _request_table(url, token, query, limit, offset, delivery="object", cancel_event=cancel_event)
+ table, source, download_s = _request_table(
+ url, token, query, limit, offset, delivery="object", cancel_event=cancel_event
+ )
temp_path = f"{dest_path}.partial"
with pa.OSFile(temp_path, "wb") as sink:
with pa.ipc.new_file(sink, table.schema) as writer:
writer.write_table(table)
os.replace(temp_path, dest_path)
- return table.num_rows, source
+ return table.num_rows, source, download_s
def _check_cancelled(cancel_event: "threading.Event | None") -> None:
@@ -118,11 +121,12 @@ def _request_table(
offset: int,
delivery: str = "inline",
cancel_event: "threading.Event | None" = None,
-) -> tuple["pa.Table", str | None]:
+) -> tuple["pa.Table", str | None, float]:
"""POST the query and (once the async manager finishes) return the raw Arrow table.
The second element is a truncated presigned-URL preview when the rows came from an
- object download, else None.
+ object download, else None; the third is the presigned download's duration in
+ seconds (0.0 when the rows arrived inline).
"""
_check_cancelled(cancel_event)
body: dict[str, Any] = {"query": query, "limit": limit, "offset": offset}
@@ -141,7 +145,7 @@ def _request_table(
with urllib.request.urlopen(request, timeout=_REQUEST_TIMEOUT_SECONDS) as response:
if _is_arrow(response):
# A pre-async-manager backend answers the POST with the rows directly.
- return _read_table(response), None
+ return _read_table(response), None, 0.0
body = json.loads(response.read() or b"{}")
except urllib.error.HTTPError as exc:
raise DataPlaneError(_error_detail(exc)) from exc
@@ -163,7 +167,7 @@ def _poll_for_table(
token: str,
expect_object: bool = False,
cancel_event: "threading.Event | None" = None,
-) -> tuple["pa.Table", str | None]:
+) -> tuple["pa.Table", str | None, float]:
request = urllib.request.Request(status_url, headers={"Authorization": f"Bearer {token}"}, method="GET")
# Only object-delivery polls intercept the completion 302 (a presigned frame handoff).
# Inline polls keep urllib's transparent redirect-following, so an infrastructure
@@ -180,7 +184,7 @@ def _poll_for_table(
# nosemgrep: python.lang.security.audit.dynamic-urllib-use-detected.dynamic-urllib-use-detected
with opener(request, timeout=_REQUEST_TIMEOUT_SECONDS) as response:
if _is_arrow(response):
- return _read_table(response), None
+ return _read_table(response), None, 0.0
# 202 — still running.
except urllib.error.HTTPError as exc:
if expect_object and exc.code == 302:
@@ -199,24 +203,25 @@ def _poll_for_table(
raise DataPlaneError("Timed out waiting for the query to finish")
-def _fetch_presigned_table(presigned_url: str) -> tuple["pa.Table", str]:
+def _fetch_presigned_table(presigned_url: str) -> tuple["pa.Table", str, float]:
"""Download the frame object from the presigned URL — deliberately credential-free.
The URL is its own short-lived authorization; the data-plane token must never reach
the object-store host. Range-based resume of an interrupted download is deferred.
- Returns the table plus a truncated URL preview — never the full URL, which is a
- bearer secret and must not travel beyond this fetch.
+ Returns the table, a truncated URL preview — never the full URL, which is a bearer
+ secret and must not travel beyond this fetch — and the download's wall time.
"""
if not presigned_url:
raise DataPlaneError("Data plane redirect carried no download URL")
source_preview = presigned_url[:_FRAME_SOURCE_PREVIEW_CHARS]
request = urllib.request.Request(presigned_url, method="GET")
+ started = time.monotonic()
try:
# The URL comes from our own backend's redirect (minted after token verification),
# never from user input.
# nosemgrep: python.lang.security.audit.dynamic-urllib-use-detected.dynamic-urllib-use-detected
with urllib.request.urlopen(request, timeout=_REQUEST_TIMEOUT_SECONDS) as response:
- return _read_table(response), source_preview
+ return _read_table(response), source_preview, time.monotonic() - started
except urllib.error.HTTPError as exc:
raise DataPlaneError(f"Frame download failed with HTTP {exc.code}") from exc
except urllib.error.URLError as exc:
diff --git a/products/notebooks/backend/sandbox/kernel/executor.py b/products/notebooks/backend/sandbox/kernel/executor.py
index 8f6a1e5aedd6..73af78fe4dd9 100644
--- a/products/notebooks/backend/sandbox/kernel/executor.py
+++ b/products/notebooks/backend/sandbox/kernel/executor.py
@@ -59,22 +59,36 @@ class KernelExecutor:
# Cancelled while queued behind another run: never touch the kernel.
if cancel_event is not None and cancel_event.is_set():
return envelope.from_python_execution(status="interrupted", error=envelope.INTERRUPTED_MESSAGE)
+ # Attached to every envelope — error paths included, so a run that died waiting
+ # on the data plane still reports where its time went (the backend turns these
+ # into the kernel-phase metrics).
+ timings: dict[str, float] = {}
try:
- self._ensure_kernel()
+ boot_started = time.monotonic()
+ try:
+ self._ensure_kernel()
+ finally:
+ # ~0 when the kernel is already warm; a cold start — or a boot
+ # failure — shows up as its own phase instead of unattributed time.
+ timings["kernel_boot_s"] = round(time.monotonic() - boot_started, 3)
fetch_notes: list[str] = []
- inputs = self._materialize_inputs(payload, cancel_event, fetch_notes)
+ inputs = self._materialize_inputs(payload, cancel_event, fetch_notes, timings)
+ exec_started = time.monotonic()
result = self._invoke_run_node(payload, inputs)
+ timings["exec_s"] = round(time.monotonic() - exec_started, 3)
if fetch_notes:
# Surface where each frame's bytes came from (truncated presigned host,
# never the full URL) in the node's stdout, next to the run's own output.
result["stdout"] = "\n".join([*fetch_notes, result.get("stdout") or ""]).strip("\n")
- return result
except data_plane.DataPlaneInterrupted:
- return envelope.from_python_execution(status="interrupted", error=envelope.INTERRUPTED_MESSAGE)
+ result = envelope.from_python_execution(status="interrupted", error=envelope.INTERRUPTED_MESSAGE)
except data_plane.DataPlaneError as exc:
- return envelope.from_python_execution(status="error", error=str(exc))
+ result = envelope.from_python_execution(status="error", error=str(exc))
except Exception as exc: # noqa: BLE001 — a run must always yield a callback envelope
- return envelope.from_python_execution(status="error", error=f"Kernel run failed: {exc}")
+ result = envelope.from_python_execution(status="error", error=f"Kernel run failed: {exc}")
+ if timings:
+ result["timings"] = {**timings, **(result.get("timings") or {})}
+ return result
def interrupt(self) -> None:
if self._km is not None:
@@ -126,8 +140,14 @@ class KernelExecutor:
payload: dict[str, Any],
cancel_event: threading.Event | None = None,
fetch_notes: list[str] | None = None,
+ timings: dict[str, float] | None = None,
) -> list[dict[str, Any]]:
- """Fetch each HogQL input to a local Arrow file; return the kernel-facing input specs (paths only)."""
+ """Fetch each HogQL input to a local Arrow file; return the kernel-facing input specs (paths only).
+
+ When `timings` is given, accumulates `input_wait_s` (total wall time waiting on the
+ data plane across all inputs; cached frames add nothing) and `download_s` (the
+ presigned-download share of that wait) into it.
+ """
kernel_inputs: list[dict[str, Any]] = []
for spec in payload.get("inputs") or []:
if cancel_event is not None and cancel_event.is_set():
@@ -145,14 +165,25 @@ class KernelExecutor:
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)
- _row_count, fetched_from = data_plane.materialize_query_to_file(
- payload["data_plane_url"],
- payload["data_plane_token"],
- spec["query"],
- frame_path,
- limit=_MATERIALIZE_ROW_CAP,
- cancel_event=cancel_event,
- )
+ wait_started = time.monotonic()
+ try:
+ _row_count, fetched_from, download_s = data_plane.materialize_query_to_file(
+ payload["data_plane_url"],
+ payload["data_plane_token"],
+ spec["query"],
+ frame_path,
+ limit=_MATERIALIZE_ROW_CAP,
+ cancel_event=cancel_event,
+ )
+ finally:
+ # Accumulated even when the fetch raises — a run that died waiting on the
+ # data plane is exactly the one whose wait must stay visible.
+ if timings is not None:
+ timings["input_wait_s"] = round(
+ timings.get("input_wait_s", 0.0) + (time.monotonic() - wait_started), 3
+ )
+ if timings is not None:
+ timings["download_s"] = round(timings.get("download_s", 0.0) + download_s, 3)
if fetched_from and fetch_notes is not None:
# Only object deliveries carry a source (the inline fallback has none) —
# this makes the frame-store path visible in the node output.
diff --git a/products/notebooks/backend/sandbox/kernel/runner.py b/products/notebooks/backend/sandbox/kernel/runner.py
index bf29bbd9c441..fc623437e5a4 100644
--- a/products/notebooks/backend/sandbox/kernel/runner.py
+++ b/products/notebooks/backend/sandbox/kernel/runner.py
@@ -13,6 +13,7 @@ sql_v2_kernel_architecture.md.
"""
import json
+import time
import logging
import threading
import urllib.error
@@ -76,6 +77,7 @@ def execute_run(payload: dict[str, Any]) -> None:
logger.warning("nb_kernel ignoring duplicate /run for in-flight run %s", run_id)
return
_cancel_states[run_id] = {"event": cancel_event, "kernel": is_kernel_node}
+ started = time.monotonic()
try:
# Interrupt-caused failures are labeled at the source (DataPlaneInterrupted, a
# SIGINT'd cell), so a real failure that merely raced the cancel keeps its error —
@@ -87,6 +89,11 @@ def execute_run(payload: dict[str, Any]) -> None:
finally:
with _cancel_states_lock:
_cancel_states.pop(run_id, None)
+ # The whole sandbox-side run — dominated by the phases below it but also covering
+ # kernel boot and queueing behind another run's cell. Backed out into metrics by the
+ # backend callback (sql_v2_metrics.py).
+ timings = result.setdefault("timings", {})
+ timings["sandbox_total_s"] = round(time.monotonic() - started, 3)
_post_callback(payload["callback_url"], payload["callback_token"], result)
@@ -156,24 +163,35 @@ def _build_envelope(payload: dict[str, Any], cancel_event: threading.Event | Non
page_limit = int(payload.get("page_limit") or _DEFAULT_PAGE_LIMIT)
cache_limit = max(int(payload.get("cache_limit") or _DEFAULT_CACHE_LIMIT), page_limit)
+ # The data-plane wait for the display fetch — the same phase a kernel node's input
+ # materialization reports, so one metric covers both lanes. Attached on error paths
+ # too: a run that died waiting on the data plane must still report where its time went.
+ timings: dict[str, float] = {}
try:
- result = _fetch_capped_page(payload, limit=cache_limit, offset=0, cancel_event=cancel_event)
+ fetch_started = time.monotonic()
+ try:
+ result = _fetch_capped_page(payload, limit=cache_limit, offset=0, cancel_event=cancel_event)
+ finally:
+ timings["input_wait_s"] = round(time.monotonic() - fetch_started, 3)
rows = envelope.json_safe_rows(result["rows"])
run_id = str(payload.get("run_id") or "")
if run_id:
_cache_result(run_id, result["columns"], result["types"], rows, complete=not result["has_more"])
- return envelope.from_columns_and_rows(
+ built = envelope.from_columns_and_rows(
result["columns"],
result["rows"][:page_limit],
result["types"],
has_more=result["has_more"] or len(rows) > page_limit,
)
except data_plane.DataPlaneInterrupted:
- return envelope.as_interrupted(envelope.from_error(envelope.INTERRUPTED_MESSAGE))
+ built = envelope.as_interrupted(envelope.from_error(envelope.INTERRUPTED_MESSAGE))
except data_plane.DataPlaneError as exc:
- return envelope.from_error(str(exc))
+ built = envelope.from_error(str(exc))
except Exception as exc: # noqa: BLE001 — any failure must still produce a callback
- return envelope.from_error(f"Run failed in the sandbox: {exc}")
+ built = envelope.from_error(f"Run failed in the sandbox: {exc}")
+ if timings:
+ built["timings"] = timings
+ return built
def fetch_page(payload: dict[str, Any]) -> dict[str, Any]:
diff --git a/products/notebooks/backend/sql_v2_callback.py b/products/notebooks/backend/sql_v2_callback.py
index 44233129bcf8..6f9ba00029b2 100644
--- a/products/notebooks/backend/sql_v2_callback.py
+++ b/products/notebooks/backend/sql_v2_callback.py
@@ -10,12 +10,14 @@ import json
from django.core import signing
from django.db.models import Q
from django.http import JsonResponse
+from django.utils import timezone
import structlog
from drf_spectacular.utils import OpenApiResponse, extend_schema
from products.notebooks.backend.models import KernelRuntime, NotebookNodeRun
from products.notebooks.backend.sql_v2 import verify_callback_token
+from products.notebooks.backend.sql_v2_metrics import outcome_for_status, record_node_run_terminal
from products.notebooks.backend.sql_v2_serializers import NotebookSQLV2CallbackRequestSerializer
logger = structlog.get_logger(__name__)
@@ -97,10 +99,29 @@ def notebook_sql_v2_callback(request, run_id: str) -> JsonResponse:
run.envelope = envelope
run.result_id = envelope.get("result_id")
run.error = envelope.get("error")
- run.save(update_fields=["status", "envelope", "result_id", "error", "updated_at"])
+ # Claim the RUNNING -> terminal transition with a status-guarded UPDATE so exactly one
+ # delivery wins it — concurrent re-deliveries must not each report the run's metrics.
+ # A loser still writes the row (the deliberate upsert: a late real result may overwrite
+ # an interrupt placeholder), it just doesn't report.
+ won_transition = bool(
+ NotebookNodeRun.objects.for_team(team_id)
+ .filter(id=run.id, status=NotebookNodeRun.Status.RUNNING)
+ .update(
+ status=run.status,
+ envelope=run.envelope,
+ result_id=run.result_id,
+ error=run.error,
+ updated_at=timezone.now(),
+ )
+ )
+ if not won_transition:
+ run.save(update_fields=["status", "envelope", "result_id", "error", "updated_at"])
_store_frame_snapshot(run, frames, team_id)
+ if won_transition:
+ record_node_run_terminal(run, outcome_for_status(run.status))
+
return JsonResponse({"ok": True})
diff --git a/products/notebooks/backend/sql_v2_direct.py b/products/notebooks/backend/sql_v2_direct.py
index ec6fc96d3375..cf02887e4cb4 100644
--- a/products/notebooks/backend/sql_v2_direct.py
+++ b/products/notebooks/backend/sql_v2_direct.py
@@ -25,6 +25,8 @@ from posthog.clickhouse.query_tagging import Feature, Product, tags_context
from products.notebooks.backend.models import NotebookNodeRun
from products.notebooks.backend.sandbox.kernel import envelope as kernel_envelope
from products.notebooks.backend.sql_v2 import DISPLAY_PAGE_LIMIT, RESULT_CACHE_ROWS
+from products.notebooks.backend.sql_v2_metrics import OUTCOME_TIMED_OUT
+from products.notebooks.backend.sql_v2_runs import finish_node_run
if TYPE_CHECKING:
from posthog.models import Team, User
@@ -93,29 +95,23 @@ def enqueue_direct_run(team: "Team", user: "User | None", run: NotebookNodeRun)
)
-def _finish_direct_run(
- run: NotebookNodeRun, status: NotebookNodeRun.Status, envelope: dict | None, error: str | None
-) -> bool:
- """Move a RUNNING run to a terminal state; return whether this call won the transition.
+def _query_status_timings(status: Any) -> dict[str, float]:
+ """Decompose a completed QueryStatus into phase timings for the run envelope.
- Guarded on the current status so concurrent pollers are idempotent and a completed
- query can never overwrite an interrupt — the opposite of the kernel callback's
- deliberate upsert, because here nothing later holds a truer outcome. Refreshes
- `run` either way so the caller always sees the row that won.
+ `queued_s` is enqueue -> Celery pickup (slot/queue wait); `clickhouse_s` is pickup ->
+ completion — HogQL compile plus the ClickHouse execution, the closest server-side
+ proxy for "how long the query itself took". Both are the decomposition fields
+ sql_v2_observability.md gap 1 called for.
"""
- updated = (
- NotebookNodeRun.objects.for_team(run.team_id)
- .filter(id=run.id, status=NotebookNodeRun.Status.RUNNING)
- .update(
- status=status,
- envelope=envelope,
- result_id=(envelope or {}).get("result_id"),
- error=error,
- updated_at=timezone.now(),
- )
- )
- run.refresh_from_db()
- return bool(updated)
+ timings: dict[str, float] = {}
+ start_time = getattr(status, "start_time", None)
+ pickup_time = getattr(status, "pickup_time", None)
+ end_time = getattr(status, "end_time", None)
+ if start_time and pickup_time:
+ timings["queued_s"] = round(max((pickup_time - start_time).total_seconds(), 0.0), 3)
+ if pickup_time and end_time:
+ timings["clickhouse_s"] = round(max((end_time - pickup_time).total_seconds(), 0.0), 3)
+ return timings
def sync_direct_run(run: NotebookNodeRun) -> list[list[Any]] | None:
@@ -139,11 +135,11 @@ def sync_direct_run(run: NotebookNodeRun) -> list[list[Any]] | None:
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.
- _finish_direct_run(
+ finish_node_run(
run,
NotebookNodeRun.Status.FAILED,
- envelope=None,
error="The query expired before completing. Re-run it.",
+ outcome=OUTCOME_TIMED_OUT,
)
return None
@@ -152,7 +148,7 @@ def sync_direct_run(run: NotebookNodeRun) -> list[list[Any]] | None:
if status.error:
if run.status == NotebookNodeRun.Status.RUNNING:
message = status.error_message or "Query execution failed."
- _finish_direct_run(run, NotebookNodeRun.Status.FAILED, envelope=None, error=message)
+ finish_node_run(run, NotebookNodeRun.Status.FAILED, error=message)
return None
results: dict[str, Any] = status.results or {}
@@ -170,7 +166,10 @@ def sync_direct_run(run: NotebookNodeRun) -> list[list[Any]] | None:
types,
has_more=fetched_has_more or len(rows) > DISPLAY_PAGE_LIMIT,
)
- _finish_direct_run(run, NotebookNodeRun.Status.DONE, envelope=envelope, error=None)
+ timings = _query_status_timings(status)
+ if timings:
+ envelope["timings"] = timings
+ finish_node_run(run, NotebookNodeRun.Status.DONE, envelope=envelope, error=None)
# Lost transitions land here too (an interrupt, or another poller); the
# refreshed row's status decides whether the rows may be served.
if run.status != NotebookNodeRun.Status.DONE:
diff --git a/products/notebooks/backend/sql_v2_metrics.py b/products/notebooks/backend/sql_v2_metrics.py
new file mode 100644
index 000000000000..c4884f38ae6a
--- /dev/null
+++ b/products/notebooks/backend/sql_v2_metrics.py
@@ -0,0 +1,157 @@
+"""Node-run observability: one recorder for every terminal run transition (sql_v2_observability.md gap 1).
+
+Every path that moves a NotebookNodeRun to a terminal status reports it here exactly once:
+the sandbox callback, the direct lane, dispatch failures, and interrupts. The recorder
+measures end-to-end duration against the run row's ``created_at``
+(the only start clock that exists) and emits three sinks at once:
+
+- a Prometheus histogram (Grafana / the rollout dashboard),
+- its OTLP twin (the PostHog Metrics product),
+- a ``notebook node run completed`` event (product analytics, sliceable per notebook).
+
+Runs additionally carry phase timings in the envelope's ``timings`` dict. Kernel runs
+report them from the sandbox (``sandbox/kernel/runner.py``): ``input_wait_s`` (waiting on
+the data plane for referenced frames or the display fetch), ``download_s`` (the presigned
+frame downloads), ``kernel_boot_s`` (ensuring the ipykernel is up — ~0 when already warm),
+``exec_s`` (ipykernel cell execution), and ``sandbox_total_s`` (the whole
+sandbox-side run). Direct (hogql) runs report them from the async query manager's status
+(``sql_v2_direct._query_status_timings``): ``queued_s`` (enqueue -> Celery pickup) and
+``clickhouse_s`` (pickup -> completion, i.e. HogQL compile + ClickHouse execution).
+"""
+
+import math
+from typing import Any
+
+from django.core.exceptions import ObjectDoesNotExist
+from django.utils import timezone
+
+import structlog
+from prometheus_client import Histogram
+
+from posthog.event_usage import report_user_or_team_action
+from posthog.models import Team
+from posthog.otel_metrics import OtelInstrumentFactory
+
+from products.notebooks.backend.models import NotebookNodeRun
+
+logger = structlog.get_logger(__name__)
+
+NODE_RUN_COMPLETED_EVENT = "notebook node run completed"
+
+# The terminal statuses, plus `timed_out` — a FAILED written by the direct lane's
+# grace-expiry watchdog. Kept distinct so an expired query is a visible bucket rather
+# than indistinguishable from a user error.
+OUTCOME_DONE = "done"
+OUTCOME_FAILED = "failed"
+OUTCOME_INTERRUPTED = "interrupted"
+OUTCOME_TIMED_OUT = "timed_out"
+
+_OUTCOME_BY_STATUS = {
+ NotebookNodeRun.Status.DONE: OUTCOME_DONE,
+ NotebookNodeRun.Status.FAILED: OUTCOME_FAILED,
+ NotebookNodeRun.Status.INTERRUPTED: OUTCOME_INTERRUPTED,
+}
+
+# Envelope timing keys -> phase label values. Anything else in `timings` is ignored, so a
+# hostile or newer sandbox cannot mint unbounded label values.
+_PHASE_BY_TIMING_KEY = {
+ "input_wait_s": "input_wait",
+ "download_s": "download",
+ "kernel_boot_s": "kernel_boot",
+ "exec_s": "exec",
+ "sandbox_total_s": "sandbox_total",
+ "queued_s": "queued",
+ "clickhouse_s": "clickhouse",
+}
+
+# Headroom over the backend-measured run duration when bounding sandbox-reported timings:
+# absorbs clock granularity and rounding without letting a forged value stretch far past
+# the run's real wall clock.
+_TIMING_CLOCK_SLACK_SECONDS = 60.0
+
+_otel = OtelInstrumentFactory("notebooks")
+
+NODE_RUN_SECONDS = Histogram(
+ "posthog_notebooks_node_run_seconds",
+ "End-to-end notebook node run duration: run-row creation to its terminal transition.",
+ labelnames=["node_type", "outcome"],
+ buckets=[0.5, 1, 2, 5, 10, 30, 60, 120, 300, 600, 1200, 1800, 2700],
+)
+NODE_RUN_PHASE_SECONDS = Histogram(
+ "posthog_notebooks_node_run_phase_seconds",
+ "Phase durations of a node run, from the run envelope's timings.",
+ labelnames=["phase", "node_type"],
+ buckets=[0.1, 0.25, 0.5, 1, 2, 5, 10, 30, 60, 120, 300, 600],
+)
+
+
+def outcome_for_status(status: str) -> str:
+ return _OUTCOME_BY_STATUS.get(NotebookNodeRun.Status(status), OUTCOME_FAILED)
+
+
+def record_node_run_terminal(run: NotebookNodeRun, outcome: str) -> None:
+ """Report one terminal transition of `run`. Call only when this caller won the
+ RUNNING -> terminal transition, so re-deliveries and racing pollers never double-count.
+
+ Never raises — telemetry must not fail the run.
+ """
+ try:
+ duration = max((timezone.now() - run.created_at).total_seconds(), 0.0)
+ NODE_RUN_SECONDS.labels(node_type=run.node_type, outcome=outcome).observe(duration)
+ _otel.record_histogram_twin(NODE_RUN_SECONDS, duration, {"node_type": run.node_type, "outcome": outcome})
+
+ timings = _sanitized_timings(run.envelope, max_seconds=duration + _TIMING_CLOCK_SLACK_SECONDS)
+ for phase, seconds in timings.items():
+ NODE_RUN_PHASE_SECONDS.labels(phase=phase, node_type=run.node_type).observe(seconds)
+ _otel.record_histogram_twin(NODE_RUN_PHASE_SECONDS, seconds, {"phase": phase, "node_type": run.node_type})
+
+ _capture_completed_event(run, outcome, duration, timings)
+ except Exception:
+ logger.exception("notebook_node_run_metrics_failed", run_id=str(run.id), outcome=outcome)
+
+
+def _sanitized_timings(envelope: Any, max_seconds: float) -> dict[str, float]:
+ """Bound the envelope's self-reported timings before they touch shared histograms.
+
+ The envelope is produced inside the sandbox, where user code can forge it — an absurd
+ but JSON-legal value like 1e300 would permanently poison the process-wide histogram
+ sums for every tenant. Every phase is a sub-span of the run, so the backend-measured
+ run duration (plus clock slack) is a hard ceiling; anything above it is clamped.
+ """
+ raw = envelope.get("timings") if isinstance(envelope, dict) else None
+ if not isinstance(raw, dict):
+ return {}
+ return {
+ _PHASE_BY_TIMING_KEY[key]: min(float(value), max_seconds)
+ for key, value in raw.items()
+ if key in _PHASE_BY_TIMING_KEY and isinstance(value, int | float) and math.isfinite(value) and value >= 0
+ }
+
+
+def _capture_completed_event(
+ run: NotebookNodeRun,
+ outcome: str,
+ duration: float,
+ timings: dict[str, float],
+) -> None:
+ envelope = run.envelope if isinstance(run.envelope, dict) else {}
+ properties: dict[str, Any] = {
+ "notebook_short_id": run.notebook.short_id,
+ "node_type": run.node_type,
+ "outcome": outcome,
+ "duration_seconds": round(duration, 3),
+ "row_count": envelope.get("row_count"),
+ "has_error": bool(run.error),
+ **{f"{phase}_seconds": round(value, 3) for phase, value in timings.items()},
+ }
+ try:
+ user = run.user
+ except ObjectDoesNotExist:
+ # The FK is db_constraint=False/DO_NOTHING: a hard-deleted user leaves a dangling
+ # id, and descriptor access raises instead of reading back as None.
+ user = None
+ # Always resolve the run's own team: with team=None, report_user_or_team_action
+ # attributes $groups to the user's *currently active* project, which can differ
+ # from the project the run belongs to (multi-project users, personal API keys).
+ team = Team.objects.filter(pk=run.team_id).first()
+ report_user_or_team_action(NODE_RUN_COMPLETED_EVENT, properties, user=user, team=team)
diff --git a/products/notebooks/backend/sql_v2_observability.md b/products/notebooks/backend/sql_v2_observability.md
new file mode 100644
index 000000000000..a2fbc7573ec2
--- /dev/null
+++ b/products/notebooks/backend/sql_v2_observability.md
@@ -0,0 +1,137 @@
+# SQLV2 rollout observability
+
+What you can watch today while rolling out the notebooks SQLV2 frame store, where each signal lives, and what is missing.
+Companion to [`sql_v2_frame_store.md`](./sql_v2_frame_store.md) — that doc decides the mechanism, this one decides whether the rollout is going well.
+
+Artifacts:
+
+- [`observability/notebooks-rollout.grafana.json`](../observability/notebooks-rollout.grafana.json) — importable Grafana dashboard (Prometheus/VictoriaMetrics).
+- [`observability/notebooks-query-log.sql`](../observability/notebooks-query-log.sql) — `query_log_archive` query pack (ClickHouse per-query cost).
+
+## The split: two surfaces, and why
+
+Nothing gives you all of this in one place, because the two halves have incompatible storage.
+
+**Prometheus (Grafana)** holds the rollout mechanics: attempt/outcome rates, materialize latency, object size, throttling, HTTP.
+It cannot hold per-query ClickHouse cost — scanned bytes per query is unbounded-cardinality data that only makes sense per row, not per series.
+
+**ClickHouse `query_log_archive`** holds the per-query cost: `read_bytes`, `result_bytes`, `result_rows`, `query_duration_ms`, `memory_usage`, `peak_threads_usage`, exception codes.
+It is not in Grafana — production ClickHouse holds customer data and there is deliberately no ClickHouse datasource there.
+The sanctioned path is the internal Metabase under your own SSO session (the `query-clickhouse-via-metabase` skill).
+
+Grafana dashboards are **not code-managed** in this repo — they are edited in the UI, reachable over Tailscale at `grafana-prod-us` / `grafana-prod-eu` (see `tools/infra-scripts/mcp/README.md`).
+The JSON here is an import artifact, not a provisioned source of truth. Import it, then own it in the UI.
+
+### Attribution is already wired
+
+Both data-plane paths wrap their enqueue in `tags_context(product=Product.NOTEBOOKS, feature=Feature.QUERY, ...)` (`sql_v2_data_plane.py:161,185`), and the tags survive the process hop:
+the inline path snapshots them into the Celery task argument (`execute_async.py:343` → `tasks.py:381-383`), and the materialize activity re-establishes them itself (`frame_materialize.py:665`).
+So **`lc_product = 'notebooks'` is the single filter that scopes every ClickHouse query**, and `lc_temporal__workflow_type` / `lc_temporal__attempt` come along for free on the materialize path — retries are attributable in ClickHouse.
+
+One caveat: this covers the **SQLV2 data plane**, which is what is being rolled out.
+Queries from the classic notebook scene's embedded insights are not covered — `SCENE_TO_TAGS` deliberately maps `Notebook`/`Notebooks` to `None` (`query_tagging.py:168`), letting the inner query kind decide, so those land under `product_analytics` and similar.
+
+### A naming trap
+
+`prometheus_client` appends `_total` to counter sample names.
+`Counter("posthog_notebooks_frame_materializations_started")` is scraped as **`posthog_notebooks_frame_materializations_started_total`**.
+The dashboard uses the `_total` names; the source code does not have them.
+
+## Coverage against what you asked for
+
+| Want | Where | State |
+| --------------------------------- | --------------------------------------------------------------------------------------------------- | --------------------------------------------------------------- |
+| Notebook request E2E latency | `posthog_notebooks_node_run_seconds{node_type,outcome}` + `notebook node run completed` event | Covered — see "Node-run instrumentation" below |
+| CH latency for notebook queries | `query_log_archive.query_duration_ms` (SQL 1) | Covered |
+| CH scanned bytes | `query_log_archive.read_bytes` (SQL 1, 6) | Covered |
+| CH bytes returned | `result_bytes` / `WriteBufferFromS3Bytes` (SQL 4) | Covered, but mode-dependent — see below |
+| CH rows returned | `result_rows` / `written_rows` (SQL 4) | Covered, mode-dependent |
+| Overall CH health | Existing shared CH Grafana dashboards + SQL 8 | Covered by platform; SQL 8 gives notebooks' share of offline |
+| Throttled queries | `posthog_clickhouse_query_concurrency_limit_exceeded_total{limit_name=~"notebooks_materialize_.*"}` | Covered (rejections only) |
+| Parallel queries per team | Reconstructed from `query_log_archive` (SQL 5) | Covered by SQL; **no live gauge** — gap 3 |
+| Parallel queries per user | Same, group by `lc_user_id` | Same |
+| Per-notebook / per-node breakdown | `NotebookNodeRun` in Postgres (gap 4) | Available in Postgres — runs, node type, status, rough duration |
+
+"Bytes/rows returned" is mode-dependent and averaging the modes together is wrong:
+the streaming path returns a result set (`result_bytes`, `result_rows`), while the CH-writes path is an `INSERT` whose result set is empty and whose delivered bytes show up as `ProfileEvents['WriteBufferFromS3Bytes']` and `written_rows`.
+`query_kind` (`Select` vs `Insert`) is what separates them.
+The Prometheus `posthog_notebooks_frame_object_bytes` histogram is the mode-independent view of the same thing, but only on the success path.
+
+## Node-run instrumentation (closes gap 1)
+
+Every terminal transition of a `NotebookNodeRun` — the sandbox callback, the direct-lane finish, dispatch failures, and interrupts — reports once through `sql_v2_metrics.record_node_run_terminal`, emitting three sinks:
+
+- **`posthog_notebooks_node_run_seconds{node_type,outcome}`** — end-to-end duration, run-row `created_at` to the terminal transition. `outcome` is `done` / `failed` / `interrupted` / `timed_out`; the direct lane's grace-expiry watchdog reports `timed_out`, so an expired query is a bucket, not a user error.
+- **`posthog_notebooks_node_run_phase_seconds{phase,node_type}`** — the decomposition, from the run envelope's `timings` dict. Sandbox-reported: `input_wait` (data-plane wait for referenced frames or the display fetch), `download` (presigned frame downloads), `exec` (ipykernel cell), `sandbox_total`. Direct lane, from `QueryStatus`: `queued` (enqueue → Celery pickup), `clickhouse` (pickup → completion).
+- **`notebook node run completed`** PostHog event with `duration_seconds`, the phase seconds, `row_count`, `outcome`, `notebook_short_id` — the per-notebook/per-team view Prometheus label cardinality can't hold.
+
+Both histograms also stream into the PostHog Metrics product via their OTLP twins (`posthog/otel_metrics.py`).
+
+One deliberate hole: the callback is best-effort, so a kernel-lane run whose sandbox dies without delivering stays RUNNING and contributes **no** sample — the row remains visible in Postgres and the node can be re-run. A periodic reaper that would fail such rows (and record them as `timed_out`) was built and dropped as more complexity than the case warrants; revisit if stranded rows become common.
+
+Still open from the original gap: lost-callback kernel runs (above), the frontend's own poll-to-render latency, and the kernel's presigned _download failure_ modes, which remain observable only as an `input_wait`-heavy failed run (see gap 5).
+
+## Gaps — suggested follow-ups
+
+Ordered by how much they'd hurt during a rollout.
+
+### 1. ~~No E2E latency for a notebook query~~ — closed by the node-run instrumentation above
+
+Shipped — see "Node-run instrumentation" above for the metric names; the lost-callback caveat there is the one remaining sliver.
+
+### 2. Success-only histograms → add an `outcome` label
+
+The existing `frame_materialize_seconds`, `frame_object_bytes`, and `frame_clickhouse_seconds` are observed only on the success path (`frame_materialize.py:877-883`).
+A materialization that dies at the 10-minute deadline contributes **no** sample, so the histograms are survivorship-biased exactly when things are going worst.
+
+Suggested: observe duration (and partial size) on the failure branches too, carrying the same `outcome` label as gap 1. One-line change per exit path.
+Partially mitigated: the node-run histogram sees every outcome, so a dying materialization now shows up as a slow `failed`/`timed_out` _run_ — but the frame-level histograms themselves are still success-only.
+
+### 3. No in-flight gauge for the concurrency slots
+
+The Redis sorted set holds current occupancy (`ZCARD`), but nothing samples it.
+You can see **rejections** after the fact and nothing else, so "are we near the global 10?" is unanswerable until you're already over.
+SQL 5 reconstructs true concurrency from `query_log_archive`, but that's forensics, not a dashboard.
+
+Suggested: a periodically-sampled gauge `posthog_notebooks_materialize_slots_in_use{scope}` from the limiter keys.
+
+### 4. Node- and notebook-level breakdowns — from Postgres, not CH tags
+
+Per-notebook and per-node breakdowns (runs per notebook, busiest notebooks, failure rate by node type, nodes per notebook) come from **`NotebookNodeRun`** (`posthog_notebooknoderun`), not from a ClickHouse tag.
+Tagging queries with `notebook_short_id` was considered and rejected — it is unbounded-cardinality label data, and it would miss the `python`/`duckdb` runs that never touch ClickHouse.
+
+The table already has everything: `notebook_id`, `node_id`, `node_type` (`hogql`/`python`/`duckdb`), `user_id`, `status` (`running`/`done`/`failed`/`interrupted`), and `created_at`/`updated_at` (so `updated_at - created_at` is a rough per-run duration).
+It is indexed on `(team, notebook, node_id)`, so these are plain ORM aggregations.
+This is the source for a PostHog/Metabase notebook-usage view; ClickHouse `query_log_archive` stays the source for per-query _cost_, joined on `lc_client_query_id` when a row-level correlation is needed.
+
+### 5. `frame_store.py` is entirely uninstrumented
+
+No counter or timer on any object-store operation. Suggested instrumentation, each failure counter split by a `reason` label because the causes map to different infra problems:
+
+- **`write_stream`** — upload-duration histogram + failure counter (`ObjectStorageError`). The phase-1 worker→S3 leg; today only inferred indirectly from the relay split, and a failed upload has no signal.
+- **`stat_frame`** — failure counter split `reason="not_stored"` (HEAD is None — a silent no-op write by an `UnavailableStorage` client, i.e. object storage misconfigured) vs `reason="predates_write"` (the CH-writes freshness guard firing — endpoint/bucket skew, CH wrote where the app can't read). "Storage down" vs "storage misrouted" — worth telling apart at a glance.
+- **`presign_get`** — mint counter + failure counter split `reason="prefix_mismatch"` (a key outside the team prefix — the tenant-isolation backstop firing, so any nonzero is security-relevant) vs `reason="presign_failed"` (empty URL — storage/config).
+- **`delete_frame`** — a counter. A rising delete rate is a leading indicator that corrupt objects are being produced upstream (mid-stream tears, or oversize objects failing the post-write cap).
+
+What this **cannot** see, and it's the riskiest leg: the kernel's actual _download_ of the presigned URL.
+The server mints the URL and never learns whether the fetch succeeded — and that fetch is the documented rollout hazard (`OBJECT_STORAGE_PUBLIC_ENDPOINT` must resolve _from the sandbox's network_).
+Observing it needs a kernel-side signal reported back, or the proxy-through-Django fallback (which would put the bytes on a meterable path) — track that as its own follow-up rather than pretending server-side metrics close it.
+
+### 6. HogQL timings are computed and thrown away
+
+`kernel_runtime.py:566-567` deletes the `timings` key from the HogQL response before returning it to the sandbox.
+Per-stage HogQL timings exist and are discarded — cheap to log or record.
+Partially closed: the direct lane now records `queued`/`clickhouse` phases from `QueryStatus` (see the node-run instrumentation); the HogQL executor's own per-stage breakdown is still discarded.
+
+### 7. No tracing
+
+No OpenTelemetry/Sentry spans anywhere in the product.
+Nothing links API request → Temporal workflow → ClickHouse → object store → kernel poll → callback.
+`client_query_id` is the only correlation id and it does not reach the frontend or the callback.
+Not a rollout blocker, but it is why gap 1 is awkward to close cleanly.
+
+## Before you trust the dashboard
+
+- **Verify the `view` label values** on the two HTTP panels with `list_prometheus_label_values`. The data-plane paths have no `name=` in `urls.py`, so Django derives the view name and the regex in the panel is a guess.
+- **Confirm the notebooks metrics are being scraped at all.** They are defined in the Temporal worker process (`frame_materialize.py`); the general-purpose worker fleet's `/metrics` endpoint must be scraped by vmagent for any of the frame panels to have data.
+- The dashboard is import-only. Grafana here is not provisioned from git, so re-importing overwrites UI edits.
diff --git a/products/notebooks/backend/sql_v2_runs.py b/products/notebooks/backend/sql_v2_runs.py
new file mode 100644
index 000000000000..18689582cba6
--- /dev/null
+++ b/products/notebooks/backend/sql_v2_runs.py
@@ -0,0 +1,49 @@
+"""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.
+"""
+
+from typing import Any
+
+from django.utils import timezone
+
+from products.notebooks.backend.models import NotebookNodeRun
+from products.notebooks.backend.sql_v2_metrics import outcome_for_status, record_node_run_terminal
+
+
+def finish_node_run(
+ run: NotebookNodeRun,
+ status: NotebookNodeRun.Status,
+ *,
+ error: str | None,
+ envelope: dict | None = None,
+ outcome: str | None = None,
+) -> bool:
+ """Move a RUNNING `run` to a terminal state; return whether this call won the transition.
+
+ Guarded on the current status so concurrent finishers are idempotent and a completed
+ query can never overwrite an interrupt. Refreshes `run` either way so the caller
+ always sees the row that won. The winner reports the run's terminal metrics, labeled
+ `outcome` when the status alone undersells it (the direct lane's watchdog expiry is a
+ timeout, not a user error). `envelope` is only written when given — a RUNNING row has
+ none yet, and interrupts and failures must not invent one.
+ """
+ fields: dict[str, Any] = {"status": status, "error": error, "updated_at": timezone.now()}
+ if envelope is not None:
+ fields["envelope"] = envelope
+ fields["result_id"] = envelope.get("result_id")
+ updated = (
+ NotebookNodeRun.objects.for_team(run.team_id)
+ .filter(id=run.id, status=NotebookNodeRun.Status.RUNNING)
+ .update(**fields)
+ )
+ # select_related: the recorder reads run.user and run.notebook; a plain refresh wipes
+ # the FK caches and forces a lazy query per relation.
+ run.refresh_from_db(from_queryset=NotebookNodeRun.objects.for_team(run.team_id).select_related("user", "notebook"))
+ if updated:
+ record_node_run_terminal(run, outcome or outcome_for_status(status))
+ return bool(updated)
diff --git a/products/notebooks/backend/sql_v2_serializers.py b/products/notebooks/backend/sql_v2_serializers.py
index 109005227c0b..b0f9d88c617f 100644
--- a/products/notebooks/backend/sql_v2_serializers.py
+++ b/products/notebooks/backend/sql_v2_serializers.py
@@ -1,6 +1,18 @@
+from drf_spectacular.utils import extend_schema_field
from rest_framework import serializers
+@extend_schema_field(serializers.DictField(child=serializers.FloatField()))
+class LenientTimingsField(serializers.JSONField):
+ """`timings` documented as a str->float map but never validated as one.
+
+ The envelope is produced inside the sandbox, where user code can forge it, and the
+ callback is fire-and-forget — a 400 here is swallowed like a network error and the
+ run is stranded RUNNING forever. So a bad timings shape must never fail the envelope;
+ `sql_v2_metrics._sanitized_timings` is the sole validator and drops bad keys.
+ """
+
+
class NotebookSQLV2RefSerializer(serializers.Serializer):
node_id = serializers.CharField(help_text="ProseMirror node id of the upstream node this name points at.")
# Named `kind` on purpose (matches the kernel input spec); avoids the `type`/`format`
@@ -201,6 +213,16 @@ class NotebookSQLV2EnvelopeSerializer(serializers.Serializer):
allow_blank=True,
help_text="Error message when status is 'error'.",
)
+ timings = LenientTimingsField(
+ required=False,
+ help_text=(
+ "Phase durations in seconds. From the sandbox: input_wait_s (waiting on the data "
+ "plane), download_s (presigned frame downloads), kernel_boot_s (ensuring the "
+ "ipykernel is up), exec_s (kernel cell execution), sandbox_total_s (the whole "
+ "sandbox-side run). From the direct lane: queued_s (enqueue to Celery pickup), "
+ "clickhouse_s (pickup to completion). Feeds the node-run metrics."
+ ),
+ )
class NotebookSQLV2CallbackRequestSerializer(serializers.Serializer):
diff --git a/products/notebooks/backend/temporal/sql_v2.py b/products/notebooks/backend/temporal/sql_v2.py
index 34eebdd1e55c..8ad8bd48a133 100644
--- a/products/notebooks/backend/temporal/sql_v2.py
+++ b/products/notebooks/backend/temporal/sql_v2.py
@@ -18,6 +18,7 @@ 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
@dataclass
@@ -72,11 +73,12 @@ def dispatch_sql_v2_run_activity(input: SQLV2RunInput) -> None:
@activity.defn(name="notebook-sandbox-cmd-mark-failed")
def mark_sql_v2_run_failed_activity(input: SQLV2RunInput) -> None:
+ # Status-guarded so a callback that completed the run between dispatch exhaustion and
+ # this activity keeps its real outcome — a stale FAILED must neither overwrite it nor
+ # report a second terminal transition.
run = NotebookNodeRun.objects.for_team(input.team_id).filter(id=input.run_id).first()
- if run is not None and run.status == NotebookNodeRun.Status.RUNNING:
- run.status = NotebookNodeRun.Status.FAILED
- run.error = "Run failed to dispatch to the kernel."
- run.save(update_fields=["status", "error", "updated_at"])
+ if run is not None:
+ finish_node_run(run, NotebookNodeRun.Status.FAILED, error="Run failed to dispatch to the kernel.")
@workflow.defn(name="notebook-sandbox-cmd-run")
diff --git a/products/notebooks/backend/test/test_sql_v2.py b/products/notebooks/backend/test/test_sql_v2.py
index 9f992515d743..937e356046c5 100644
--- a/products/notebooks/backend/test/test_sql_v2.py
+++ b/products/notebooks/backend/test/test_sql_v2.py
@@ -1984,7 +1984,7 @@ class TestSQLV2KernelPackage(SimpleTestCase):
patch.object(kernel_data_plane.urllib.request, "urlopen", side_effect=fake_urlopen),
patch.object(kernel_data_plane._no_redirect_opener, "open", side_effect=fake_poll_open),
):
- rows, fetched_from = kernel_data_plane.materialize_query_to_file(
+ rows, fetched_from, _download_s = kernel_data_plane.materialize_query_to_file(
"http://backend/dp", "secret-token", "select 1", dest, limit=1000
)
self.assertEqual(rows, 2)
@@ -2035,7 +2035,7 @@ class TestSQLV2PythonNodeRun(SimpleTestCase):
"urlopen",
side_effect=lambda request, timeout=None: _FakeResponse(arrow_bytes),
):
- rows, fetched_from = kernel_data_plane.materialize_query_to_file(
+ rows, fetched_from, _download_s = kernel_data_plane.materialize_query_to_file(
"http://backend/dp", "t", "select 1", dest, limit=1000
)
self.assertEqual(rows, 2)
@@ -2123,3 +2123,226 @@ class TestSQLV2PythonNodeRun(SimpleTestCase):
):
kernel_runner.execute_run(payload)
run_kernel.assert_not_called()
+
+
+class TestSQLV2NodeRunMetrics(APIBaseTest):
+ def setUp(self):
+ super().setUp()
+ self.notebook = Notebook.objects.create(team=self.team, short_id="nbmet01")
+
+ def _create_run(self, **overrides) -> NotebookNodeRun:
+ with team_scope(self.team.id):
+ return NotebookNodeRun.objects.create(
+ team=self.team,
+ notebook=self.notebook,
+ user=self.user,
+ node_id=overrides.pop("node_id", "node-1"),
+ status=overrides.pop("status", NotebookNodeRun.Status.RUNNING),
+ **overrides,
+ )
+
+ def _histogram_count(self, labels: dict[str, str]) -> float:
+ from prometheus_client import REGISTRY
+
+ return REGISTRY.get_sample_value("posthog_notebooks_node_run_seconds_count", labels) or 0.0
+
+ @parameterized.expand(
+ [
+ ("ok", "done"),
+ ("interrupted", "interrupted"),
+ ("error", "failed"),
+ ]
+ )
+ @patch("products.notebooks.backend.sql_v2_metrics.report_user_or_team_action")
+ def test_callback_reports_the_run_with_its_outcome(self, envelope_status, expected_outcome, mock_report):
+ run = self._create_run()
+ token = mint_callback_token(str(run.id), self.team.id)
+ before = self._histogram_count({"node_type": "hogql", "outcome": expected_outcome})
+ response = self.client.post(
+ f"/internal/notebooks/runs/{run.id}/result/",
+ data=json.dumps(
+ {
+ "envelope": {
+ "status": envelope_status,
+ "row_count": 3,
+ "timings": {"input_wait_s": 1.5, "exec_s": 0.4, "sandbox_total_s": 2.0},
+ }
+ }
+ ),
+ content_type="application/json",
+ HTTP_AUTHORIZATION=f"Bearer {token}",
+ )
+ self.assertEqual(response.status_code, 200)
+ mock_report.assert_called_once()
+ event, properties = mock_report.call_args[0]
+ self.assertEqual(event, "notebook node run completed")
+ self.assertEqual(properties["outcome"], expected_outcome)
+ self.assertEqual(properties["notebook_short_id"], "nbmet01")
+ self.assertEqual(properties["node_type"], "hogql")
+ self.assertEqual(properties["row_count"], 3)
+ self.assertEqual(properties["input_wait_seconds"], 1.5)
+ self.assertEqual(properties["exec_seconds"], 0.4)
+ self.assertEqual(properties["sandbox_total_seconds"], 2.0)
+ self.assertGreaterEqual(properties["duration_seconds"], 0)
+ # $groups must come from the run's own team, not the user's currently active project.
+ self.assertEqual(mock_report.call_args.kwargs["team"].id, self.team.id)
+ after = self._histogram_count({"node_type": "hogql", "outcome": expected_outcome})
+ self.assertEqual(after, before + 1)
+
+ @patch("products.notebooks.backend.sql_v2_metrics.report_user_or_team_action")
+ def test_redelivered_callback_reports_the_run_once(self, mock_report):
+ # The callback deliberately upserts on re-delivery; without the was-running guard a
+ # retried POST would double-count every run in the dashboard's headline metric.
+ run = self._create_run()
+ token = mint_callback_token(str(run.id), self.team.id)
+ for _ in range(2):
+ self.client.post(
+ f"/internal/notebooks/runs/{run.id}/result/",
+ data=json.dumps({"envelope": {"status": "ok"}}),
+ content_type="application/json",
+ HTTP_AUTHORIZATION=f"Bearer {token}",
+ )
+ self.assertEqual(mock_report.call_count, 1)
+
+ @parameterized.expand(
+ [
+ ("done", NotebookNodeRun.Status.DONE, None, "done"),
+ ("failed", NotebookNodeRun.Status.FAILED, None, "failed"),
+ ("watchdog_timeout", NotebookNodeRun.Status.FAILED, "timed_out", "timed_out"),
+ ]
+ )
+ @patch("products.notebooks.backend.sql_v2_metrics.report_user_or_team_action")
+ def test_direct_lane_finish_reports_the_winning_transition(
+ self, _name, status, outcome_override, expected_outcome, mock_report
+ ):
+ from products.notebooks.backend.sql_v2_runs import finish_node_run
+
+ run = self._create_run()
+ finish_node_run(run, status, error=None, outcome=outcome_override)
+ mock_report.assert_called_once()
+ event, properties = mock_report.call_args[0]
+ self.assertEqual(event, "notebook node run completed")
+ self.assertEqual(properties["outcome"], expected_outcome)
+
+ @patch("products.notebooks.backend.sql_v2_metrics.report_user_or_team_action")
+ def test_direct_lane_finish_does_not_report_a_lost_transition(self, mock_report):
+ # A poller that loses the RUNNING -> terminal race (e.g. to an interrupt) must not
+ # add a second sample for the same run.
+ from products.notebooks.backend.sql_v2_runs import finish_node_run
+
+ run = self._create_run(status=NotebookNodeRun.Status.INTERRUPTED)
+ finish_node_run(run, NotebookNodeRun.Status.DONE, error=None)
+ mock_report.assert_not_called()
+
+ @patch("products.notebooks.backend.presentation.views.notebook.is_sql_v2_enabled", return_value=True)
+ @patch("products.notebooks.backend.sql_v2_metrics.report_user_or_team_action")
+ def test_direct_run_reports_queued_and_clickhouse_phases(self, mock_report, _mock_enabled):
+ # The "why was it slow: queue wait vs ClickHouse" split rides QueryStatus into the
+ # envelope; if the attach (or a QueryStatus field) silently changes, the phase
+ # decomposition disappears from every dashboard while the run still completes.
+ run_url = f"/api/projects/{self.team.id}/notebooks/{self.notebook.short_id}/sql_v2/run/"
+ response = self.client.post(run_url, data={"node_id": "n1", "code": "select 1 as a"}, format="json")
+ self.assertEqual(response.status_code, 200)
+ run_id = response.json()["run_id"]
+ body = self.client.get(
+ f"/api/projects/{self.team.id}/notebooks/{self.notebook.short_id}/sql_v2/runs/{run_id}/"
+ ).json()
+ self.assertEqual(body["status"], NotebookNodeRun.Status.DONE)
+
+ mock_report.assert_called_once()
+ _event, properties = mock_report.call_args[0]
+ self.assertEqual(properties["outcome"], "done")
+ self.assertGreaterEqual(properties["queued_seconds"], 0)
+ self.assertGreaterEqual(properties["clickhouse_seconds"], 0)
+
+ @parameterized.expand(
+ [
+ ("still_running_fails", NotebookNodeRun.Status.RUNNING, NotebookNodeRun.Status.FAILED, 1),
+ ("completed_run_is_kept", NotebookNodeRun.Status.DONE, NotebookNodeRun.Status.DONE, 0),
+ ]
+ )
+ @patch("products.notebooks.backend.sql_v2_metrics.report_user_or_team_action")
+ def test_mark_failed_activity_never_overwrites_a_completed_run(
+ self, _name, initial_status, expected_status, expected_reports, mock_report
+ ):
+ # Dispatch retries can exhaust after a late callback already completed the run; the
+ # stale FAILED must neither clobber the real outcome nor report a second transition.
+ run = self._create_run(status=initial_status)
+ mark_sql_v2_run_failed_activity(
+ SQLV2RunInput(run_id=str(run.id), notebook_short_id=self.notebook.short_id, team_id=self.team.id)
+ )
+ run.refresh_from_db()
+ self.assertEqual(run.status, expected_status)
+ self.assertEqual(mock_report.call_count, expected_reports)
+
+ @patch("products.notebooks.backend.sql_v2_metrics.report_user_or_team_action")
+ def test_forged_envelope_timings_are_clamped(self, mock_report):
+ # The envelope comes from the sandbox, where user code can forge it; a JSON-legal
+ # 1e300 must not poison the shared histogram sums. Phases are sub-spans of the run,
+ # so the backend-measured duration (plus slack) is the ceiling.
+ run = self._create_run()
+ token = mint_callback_token(str(run.id), self.team.id)
+ response = self.client.post(
+ f"/internal/notebooks/runs/{run.id}/result/",
+ data=json.dumps({"envelope": {"status": "ok", "timings": {"exec_s": 1e300, "input_wait_s": 0.2}}}),
+ content_type="application/json",
+ HTTP_AUTHORIZATION=f"Bearer {token}",
+ )
+ self.assertEqual(response.status_code, 200)
+ properties = mock_report.call_args[0][1]
+ self.assertLessEqual(properties["exec_seconds"], 120) # clamped to duration + slack
+ self.assertEqual(properties["input_wait_seconds"], 0.2) # honest values pass through
+
+ @parameterized.expand(
+ [
+ ("garbage_values", {"exec_s": "n/a", "input_wait_s": None, "nested": {"x": 1}}),
+ ("not_a_dict", "n/a"),
+ ]
+ )
+ @patch("products.notebooks.backend.sql_v2_metrics.report_user_or_team_action")
+ def test_malformed_envelope_timings_never_strand_the_run(self, _name, timings, mock_report):
+ # The callback is fire-and-forget from the sandbox: a 400 is swallowed like a
+ # network error and never retried, so a forged/garbage timings shape failing
+ # serializer validation would leave the run RUNNING forever.
+ run = self._create_run()
+ token = mint_callback_token(str(run.id), self.team.id)
+ response = self.client.post(
+ f"/internal/notebooks/runs/{run.id}/result/",
+ data=json.dumps({"envelope": {"status": "ok", "timings": timings}}),
+ content_type="application/json",
+ HTTP_AUTHORIZATION=f"Bearer {token}",
+ )
+ self.assertEqual(response.status_code, 200)
+ run.refresh_from_db()
+ self.assertEqual(run.status, NotebookNodeRun.Status.DONE)
+ properties = mock_report.call_args[0][1]
+ self.assertNotIn("exec_seconds", properties)
+
+ @patch("products.notebooks.backend.sql_v2_metrics.report_user_or_team_action")
+ def test_completed_event_survives_a_hard_deleted_user(self, mock_report):
+ # run.user is db_constraint=False/DO_NOTHING: a hard-deleted user leaves a dangling
+ # id and descriptor access raises. The event must fall back to team attribution
+ # instead of silently vanishing inside the recorder's broad except.
+ from products.notebooks.backend.sql_v2_runs import finish_node_run
+
+ run = self._create_run()
+ User.objects.filter(id=self.user.id).delete()
+ finish_node_run(run, NotebookNodeRun.Status.DONE, error=None)
+ mock_report.assert_called_once()
+ self.assertIsNone(mock_report.call_args.kwargs["user"])
+ self.assertEqual(mock_report.call_args.kwargs["team"].id, self.team.id)
+
+ @patch("products.notebooks.backend.sql_v2_metrics.report_user_or_team_action", side_effect=RuntimeError("boom"))
+ def test_metrics_failure_never_fails_the_callback(self, _mock_report):
+ run = self._create_run()
+ token = mint_callback_token(str(run.id), self.team.id)
+ response = self.client.post(
+ f"/internal/notebooks/runs/{run.id}/result/",
+ data=json.dumps({"envelope": {"status": "ok"}}),
+ content_type="application/json",
+ HTTP_AUTHORIZATION=f"Bearer {token}",
+ )
+ self.assertEqual(response.status_code, 200)
+ self.assertEqual(
+ NotebookNodeRun.objects.for_team(self.team.id).get(id=run.id).status, NotebookNodeRun.Status.DONE
+ )
diff --git a/products/notebooks/observability/notebooks-query-log.sql b/products/notebooks/observability/notebooks-query-log.sql
new file mode 100644
index 000000000000..ed0c7fffc591
--- /dev/null
+++ b/products/notebooks/observability/notebooks-query-log.sql
@@ -0,0 +1,240 @@
+-- Notebooks ClickHouse observability — query_log_archive query pack.
+--
+-- Every notebook data-plane query is tagged `product=notebooks, feature=query`
+-- (sql_v2_data_plane.py wraps both enqueue paths in tags_context; the tags ride the
+-- Celery task argument on the inline path and the Temporal activity's context on the
+-- materialize path), so `lc_product = 'notebooks'` is the one filter that scopes
+-- everything below.
+--
+-- Run these through the internal Metabase against "PostHog ClickHouse PROD <REGION>
+-- Data Tier" (see the query-clickhouse-via-metabase skill):
+-- hogli metabase:login --region us
+-- hogli metabase:databases --region us
+-- hogli metabase:query --region us --database-id <id> < this-file
+--
+-- Reading notes that apply throughout:
+-- * `is_initial_query` drops the per-shard sub-queries a distributed query fans out
+-- into. The initiator row already sums read_bytes/read_rows across replicas, so
+-- without this filter every cost number roughly doubles.
+-- * `query_log_archive` is a Distributed read table pointing at the OPS cluster and is
+-- readable from any cluster. Always bound `event_date` — it is partitioned by month.
+-- * Rows are QueryFinish / ExceptionBeforeStart / ExceptionWhileProcessing only
+-- (the MV filters out QueryStart), so one row is one finished query attempt.
+-- * The two write modes are distinguishable by `query_kind`: 'Select' is the
+-- phase-1 worker-relay stream, 'Insert' is the phase-2 CH-writes
+-- `INSERT INTO FUNCTION s3`. This matters for result columns — see query 4.
+-- * `lc_temporal__attempt` is the Temporal retry attempt, so re-executions of the
+-- same materialization are visible and attributable.
+
+
+-- ---------------------------------------------------------------------------
+-- 1. Headline: notebook query volume, latency, and ClickHouse cost per hour.
+-- This is the panel to watch during a rollout.
+-- ---------------------------------------------------------------------------
+SELECT
+ toStartOfHour(event_time) AS hour,
+ count() AS queries,
+ countIf(exception_code != 0) AS errors,
+ round(quantile(0.50)(query_duration_ms)) AS p50_ms,
+ round(quantile(0.95)(query_duration_ms)) AS p95_ms,
+ round(quantile(0.99)(query_duration_ms)) AS p99_ms,
+ formatReadableSize(sum(read_bytes)) AS scanned_total,
+ formatReadableSize(quantile(0.95)(read_bytes)) AS scanned_p95,
+ formatReadableSize(sum(result_bytes)) AS returned_total,
+ sum(result_rows) AS rows_returned,
+ formatReadableSize(quantile(0.95)(memory_usage)) AS memory_p95
+FROM query_log_archive
+WHERE event_date >= today() - 7
+ AND lc_product = 'notebooks'
+ AND is_initial_query
+GROUP BY hour
+ORDER BY hour;
+
+
+-- ---------------------------------------------------------------------------
+-- 2. Rollout verification: which path, pool, and ClickHouse identity is actually
+-- serving notebook queries. The design doc's phase-1/phase-2 prerequisites
+-- (dedicated `notebooks` CH user, offline pool) fail *open* and silently — this
+-- is the ClickHouse-side confirmation that they engaged.
+-- user — 'notebooks' once the dedicated CH user is provisioned, else the default
+-- lc_workload — 'offline' once CLICKHOUSE_OFFLINE_CLUSTER_HOST is set on the worker fleet
+-- query_kind — Select = worker relay (phase 1); Insert = CH writes (phase 2)
+-- ---------------------------------------------------------------------------
+SELECT
+ toStartOfHour(event_time) AS hour,
+ user AS ch_user,
+ lc_workload AS workload,
+ query_kind,
+ lc_temporal__workflow_type AS workflow,
+ count() AS queries,
+ countIf(exception_code != 0) AS errors
+FROM query_log_archive
+WHERE event_date >= today() - 7
+ AND lc_product = 'notebooks'
+ AND is_initial_query
+GROUP BY hour, ch_user, workload, query_kind, workflow
+ORDER BY hour, queries DESC;
+
+
+-- ---------------------------------------------------------------------------
+-- 3. Failures by ClickHouse exception code. The budget codes the materialize path
+-- treats as terminal: 158 TOO_MANY_ROWS, 159 TIMEOUT_EXCEEDED, 160 TOO_SLOW,
+-- 241 MEMORY_LIMIT_EXCEEDED, 307 TOO_MANY_BYTES, 396 TOO_MANY_ROWS_OR_BYTES
+-- (the result-bytes cap). 202 TOO_MANY_SIMULTANEOUS_QUERIES means the cluster
+-- or the notebooks user's own quota is saturated, not that the query is bad.
+-- ---------------------------------------------------------------------------
+SELECT
+ exception_code,
+ errorCodeToName(exception_code) AS exception_name,
+ count() AS occurrences,
+ uniq(team_id) AS teams_affected,
+ round(avg(query_duration_ms)) AS avg_ms_before_failing,
+ formatReadableSize(sum(read_bytes)) AS wasted_scan,
+ max(event_time) AS last_seen
+FROM query_log_archive
+WHERE event_date >= today() - 7
+ AND lc_product = 'notebooks'
+ AND is_initial_query
+ AND exception_code != 0
+GROUP BY exception_code
+ORDER BY occurrences DESC;
+
+
+-- ---------------------------------------------------------------------------
+-- 4. Bytes and rows delivered to the user, split by write mode.
+-- The two modes populate different columns and averaging them together is wrong:
+-- * Select (worker relay): the frame leaves CH as a result set -> result_bytes / result_rows
+-- * Insert (CH writes s3): the frame is written to S3 by CH -> written_rows, and
+-- ProfileEvents['WriteBufferFromS3Bytes'] for the bytes actually pushed to S3
+-- (result_bytes is ~0 for an INSERT).
+-- `posthog_notebooks_frame_object_bytes` is the mode-independent equivalent, but
+-- only on the success path — this query also sees the runs that died.
+-- ---------------------------------------------------------------------------
+SELECT
+ query_kind,
+ count() AS queries,
+ formatReadableSize(quantile(0.95)(result_bytes)) AS result_bytes_p95,
+ quantile(0.95)(result_rows) AS result_rows_p95,
+ quantile(0.95)(written_rows) AS written_rows_p95,
+ formatReadableSize(quantile(0.95)(ProfileEvents_WriteBufferFromS3Bytes)) AS s3_written_p95,
+ formatReadableSize(sum(ProfileEvents_WriteBufferFromS3Bytes)) AS s3_written_total
+FROM query_log_archive
+WHERE event_date >= today() - 7
+ AND lc_product = 'notebooks'
+ AND is_initial_query
+GROUP BY query_kind;
+
+
+-- ---------------------------------------------------------------------------
+-- 5. Parallel notebook queries per team — exact concurrency, not a rejection count.
+-- Prometheus only counts limiter *rejections*; this reconstructs actual occupancy
+-- by replaying each query as a +1 at its start and a -1 at its end and taking a
+-- running sum. Compare the peak against the design doc's per-team ceiling of 2
+-- (MATERIALIZE_PER_TEAM_CONCURRENCY) and global 10.
+-- Swap `team_id` for `lc_user_id` to get the per-user view.
+-- Note: there is no notebook_short_id in the query tags today, so a per-notebook
+-- breakdown is not possible — see the gaps list in sql_v2_observability.md.
+-- ---------------------------------------------------------------------------
+WITH notebook_queries AS (
+ SELECT
+ team_id,
+ query_start_time_microseconds AS started,
+ query_start_time_microseconds + toIntervalMillisecond(query_duration_ms) AS ended
+ FROM query_log_archive
+ WHERE event_date >= today() - 1
+ AND lc_product = 'notebooks'
+ AND is_initial_query
+),
+edges AS (
+ SELECT team_id, started AS t, 1 AS delta FROM notebook_queries
+ UNION ALL
+ SELECT team_id, ended AS t, -1 AS delta FROM notebook_queries
+)
+SELECT
+ team_id,
+ max(running) AS peak_concurrent_queries
+FROM (
+ SELECT
+ team_id,
+ t,
+ sum(delta) OVER (
+ PARTITION BY team_id ORDER BY t
+ ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW
+ ) AS running
+ FROM edges
+)
+GROUP BY team_id
+ORDER BY peak_concurrent_queries DESC
+LIMIT 20;
+
+
+-- ---------------------------------------------------------------------------
+-- 6. The whales: most expensive individual notebook queries.
+-- `lc_client_query_id` is the data-plane query_id, so a row here joins straight to
+-- the `notebook_frame_materialized` structured log and to the Temporal workflow.
+-- NB: the `query` column is user-authored SQL — internal triage only, never paste
+-- it into a public PR or issue.
+-- ---------------------------------------------------------------------------
+SELECT
+ event_time,
+ team_id,
+ lc_user_id AS user_id,
+ lc_client_query_id AS data_plane_query_id,
+ lc_temporal__attempt AS temporal_attempt,
+ query_duration_ms,
+ formatReadableSize(read_bytes) AS scanned,
+ read_rows,
+ formatReadableSize(memory_usage) AS memory,
+ peak_threads_usage,
+ exception_code,
+ substring(query, 1, 200) AS query_head
+FROM query_log_archive
+WHERE event_date >= today() - 1
+ AND lc_product = 'notebooks'
+ AND is_initial_query
+ORDER BY read_bytes DESC
+LIMIT 25;
+
+
+-- ---------------------------------------------------------------------------
+-- 7. Retry amplification. A deterministically-failing whale can re-execute up to 10
+-- times (the workflow's maximum_attempts), re-scanning on every attempt. Any row
+-- here with attempts > 1 is ClickHouse work spent on a query that was already
+-- doomed — the terminal-vs-retryable error classification is what bounds it.
+-- ---------------------------------------------------------------------------
+SELECT
+ lc_client_query_id AS data_plane_query_id,
+ team_id,
+ max(lc_temporal__attempt) AS attempts,
+ count() AS ch_executions,
+ formatReadableSize(sum(read_bytes)) AS total_scanned,
+ sum(query_duration_ms) AS total_ms,
+ groupUniqArray(exception_code) AS exception_codes
+FROM query_log_archive
+WHERE event_date >= today() - 1
+ AND lc_product = 'notebooks'
+ AND is_initial_query
+ AND lc_temporal__workflow_type = 'notebook-frame-materialize'
+GROUP BY data_plane_query_id, team_id
+HAVING attempts > 1
+ORDER BY total_scanned DESC
+LIMIT 25;
+
+
+-- ---------------------------------------------------------------------------
+-- 8. Notebooks' share of the offline pool — the "am I hurting batch exports?"
+-- question the design doc's pool-isolation decision rests on.
+-- ---------------------------------------------------------------------------
+SELECT
+ toStartOfHour(event_time) AS hour,
+ if(lc_product = 'notebooks', 'notebooks', 'other offline work') AS bucket,
+ count() AS queries,
+ formatReadableSize(sum(read_bytes)) AS scanned,
+ round(sum(query_duration_ms) / 1000) AS ch_seconds,
+ round(sum(ProfileEvents_OSCPUVirtualTimeMicroseconds) / 1e6) AS cpu_seconds
+FROM query_log_archive
+WHERE event_date >= today() - 3
+ AND lc_workload = 'offline'
+ AND is_initial_query
+GROUP BY hour, bucket
+ORDER BY hour, bucket;
diff --git a/products/notebooks/observability/notebooks-rollout.grafana.json b/products/notebooks/observability/notebooks-rollout.grafana.json
new file mode 100644
index 000000000000..994f38259878
--- /dev/null
+++ b/products/notebooks/observability/notebooks-rollout.grafana.json
@@ -0,0 +1,675 @@
+{
+ "title": "Notebooks \u2014 SQLV2 rollout",
+ "uid": "notebooks-sqlv2-rollout",
+ "tags": ["notebooks", "sqlv2", "frame-store"],
+ "timezone": "utc",
+ "schemaVersion": 39,
+ "editable": true,
+ "refresh": "1m",
+ "time": {
+ "from": "now-6h",
+ "to": "now"
+ },
+ "description": "Rollout observability for the notebooks SQLV2 frame store. Prometheus/VictoriaMetrics side only \u2014 ClickHouse per-query cost (scanned bytes, result bytes, rows) lives in query_log_archive, see observability/notebooks-query-log.sql. Panel details and known blind spots: products/notebooks/backend/sql_v2_observability.md",
+ "templating": {
+ "list": [
+ {
+ "name": "datasource",
+ "type": "datasource",
+ "query": "prometheus",
+ "current": {
+ "text": "victoriametrics",
+ "value": "victoriametrics"
+ },
+ "hide": 0
+ }
+ ]
+ },
+ "panels": [
+ {
+ "type": "row",
+ "title": "Node runs \u2014 end to end (every run, every outcome)",
+ "gridPos": {
+ "h": 1,
+ "w": 24,
+ "x": 0,
+ "y": 0
+ }
+ },
+ {
+ "type": "timeseries",
+ "title": "Node run duration p50/p95, by node type",
+ "description": "End to end: run-row creation to the terminal transition (callback, direct-lane finish, or interrupt). Unlike the frame histograms below, every terminal outcome contributes a sample \u2014 but a kernel run whose sandbox callback is lost stays RUNNING and is missing here until re-run.",
+ "datasource": {
+ "type": "prometheus",
+ "uid": "${datasource}"
+ },
+ "gridPos": {
+ "h": 8,
+ "w": 8,
+ "x": 0,
+ "y": 1
+ },
+ "fieldConfig": {
+ "defaults": {
+ "unit": "s"
+ }
+ },
+ "targets": [
+ {
+ "refId": "A",
+ "expr": "histogram_quantile(0.95, sum by (le, node_type) (rate(posthog_notebooks_node_run_seconds_bucket[$__rate_interval])))",
+ "legendFormat": "p95 {{node_type}}"
+ },
+ {
+ "refId": "B",
+ "expr": "histogram_quantile(0.50, sum by (le, node_type) (rate(posthog_notebooks_node_run_seconds_bucket[$__rate_interval])))",
+ "legendFormat": "p50 {{node_type}}"
+ }
+ ]
+ },
+ {
+ "type": "timeseries",
+ "title": "Run outcomes",
+ "description": "done / failed / interrupted / timed_out. timed_out comes from the direct lane's grace-expiry watchdog \u2014 a rising timed_out rate means queries are expiring in the async manager, not that users are writing bad queries.",
+ "datasource": {
+ "type": "prometheus",
+ "uid": "${datasource}"
+ },
+ "gridPos": {
+ "h": 8,
+ "w": 8,
+ "x": 8,
+ "y": 1
+ },
+ "fieldConfig": {
+ "defaults": {
+ "unit": "ops"
+ }
+ },
+ "targets": [
+ {
+ "refId": "A",
+ "expr": "sum by (outcome) (rate(posthog_notebooks_node_run_seconds_count[$__rate_interval]))",
+ "legendFormat": "{{outcome}}"
+ }
+ ]
+ },
+ {
+ "type": "timeseries",
+ "title": "Where the time goes \u2014 phase p95",
+ "description": "queued: enqueue to Celery pickup (direct lane). clickhouse: pickup to completion, HogQL compile + CH execution (direct lane). input_wait: sandbox waiting on the data plane for referenced frames. download: presigned frame downloads. exec: ipykernel cell execution. sandbox_total: the whole sandbox-side run.",
+ "datasource": {
+ "type": "prometheus",
+ "uid": "${datasource}"
+ },
+ "gridPos": {
+ "h": 8,
+ "w": 8,
+ "x": 16,
+ "y": 1
+ },
+ "fieldConfig": {
+ "defaults": {
+ "unit": "s"
+ }
+ },
+ "targets": [
+ {
+ "refId": "A",
+ "expr": "histogram_quantile(0.95, sum by (le, phase) (rate(posthog_notebooks_node_run_phase_seconds_bucket[$__rate_interval])))",
+ "legendFormat": "p95 {{phase}}"
+ }
+ ]
+ },
+ {
+ "type": "row",
+ "title": "Rollout state \u2014 is the new path actually engaged?",
+ "gridPos": {
+ "h": 1,
+ "w": 24,
+ "x": 0,
+ "y": 9
+ },
+ "collapsed": false
+ },
+ {
+ "type": "timeseries",
+ "title": "Materialize attempts",
+ "description": "Materialize activity attempts started. The started counter carries no labels today \u2014 a mode label (streaming vs CH writes) requires a code change before this can split by delivery path.",
+ "datasource": {
+ "type": "prometheus",
+ "uid": "${datasource}"
+ },
+ "gridPos": {
+ "h": 8,
+ "w": 8,
+ "x": 0,
+ "y": 10
+ },
+ "fieldConfig": {
+ "defaults": {
+ "unit": "reqps"
+ }
+ },
+ "targets": [
+ {
+ "refId": "A",
+ "expr": "sum(rate(posthog_notebooks_frame_materializations_started_total[$__rate_interval]))",
+ "legendFormat": "started"
+ }
+ ]
+ },
+ {
+ "type": "text",
+ "title": "Prerequisite check \u2014 CH user and pool routing",
+ "gridPos": {
+ "h": 8,
+ "w": 8,
+ "x": 8,
+ "y": 10
+ },
+ "options": {
+ "mode": "markdown",
+ "content": "No Prometheus metric carries the ClickHouse identity \u2014 the dedicated `notebooks` CH user and offline-pool prerequisites fail open and silently.\n\nVerify them ClickHouse-side with **query 2** of `observability/notebooks-query-log.sql` (Metabase): `user` should be `notebooks` and `lc_workload` should be `offline` once provisioned."
+ }
+ },
+ {
+ "type": "timeseries",
+ "title": "Degraded mode \u2014 object delivery falling back to inline",
+ "description": "An object-delivery request served over the Redis transport instead, silently clamped at 50k rows. Non-zero means the frame store is disabled or object storage is unconfigured, and users may be getting truncated frames with no signal. Should be flat zero once the flag is on.",
+ "datasource": {
+ "type": "prometheus",
+ "uid": "${datasource}"
+ },
+ "gridPos": {
+ "h": 8,
+ "w": 8,
+ "x": 16,
+ "y": 10
+ },
+ "fieldConfig": {
+ "defaults": {
+ "unit": "reqps",
+ "custom": {
+ "fillOpacity": 20
+ },
+ "thresholds": {
+ "mode": "absolute",
+ "steps": [
+ {
+ "color": "green",
+ "value": null
+ },
+ {
+ "color": "red",
+ "value": 0.001
+ }
+ ]
+ }
+ }
+ },
+ "targets": [
+ {
+ "refId": "A",
+ "expr": "sum(rate(posthog_notebooks_frame_store_fallback_inline_total[$__rate_interval]))",
+ "legendFormat": "fallback to inline"
+ }
+ ]
+ },
+ {
+ "type": "row",
+ "title": "Outcomes",
+ "gridPos": {
+ "h": 1,
+ "w": 24,
+ "x": 0,
+ "y": 18
+ },
+ "collapsed": false
+ },
+ {
+ "type": "timeseries",
+ "title": "Terminal outcomes",
+ "datasource": {
+ "type": "prometheus",
+ "uid": "${datasource}"
+ },
+ "gridPos": {
+ "h": 8,
+ "w": 8,
+ "x": 0,
+ "y": 19
+ },
+ "fieldConfig": {
+ "defaults": {
+ "unit": "reqps"
+ }
+ },
+ "targets": [
+ {
+ "refId": "A",
+ "expr": "sum by (outcome) (rate(posthog_notebooks_frame_materializations_finished_total[$__rate_interval]))",
+ "legendFormat": "{{outcome}}"
+ }
+ ],
+ "description": "Materialize jobs reaching a terminal state, by outcome. The finished counter has no mode label \u2014 path-specific failure rates need a code change first."
+ },
+ {
+ "type": "stat",
+ "title": "Failure ratio",
+ "description": "Share of materialize jobs reaching a terminal failed state. Counts jobs, not attempts.",
+ "datasource": {
+ "type": "prometheus",
+ "uid": "${datasource}"
+ },
+ "gridPos": {
+ "h": 8,
+ "w": 4,
+ "x": 8,
+ "y": 19
+ },
+ "fieldConfig": {
+ "defaults": {
+ "unit": "percentunit",
+ "thresholds": {
+ "mode": "absolute",
+ "steps": [
+ {
+ "color": "green",
+ "value": null
+ },
+ {
+ "color": "yellow",
+ "value": 0.02
+ },
+ {
+ "color": "red",
+ "value": 0.1
+ }
+ ]
+ }
+ }
+ },
+ "targets": [
+ {
+ "refId": "A",
+ "expr": "sum(rate(posthog_notebooks_frame_materializations_finished_total{outcome=\"failed\"}[$__rate_interval])) / clamp_min(sum(rate(posthog_notebooks_frame_materializations_finished_total[$__rate_interval])), 0.0000001)",
+ "legendFormat": "failed"
+ }
+ ]
+ },
+ {
+ "type": "stat",
+ "title": "Retry amplification (attempts per job)",
+ "description": "started counts attempts; finished counts jobs. 1.0 means every job succeeds first try. Sustained >2 means jobs are bouncing off the concurrency limiter or hitting retryable ClickHouse errors, and each retry re-executes the scan.",
+ "datasource": {
+ "type": "prometheus",
+ "uid": "${datasource}"
+ },
+ "gridPos": {
+ "h": 8,
+ "w": 4,
+ "x": 12,
+ "y": 19
+ },
+ "fieldConfig": {
+ "defaults": {
+ "unit": "none",
+ "decimals": 2,
+ "thresholds": {
+ "mode": "absolute",
+ "steps": [
+ {
+ "color": "green",
+ "value": null
+ },
+ {
+ "color": "yellow",
+ "value": 2
+ },
+ {
+ "color": "red",
+ "value": 4
+ }
+ ]
+ }
+ }
+ },
+ "targets": [
+ {
+ "refId": "A",
+ "expr": "sum(rate(posthog_notebooks_frame_materializations_started_total[$__rate_interval])) / clamp_min(sum(rate(posthog_notebooks_frame_materializations_finished_total[$__rate_interval])), 0.0000001)",
+ "legendFormat": "attempts/job"
+ }
+ ]
+ },
+ {
+ "type": "timeseries",
+ "title": "Deduplicated requests",
+ "description": "Identical in-flight materializations (same team + user + query) joining a running job instead of stacking ClickHouse load. Healthy \u2014 this is load the cluster never saw.",
+ "datasource": {
+ "type": "prometheus",
+ "uid": "${datasource}"
+ },
+ "gridPos": {
+ "h": 8,
+ "w": 8,
+ "x": 16,
+ "y": 19
+ },
+ "fieldConfig": {
+ "defaults": {
+ "unit": "reqps"
+ }
+ },
+ "targets": [
+ {
+ "refId": "A",
+ "expr": "sum(rate(posthog_notebooks_frame_materializations_deduplicated_total[$__rate_interval]))",
+ "legendFormat": "deduplicated"
+ }
+ ]
+ },
+ {
+ "type": "row",
+ "title": "Latency \u2014 WARNING: success-only, see dashboard description",
+ "gridPos": {
+ "h": 1,
+ "w": 24,
+ "x": 0,
+ "y": 27
+ },
+ "collapsed": false
+ },
+ {
+ "type": "timeseries",
+ "title": "Materialize duration (activity start to object stored)",
+ "description": "SUCCESS ONLY, and the clock starts at ACTIVITY START \u2014 enqueue, Temporal scheduling, task-queue wait and retry backoff are all excluded. A job that times out at 10 minutes contributes no sample at all. Treat as a floor on user-perceived latency, not as E2E.",
+ "datasource": {
+ "type": "prometheus",
+ "uid": "${datasource}"
+ },
+ "gridPos": {
+ "h": 8,
+ "w": 12,
+ "x": 0,
+ "y": 28
+ },
+ "fieldConfig": {
+ "defaults": {
+ "unit": "s"
+ }
+ },
+ "targets": [
+ {
+ "refId": "A",
+ "expr": "histogram_quantile(0.50, sum by (le) (rate(posthog_notebooks_frame_materialize_seconds_bucket[$__rate_interval])))",
+ "legendFormat": "p50"
+ },
+ {
+ "refId": "B",
+ "expr": "histogram_quantile(0.95, sum by (le) (rate(posthog_notebooks_frame_materialize_seconds_bucket[$__rate_interval])))",
+ "legendFormat": "p95"
+ },
+ {
+ "refId": "C",
+ "expr": "histogram_quantile(0.99, sum by (le) (rate(posthog_notebooks_frame_materialize_seconds_bucket[$__rate_interval])))",
+ "legendFormat": "p99"
+ }
+ ]
+ },
+ {
+ "type": "timeseries",
+ "title": "ClickHouse time p95",
+ "description": "Time a successful materialize spent blocked on ClickHouse: response headers plus blocking body reads of the streaming relay. Success-only (see dashboard description).",
+ "datasource": {
+ "type": "prometheus",
+ "uid": "${datasource}"
+ },
+ "gridPos": {
+ "h": 8,
+ "w": 12,
+ "x": 12,
+ "y": 28
+ },
+ "fieldConfig": {
+ "defaults": {
+ "unit": "s"
+ }
+ },
+ "targets": [
+ {
+ "refId": "A",
+ "expr": "histogram_quantile(0.95, sum by (le) (rate(posthog_notebooks_frame_clickhouse_seconds_bucket[$__rate_interval])))",
+ "legendFormat": "p95"
+ }
+ ]
+ },
+ {
+ "type": "timeseries",
+ "title": "Relay split \u2014 where is the worker blocked? (streaming only)",
+ "description": "Mean seconds per successful materialize spent on each side of the worker relay. If the upload half starts dominating p95, that is the design doc's stated trigger for flipping NOTEBOOKS_FRAME_STORE_CH_WRITES on. No upload series is emitted on the ch_writes path \u2014 ClickHouse does the upload there.",
+ "datasource": {
+ "type": "prometheus",
+ "uid": "${datasource}"
+ },
+ "gridPos": {
+ "h": 8,
+ "w": 12,
+ "x": 0,
+ "y": 36
+ },
+ "fieldConfig": {
+ "defaults": {
+ "unit": "s"
+ }
+ },
+ "targets": [
+ {
+ "refId": "A",
+ "expr": "sum(rate(posthog_notebooks_frame_clickhouse_seconds_sum[$__rate_interval])) / clamp_min(sum(rate(posthog_notebooks_frame_clickhouse_seconds_count[$__rate_interval])), 0.0000001)",
+ "legendFormat": "clickhouse (mean)"
+ },
+ {
+ "refId": "B",
+ "expr": "sum(rate(posthog_notebooks_frame_upload_seconds_sum[$__rate_interval])) / clamp_min(sum(rate(posthog_notebooks_frame_upload_seconds_count[$__rate_interval])), 0.0000001)",
+ "legendFormat": "object store upload (mean)"
+ }
+ ]
+ },
+ {
+ "type": "timeseries",
+ "title": "Frame object size",
+ "description": "Stored object bytes. The 2GB result cap (_MAX_RESULT_BYTES) is enforced in-flight on the streaming path but only POST-WRITE on the ch_writes path \u2014 on ch_writes a pathological wide-row query can write tens of GB before the size check deletes it. Watch the top bucket after flipping that flag.",
+ "datasource": {
+ "type": "prometheus",
+ "uid": "${datasource}"
+ },
+ "gridPos": {
+ "h": 8,
+ "w": 12,
+ "x": 12,
+ "y": 36
+ },
+ "fieldConfig": {
+ "defaults": {
+ "unit": "bytes"
+ }
+ },
+ "targets": [
+ {
+ "refId": "A",
+ "expr": "histogram_quantile(0.50, sum by (le) (rate(posthog_notebooks_frame_object_bytes_bucket[$__rate_interval])))",
+ "legendFormat": "p50"
+ },
+ {
+ "refId": "B",
+ "expr": "histogram_quantile(0.95, sum by (le) (rate(posthog_notebooks_frame_object_bytes_bucket[$__rate_interval])))",
+ "legendFormat": "p95"
+ },
+ {
+ "refId": "C",
+ "expr": "histogram_quantile(0.99, sum by (le) (rate(posthog_notebooks_frame_object_bytes_bucket[$__rate_interval])))",
+ "legendFormat": "p99"
+ }
+ ]
+ },
+ {
+ "type": "row",
+ "title": "Throttling and concurrency",
+ "gridPos": {
+ "h": 1,
+ "w": 24,
+ "x": 0,
+ "y": 44
+ },
+ "collapsed": false
+ },
+ {
+ "type": "timeseries",
+ "title": "Concurrency slot rejections",
+ "description": "Rejections against the Redis-Lua slots (global 10, per-team 2). A rejection is retryable \u2014 Temporal backs off \u2014 so a moderate rate is the limiter working, not an outage. Sustained per-team blocks with a low global rate means one team is self-limiting; a high global rate means the fleet ceiling is the binding constraint. NOTE: notebooks' limiters do not set RateLimit.retry, so rejections land as result=block and never result=retry.",
+ "datasource": {
+ "type": "prometheus",
+ "uid": "${datasource}"
+ },
+ "gridPos": {
+ "h": 8,
+ "w": 12,
+ "x": 0,
+ "y": 45
+ },
+ "fieldConfig": {
+ "defaults": {
+ "unit": "reqps"
+ }
+ },
+ "targets": [
+ {
+ "refId": "A",
+ "expr": "sum by (limit_name, result) (rate(posthog_clickhouse_query_concurrency_limit_exceeded_total{limit_name=~\"notebooks_materialize_.*\"}[$__rate_interval]))",
+ "legendFormat": "{{limit_name}} / {{result}}"
+ }
+ ]
+ },
+ {
+ "type": "timeseries",
+ "title": "Top teams hitting the per-team ceiling",
+ "description": "Teams whose materializations are being blocked. Identifies who to talk to before raising MATERIALIZE_PER_TEAM_CONCURRENCY. For actual slot occupancy (which nothing exports today) reconstruct it from query_log_archive \u2014 see notebooks-query-log.sql query 5.",
+ "datasource": {
+ "type": "prometheus",
+ "uid": "${datasource}"
+ },
+ "gridPos": {
+ "h": 8,
+ "w": 12,
+ "x": 12,
+ "y": 45
+ },
+ "fieldConfig": {
+ "defaults": {
+ "unit": "reqps"
+ }
+ },
+ "targets": [
+ {
+ "refId": "A",
+ "expr": "topk(10, sum by (team_id) (rate(posthog_clickhouse_query_concurrency_limit_exceeded_total{limit_name=~\"notebooks_materialize_.*\", result=\"block\"}[$__rate_interval])))",
+ "legendFormat": "team {{team_id}}"
+ }
+ ]
+ },
+ {
+ "type": "row",
+ "title": "HTTP surface",
+ "gridPos": {
+ "h": 1,
+ "w": 24,
+ "x": 0,
+ "y": 53
+ },
+ "collapsed": false
+ },
+ {
+ "type": "timeseries",
+ "title": "Data-plane endpoint latency p95",
+ "description": "Per-REQUEST latency of the sandbox's POST /internal/notebooks/data_plane/query/ and its status polls. This is NOT query latency \u2014 the POST returns 202 as soon as the job is enqueued and each poll returns 202 or a 302 immediately. It answers 'is the data plane responsive', not 'how long do users wait'. The view label value is unverified: these paths have no name= in urls.py, so confirm it with list_prometheus_label_values before trusting this panel.",
+ "datasource": {
+ "type": "prometheus",
+ "uid": "${datasource}"
+ },
+ "gridPos": {
+ "h": 8,
+ "w": 12,
+ "x": 0,
+ "y": 54
+ },
+ "fieldConfig": {
+ "defaults": {
+ "unit": "s"
+ }
+ },
+ "targets": [
+ {
+ "refId": "A",
+ "expr": "histogram_quantile(0.95, sum by (le, view) (rate(django_http_requests_latency_seconds_by_view_method_bucket{view=~\".*notebook.*data_plane.*\"}[$__rate_interval])))",
+ "legendFormat": "p95 {{view}}"
+ }
+ ]
+ },
+ {
+ "type": "timeseries",
+ "title": "Notebooks API latency p95 by view",
+ "description": "The user-facing REST surface (api/projects/:id/notebooks/...), including the sql_v2_run dispatch action. posthog_api_requests_latency_seconds only covers paths containing 'api/', which is why the internal data-plane endpoints are on the panel to the left instead.",
+ "datasource": {
+ "type": "prometheus",
+ "uid": "${datasource}"
+ },
+ "gridPos": {
+ "h": 8,
+ "w": 12,
+ "x": 12,
+ "y": 54
+ },
+ "fieldConfig": {
+ "defaults": {
+ "unit": "s"
+ }
+ },
+ "targets": [
+ {
+ "refId": "A",
+ "expr": "histogram_quantile(0.95, sum by (le, view) (rate(posthog_api_requests_latency_seconds_bucket{view=~\".*notebook.*\"}[$__rate_interval])))",
+ "legendFormat": "p95 {{view}}"
+ }
+ ]
+ },
+ {
+ "type": "timeseries",
+ "title": "Notebooks API responses by status class",
+ "datasource": {
+ "type": "prometheus",
+ "uid": "${datasource}"
+ },
+ "gridPos": {
+ "h": 8,
+ "w": 24,
+ "x": 0,
+ "y": 62
+ },
+ "fieldConfig": {
+ "defaults": {
+ "unit": "reqps"
+ }
+ },
+ "targets": [
+ {
+ "refId": "A",
+ "expr": "sum by (view, status_class) (rate(posthog_api_requests_latency_seconds_count{view=~\".*notebook.*\"}[$__rate_interval]))",
+ "legendFormat": "{{view}} {{status_class}}"
+ }
+ ]
+ }
+ ]
+}
diff --git a/pyproject.toml b/pyproject.toml
index 07db233ab128..b5118d3ed498 100644
--- a/pyproject.toml
+++ b/pyproject.toml
@@ -591,6 +591,7 @@ ignore_imports = [
"products.notebooks.backend.presentation.views.notebook -> products.notebooks.backend.sql_v2",
"products.notebooks.backend.presentation.views.notebook -> products.notebooks.backend.sql_v2_direct",
"products.notebooks.backend.presentation.views.notebook -> products.notebooks.backend.sql_v2_references",
+ "products.notebooks.backend.presentation.views.notebook -> products.notebooks.backend.sql_v2_runs",
"products.notebooks.backend.presentation.views.notebook -> products.notebooks.backend.sql_v2_serializers",
"products.notebooks.backend.presentation.views.notebook -> products.notebooks.backend.temporal.client",
"products.notebooks.backend.presentation.views.notebook -> products.notebooks.backend.temporal.sql_v2",