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.

chore(notebooks): extract node run dispatch and add NotebookRun model (#98143)

Sinan Kucukkoselera6ea0480e39a
diff --git a/.semgrep/rules/security/idor-team-scoped-models.yaml b/.semgrep/rules/security/idor-team-scoped-models.yaml
index dde1e69fe640..d8041ffa67d6 100644
--- a/.semgrep/rules/security/idor-team-scoped-models.yaml
+++ b/.semgrep/rules/security/idor-team-scoped-models.yaml
@@ -301,6 +301,7 @@ rules:
|NotificationEvent
|Notebook
|NotebookNodeRun
+ |NotebookRun
|ObjectMediaPreview
|ParserRecipe
|PendingSourceCredential
@@ -718,6 +719,7 @@ rules:
|NotificationEvent
|Notebook
|NotebookNodeRun
+ |NotebookRun
|ObjectMediaPreview
|ParserRecipe
|PendingSourceCredential
diff --git a/products/notebooks/backend/facade/sql_v2.py b/products/notebooks/backend/facade/sql_v2.py
index 587679452bc7..b2537c899db4 100644
--- a/products/notebooks/backend/facade/sql_v2.py
+++ b/products/notebooks/backend/facade/sql_v2.py
@@ -5,16 +5,24 @@ Core (`posthog/urls.py`) wires the internal sandbox -> backend endpoints — the
run result callback and the data plane — through these re-exports rather than
importing the view modules directly.
-The run-concurrency helpers sit here too, because the HTTP surface takes and gives back a
-run's slots and may only reach in-product code through this package.
+The cell-dispatch surface sits here too, because the HTTP surface starts a cell run and
+may only reach in-product code through this package. Both entry points take ids and
+contracts and resolve the models inside the product, so no caller holds a Django object.
+`dispatch_cell_run` takes and gives back the run's concurrency slots itself, so the view
+never handles them.
"""
from ..sql_v2_callback import notebook_sql_v2_callback as notebook_sql_v2_callback
-from ..sql_v2_concurrency import (
- acquire_run_slots as acquire_run_slots,
- release_run_slots as release_run_slots,
-)
from ..sql_v2_data_plane import (
notebook_sql_v2_data_plane as notebook_sql_v2_data_plane,
notebook_sql_v2_data_plane_status as notebook_sql_v2_data_plane_status,
)
+from ..sql_v2_dispatch import (
+ NodeRunDispatchFailed as NodeRunDispatchFailed,
+ NodeRunInvalid as NodeRunInvalid,
+ NodeRunNotPermitted as NodeRunNotPermitted,
+ NodeRunRequest as NodeRunRequest,
+ build_ref_specs as build_ref_specs,
+ dispatch_cell_run as dispatch_cell_run,
+ kernel_sandbox_is_live as kernel_sandbox_is_live,
+)
diff --git a/products/notebooks/backend/migrations/0024_notebook_run.py b/products/notebooks/backend/migrations/0024_notebook_run.py
new file mode 100644
index 000000000000..0cfea496e749
--- /dev/null
+++ b/products/notebooks/backend/migrations/0024_notebook_run.py
@@ -0,0 +1,96 @@
+# Generated by Django 5.2.17 on 2026-09-10 08:07
+
+import django.db.models.deletion
+from django.conf import settings
+from django.db import migrations, models
+
+import posthog.uuidt
+
+
+class Migration(migrations.Migration):
+ dependencies = [
+ ("notebooks", "0023_generated_widget_generation_cost"),
+ ("posthog", "1350_alter_userscenepersonalisation_dashboard"),
+ migrations.swappable_dependency(settings.AUTH_USER_MODEL),
+ ]
+
+ operations = [
+ migrations.CreateModel(
+ name="NotebookRun",
+ fields=[
+ (
+ "id",
+ models.UUIDField(default=posthog.uuidt.uuid7, editable=False, primary_key=True, serialize=False),
+ ),
+ ("trigger", models.CharField(choices=[("ui", "ui"), ("mcp", "mcp")], max_length=20)),
+ (
+ "status",
+ models.CharField(
+ choices=[
+ ("running", "running"),
+ ("done", "done"),
+ ("failed", "failed"),
+ ("interrupted", "interrupted"),
+ ],
+ default="running",
+ max_length=20,
+ ),
+ ),
+ ("variables", models.JSONField(blank=True, default=list)),
+ ("cell_plan", models.JSONField(blank=True, default=list)),
+ ("current_index", models.IntegerField(db_default=0, default=0)),
+ ("failed_node_id", models.CharField(blank=True, max_length=128, null=True)),
+ ("error", models.TextField(blank=True, null=True)),
+ ("created_at", models.DateTimeField(auto_now_add=True)),
+ ("updated_at", models.DateTimeField(auto_now=True)),
+ ("finished_at", models.DateTimeField(blank=True, null=True)),
+ ("notebook", models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to="notebooks.notebook")),
+ (
+ "team",
+ models.ForeignKey(
+ db_constraint=False,
+ on_delete=django.db.models.deletion.CASCADE,
+ related_name="+",
+ to="posthog.team",
+ ),
+ ),
+ (
+ "user",
+ models.ForeignKey(
+ blank=True,
+ db_constraint=False,
+ db_index=False,
+ null=True,
+ on_delete=django.db.models.deletion.DO_NOTHING,
+ related_name="+",
+ to=settings.AUTH_USER_MODEL,
+ ),
+ ),
+ ],
+ options={
+ "db_table": "posthog_notebookrun",
+ },
+ ),
+ migrations.AddField(
+ model_name="notebooknoderun",
+ name="notebook_run",
+ field=models.ForeignKey(
+ blank=True,
+ db_index=False,
+ null=True,
+ on_delete=django.db.models.deletion.SET_NULL,
+ related_name="node_runs",
+ to="notebooks.notebookrun",
+ ),
+ ),
+ migrations.AddIndex(
+ model_name="notebookrun",
+ index=models.Index(fields=["team", "notebook", "-created_at"], name="posthog_not_team_id_ae0668_idx"),
+ ),
+ migrations.AddConstraint(
+ model_name="notebookrun",
+ constraint=models.UniqueConstraint(
+ condition=models.Q(("status", "running")), fields=("notebook",), name="unique_running_notebook_run"
+ ),
+ ),
+ ]
diff --git a/products/notebooks/backend/migrations/0025_notebook_node_run_by_run_idx.py b/products/notebooks/backend/migrations/0025_notebook_node_run_by_run_idx.py
new file mode 100644
index 000000000000..ab739a5c8b8c
--- /dev/null
+++ b/products/notebooks/backend/migrations/0025_notebook_node_run_by_run_idx.py
@@ -0,0 +1,26 @@
+from django.db import migrations, models
+
+from posthog.migration_helpers import SafeAddIndexConcurrently
+
+
+class Migration(migrations.Migration):
+ # CONCURRENTLY cannot run inside a transaction. Its own migration rather than 0021's, because
+ # 0021 creates a table and adds a constraint and so has to stay atomic — and because a
+ # non-concurrent build there would run while the AddField still held ACCESS EXCLUSIVE on
+ # posthog_notebooknoderun, stopping every dispatch, callback, and status read on it.
+ atomic = False
+
+ dependencies = [
+ ("notebooks", "0024_notebook_run"),
+ ]
+
+ operations = [
+ SafeAddIndexConcurrently(
+ model_name="notebooknoderun",
+ index=models.Index(
+ fields=["notebook_run"],
+ name="notebook_node_run_by_run_idx",
+ condition=models.Q(notebook_run__isnull=False),
+ ),
+ ),
+ ]
diff --git a/products/notebooks/backend/migrations/max_migration.txt b/products/notebooks/backend/migrations/max_migration.txt
index 5874819f088b..d0370fb04771 100644
--- a/products/notebooks/backend/migrations/max_migration.txt
+++ b/products/notebooks/backend/migrations/max_migration.txt
@@ -1 +1 @@
-0023_generated_widget_generation_cost
+0025_notebook_node_run_by_run_idx
diff --git a/products/notebooks/backend/models.py b/products/notebooks/backend/models.py
index 9300b94744fb..31fc10c75f49 100644
--- a/products/notebooks/backend/models.py
+++ b/products/notebooks/backend/models.py
@@ -204,6 +204,70 @@ class KernelRuntime(UUIDTModel):
]
+class NotebookRun(TeamScopedRootMixin, UUIDModel):
+ """One execution of a whole markdown notebook: every runnable cell, in document order.
+
+ The orchestrator owns this row. Each cell it starts is a `NotebookNodeRun` pointing back
+ here, so the status endpoint reads the whole run with one join.
+ """
+
+ class Status(models.TextChoices):
+ RUNNING = "running", "running"
+ DONE = "done", "done"
+ FAILED = "failed", "failed"
+ INTERRUPTED = "interrupted", "interrupted"
+
+ class Trigger(models.TextChoices):
+ UI = "ui", "ui"
+ MCP = "mcp", "mcp"
+
+ # db_constraint=False on both FKs to hot tables, for the reasons NotebookNodeRun states below.
+ team = models.ForeignKey("posthog.Team", on_delete=models.CASCADE, db_constraint=False, related_name="+")
+ # No related_name, like NotebookNodeRun: a named reverse accessor on Notebook would join the
+ # fields the activity log walks, and reading it outside a team scope raises.
+ notebook = models.ForeignKey("notebooks.Notebook", on_delete=models.CASCADE)
+ user = models.ForeignKey(
+ "posthog.User",
+ on_delete=models.DO_NOTHING,
+ null=True,
+ blank=True,
+ db_constraint=False,
+ db_index=False,
+ related_name="+",
+ )
+ # Which surface started the run. Read as a metric label, so the outcome of a person's click
+ # and of an agent's tool call can be told apart.
+ trigger = models.CharField(choices=Trigger, max_length=20)
+ status = models.CharField(choices=Status, default=Status.RUNNING, max_length=20)
+ # The variable values this run bound, snapshotted at start. The notebook's own list can
+ # change while the run works, and the results have to stay readable against what produced them.
+ variables: JSONField = JSONField(default=list, blank=True)
+ # The cells to run, as [{node_id, cell_type, dataframe_name}] in document order, frozen at
+ # start. An edit during the run does not add or remove cells from it.
+ cell_plan: JSONField = JSONField(default=list, blank=True)
+ # How far through `cell_plan` the orchestrator is; the status endpoint reads it.
+ current_index = models.IntegerField(default=0, db_default=0)
+ failed_node_id = models.CharField(max_length=128, null=True, blank=True)
+ error = models.TextField(null=True, blank=True)
+ created_at = models.DateTimeField(auto_now_add=True)
+ updated_at = models.DateTimeField(auto_now=True)
+ finished_at = models.DateTimeField(null=True, blank=True)
+
+ class Meta:
+ db_table = "posthog_notebookrun"
+ indexes = [
+ models.Index(fields=["team", "notebook", "-created_at"]),
+ ]
+ constraints = [
+ # One whole-notebook run at a time, enforced by the database rather than by a lock.
+ models.UniqueConstraint(
+ fields=["notebook"],
+ condition=models.Q(status="running"),
+ name="unique_running_notebook_run",
+ )
+ ]
+
+
class NotebookNodeRun(TeamScopedRootMixin, UUIDModel):
"""A single execution of a revamped-notebooks (SQLV2) node.
The primary key is the run_id referenced by the run/callback/stream endpoints.
@@ -244,6 +308,20 @@ class NotebookNodeRun(TeamScopedRootMixin, UUIDModel):
related_name="+",
)
node_id = models.CharField(max_length=128)
+ # The whole-notebook run that dispatched this cell, or null for a single-cell run. SET_NULL
+ # rather than CASCADE: a run record is bookkeeping, and deleting one must not take the
+ # results it produced with it.
+ # db_index=False here, with a partial index in Meta instead: the default full index would be
+ # built inside the AddField's ACCESS EXCLUSIVE lock, and it would index the null rows that
+ # every single-cell run leaves behind on the table that grows fastest.
+ notebook_run = models.ForeignKey(
+ "notebooks.NotebookRun",
+ on_delete=models.SET_NULL,
+ null=True,
+ blank=True,
+ db_index=False,
+ related_name="node_runs",
+ )
# How the run executed: hogql pushed to ClickHouse (pages re-query by `code`); python and
# duckdb ran in the sandbox kernel (pages slice the on-sandbox result frame by `result_id`).
node_type = models.CharField(choices=NodeType, default=NodeType.HOGQL, max_length=20)
@@ -274,6 +352,14 @@ class NotebookNodeRun(TeamScopedRootMixin, UUIDModel):
db_table = "posthog_notebooknoderun"
indexes = [
models.Index(fields=["team", "notebook", "node_id"]),
+ # Partial, because only a whole-notebook run's cells carry this column: the status
+ # read joins by it, and SET_NULL updates by it when a run record is deleted. A single
+ # cell run leaves it null and is never looked up this way, so those rows stay out.
+ models.Index(
+ fields=["notebook_run"],
+ name="notebook_node_run_by_run_idx",
+ condition=models.Q(notebook_run__isnull=False),
+ ),
]
diff --git a/products/notebooks/backend/presentation/views/notebook.py b/products/notebooks/backend/presentation/views/notebook.py
index 1fea31ca2672..e47add9c8635 100644
--- a/products/notebooks/backend/presentation/views/notebook.py
+++ b/products/notebooks/backend/presentation/views/notebook.py
@@ -1,7 +1,6 @@
import math
import hashlib
from collections import Counter
-from datetime import timedelta
from typing import Any, cast
from django.conf import settings
@@ -29,8 +28,7 @@ from rest_framework.request import Request
from rest_framework.response import Response
from rest_framework.serializers import BaseSerializer
-from posthog.hogql.direct_connection import INVALID_CONNECTION_ID_ERROR, get_direct_connection_source
-from posthog.hogql.errors import ExposedHogQLError
+from posthog.hogql.direct_connection import get_direct_connection_source
from posthog.api.forbid_destroy_model import ForbidDestroyModel
from posthog.api.routing import TeamAndOrgViewSetMixin
@@ -45,7 +43,7 @@ from posthog.helpers.impersonation import is_impersonated
from posthog.models import User
from posthog.models.activity_logging.activity_log import Change, changes_between, load_activity
from posthog.models.activity_logging.activity_page import activity_page_response, parse_activity_page_params
-from posthog.models.utils import UUIDT, uuid7
+from posthog.models.utils import UUIDT
from posthog.renderers import ServerSentEventRenderer
from posthog.settings import SERVER_GATEWAY_INTERFACE
from posthog.utils import relative_date_parse
@@ -77,7 +75,15 @@ from products.notebooks.backend.facade.contracts import (
TeamRunCapacityFull,
)
from products.notebooks.backend.facade.kernel_sandbox_usage import record_sandbox_ended_by_id
-from products.notebooks.backend.facade.sql_v2 import acquire_run_slots, release_run_slots
+from products.notebooks.backend.facade.sql_v2 import (
+ NodeRunDispatchFailed,
+ NodeRunInvalid,
+ NodeRunNotPermitted,
+ NodeRunRequest,
+ build_ref_specs,
+ dispatch_cell_run,
+ kernel_sandbox_is_live,
+)
from products.notebooks.backend.facade.widgets import (
WidgetConflictError,
WidgetError,
@@ -135,14 +141,7 @@ from products.notebooks.backend.sql_v2 import (
is_sql_v2_enabled,
sql_v2_page_lock_key,
)
-from products.notebooks.backend.sql_v2_direct import cancel_direct_run, enqueue_direct_run, sync_direct_run
-from products.notebooks.backend.sql_v2_references import (
- SQLV2Ref,
- SQLV2ReferenceError,
- SQLV2RunPlan,
- resolve_python_node_inputs,
- resolve_sql_node_run,
-)
+from products.notebooks.backend.sql_v2_direct import cancel_direct_run, sync_direct_run
from products.notebooks.backend.sql_v2_runs import expire_stale_kernel_run, finish_node_run
from products.notebooks.backend.sql_v2_serializers import (
MAX_VARIABLES_PER_NOTEBOOK,
@@ -162,14 +161,7 @@ from products.notebooks.backend.sql_v2_state import (
build_notebook_cell_state,
validate_cell_count,
)
-from products.notebooks.backend.sql_v2_variables import (
- NotebookVariableError,
- build_notebook_variables,
- python_variable_bindings,
- reject_variables_in_raw_query,
-)
-from products.notebooks.backend.temporal.client import start_sql_v2_run_workflow
-from products.notebooks.backend.temporal.sql_v2 import SQLV2RunInput
+from products.notebooks.backend.sql_v2_variables import build_notebook_variables
from products.tasks.backend.facade.exceptions import SandboxProvisionError
from products.tasks.backend.facade.sandbox import SandboxStatus
@@ -177,22 +169,6 @@ from ee.hogai.utils.aio import async_to_sync
logger = structlog.get_logger(__name__)
-# Raised when a cell reads a sibling whose last result lives somewhere this run can't reach.
-_CROSS_ENGINE_REF_ERROR = (
- "'{name}' last ran on a different connection, so this cell can't read it. "
- "Point both cells at the same connection and re-run, or inline its query here."
-)
-# Python cells read upstream results through the data plane, which only reaches PostHog.
-_CROSS_ENGINE_REF_ERROR_FOR_PYTHON = (
- "'{name}' ran on a warehouse connection, and Python cells can only read PostHog results. "
- "Re-run '{name}' on PostHog to use it here."
-)
-# Covers both kinds of local frame: one a Python cell bound, and one a SQL cell left behind when
-# reading a Python dataframe rerouted it to the sandbox. Neither is reachable from a warehouse.
-_LOCAL_FRAME_REF_ERROR = (
- "You can't query the local dataframe '{name}' because this cell points to a data source other than PostHog."
-)
-
def depluralize(string: str | None) -> str | None:
if not string:
@@ -1618,7 +1594,12 @@ class NotebookViewSet(TeamAndOrgViewSetMixin, AccessControlViewSetMixin, ForbidD
)
# A RUNNING row can outlive its sandbox, and restarting on a stale one would turn a
# config-only call into new paid compute. Confirm the sandbox before acting on the row.
- kernel_is_live = live_runtime is not None and self._sandbox_is_running(notebook, config_user, live_runtime)
+ kernel_is_live = live_runtime is not None and kernel_sandbox_is_live(
+ team_id=self.team_id,
+ notebook_short_id=notebook.short_id,
+ user_id=config_user.id if isinstance(config_user, User) else None,
+ runtime_id=live_runtime.id,
+ )
# Compare the desired shape against what the running sandbox was provisioned with, not just
# this request's change, so a retry after a failed restart still triggers one. Fall back to
# the pre-write config when no runtime has recorded a shape.
@@ -1682,20 +1663,6 @@ class NotebookViewSet(TeamAndOrgViewSetMixin, AccessControlViewSetMixin, ForbidD
return ComputeShape(cpu_cores=runtime.provisioned_cpu_cores, memory_gb=runtime.provisioned_memory_gb)
return fallback
- def _sandbox_is_running(self, notebook: Notebook, user: Any, runtime: KernelRuntime) -> bool:
- """Whether the runtime row still has a sandbox behind it, the check kernel_status makes."""
- if not runtime.sandbox_id or runtime.backend not in (
- KernelRuntime.Backend.MODAL,
- KernelRuntime.Backend.DOCKER,
- ):
- return False
- try:
- service = get_kernel_runtime(notebook, user).service
- sandbox = service._get_sandbox_class(runtime.backend).get_by_id(runtime.sandbox_id)
- return sandbox.get_status() == SandboxStatus.RUNNING
- except Exception:
- return False
-
@staticmethod
def _preset_key_for(cpu_cores: float | None, memory_gb: float | None) -> str | None:
preset = find_matching_preset(cpu_cores=cpu_cores, memory_gb=memory_gb)
@@ -1851,152 +1818,36 @@ class NotebookViewSet(TeamAndOrgViewSetMixin, AccessControlViewSetMixin, ForbidD
self._require_query_access()
node_type = serializer.validated_data["node_type"]
- code = serializer.validated_data["code"]
- output_name = serializer.validated_data["output_name"]
# Only SQL nodes carry a connection; python always runs in the kernel against PostHog.
connection_id = serializer.validated_data["connection_id"] if node_type != "python" else None
- send_raw_query = bool(serializer.validated_data["send_raw_query"]) and connection_id is not None
- if connection_id is not None and (
- # Resolve up front so a stale or unreachable connection fails the dispatch with the
- # shared message, rather than surfacing later as an opaque failed run.
- get_direct_connection_source(
- self.team,
- str(connection_id),
- user=user if isinstance(user, User) else None,
- require_pure_direct=send_raw_query,
- )
- is None
- ):
- return Response({"detail": INVALID_CONNECTION_ID_ERROR}, status=400)
-
- # Resolve each referenced hogql node to its last-run query (not its live editor text),
- # so a join recomputes against the definitions that produced the results on screen.
- # Inlining happens once here, so the run stores a self-contained query and paging
- # re-queries it without re-resolving refs. Local refs (Python-made frames) carry no
- # query — they live in the kernel namespace.
- ref_specs: dict[str, dict] = serializer.validated_data.get("refs") or {}
- hogql_node_ids = {spec["node_id"] for spec in ref_specs.values() if spec["kind"] == "hogql"}
- # One DISTINCT ON query fetches the latest DONE run (id + code) for every referenced node.
- latest_runs = (
- NotebookNodeRun.objects.for_team(self.team_id)
- .filter(notebook=notebook, node_id__in=hogql_node_ids, status=NotebookNodeRun.Status.DONE)
- .order_by("node_id", "-created_at")
- .distinct("node_id")
- .values_list("node_id", "id", "code", "node_type", "connection_id", "send_raw_query")
+ run_request = NodeRunRequest(
+ node_id=serializer.validated_data["node_id"],
+ node_type=node_type,
+ code=serializer.validated_data["code"],
+ output_name=serializer.validated_data["output_name"],
+ refs=build_ref_specs(serializer.validated_data.get("refs") or {}),
+ # The notebook's variables as of this run. A SQL node has them bound into its
+ # code; a python node carries them to the kernel, which binds them as globals.
+ variables=build_notebook_variables(serializer.validated_data.get("variables") or []),
+ connection_id=connection_id,
+ send_raw_query=bool(serializer.validated_data["send_raw_query"]) and connection_id is not None,
+ reuse_results=serializer.validated_data["reuse_results"],
+ allow_sandbox=full_compute_enabled,
)
- # A ref is only inlinable when the upstream node's LATEST run executed the same way this
- # one will. A SQL node's runs can alternate between hogql and duckdb (Journey 5
- # rerouting) and between engines, and its stored code only means anything on the engine
- # that produced it — a duckdb run's code names kernel frames, and a connection run's is
- # that warehouse's SQL. Inlining either elsewhere would ship the wrong query.
- latest_by_node: dict[str, tuple[str, str]] = {}
- other_engine_nodes: set[str] = set()
- # A SQL node rerouted to DuckDB binds its result into the kernel namespace under its
- # dataframe name, exactly like a Python node — there is no ClickHouse query to inline,
- # but the frame is there to read. So it becomes a local ref rather than an absent one.
- kernel_frame_nodes: set[str] = set()
- for other_node_id, run_id, run_code, run_type, run_connection_id, run_send_raw in latest_runs:
- if run_type == NotebookNodeRun.NodeType.DUCKDB:
- kernel_frame_nodes.add(other_node_id)
- continue
- if run_type != NotebookNodeRun.NodeType.HOGQL:
- continue
- if run_connection_id == connection_id and bool(run_send_raw) == send_raw_query:
- latest_by_node[other_node_id] = (str(run_id), run_code)
- else:
- other_engine_nodes.add(other_node_id)
- cross_engine_error = _CROSS_ENGINE_REF_ERROR_FOR_PYTHON if node_type == "python" else _CROSS_ENGINE_REF_ERROR
- refs: dict[str, SQLV2Ref] = {}
- for name, spec in ref_specs.items():
- if spec["kind"] == "local" or spec["node_id"] in kernel_frame_nodes:
- # A kernel frame lives in the sandbox, which only reaches PostHog's own data — a
- # connection run can't be rerouted there, so mark it unusable instead.
- refs[name] = (
- SQLV2Ref(kind="hogql", node_id=None, unavailable_reason=_LOCAL_FRAME_REF_ERROR.format(name=name))
- if connection_id is not None
- else SQLV2Ref(kind="local")
- )
- continue
- latest = latest_by_node.get(spec["node_id"])
- refs[name] = SQLV2Ref(
- kind="hogql",
- node_id=spec["node_id"],
- run_id=latest[0] if latest else None,
- last_run_code=latest[1] if latest else None,
- unavailable_reason=(
- cross_engine_error.format(name=name) if spec["node_id"] in other_engine_nodes else None
- ),
- )
- # The notebook's variables as of this run. A SQL node has them bound into its code
- # below; a python node carries them to the kernel, which binds them as globals.
- variables = build_notebook_variables(serializer.validated_data.get("variables") or [])
try:
- if node_type == "python":
- # A python node stores its code as-is; referenced frames become kernel inputs,
- # keyed by the upstream run_id so a re-run yields a fresh (not stale) frame.
- plan = SQLV2RunPlan(node_type="python", code=code, inputs=resolve_python_node_inputs(code, refs))
- elif send_raw_query:
- # Raw SQL is the connection's own dialect, so the HogQL parser can't read it and
- # there is nothing to inline: it reaches the engine exactly as written. Variables
- # are refused here rather than escaped by hand — see reject_variables_in_raw_query.
- reject_variables_in_raw_query(code, variables)
- plan = SQLV2RunPlan(node_type="hogql", code=code, inputs=[])
- else:
- # A SQL node pushes to ClickHouse — unless it references a local frame, which
- # reroutes it to the sandbox's DuckDB (Journey 5).
- plan = resolve_sql_node_run(code, refs, variables)
- # ExposedHogQLError: with refs present the user's own code is parsed at dispatch, so a
- # plain typo raises here — it's a bad query (400 with the parse message), not a 500.
- except (SQLV2ReferenceError, NotebookVariableError, ExposedHogQLError) as e:
- return Response({"detail": str(e)}, status=400)
-
- if not full_compute_enabled and plan.node_type != "hogql":
- raise Http404()
-
- reusable_runs = (
- NotebookNodeRun.objects.for_team(self.team_id)
- .filter(
- notebook=notebook,
- user=user,
- node_id=serializer.validated_data["node_id"],
- code=plan.code,
- node_type="hogql",
- connection_id__isnull=True,
- status__in=[NotebookNodeRun.Status.RUNNING, NotebookNodeRun.Status.DONE],
- created_at__gte=now() - timedelta(hours=1),
- )
- .order_by("-created_at")
- if serializer.validated_data["reuse_results"]
- and user is not None
- and plan.node_type == "hogql"
- and connection_id is None
- else None
- )
-
- def reused_response() -> Response | None:
- existing_run = reusable_runs.first() if reusable_runs is not None else None
- if existing_run is None:
- return None
- return Response(
- NotebookSQLV2RunResponseSerializer(
- {"run_id": str(existing_run.id), "starts_sandbox": False, "sandbox_hourly_price": None}
- ).data
+ dispatch = dispatch_cell_run(
+ team_id=self.team_id,
+ notebook_short_id=notebook.short_id,
+ user_id=user.id if isinstance(user, User) else None,
+ request=run_request,
)
-
- if cached_response := reused_response():
- return cached_response
-
- # Taken before the row exists, so a refused dispatch writes nothing: an agent retrying
- # into a full ceiling must not leave a trail of rows behind it. The id is minted here
- # because the slot is keyed on it and has to be released by the run that took it.
- # Not `run_id`: the ref-inlining loop above binds that name to each *upstream* run, and
- # reusing it here would leave two different runs behind one variable.
- new_run_id = uuid7()
- try:
- acquire_run_slots(self.team_id, notebook.short_id, str(new_run_id))
+ except NodeRunNotPermitted:
+ # The plan resolved to the sandbox for a caller without full compute. 404 like
+ # the gates above: they are not told the lane exists.
+ raise Http404()
+ except NodeRunInvalid as e:
+ return Response({"detail": str(e)}, status=400)
except NotebookRunBusy as e:
- if cached_response := reused_response():
- return cached_response
# 409, not 429: a conflict with the notebook's state rather than a rate. The MCP
# client retries every 429 with backoff and then replaces the body with its own
# rate-limit message, so a 429 here would cost an agent seconds of pointless waiting
@@ -2004,94 +1855,18 @@ class NotebookViewSet(TeamAndOrgViewSetMixin, AccessControlViewSetMixin, ForbidD
return Response({"detail": str(e)}, status=409)
except TeamRunCapacityFull as e:
return Response({"detail": str(e)}, status=429)
+ except NodeRunDispatchFailed as e:
+ return Response({"detail": str(e)}, status=503)
- if cached_response := reused_response():
- release_run_slots(self.team_id, notebook.short_id, str(new_run_id))
- return cached_response
-
- try:
- run = NotebookNodeRun.objects.create(
- id=new_run_id,
- team_id=self.team_id,
- notebook=notebook,
- # The same user the run's kernel is resolved for, so the callback can scope the
- # frame snapshot to that kernel. A token user has no kernel of its own, hence None.
- user=user if isinstance(user, User) else None,
- node_id=serializer.validated_data["node_id"],
- code=plan.code,
- node_type=plan.node_type,
- connection_id=connection_id,
- send_raw_query=send_raw_query,
- status=NotebookNodeRun.Status.RUNNING,
- )
- except Exception:
- # No row means no release site will ever learn this run id, so hand the slots back
- # here or the notebook stays blocked with nothing running in it.
- release_run_slots(self.team_id, notebook.short_id, str(new_run_id))
- raise
-
- try:
- if plan.node_type == "hogql":
- # Direct lane: a pure-HogQL run never touches the sandbox — it rides the
- # async query manager, and the run-result poll advances the row.
- enqueue_direct_run(self.team, user if isinstance(user, User) else None, run)
- else:
- start_sql_v2_run_workflow(
- SQLV2RunInput(
- run_id=str(run.id),
- notebook_short_id=notebook.short_id,
- team_id=self.team_id,
- user_id=user.id if isinstance(user, User) else None,
- code=plan.code,
- node_type=plan.node_type,
- output_name=output_name,
- inputs=plan.inputs,
- # A python node reads these as globals; a duckdb node binds them as
- # `$name` query parameters, so it carries only the ones its SQL uses.
- variables=(
- python_variable_bindings(variables) if plan.node_type == "python" else plan.variables
- ),
- )
- )
- except Exception:
- logger.exception("notebook_sql_v2_run_start_failed", notebook_short_id=notebook.short_id)
- # 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)
-
- # Whether this run has to build a sandbox, decided here rather than inferred by a client
- # from a kernel status poll that can be ten seconds old. That cache could stay silent
- # through a sandbox that timed out between polls, which is the one case worth disclosing.
- uses_sandbox = plan.node_type != "hogql"
- live_runtime = (
- KernelRuntime.objects.filter(
- team_id=self.team_id,
- notebook_short_id=notebook.short_id,
- user=user if isinstance(user, User) else None,
- status__in=(KernelRuntime.Status.RUNNING, KernelRuntime.Status.STARTING),
- )
- .order_by("-last_used_at")
- .first()
- if uses_sandbox
- else None
- )
- starts_sandbox = uses_sandbox and not (
- live_runtime is not None and self._sandbox_is_running(notebook, user, live_runtime)
+ return Response(
+ NotebookSQLV2RunResponseSerializer(
+ {
+ "run_id": str(dispatch.run_id),
+ "starts_sandbox": dispatch.starts_sandbox,
+ "sandbox_hourly_price": dispatch.sandbox_hourly_price,
+ }
+ ).data
)
- sandbox_config = build_notebook_sandbox_config(notebook) if starts_sandbox else None
- run_payload = {
- "run_id": str(run.id),
- "starts_sandbox": starts_sandbox,
- # Only a modal sandbox is charged, so a docker kernel carries no price to disclose.
- "sandbox_hourly_price": (
- get_compute_rates().hourly_price(cpu_cores=sandbox_config.cpu_cores, memory_gb=sandbox_config.memory_gb)
- if sandbox_config is not None
- and get_kernel_runtime(notebook, user).service._get_backend() == KernelRuntime.Backend.MODAL
- else None
- ),
- }
- return Response(NotebookSQLV2RunResponseSerializer(run_payload).data)
@extend_schema(
parameters=[
diff --git a/products/notebooks/backend/sql_v2_dispatch.py b/products/notebooks/backend/sql_v2_dispatch.py
new file mode 100644
index 000000000000..dd2165beedd4
--- /dev/null
+++ b/products/notebooks/backend/sql_v2_dispatch.py
@@ -0,0 +1,488 @@
+"""Start one cell run: resolve its references, take its slots, and hand it to a lane.
+
+The run view used to hold all of this inline. It moved here so the whole-notebook
+orchestrator starts a cell exactly the way a person's click does — the same ref inlining,
+the same concurrency ceilings, the same routing between the direct (ClickHouse) lane and
+the sandbox kernel. The view keeps only what a view owns: validate, call, format.
+"""
+
+from datetime import timedelta
+from typing import Literal, TypedDict
+from uuid import UUID
+
+from django.db.models import QuerySet
+from django.utils.timezone import now
+
+import structlog
+
+from posthog.hogql.direct_connection import INVALID_CONNECTION_ID_ERROR, get_direct_connection_source
+from posthog.hogql.errors import ExposedHogQLError
+
+from posthog.dataclasses import frozen
+from posthog.models import Team, User
+from posthog.models.utils import uuid7
+
+from products.notebooks.backend.compute_pricing import get_compute_rates
+from products.notebooks.backend.facade.contracts import NotebookRunBusy, TeamRunCapacityFull
+from products.notebooks.backend.kernel_runtime import build_notebook_sandbox_config, get_kernel_runtime
+from products.notebooks.backend.models import KernelRuntime, Notebook, NotebookNodeRun
+from products.notebooks.backend.sql_v2_concurrency import acquire_run_slots, release_run_slots
+from products.notebooks.backend.sql_v2_direct import enqueue_direct_run
+from products.notebooks.backend.sql_v2_references import (
+ SQLV2Ref,
+ SQLV2ReferenceError,
+ SQLV2RunPlan,
+ 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_variables import (
+ NotebookVariable,
+ NotebookVariableError,
+ python_variable_bindings,
+ reject_variables_in_raw_query,
+)
+from products.notebooks.backend.temporal.client import start_sql_v2_run_workflow
+from products.notebooks.backend.temporal.sql_v2 import SQLV2RunInput
+from products.tasks.backend.facade.sandbox import SandboxStatus
+
+logger = structlog.get_logger(__name__)
+
+# Raised when a cell reads a sibling whose last result lives somewhere this run can't reach.
+CROSS_ENGINE_REF_ERROR = (
+ "'{name}' last ran on a different connection, so this cell can't read it. "
+ "Point both cells at the same connection and re-run, or inline its query here."
+)
+# Python cells read upstream results through the data plane, which only reaches PostHog.
+CROSS_ENGINE_REF_ERROR_FOR_PYTHON = (
+ "'{name}' ran on a warehouse connection, and Python cells can only read PostHog results. "
+ "Re-run '{name}' on PostHog to use it here."
+)
+# Covers both kinds of local frame: one a Python cell bound, and one a SQL cell left behind when
+# reading a Python dataframe rerouted it to the sandbox. Neither is reachable from a warehouse.
+LOCAL_FRAME_REF_ERROR = (
+ "You can't query the local dataframe '{name}' because this cell points to a data source other than PostHog."
+)
+
+
+class NodeRunInvalid(Exception):
+ """The run can't be dispatched as written — a bad connection, ref, variable, or query."""
+
+
+class NodeRunDispatchFailed(Exception):
+ """The run row exists but no lane took it. The row is already terminal."""
+
+
+class NodeRunNotPermitted(Exception):
+ """The resolved plan needs a lane this caller's flags do not grant."""
+
+
+@frozen
+class RefSpec:
+ """A name a cell may read, and the sibling cell that exports it."""
+
+ node_id: str
+ kind: Literal["hogql", "local"]
+
+
+@frozen
+class NodeRunRequest:
+ """One cell's run, as the caller describes it before any resolution happens."""
+
+ node_id: str
+ node_type: Literal["hogql", "python"]
+ code: str
+ output_name: str
+ refs: dict[str, RefSpec]
+ variables: list[NotebookVariable]
+ connection_id: UUID | None = None
+ send_raw_query: bool = False
+ # Answer with the caller's own identical run from the last hour instead of executing
+ # again, when one is still running or already done.
+ reuse_results: bool = False
+ # False for a caller gated out of full compute: it may run HogQL but not the sandbox.
+ allow_sandbox: bool = True
+ # Set when a whole-notebook run started this cell, so the status endpoint can find it.
+ notebook_run_id: UUID | None = None
+
+
+@frozen
+class NodeRunDispatch:
+ """What the caller has to tell the user once the run is on its way."""
+
+ run_id: UUID
+ starts_sandbox: bool
+ sandbox_hourly_price: float | None
+
+
+def sandbox_is_running(notebook: Notebook, user: User | None, runtime: KernelRuntime) -> bool:
+ """Whether the runtime row still has a sandbox behind it, the check kernel_status makes."""
+ if not runtime.sandbox_id or runtime.backend not in (
+ KernelRuntime.Backend.MODAL,
+ KernelRuntime.Backend.DOCKER,
+ ):
+ return False
+ try:
+ service = get_kernel_runtime(notebook, user).service
+ sandbox = service._get_sandbox_class(runtime.backend).get_by_id(runtime.sandbox_id)
+ return sandbox.get_status() == SandboxStatus.RUNNING
+ except Exception:
+ return False
+
+
+def live_kernel_runtime(notebook: Notebook, user: User | None) -> KernelRuntime | None:
+ """The user's most recently used runtime row for this notebook that claims to be up."""
+ return (
+ KernelRuntime.objects.filter(
+ team_id=notebook.team_id,
+ notebook_short_id=notebook.short_id,
+ user=user,
+ status__in=(KernelRuntime.Status.RUNNING, KernelRuntime.Status.STARTING),
+ )
+ .order_by("-last_used_at")
+ .first()
+ )
+
+
+def sandbox_disclosure(notebook: Notebook, user: User | None, *, uses_sandbox: bool) -> tuple[bool, float | None]:
+ """Whether this dispatch starts a paid sandbox, and what an hour of it costs.
+
+ Decided here rather than inferred by a client from a kernel status poll that can be ten
+ seconds old. That cache could stay silent through a sandbox that timed out between polls,
+ which is the one case worth disclosing.
+ """
+ live_runtime = live_kernel_runtime(notebook, user) if uses_sandbox else None
+ starts_sandbox = uses_sandbox and not (
+ live_runtime is not None and sandbox_is_running(notebook, user, live_runtime)
+ )
+ if not starts_sandbox:
+ return False, None
+ config = build_notebook_sandbox_config(notebook)
+ # Only a modal sandbox is charged, so a docker kernel carries no price to disclose.
+ if get_kernel_runtime(notebook, user).service._get_backend() != KernelRuntime.Backend.MODAL:
+ return True, None
+ return True, get_compute_rates().hourly_price(cpu_cores=config.cpu_cores, memory_gb=config.memory_gb)
+
+
+def _latest_runs_for(team_id: int, notebook: Notebook, node_ids: set[str]) -> QuerySet:
+ # One DISTINCT ON query fetches the latest DONE run (id + code) for every referenced node.
+ return (
+ NotebookNodeRun.objects.for_team(team_id)
+ .filter(notebook=notebook, node_id__in=node_ids, status=NotebookNodeRun.Status.DONE)
+ .order_by("node_id", "-created_at")
+ .distinct("node_id")
+ .values_list("node_id", "id", "code", "node_type", "connection_id", "send_raw_query")
+ )
+
+
+def resolve_refs(
+ team_id: int,
+ notebook: Notebook,
+ request: NodeRunRequest,
+) -> dict[str, SQLV2Ref]:
+ """Bind each named sibling to the definition this run should read it through.
+
+ Resolve each referenced hogql node to its last-run query (not its live editor text),
+ so a join recomputes against the definitions that produced the results on screen.
+ Inlining happens once here, so the run stores a self-contained query and paging
+ re-queries it without re-resolving refs. Local refs (Python-made frames) carry no
+ query — they live in the kernel namespace.
+ """
+ hogql_node_ids = {spec.node_id for spec in request.refs.values() if spec.kind == "hogql"}
+ # A ref is only inlinable when the upstream node's LATEST run executed the same way this
+ # one will. A SQL node's runs can alternate between hogql and duckdb (Journey 5
+ # rerouting) and between engines, and its stored code only means anything on the engine
+ # that produced it — a duckdb run's code names kernel frames, and a connection run's is
+ # that warehouse's SQL. Inlining either elsewhere would ship the wrong query.
+ latest_by_node: dict[str, tuple[str, str]] = {}
+ other_engine_nodes: set[str] = set()
+ # A SQL node rerouted to DuckDB binds its result into the kernel namespace under its
+ # dataframe name, exactly like a Python node — there is no ClickHouse query to inline,
+ # but the frame is there to read. So it becomes a local ref rather than an absent one.
+ kernel_frame_nodes: set[str] = set()
+ for other_node_id, run_id, run_code, run_type, run_connection_id, run_send_raw in _latest_runs_for(
+ team_id, notebook, hogql_node_ids
+ ):
+ if run_type == NotebookNodeRun.NodeType.DUCKDB:
+ kernel_frame_nodes.add(other_node_id)
+ continue
+ if run_type != NotebookNodeRun.NodeType.HOGQL:
+ continue
+ if run_connection_id == request.connection_id and bool(run_send_raw) == request.send_raw_query:
+ latest_by_node[other_node_id] = (str(run_id), run_code)
+ else:
+ other_engine_nodes.add(other_node_id)
+ cross_engine_error = CROSS_ENGINE_REF_ERROR_FOR_PYTHON if request.node_type == "python" else CROSS_ENGINE_REF_ERROR
+ refs: dict[str, SQLV2Ref] = {}
+ for name, spec in request.refs.items():
+ if spec.kind == "local" or spec.node_id in kernel_frame_nodes:
+ # A kernel frame lives in the sandbox, which only reaches PostHog's own data — a
+ # connection run can't be rerouted there, so mark it unusable instead.
+ refs[name] = (
+ SQLV2Ref(kind="hogql", node_id=None, unavailable_reason=LOCAL_FRAME_REF_ERROR.format(name=name))
+ if request.connection_id is not None
+ else SQLV2Ref(kind="local")
+ )
+ continue
+ latest = latest_by_node.get(spec.node_id)
+ refs[name] = SQLV2Ref(
+ kind="hogql",
+ node_id=spec.node_id,
+ run_id=latest[0] if latest else None,
+ last_run_code=latest[1] if latest else None,
+ unavailable_reason=(cross_engine_error.format(name=name) if spec.node_id in other_engine_nodes else None),
+ )
+ return refs
+
+
+def _build_plan(request: NodeRunRequest, refs: dict[str, SQLV2Ref]) -> SQLV2RunPlan:
+ try:
+ if request.node_type == "python":
+ # A python node stores its code as-is; referenced frames become kernel inputs,
+ # keyed by the upstream run_id so a re-run yields a fresh (not stale) frame.
+ return SQLV2RunPlan(
+ node_type="python", code=request.code, inputs=resolve_python_node_inputs(request.code, refs)
+ )
+ if request.send_raw_query:
+ # Raw SQL is the connection's own dialect, so the HogQL parser can't read it and
+ # there is nothing to inline: it reaches the engine exactly as written. Variables
+ # are refused here rather than escaped by hand — see reject_variables_in_raw_query.
+ reject_variables_in_raw_query(request.code, request.variables)
+ return SQLV2RunPlan(node_type="hogql", code=request.code, inputs=[])
+ # A SQL node pushes to ClickHouse — unless it references a local frame, which
+ # reroutes it to the sandbox's DuckDB (Journey 5).
+ return resolve_sql_node_run(request.code, refs, request.variables)
+ # ExposedHogQLError: with refs present the user's own code is parsed at dispatch, so a
+ # plain typo raises here — it's a bad query (400 with the parse message), not a 500.
+ except (SQLV2ReferenceError, NotebookVariableError, ExposedHogQLError) as e:
+ raise NodeRunInvalid(str(e)) from e
+
+
+def _reusable_runs(
+ notebook: Notebook, user: User | None, team_id: int, request: NodeRunRequest, plan: SQLV2RunPlan
+) -> QuerySet | None:
+ """This caller's own runs of the same cell and resolved query from the last hour, or None.
+
+ Deliberately narrow. A kernel run can have side effects worth repeating, a connection run's
+ rows are not ours to hand back, and a token caller has no user to key the reuse on.
+ """
+ if not (request.reuse_results and user is not None and plan.node_type == "hogql" and request.connection_id is None):
+ return None
+ return (
+ NotebookNodeRun.objects.for_team(team_id)
+ .filter(
+ notebook=notebook,
+ user=user,
+ node_id=request.node_id,
+ code=plan.code,
+ node_type="hogql",
+ connection_id__isnull=True,
+ status__in=[NotebookNodeRun.Status.RUNNING, NotebookNodeRun.Status.DONE],
+ created_at__gte=now() - timedelta(hours=1),
+ )
+ .order_by("-created_at")
+ )
+
+
+def _resolve_notebook(team_id: int, notebook_short_id: str) -> Notebook:
+ """The team's notebook, or `NodeRunInvalid` when it has none by that id.
+
+ Resolving here rather than taking the object is what keeps the team and the notebook from
+ drifting apart: one from another team is simply not found, so no caller can pair them wrong.
+ """
+ notebook = (
+ Notebook.objects.select_related("team")
+ .filter(team_id=team_id, short_id=notebook_short_id, deleted=False)
+ .first()
+ )
+ if notebook is None:
+ raise NodeRunInvalid(f"Notebook {notebook_short_id} was not found.")
+ return notebook
+
+
+def _resolve_user(user_id: int | None) -> User | None:
+ return User.objects.filter(id=user_id).first() if user_id is not None else None
+
+
+def dispatch_cell_run(
+ *, team_id: int, notebook_short_id: str, user_id: int | None, request: NodeRunRequest
+) -> NodeRunDispatch:
+ """Start one cell run, addressed by id.
+
+ The entry point for callers outside this module: it takes ids and a contract, so nobody
+ holds a Django object across the boundary, and resolves the models here instead.
+ """
+ notebook = _resolve_notebook(team_id, notebook_short_id)
+ return dispatch_node_run(notebook, _resolve_user(user_id), notebook.team, request)
+
+
+def kernel_sandbox_is_live(*, team_id: int, notebook_short_id: str, user_id: int | None, runtime_id: UUID) -> bool:
+ """Whether the runtime row still has a live sandbox behind it, addressed by id.
+
+ A RUNNING row can outlive its sandbox, so a caller deciding whether to restart needs this
+ rather than the row's own status.
+
+ Scoped to the user as well as the team, because runtimes are per user and the check below
+ resolves the kernel service for this one: another user's row would answer about their
+ sandbox. A token user owns no runtime, so `user=None` matches only the unowned rows.
+ """
+ notebook = _resolve_notebook(team_id, notebook_short_id)
+ user = _resolve_user(user_id)
+ if user_id is not None and user is None:
+ # The user is gone, so none of their runtimes are theirs to report on. Without this,
+ # the filter below would quietly widen to the unowned rows.
+ return False
+ runtime = KernelRuntime.objects.filter(id=runtime_id, team_id=team_id, user=user).first()
+ if runtime is None:
+ return False
+ return sandbox_is_running(notebook, user, runtime)
+
+
+def dispatch_node_run(notebook: Notebook, user: User | None, team: Team, request: NodeRunRequest) -> NodeRunDispatch:
+ """Start one cell run and return what the caller must disclose about it.
+
+ Raises `NodeRunInvalid` for a request the user has to fix, `NotebookRunBusy` when the
+ notebook already has a cell in flight, `TeamRunCapacityFull` when the project is at its
+ ceiling, and `NodeRunDispatchFailed` when no lane accepted the run.
+ """
+ # The row this writes carries `team` and `notebook` as separate columns, so a caller that
+ # paired them wrong would file a run under one tenant against another's notebook. Both
+ # callers resolve the notebook through a team-scoped queryset, which makes this a cheap
+ # assertion rather than a check — but it is the one that stops the pair drifting apart.
+ if notebook.team_id != team.id:
+ raise ValueError(f"Notebook {notebook.short_id} does not belong to team {team.id}")
+
+ if request.connection_id is not None and (
+ # Resolve up front so a stale or unreachable connection fails the dispatch with the
+ # shared message, rather than surfacing later as an opaque failed run.
+ get_direct_connection_source(
+ team,
+ str(request.connection_id),
+ user=user,
+ require_pure_direct=request.send_raw_query,
+ )
+ is None
+ ):
+ raise NodeRunInvalid(INVALID_CONNECTION_ID_ERROR)
+
+ plan = _build_plan(request, resolve_refs(team.id, notebook, request))
+
+ # Reading a sibling's kernel frame reroutes a hogql request to the sandbox's DuckDB, so the
+ # sandbox gate has to sit behind the resolved plan rather than the request's own node_type.
+ if not request.allow_sandbox and plan.node_type != "hogql":
+ raise NodeRunNotPermitted()
+
+ reusable = _reusable_runs(notebook, user, team.id, request, plan)
+ if (existing := reusable.first() if reusable is not None else None) is not None:
+ return NodeRunDispatch(run_id=existing.id, starts_sandbox=False, sandbox_hourly_price=None)
+
+ # Taken before the row exists, so a refused dispatch writes nothing: an agent retrying
+ # into a full ceiling must not leave a trail of rows behind it. The id is minted here
+ # because the slot is keyed on it and has to be released by the run that took it.
+ new_run_id = uuid7()
+ try:
+ # NotebookRunBusy (409) and TeamRunCapacityFull (429) reach the caller as they are.
+ acquire_run_slots(team.id, notebook.short_id, str(new_run_id))
+ except NotebookRunBusy:
+ # Not a failure for a reuse caller: the cell holding the notebook may be the very run
+ # they would have been handed, so answer with it rather than telling them to wait.
+ if (existing := reusable.first() if reusable is not None else None) is not None:
+ return NodeRunDispatch(run_id=existing.id, starts_sandbox=False, sandbox_hourly_price=None)
+ raise
+
+ # Read again behind the slot. An identical run can land between the check above and this
+ # one, and taking the slot is what serialises the two.
+ if (existing := reusable.first() if reusable is not None else None) is not None:
+ release_run_slots(team.id, notebook.short_id, str(new_run_id))
+ return NodeRunDispatch(run_id=existing.id, starts_sandbox=False, sandbox_hourly_price=None)
+
+ try:
+ run = NotebookNodeRun.objects.create(
+ id=new_run_id,
+ team_id=team.id,
+ notebook=notebook,
+ # The same user the run's kernel is resolved for, so the callback can scope the
+ # frame snapshot to that kernel. A token user has no kernel of its own, hence None.
+ user=user,
+ node_id=request.node_id,
+ notebook_run_id=request.notebook_run_id,
+ code=plan.code,
+ node_type=plan.node_type,
+ connection_id=request.connection_id,
+ send_raw_query=request.send_raw_query,
+ status=NotebookNodeRun.Status.RUNNING,
+ )
+ except Exception:
+ # No row means no release site will ever learn this run id, so hand the slots back
+ # here or the notebook stays blocked with nothing running in it.
+ release_run_slots(team.id, notebook.short_id, str(new_run_id))
+ raise
+
+ # Read before the handoff, never after: the sandbox lane provisions a kernel of its own, so
+ # a disclosure taken afterwards can observe this very dispatch's sandbox and report that it
+ # started nothing — exactly when the user most needs telling they are being charged.
+ starts_sandbox, hourly_price = sandbox_disclosure(notebook, user, uses_sandbox=plan.node_type != "hogql")
+
+ try:
+ if plan.node_type == "hogql":
+ # Direct lane: a pure-HogQL run never touches the sandbox — it rides the
+ # async query manager, and the run-result poll advances the row.
+ enqueue_direct_run(team, user, run)
+ else:
+ start_sql_v2_run_workflow(
+ SQLV2RunInput(
+ run_id=str(run.id),
+ notebook_short_id=notebook.short_id,
+ team_id=team.id,
+ user_id=user.id if user is not None else None,
+ code=plan.code,
+ node_type=plan.node_type,
+ output_name=request.output_name,
+ inputs=plan.inputs,
+ # A python node reads these as globals; a duckdb node binds them as
+ # `$name` query parameters, so it carries only the ones its SQL uses.
+ variables=(
+ python_variable_bindings(request.variables) if plan.node_type == "python" else plan.variables
+ ),
+ )
+ )
+ except Exception:
+ logger.exception("notebook_sql_v2_run_start_failed", notebook_short_id=notebook.short_id)
+ # 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.")
+ raise NodeRunDispatchFailed("Failed to start run.")
+
+ return NodeRunDispatch(run_id=run.id, starts_sandbox=starts_sandbox, sandbox_hourly_price=hourly_price)
+
+
+class RawRefSpec(TypedDict):
+ """One ref as `NotebookSQLV2RefSerializer` validates it."""
+
+ node_id: str
+ kind: Literal["hogql", "local"]
+
+
+def build_ref_specs(raw: dict[str, RawRefSpec]) -> dict[str, RefSpec]:
+ """Turn the serializer's plain ref dicts into typed specs."""
+ return {name: RefSpec(node_id=spec["node_id"], kind=spec["kind"]) for name, spec in raw.items()}
+
+
+__all__ = [
+ "NodeRunDispatch",
+ "NodeRunDispatchFailed",
+ "NodeRunInvalid",
+ "NodeRunNotPermitted",
+ "NodeRunRequest",
+ "NotebookRunBusy",
+ "RawRefSpec",
+ "RefSpec",
+ "TeamRunCapacityFull",
+ "build_ref_specs",
+ "dispatch_cell_run",
+ "dispatch_node_run",
+ "kernel_sandbox_is_live",
+ "live_kernel_runtime",
+ "sandbox_disclosure",
+ "sandbox_is_running",
+]
diff --git a/products/notebooks/backend/test/test_compute_pricing.py b/products/notebooks/backend/test/test_compute_pricing.py
index 044d83b4945f..0d4262bce2c4 100644
--- a/products/notebooks/backend/test/test_compute_pricing.py
+++ b/products/notebooks/backend/test/test_compute_pricing.py
@@ -128,7 +128,7 @@ class TestComputeOptionsEndpoint(APIBaseTest):
)
@patch(
- "products.notebooks.backend.presentation.views.notebook.NotebookViewSet._sandbox_is_running",
+ "products.notebooks.backend.presentation.views.notebook.kernel_sandbox_is_live",
return_value=True,
)
@patch("products.notebooks.backend.presentation.views.notebook.get_kernel_runtime")
@@ -149,7 +149,7 @@ class TestComputeOptionsEndpoint(APIBaseTest):
assert payload["restart_required"] is False
@patch(
- "products.notebooks.backend.presentation.views.notebook.NotebookViewSet._sandbox_is_running",
+ "products.notebooks.backend.presentation.views.notebook.kernel_sandbox_is_live",
return_value=True,
)
@patch("products.notebooks.backend.presentation.views.notebook.get_kernel_runtime")
@@ -184,7 +184,7 @@ class TestComputeOptionsEndpoint(APIBaseTest):
assert response.json()["restarted"] is False
@patch(
- "products.notebooks.backend.presentation.views.notebook.NotebookViewSet._sandbox_is_running",
+ "products.notebooks.backend.presentation.views.notebook.kernel_sandbox_is_live",
return_value=True,
)
@patch("products.notebooks.backend.presentation.views.notebook.get_kernel_runtime")
@@ -207,7 +207,7 @@ class TestComputeOptionsEndpoint(APIBaseTest):
assert response.json()["restarted"] is False
@patch(
- "products.notebooks.backend.presentation.views.notebook.NotebookViewSet._sandbox_is_running",
+ "products.notebooks.backend.presentation.views.notebook.kernel_sandbox_is_live",
return_value=False,
)
@patch("products.notebooks.backend.presentation.views.notebook.get_kernel_runtime")
@@ -227,7 +227,7 @@ class TestComputeOptionsEndpoint(APIBaseTest):
assert response.json()["restarted"] is False
@patch(
- "products.notebooks.backend.presentation.views.notebook.NotebookViewSet._sandbox_is_running",
+ "products.notebooks.backend.presentation.views.notebook.kernel_sandbox_is_live",
return_value=True,
)
@patch("products.notebooks.backend.presentation.views.notebook.get_kernel_runtime")
@@ -265,7 +265,7 @@ class TestComputeOptionsEndpoint(APIBaseTest):
assert status_payload["hourly_price"] == get_compute_rates().hourly_price(cpu_cores=1, memory_gb=2)
@patch(
- "products.notebooks.backend.presentation.views.notebook.NotebookViewSet._sandbox_is_running",
+ "products.notebooks.backend.presentation.views.notebook.kernel_sandbox_is_live",
return_value=True,
)
@patch("products.notebooks.backend.presentation.views.notebook.get_kernel_runtime")
@@ -342,10 +342,10 @@ class TestComputeOptionsEndpoint(APIBaseTest):
assert payload["status"] == expected_status
- @patch("products.notebooks.backend.presentation.views.notebook.start_sql_v2_run_workflow")
+ @patch("products.notebooks.backend.sql_v2_dispatch.start_sql_v2_run_workflow")
@patch("products.notebooks.backend.presentation.views.notebook.is_sql_v2_enabled", return_value=True)
@patch(
- "products.notebooks.backend.presentation.views.notebook.NotebookViewSet._sandbox_is_running",
+ "products.notebooks.backend.sql_v2_dispatch.sandbox_is_running",
return_value=True,
)
def test_a_run_reusing_a_live_sandbox_discloses_nothing(
@@ -363,7 +363,7 @@ class TestComputeOptionsEndpoint(APIBaseTest):
assert response.json()["starts_sandbox"] is False
@patch("products.notebooks.backend.presentation.views.notebook.is_sql_v2_enabled", return_value=True)
- @patch("products.notebooks.backend.presentation.views.notebook.start_sql_v2_run_workflow")
+ @patch("products.notebooks.backend.sql_v2_dispatch.start_sql_v2_run_workflow")
def test_a_run_with_no_live_sandbox_discloses_the_start(self, _flag: MagicMock, _workflow: MagicMock) -> None:
# The client used to answer this from a kernel poll up to ten seconds old, which stayed
# silent through a sandbox that timed out between polls.
@@ -378,7 +378,38 @@ class TestComputeOptionsEndpoint(APIBaseTest):
assert response.json()["starts_sandbox"] is True
@patch("products.notebooks.backend.presentation.views.notebook.is_sql_v2_enabled", return_value=True)
- @patch("products.notebooks.backend.presentation.views.notebook.enqueue_direct_run")
+ def test_the_disclosure_ignores_the_sandbox_this_run_starts(self, _flag: MagicMock) -> None:
+ # The sandbox lane provisions a kernel of its own. Read after the handoff, the
+ # disclosure can see that kernel and report that this run started nothing — silence
+ # exactly when the user is first being charged.
+ notebook = Notebook.objects.create(team=self.team, created_by=self.user, kernel_cpu_cores=1, kernel_memory_gb=2)
+ self._live_kernel(notebook)
+ sandbox_up = False
+
+ def provision(*_args: object, **_kwargs: object) -> None:
+ nonlocal sandbox_up
+ sandbox_up = True
+
+ with (
+ patch(
+ "products.notebooks.backend.sql_v2_dispatch.start_sql_v2_run_workflow",
+ side_effect=provision,
+ ),
+ patch(
+ "products.notebooks.backend.sql_v2_dispatch.sandbox_is_running",
+ side_effect=lambda *_a, **_k: sandbox_up,
+ ),
+ ):
+ response = self.client.post(
+ f"/api/projects/{self.team.id}/notebooks/{notebook.short_id}/sql_v2/run/",
+ {"node_id": "n1", "code": "print(1)", "node_type": "python"},
+ )
+
+ assert response.status_code == 200, response.json()
+ assert response.json()["starts_sandbox"] is True
+
+ @patch("products.notebooks.backend.presentation.views.notebook.is_sql_v2_enabled", return_value=True)
+ @patch("products.notebooks.backend.sql_v2_dispatch.enqueue_direct_run")
def test_a_pure_hogql_run_never_discloses_a_sandbox(self, _flag: MagicMock, _direct: MagicMock) -> None:
notebook = Notebook.objects.create(team=self.team, created_by=self.user)
diff --git a/products/notebooks/backend/test/test_sql_v2.py b/products/notebooks/backend/test/test_sql_v2.py
index c84b541c0b78..ecc66aadbf06 100644
--- a/products/notebooks/backend/test/test_sql_v2.py
+++ b/products/notebooks/backend/test/test_sql_v2.py
@@ -17,11 +17,12 @@ from typing import Any
import time_machine
from posthog.test.base import APIBaseTest
-from unittest.mock import Mock, patch
+from unittest.mock import MagicMock, Mock, patch
from django.conf import settings
from django.core import signing
from django.core.cache import cache
+from django.db import IntegrityError, transaction
from django.test import SimpleTestCase, override_settings
from django.utils import timezone
@@ -35,13 +36,15 @@ from posthog.clickhouse.client.execute_async import QueryNotFoundError
from posthog.constants import AvailableFeature
from posthog.models.organization import OrganizationMembership
from posthog.models.scoping import team_scope
+from posthog.models.team import Team
from posthog.models.user import User
from posthog.models.utils import UUIDT
+from posthog.uuidt import uuid7
from products.access_control.backend.models.access_control import AccessControl
from products.notebooks.backend import sql_v2_concurrency
from products.notebooks.backend.kernel_package import kernel_package_bytes_and_hash
-from products.notebooks.backend.models import KernelRuntime, Notebook, NotebookNodeRun
+from products.notebooks.backend.models import KernelRuntime, Notebook, NotebookNodeRun, NotebookRun
from products.notebooks.backend.sandbox.kernel import (
auth as kernel_auth,
envelope as kernel_envelope,
@@ -77,6 +80,7 @@ from products.notebooks.backend.sql_v2_direct import (
notebook_direct_query_id,
sync_direct_run,
)
+from products.notebooks.backend.sql_v2_dispatch import NodeRunRequest, dispatch_node_run
from products.notebooks.backend.sql_v2_runs import finish_node_run, touch_run_progress
from products.notebooks.backend.temporal.sql_v2 import (
SQLV2RunInput,
@@ -431,8 +435,8 @@ class TestSQLV2Run(APIBaseTest):
self.notebook = Notebook.objects.create(team=self.team, short_id="nbrun01")
self.run_url = f"/api/projects/{self.team.id}/notebooks/{self.notebook.short_id}/sql_v2/run/"
- @patch("products.notebooks.backend.presentation.views.notebook.start_sql_v2_run_workflow")
- @patch("products.notebooks.backend.presentation.views.notebook.enqueue_direct_run")
+ @patch("products.notebooks.backend.sql_v2_dispatch.start_sql_v2_run_workflow")
+ @patch("products.notebooks.backend.sql_v2_dispatch.enqueue_direct_run")
@patch("products.notebooks.backend.presentation.views.notebook.is_sql_v2_enabled", return_value=True)
def test_sql_run_takes_the_direct_lane_not_the_sandbox(self, _mock_enabled, mock_enqueue, mock_start):
# A pure-SQL run must never require a sandbox: no Temporal workflow, no kernel.
@@ -459,8 +463,8 @@ class TestSQLV2Run(APIBaseTest):
@override_settings(DEBUG=False)
@patch("products.notebooks.backend.presentation.views.notebook.is_sql_v2_enabled", return_value=False)
@patch("products.notebooks.backend.presentation.views.notebook.is_notebook_widget_enabled", return_value=True)
- @patch("products.notebooks.backend.presentation.views.notebook.enqueue_direct_run")
- @patch("products.notebooks.backend.presentation.views.notebook.start_sql_v2_run_workflow")
+ @patch("products.notebooks.backend.sql_v2_dispatch.enqueue_direct_run")
+ @patch("products.notebooks.backend.sql_v2_dispatch.start_sql_v2_run_workflow")
def test_widget_only_access(self, _name, payload, expected_status, start_workflow, enqueue, _widget, _python):
response = self.client.post(self.run_url, data={"node_id": "n1", **payload}, format="json")
assert response.status_code == expected_status
@@ -482,7 +486,7 @@ class TestSQLV2Run(APIBaseTest):
]
)
@patch("products.notebooks.backend.presentation.views.notebook.is_sql_v2_enabled", return_value=True)
- @patch("products.notebooks.backend.presentation.views.notebook.enqueue_direct_run")
+ @patch("products.notebooks.backend.sql_v2_dispatch.enqueue_direct_run")
def test_reuses_only_matching_active_or_completed_run(
self, status: str, principal: str, should_reuse: bool, enqueue: Mock, _enabled: Mock
) -> None:
@@ -521,8 +525,8 @@ class TestSQLV2Run(APIBaseTest):
client = redis.get_client()
client.zadd(key, {run_id: time.time() + sql_v2_concurrency._NOTEBOOK_SLOT_TTL_SECONDS - 7200})
- @patch("products.notebooks.backend.presentation.views.notebook.start_sql_v2_run_workflow")
- @patch("products.notebooks.backend.presentation.views.notebook.enqueue_direct_run")
+ @patch("products.notebooks.backend.sql_v2_dispatch.start_sql_v2_run_workflow")
+ @patch("products.notebooks.backend.sql_v2_dispatch.enqueue_direct_run")
@patch("products.notebooks.backend.presentation.views.notebook.is_sql_v2_enabled", return_value=True)
def test_one_run_at_a_time_per_notebook(self, _mock_enabled, _mock_enqueue, _mock_start):
# The editor has always shown one run at a time per notebook, but that rule was kea
@@ -548,8 +552,8 @@ class TestSQLV2Run(APIBaseTest):
third = self.client.post(self.run_url, data={"node_id": "n2", "code": "select 2"}, format="json")
self.assertEqual(third.status_code, 200, third.content)
- @patch("products.notebooks.backend.presentation.views.notebook.start_sql_v2_run_workflow")
- @patch("products.notebooks.backend.presentation.views.notebook.enqueue_direct_run")
+ @patch("products.notebooks.backend.sql_v2_dispatch.start_sql_v2_run_workflow")
+ @patch("products.notebooks.backend.sql_v2_dispatch.enqueue_direct_run")
@patch("products.notebooks.backend.presentation.views.notebook.is_sql_v2_enabled", return_value=True)
def test_a_slot_left_behind_by_an_abandoned_run_does_not_block_the_notebook(
self, _mock_enabled, _mock_enqueue, _mock_start
@@ -568,8 +572,8 @@ class TestSQLV2Run(APIBaseTest):
second = self.client.post(self.run_url, data={"node_id": "n2", "code": "select 2"}, format="json")
self.assertEqual(second.status_code, 200, second.content)
- @patch("products.notebooks.backend.presentation.views.notebook.start_sql_v2_run_workflow")
- @patch("products.notebooks.backend.presentation.views.notebook.enqueue_direct_run")
+ @patch("products.notebooks.backend.sql_v2_dispatch.start_sql_v2_run_workflow")
+ @patch("products.notebooks.backend.sql_v2_dispatch.enqueue_direct_run")
@patch("products.notebooks.backend.presentation.views.notebook.is_sql_v2_enabled", return_value=True)
def test_a_slot_taken_moments_ago_is_not_mistaken_for_a_leak(self, _mock_enabled, _mock_enqueue, _mock_start):
# The race three reviewers found: the run row is written after the slot is taken, so a
@@ -621,8 +625,8 @@ class TestSQLV2Run(APIBaseTest):
self.assertFalse(sql_v2_concurrency._evict_if_unchanged(limiter, key, "holder", observed_score))
self.assertEqual(client.zrange(key, 0, -1), [b"holder"])
- @patch("products.notebooks.backend.presentation.views.notebook.start_sql_v2_run_workflow")
- @patch("products.notebooks.backend.presentation.views.notebook.enqueue_direct_run")
+ @patch("products.notebooks.backend.sql_v2_dispatch.start_sql_v2_run_workflow")
+ @patch("products.notebooks.backend.sql_v2_dispatch.enqueue_direct_run")
@patch("products.notebooks.backend.presentation.views.notebook.is_sql_v2_enabled", return_value=True)
def test_a_working_run_keeps_its_slot_from_expiring(self, _mock_enabled, _mock_enqueue, _mock_start):
# No fixed TTL outlasts a working run: a python cell materializes one input per upstream
@@ -653,8 +657,8 @@ class TestSQLV2Run(APIBaseTest):
self.assertEqual(client.zrange(team_key, 0, -1), [])
- @patch("products.notebooks.backend.presentation.views.notebook.start_sql_v2_run_workflow")
- @patch("products.notebooks.backend.presentation.views.notebook.enqueue_direct_run")
+ @patch("products.notebooks.backend.sql_v2_dispatch.start_sql_v2_run_workflow")
+ @patch("products.notebooks.backend.sql_v2_dispatch.enqueue_direct_run")
@patch("products.notebooks.backend.presentation.views.notebook.is_sql_v2_enabled", return_value=True)
def test_a_run_abandoned_in_running_stops_blocking_its_notebook(self, _mock_enabled, _mock_enqueue, _mock_start):
# A direct (hogql) run only turns terminal when a client polls it, and nothing sweeps
@@ -673,8 +677,8 @@ class TestSQLV2Run(APIBaseTest):
second = self.client.post(self.run_url, data={"node_id": "n2", "code": "select 2"}, format="json")
self.assertEqual(second.status_code, 200, second.content)
- @patch("products.notebooks.backend.presentation.views.notebook.start_sql_v2_run_workflow")
- @patch("products.notebooks.backend.presentation.views.notebook.enqueue_direct_run")
+ @patch("products.notebooks.backend.sql_v2_dispatch.start_sql_v2_run_workflow")
+ @patch("products.notebooks.backend.sql_v2_dispatch.enqueue_direct_run")
@patch("products.notebooks.backend.presentation.views.notebook.is_sql_v2_enabled", return_value=True)
def test_a_busy_notebook_does_not_block_another_notebook(self, _mock_enabled, _mock_enqueue, _mock_start):
# The ceiling is keyed per notebook, so one busy notebook must not stop the rest. If the
@@ -725,7 +729,7 @@ class TestSQLV2Run(APIBaseTest):
self.assertEqual(mock_status.call_args.kwargs["query_id"], notebook_direct_query_id(str(run.id)))
self.assertNotEqual(mock_status.call_args.kwargs["query_id"], str(run.id))
- @patch("products.notebooks.backend.presentation.views.notebook.start_sql_v2_run_workflow")
+ @patch("products.notebooks.backend.sql_v2_dispatch.start_sql_v2_run_workflow")
@patch("products.notebooks.backend.presentation.views.notebook.is_sql_v2_enabled", return_value=True)
def test_sql_run_completes_direct_with_no_kernel(self, _mock_enabled, mock_start):
# End to end through the real async query manager (inline in tests): run a SQL
@@ -751,7 +755,7 @@ class TestSQLV2Run(APIBaseTest):
mock_start.assert_not_called()
self.assertFalse(KernelRuntime.objects.filter(team=self.team).exists())
- @patch("products.notebooks.backend.presentation.views.notebook.start_sql_v2_run_workflow")
+ @patch("products.notebooks.backend.sql_v2_dispatch.start_sql_v2_run_workflow")
@patch("products.notebooks.backend.presentation.views.notebook.is_sql_v2_enabled", return_value=True)
def test_query_restricted_member_cannot_run(self, _mock_enabled, mock_start):
# A notebook editor whose query access is denied must not execute HogQL through the node.
@@ -761,7 +765,7 @@ class TestSQLV2Run(APIBaseTest):
mock_start.assert_not_called()
self.assertFalse(NotebookNodeRun.objects.for_team(self.team.id).exists())
- @patch("products.notebooks.backend.presentation.views.notebook.start_sql_v2_run_workflow")
+ @patch("products.notebooks.backend.sql_v2_dispatch.start_sql_v2_run_workflow")
@patch("products.notebooks.backend.presentation.views.notebook.is_sql_v2_enabled", return_value=True)
def test_blank_code_is_rejected_before_dispatch(self, _mock_enabled, mock_start):
# A stale-attribute FE bug once sent empty code all the way into the sandbox; fail fast here instead.
@@ -780,7 +784,7 @@ class TestSQLV2Run(APIBaseTest):
status=NotebookNodeRun.Status.DONE,
)
- @patch("products.notebooks.backend.presentation.views.notebook.enqueue_direct_run")
+ @patch("products.notebooks.backend.sql_v2_dispatch.enqueue_direct_run")
@patch("products.notebooks.backend.presentation.views.notebook.is_sql_v2_enabled", return_value=True)
def test_run_inlines_referenced_nodes_last_run_query_as_ctes(self, _mock_enabled, mock_enqueue):
# The direct lane executes run.code verbatim, so the stored query must already carry
@@ -802,7 +806,7 @@ class TestSQLV2Run(APIBaseTest):
self.assertIn("df2 AS (SELECT id FROM persons)", run.code)
mock_enqueue.assert_called_once()
- @patch("products.notebooks.backend.presentation.views.notebook.enqueue_direct_run")
+ @patch("products.notebooks.backend.sql_v2_dispatch.enqueue_direct_run")
@patch("products.notebooks.backend.presentation.views.notebook.is_sql_v2_enabled", return_value=True)
def test_run_uses_the_latest_done_run_of_a_referenced_node(self, _mock_enabled, _mock_enqueue):
# An edited-then-rerun upstream: only its most recent run should be inlined.
@@ -826,7 +830,7 @@ class TestSQLV2Run(APIBaseTest):
("python_consumer", "python", "print(sql_df)", NotebookNodeRun.NodeType.PYTHON),
]
)
- @patch("products.notebooks.backend.presentation.views.notebook.start_sql_v2_run_workflow")
+ @patch("products.notebooks.backend.sql_v2_dispatch.start_sql_v2_run_workflow")
@patch("products.notebooks.backend.presentation.views.notebook.is_sql_v2_enabled", return_value=True)
def test_ref_whose_latest_run_was_duckdb_reads_it_as_a_kernel_frame(
self, _name, consumer_node_type, code, expected_node_type, _mock_enabled, mock_start
@@ -865,7 +869,7 @@ class TestSQLV2Run(APIBaseTest):
dispatched = mock_start.call_args.args[0]
self.assertEqual([(i["name"], i["kind"]) for i in dispatched.inputs], [("sql_df", "local")])
- @patch("products.notebooks.backend.presentation.views.notebook.start_sql_v2_run_workflow")
+ @patch("products.notebooks.backend.sql_v2_dispatch.start_sql_v2_run_workflow")
@patch("products.notebooks.backend.presentation.views.notebook.is_sql_v2_enabled", return_value=True)
def test_hogql_typo_with_refs_present_is_a_400_not_a_500(self, _mock_enabled, mock_start):
# With refs present the user's code is parsed at dispatch, so a plain typo raises
@@ -879,7 +883,7 @@ class TestSQLV2Run(APIBaseTest):
self.assertEqual(response.status_code, 400)
mock_start.assert_not_called()
- @patch("products.notebooks.backend.presentation.views.notebook.start_sql_v2_run_workflow")
+ @patch("products.notebooks.backend.sql_v2_dispatch.start_sql_v2_run_workflow")
@patch("products.notebooks.backend.presentation.views.notebook.is_sql_v2_enabled", return_value=True)
def test_run_rejects_referencing_a_never_run_node(self, _mock_enabled, mock_start):
response = self.client.post(
@@ -891,7 +895,7 @@ class TestSQLV2Run(APIBaseTest):
self.assertEqual(NotebookNodeRun.objects.for_team(self.team.id).filter(node_id="c").count(), 0)
mock_start.assert_not_called()
- @patch("products.notebooks.backend.presentation.views.notebook.start_sql_v2_run_workflow")
+ @patch("products.notebooks.backend.sql_v2_dispatch.start_sql_v2_run_workflow")
@patch("products.notebooks.backend.presentation.views.notebook.is_sql_v2_enabled", return_value=True)
def test_python_node_dispatches_with_materialization_inputs(self, _mock_enabled, mock_start):
# A python node keeps its code verbatim and ships the frames it reads as materialization inputs.
@@ -916,7 +920,7 @@ class TestSQLV2Run(APIBaseTest):
self.assertEqual([i["name"] for i in dispatched.inputs], ["df1"])
self.assertEqual(dispatched.inputs[0]["query"], "select id from events")
- @patch("products.notebooks.backend.presentation.views.notebook.start_sql_v2_run_workflow")
+ @patch("products.notebooks.backend.sql_v2_dispatch.start_sql_v2_run_workflow")
@patch("products.notebooks.backend.presentation.views.notebook.is_sql_v2_enabled", return_value=True)
def test_python_node_referencing_a_never_run_node_is_rejected(self, _mock_enabled, mock_start):
response = self.client.post(
@@ -932,7 +936,7 @@ class TestSQLV2Run(APIBaseTest):
self.assertEqual(response.status_code, 400)
mock_start.assert_not_called()
- @patch("products.notebooks.backend.presentation.views.notebook.start_sql_v2_run_workflow")
+ @patch("products.notebooks.backend.sql_v2_dispatch.start_sql_v2_run_workflow")
@patch("products.notebooks.backend.presentation.views.notebook.is_sql_v2_enabled", return_value=True)
def test_sql_node_referencing_a_local_frame_reroutes_to_duckdb(self, _mock_enabled, mock_start):
# Journey 5: a local (Python-made) frame can't push to ClickHouse, so the join runs in
@@ -962,7 +966,7 @@ class TestSQLV2Run(APIBaseTest):
)
@patch(
- "products.notebooks.backend.presentation.views.notebook.enqueue_direct_run",
+ "products.notebooks.backend.sql_v2_dispatch.enqueue_direct_run",
side_effect=RuntimeError("redis unavailable"),
)
@patch("products.notebooks.backend.presentation.views.notebook.is_sql_v2_enabled", return_value=True)
@@ -985,12 +989,15 @@ class TestSQLV2RunOnAConnection(APIBaseTest):
# only ever reaches it through core's resolver, so stub that seam: what this suite owns is
# whether notebooks calls it with the right arguments and honors its verdict. The
# resolver's own RBAC behavior is covered by the direct-connection tests in core.
- patcher = patch(
+ # Dispatch resolves the source, and so does the run-result read, from two modules.
+ self.mock_resolve_source = MagicMock(return_value=SimpleNamespace(id=self.source_id))
+ for target in (
+ "products.notebooks.backend.sql_v2_dispatch.get_direct_connection_source",
"products.notebooks.backend.presentation.views.notebook.get_direct_connection_source",
- return_value=SimpleNamespace(id=self.source_id),
- )
- self.mock_resolve_source = patcher.start()
- self.addCleanup(patcher.stop)
+ ):
+ patcher = patch(target, new=self.mock_resolve_source)
+ patcher.start()
+ self.addCleanup(patcher.stop)
def _post(self, **data: Any):
return self.client.post(self.run_url, data={"node_id": "n1", **data}, format="json")
@@ -1041,7 +1048,7 @@ class TestSQLV2RunOnAConnection(APIBaseTest):
self.assertEqual(resolve_kwargs["user"], self.user)
self.assertTrue(resolve_kwargs["require_pure_direct"])
- @patch("products.notebooks.backend.presentation.views.notebook.enqueue_direct_run")
+ @patch("products.notebooks.backend.sql_v2_dispatch.enqueue_direct_run")
def test_unknown_connection_fails_the_dispatch(self, mock_enqueue, _mock_enabled):
# Fail here rather than stranding a run that can only report an opaque error later.
self.mock_resolve_source.return_value = None
@@ -1057,7 +1064,7 @@ class TestSQLV2RunOnAConnection(APIBaseTest):
("posthog_cell_reading_a_connection_cell", False),
]
)
- @patch("products.notebooks.backend.presentation.views.notebook.enqueue_direct_run")
+ @patch("products.notebooks.backend.sql_v2_dispatch.enqueue_direct_run")
def test_cross_engine_reference_is_rejected(self, _name, run_on_connection, mock_enqueue, _mock_enabled):
# Both directions: a cell's stored SQL only means anything on the engine that ran it, so
# inlining it as a CTE elsewhere would silently ship the wrong query.
@@ -1073,7 +1080,7 @@ class TestSQLV2RunOnAConnection(APIBaseTest):
self.assertIn("last ran on a different connection", response.json()["detail"])
mock_enqueue.assert_not_called()
- @patch("products.notebooks.backend.presentation.views.notebook.start_sql_v2_run_workflow")
+ @patch("products.notebooks.backend.sql_v2_dispatch.start_sql_v2_run_workflow")
def test_python_reading_a_connection_cell_says_what_to_do(self, mock_start, _mock_enabled):
# A Python cell materializes upstream results through the data plane, which only reaches
# PostHog — so it must say that, not tell the user to move a Python cell onto a warehouse.
@@ -1148,8 +1155,8 @@ class TestSQLV2RunOnAConnection(APIBaseTest):
self.assertEqual(run.status, NotebookNodeRun.Status.FAILED)
@parameterized.expand([("python_frame", False), ("duckdb_node_frame", True)])
- @patch("products.notebooks.backend.presentation.views.notebook.start_sql_v2_run_workflow")
- @patch("products.notebooks.backend.presentation.views.notebook.enqueue_direct_run")
+ @patch("products.notebooks.backend.sql_v2_dispatch.start_sql_v2_run_workflow")
+ @patch("products.notebooks.backend.sql_v2_dispatch.enqueue_direct_run")
def test_a_local_frame_never_reroutes_a_connection_run_to_the_sandbox(
self, _name, from_duckdb_run, mock_enqueue, mock_start, _mock_enabled
):
@@ -3193,7 +3200,7 @@ class TestSQLV2RunWithNotebookVariables(APIBaseTest):
self.notebook = Notebook.objects.create(team=self.team, short_id="nbvars01")
self.run_url = f"/api/projects/{self.team.id}/notebooks/{self.notebook.short_id}/sql_v2/run/"
- @patch("products.notebooks.backend.presentation.views.notebook.enqueue_direct_run")
+ @patch("products.notebooks.backend.sql_v2_dispatch.enqueue_direct_run")
@patch("products.notebooks.backend.presentation.views.notebook.is_sql_v2_enabled", return_value=True)
def test_a_sql_run_stores_the_query_with_its_variables_bound(self, _mock_enabled, _mock_enqueue):
# The stored code is what the direct lane executes and what paging re-queries, so an
@@ -3213,7 +3220,7 @@ class TestSQLV2RunWithNotebookVariables(APIBaseTest):
self.assertNotIn("{country}", run.code)
@parameterized.expand([("relative", "-7d"), ("relative_boundary", "mStart"), ("not_a_date", "yesterday")])
- @patch("products.notebooks.backend.presentation.views.notebook.enqueue_direct_run")
+ @patch("products.notebooks.backend.sql_v2_dispatch.enqueue_direct_run")
@patch("products.notebooks.backend.presentation.views.notebook.is_sql_v2_enabled", return_value=True)
def test_a_date_variable_must_be_an_absolute_date(self, _name, value, _mock_enabled, mock_enqueue):
# The editor's picker only writes absolute dates, and a relative one would re-resolve
@@ -3231,7 +3238,7 @@ class TestSQLV2RunWithNotebookVariables(APIBaseTest):
self.assertIn("absolute date", str(response.json()))
mock_enqueue.assert_not_called()
- @patch("products.notebooks.backend.presentation.views.notebook.enqueue_direct_run")
+ @patch("products.notebooks.backend.sql_v2_dispatch.enqueue_direct_run")
@patch("products.notebooks.backend.presentation.views.notebook.is_sql_v2_enabled", return_value=True)
def test_reading_an_undeclared_variable_is_a_400(self, _mock_enabled, mock_enqueue):
response = self.client.post(
@@ -3243,7 +3250,7 @@ class TestSQLV2RunWithNotebookVariables(APIBaseTest):
self.assertIn("not a notebook variable", response.json()["detail"])
mock_enqueue.assert_not_called()
- @patch("products.notebooks.backend.presentation.views.notebook.start_sql_v2_run_workflow")
+ @patch("products.notebooks.backend.sql_v2_dispatch.start_sql_v2_run_workflow")
@patch("products.notebooks.backend.presentation.views.notebook.is_sql_v2_enabled", return_value=True)
def test_a_python_run_carries_the_variables_to_the_kernel_unsubstituted(self, _mock_enabled, mock_start):
# Python reads them as globals, so the code must reach the kernel untouched with the
@@ -3267,7 +3274,7 @@ class TestSQLV2RunWithNotebookVariables(APIBaseTest):
self.assertEqual(run.code, code)
self.assertEqual(mock_start.call_args.args[0].variables, {"country": "US", "days": 30})
- @patch("products.notebooks.backend.presentation.views.notebook.enqueue_direct_run")
+ @patch("products.notebooks.backend.sql_v2_dispatch.enqueue_direct_run")
@patch("products.notebooks.backend.presentation.views.notebook.is_sql_v2_enabled", return_value=True)
def test_a_run_without_variables_is_unchanged(self, _mock_enabled, _mock_enqueue):
response = self.client.post(self.run_url, data={"node_id": "n1", "code": "select 1"}, format="json")
@@ -3275,9 +3282,9 @@ class TestSQLV2RunWithNotebookVariables(APIBaseTest):
run = NotebookNodeRun.objects.for_team(self.team.id).get(id=response.json()["run_id"])
self.assertEqual(run.code, "select 1")
- @patch("products.notebooks.backend.presentation.views.notebook.get_direct_connection_source")
- @patch("products.notebooks.backend.presentation.views.notebook.start_sql_v2_run_workflow")
- @patch("products.notebooks.backend.presentation.views.notebook.enqueue_direct_run")
+ @patch("products.notebooks.backend.sql_v2_dispatch.get_direct_connection_source")
+ @patch("products.notebooks.backend.sql_v2_dispatch.start_sql_v2_run_workflow")
+ @patch("products.notebooks.backend.sql_v2_dispatch.enqueue_direct_run")
@patch("products.notebooks.backend.presentation.views.notebook.is_sql_v2_enabled", return_value=True)
def test_a_raw_connection_query_refuses_variables(
self, _mock_enabled, mock_enqueue, mock_start, mock_source
@@ -3300,3 +3307,73 @@ class TestSQLV2RunWithNotebookVariables(APIBaseTest):
self.assertIn("raw query", response.json()["detail"])
mock_enqueue.assert_not_called()
mock_start.assert_not_called()
+
+
+class TestNotebookRunUniqueness(APIBaseTest):
+ def test_a_second_running_row_for_one_notebook_is_refused(self) -> None:
+ # The partial unique constraint is what stops two orchestrators driving the same
+ # notebook at once, so a dropped condition must fail here rather than in production.
+ notebook = Notebook.objects.create(team=self.team, short_id="nbrun01")
+ with team_scope(self.team.id):
+ NotebookRun.objects.create(team=self.team, notebook=notebook, trigger=NotebookRun.Trigger.UI)
+ with self.assertRaises(IntegrityError), transaction.atomic():
+ NotebookRun.objects.create(team=self.team, notebook=notebook, trigger=NotebookRun.Trigger.MCP)
+
+ def test_a_finished_run_leaves_room_for_the_next_one(self) -> None:
+ notebook = Notebook.objects.create(team=self.team, short_id="nbrun02")
+ with team_scope(self.team.id):
+ first = NotebookRun.objects.create(team=self.team, notebook=notebook, trigger=NotebookRun.Trigger.UI)
+ first.status = NotebookRun.Status.DONE
+ first.save(update_fields=["status"])
+ NotebookRun.objects.create(team=self.team, notebook=notebook, trigger=NotebookRun.Trigger.UI)
+
+
+class TestDispatchNodeRunDirectly(APIBaseTest):
+ """`dispatch_node_run` is the seam the whole-notebook orchestrator calls, so these cover
+ the two parts of its contract no HTTP request can reach: the view always pairs a notebook
+ with its own team, and never sets `notebook_run_id`."""
+
+ def setUp(self) -> None:
+ super().setUp()
+ self.notebook = Notebook.objects.create(team=self.team, short_id="nbdisp01")
+
+ def _request(self, **overrides: Any) -> NodeRunRequest:
+ return NodeRunRequest(
+ node_id="n1",
+ node_type="hogql",
+ code="select 1",
+ output_name="df",
+ refs={},
+ variables=[],
+ **overrides,
+ )
+
+ @patch("products.notebooks.backend.sql_v2_dispatch.enqueue_direct_run")
+ def test_the_notebook_run_link_reaches_the_row(self, _mock_enqueue: MagicMock) -> None:
+ # The status endpoint joins on this column, and only the orchestrator ever sets it.
+ notebook_run_id = uuid7()
+ with team_scope(self.team.id):
+ NotebookRun.objects.create(
+ id=notebook_run_id, team=self.team, notebook=self.notebook, trigger=NotebookRun.Trigger.UI
+ )
+
+ with team_scope(self.team.id):
+ dispatch = dispatch_node_run(
+ self.notebook, self.user, self.team, self._request(notebook_run_id=notebook_run_id)
+ )
+
+ run = NotebookNodeRun.objects.for_team(self.team.id).get(id=dispatch.run_id)
+ self.assertEqual(run.notebook_run_id, notebook_run_id)
+
+ @patch("products.notebooks.backend.sql_v2_dispatch.enqueue_direct_run")
+ def test_a_notebook_from_another_team_is_refused(self, mock_enqueue: MagicMock) -> None:
+ # The row stores team and notebook as separate columns, so a caller that paired them
+ # wrong would file a run under one tenant against another tenant's notebook.
+ other_team = Team.objects.create(organization=self.organization, name="other")
+ stranger = Notebook.objects.create(team=other_team, short_id="nbdisp02")
+
+ with self.assertRaises(ValueError), team_scope(self.team.id):
+ dispatch_node_run(stranger, self.user, self.team, self._request())
+
+ mock_enqueue.assert_not_called()
+ self.assertFalse(NotebookNodeRun.objects.for_team(self.team.id).filter(notebook=stranger).exists())
diff --git a/pyproject.toml b/pyproject.toml
index eff90e0dd291..27b52ef72bef 100644
--- a/pyproject.toml
+++ b/pyproject.toml
@@ -682,13 +682,10 @@ ignore_imports = [
"products.notebooks.backend.presentation.views.notebook -> products.notebooks.backend.query_validation",
"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.sql_v2_state",
"products.notebooks.backend.presentation.views.notebook -> products.notebooks.backend.sql_v2_variables",
- "products.notebooks.backend.presentation.views.notebook -> products.notebooks.backend.temporal.client",
- "products.notebooks.backend.presentation.views.notebook -> products.notebooks.backend.temporal.sql_v2",
# TODO: experiments presentation wave — these were invisible to import-linter until
# backend/presentation/ got its package marker, so they are newly surfaced debt, not new
# coupling. experiments is not isolated, so nothing was being skipped on their account.