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): limit how many cell runs execute at once (#89938)

Sinan Kucukkoseler57511f311234
diff --git a/products/notebooks/backend/facade/contracts.py b/products/notebooks/backend/facade/contracts.py
index 2a80949f4d5d..3c021ca2fb8e 100644
--- a/products/notebooks/backend/facade/contracts.py
+++ b/products/notebooks/backend/facade/contracts.py
@@ -18,6 +18,24 @@ from uuid import UUID
from pydantic.dataclasses import dataclass
+class NotebookRunBusy(Exception):
+ """Raised when the notebook already has a cell running.
+
+ Surfaced as 409, not 429. It is a conflict with the notebook's state rather than a rate,
+ and the MCP client rewrites every 429 into its own rate-limit error after retrying with
+ backoff — so a 429 would cost an agent seconds of pointless waiting and then hide the one
+ sentence telling it what to do.
+ """
+
+
+class TeamRunCapacityFull(Exception):
+ """Raised when the project already has as many notebook cells in flight as it may.
+
+ A rate rather than a state conflict, so this one is a 429: retrying later genuinely helps,
+ which is exactly what the MCP client's backoff does.
+ """
+
+
class NotebookCellLimitExceeded(Exception):
"""Raised when a write would grow a notebook past its cell ceiling.
diff --git a/products/notebooks/backend/facade/sql_v2.py b/products/notebooks/backend/facade/sql_v2.py
index 678658d0d286..587679452bc7 100644
--- a/products/notebooks/backend/facade/sql_v2.py
+++ b/products/notebooks/backend/facade/sql_v2.py
@@ -4,9 +4,16 @@ Facade re-exports for the SQLV2 sandbox-facing endpoints.
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.
"""
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,
diff --git a/products/notebooks/backend/presentation/views/notebook.py b/products/notebooks/backend/presentation/views/notebook.py
index a99cfb06cd25..38b2680c2482 100644
--- a/products/notebooks/backend/presentation/views/notebook.py
+++ b/products/notebooks/backend/presentation/views/notebook.py
@@ -18,6 +18,7 @@ from drf_spectacular.types import OpenApiTypes
from drf_spectacular.utils import (
OpenApiExample,
OpenApiParameter,
+ OpenApiResponse,
extend_schema,
extend_schema_field,
extend_schema_view,
@@ -45,7 +46,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
-from posthog.models.utils import UUIDT
+from posthog.models.utils import UUIDT, uuid7
from posthog.renderers import SafeJSONRenderer, ServerSentEventRenderer
from posthog.settings import SERVER_GATEWAY_INTERFACE
from posthog.utils import relative_date_parse
@@ -63,6 +64,8 @@ from products.notebooks.backend.analytics import (
notebook_node_count,
)
from products.notebooks.backend.collab import submit_steps
+from products.notebooks.backend.facade.contracts import NotebookRunBusy, TeamRunCapacityFull
+from products.notebooks.backend.facade.sql_v2 import acquire_run_slots, release_run_slots
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.python_analysis import analyze_python_globals, annotate_python_nodes
@@ -1176,10 +1179,26 @@ class NotebookViewSet(TeamAndOrgViewSetMixin, AccessControlViewSetMixin, ForbidD
@extend_schema(
request=NotebookSQLV2RunRequestSerializer,
- responses={200: NotebookSQLV2RunResponseSerializer},
+ responses={
+ 200: NotebookSQLV2RunResponseSerializer,
+ 409: OpenApiResponse(
+ description=(
+ "The notebook already has a cell running. Wait for it to finish, then run this one. "
+ "A conflict with the notebook's state rather than a rate, so it is not worth retrying "
+ "on a timer."
+ )
+ ),
+ 429: OpenApiResponse(
+ description=(
+ "The project has as many notebook cells in flight as it may. Unlike the 409, retrying "
+ "shortly is the right response."
+ )
+ ),
+ },
description=(
"Dispatch an asynchronous run of a notebook SQL or Python cell. Returns a run_id immediately; "
- "poll the run result endpoint until the status is terminal. Flag-gated (revamped-py-notebooks)."
+ "poll the run result endpoint until the status is terminal. One run at a time per notebook. "
+ "Flag-gated (revamped-py-notebooks)."
),
)
@action(methods=["POST"], url_path="sql_v2/run", detail=True, required_scopes=["notebook:write", "query:read"])
@@ -1294,19 +1313,43 @@ class NotebookViewSet(TeamAndOrgViewSetMixin, AccessControlViewSetMixin, ForbidD
except (SQLV2ReferenceError, NotebookVariableError, ExposedHogQLError) as e:
return Response({"detail": str(e)}, status=400)
- run = NotebookNodeRun.objects.create(
- 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,
- )
+ # 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 NotebookRunBusy as e:
+ # 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
+ # and hide the sentence telling it to wait for the running cell.
+ return Response({"detail": str(e)}, status=409)
+ except TeamRunCapacityFull as e:
+ return Response({"detail": str(e)}, status=429)
+
+ 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":
diff --git a/products/notebooks/backend/sql_v2_callback.py b/products/notebooks/backend/sql_v2_callback.py
index 7aadda4cec6c..28104dc597ee 100644
--- a/products/notebooks/backend/sql_v2_callback.py
+++ b/products/notebooks/backend/sql_v2_callback.py
@@ -17,6 +17,7 @@ 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_concurrency import release_run_slots
from products.notebooks.backend.sql_v2_metrics import outcome_for_status, record_node_run_terminal
from products.notebooks.backend.sql_v2_serializers import NotebookSQLV2CallbackRequestSerializer
@@ -85,9 +86,10 @@ def notebook_sql_v2_callback(request, run_id: str) -> JsonResponse:
frames = envelope.pop("frames", None)
try:
- # select_related: the frame snapshot below scopes to the run's user, so fetch it up front
- # rather than lazy-loading it on attribute access.
- run = NotebookNodeRun.objects.for_team(team_id).select_related("user").get(id=run_id)
+ # select_related: the frame snapshot below scopes to the run's user and the slot release
+ # reads the notebook's short id, so fetch both up front rather than lazy-loading each on
+ # attribute access.
+ run = NotebookNodeRun.objects.for_team(team_id).select_related("user", "notebook").get(id=run_id)
except NotebookNodeRun.DoesNotExist:
return JsonResponse({"error": "Run not found"}, status=404)
@@ -119,6 +121,11 @@ def notebook_sql_v2_callback(request, run_id: str) -> JsonResponse:
_store_frame_snapshot(run, frames, team_id)
+ # The kernel lane's release site. This callback claims its own transition rather than going
+ # through finish_node_run, so it has to hand the slot back itself or the notebook stays
+ # blocked until the TTL.
+ release_run_slots(team_id, run.notebook.short_id, str(run.id))
+
if won_transition:
record_node_run_terminal(run, outcome_for_status(run.status))
diff --git a/products/notebooks/backend/sql_v2_concurrency.py b/products/notebooks/backend/sql_v2_concurrency.py
new file mode 100644
index 000000000000..9f7a93a24a83
--- /dev/null
+++ b/products/notebooks/backend/sql_v2_concurrency.py
@@ -0,0 +1,278 @@
+"""Ceilings on how many notebook cell runs execute at once.
+
+The editor shows one run at a time per notebook, but that rule is kea state in a single
+browser tab: a second tab, a collaborator, or an API caller is not serialized by it, and the
+MCP cell tools are API callers. These slots are the server-side rule the editor's behavior
+already implies, so an agent dispatching cells in parallel meets the same ceiling a person
+does.
+
+Slots rather than a request rate, because the cost of a run is a ClickHouse query or a held
+sandbox: what has to be bounded is how many are in flight, not how often one starts. Same
+Redis mechanism `temporal/frame_materialize.py` already uses for materializations, which also
+brings the ClickHouse kill switch with it — during an incident the limiter halves or quarters
+these ceilings on its own.
+
+A slot is taken at dispatch and given back when the run reaches a terminal state. Every lane
+funnels through `finish_node_run`, and the sandbox callback claims its own transition, so
+those are the two release sites. The TTL is the backstop for a process that dies in between.
+"""
+
+import time
+from contextlib import suppress
+from datetime import timedelta
+
+from django.core.exceptions import ValidationError as DjangoValidationError
+from django.utils import timezone
+
+from posthog.clickhouse.client.limit import ConcurrencyLimitExceeded, ConcurrencySlot, RateLimit
+
+from products.notebooks.backend.facade.contracts import NotebookRunBusy, TeamRunCapacityFull
+from products.notebooks.backend.models import NotebookNodeRun
+
+# One run at a time per notebook, matching what the editor has always shown. A notebook is the
+# unit a person reasons about, and cells in one notebook usually depend on each other, so
+# serializing them costs little and makes a runaway caller wait rather than fan out.
+NOTEBOOK_RUN_CONCURRENCY = 1
+# The ceiling across a whole project, so one team's notebooks cannot take the ClickHouse
+# concurrency everyone else's queries need.
+TEAM_RUN_CONCURRENCY = 10
+
+# The per-notebook slot is deliberately long-lived, because no fixed number bounds a working
+# run: a python cell materializes one input per referenced upstream node, in sequence, each
+# with its own 11 minute deadline, before it executes at all. A TTL sized against the kernel
+# watchdog's 20 minutes would evict the slot of a two-input cell that is still working, and let
+# a second cell into the same kernel. Staleness is caught by asking the run rows instead (see
+# `acquire_run_slots`), so this only has to outlast any real run.
+_NOTEBOOK_SLOT_TTL_SECONDS = 2 * 60 * 60
+# The per-team slot is shorter because there is no cheap index to check a whole team's
+# in-flight runs against, so it cannot fall back on the row check the notebook slot uses. It
+# does not expire under a working run: `renew_run_slots` pushes it out on every sign of life.
+_TEAM_SLOT_TTL_SECONDS = 25 * 60
+
+# How long a slot is trusted purely because it is recent. The run row is written after the
+# slot is taken, so between those two steps a slot legitimately exists with no row behind it.
+# Without this window a second dispatch arriving in that gap would read "slot held, no run" as
+# a leak, clear it, and admit itself — defeating the ceiling in exactly the parallel-dispatch
+# case it exists for. Far longer than the gap, far shorter than any TTL.
+_SLOT_CONFIRM_GRACE_SECONDS = 60
+
+# How recently a RUNNING row must have been touched to count as genuinely in flight. A direct
+# (hogql) run only turns terminal when a client polls it, and nothing sweeps one server-side,
+# so an abandoned row stays RUNNING for good. Treating that as active would block its notebook
+# permanently rather than for a TTL. Past every lane's watchdog budget (600s direct, 1200s
+# kernel, which `touch_run_progress` re-anchors), a row is abandoned, not running. Kept as a
+# literal because sql_v2_runs, which owns those budgets, releases these slots.
+_RUN_ACTIVE_WINDOW_SECONDS = 25 * 60
+
+_NOTEBOOK_LIMITER: RateLimit | None = None
+_TEAM_LIMITER: RateLimit | None = None
+
+
+def _notebook_key(team_id: int, notebook_short_id: str) -> str:
+ return f"notebooks:run:per-notebook:{team_id}:{notebook_short_id}"
+
+
+def _team_key(team_id: int) -> str:
+ return f"notebooks:run:per-team:{team_id}"
+
+
+def _get_notebook_limiter() -> RateLimit:
+ global _NOTEBOOK_LIMITER
+ if _NOTEBOOK_LIMITER is None:
+ _NOTEBOOK_LIMITER = RateLimit(
+ max_concurrency=NOTEBOOK_RUN_CONCURRENCY,
+ limit_name="notebooks_run_per_notebook",
+ # Stable: `use()` exports this as the `task_name` metric label, so a per-notebook
+ # value would mint a Prometheus series per contended notebook, in every web process,
+ # and a caller could grow that set at will. The dynamic part is the Redis key below.
+ get_task_name=lambda *args, **kwargs: "notebooks:run:per-notebook",
+ get_task_key=lambda *args, **kwargs: _notebook_key(kwargs["team_id"], kwargs["notebook_short_id"]),
+ get_task_id=lambda *args, **kwargs: kwargs["task_id"],
+ ttl=_NOTEBOOK_SLOT_TTL_SECONDS,
+ # No `retry`: a full ceiling refuses straight away rather than holding the request.
+ # A waiting dispatch would occupy a web worker, which is the shape that lets a
+ # sandbox provider's bad day spread past notebooks.
+ )
+ return _NOTEBOOK_LIMITER
+
+
+def _get_team_limiter() -> RateLimit:
+ global _TEAM_LIMITER
+ if _TEAM_LIMITER is None:
+ _TEAM_LIMITER = RateLimit(
+ max_concurrency=TEAM_RUN_CONCURRENCY,
+ limit_name="notebooks_run_per_team",
+ # Same split as above. team_id is already its own label on the counter, so carrying
+ # it in the name only duplicated it.
+ get_task_name=lambda *args, **kwargs: "notebooks:run:per-team",
+ get_task_key=lambda *args, **kwargs: _team_key(kwargs["team_id"]),
+ get_task_id=lambda *args, **kwargs: kwargs["task_id"],
+ ttl=_TEAM_SLOT_TTL_SECONDS,
+ )
+ return _TEAM_LIMITER
+
+
+# Remove a slot member only if it still carries the score we read. Redis has no conditional
+# ZREM, and an unconditional one is not enough: between reading a stale member and dropping it,
+# another dispatch can reclaim the slot and put its own member there, or the holder can come
+# back to life and renew. Both would be destroyed by a blind removal, letting two runs into a
+# ceiling of one.
+_EVICT_IF_UNCHANGED = """
+local score = redis.call('ZSCORE', KEYS[1], ARGV[1])
+if score and tonumber(score) == tonumber(ARGV[2]) then
+ return redis.call('ZREM', KEYS[1], ARGV[1])
+end
+return 0
+"""
+
+
+def acquire_run_slots(team_id: int, notebook_short_id: str, run_id: str) -> None:
+ """Take one per-notebook and one per-team slot, or raise.
+
+ Taken before the run row exists, so a refused dispatch writes nothing: an agent retrying
+ into a full ceiling must not leave a trail of rows on the table that already grows fastest.
+
+ A full ceiling is not proof that anything is running. Both release sites need a client still
+ watching, and a direct run has no server-side sweeper at all, so a caller that dispatches and
+ walks away leaves its slot held. Each ceiling therefore reclaims demonstrably dead members
+ once before refusing.
+ """
+ notebook_limiter = _get_notebook_limiter()
+ team_limiter = _get_team_limiter()
+
+ # Only a full ceiling raises. Anything else — Redis unreachable above all — propagates as
+ # the error it is, rather than telling a caller its notebook is busy when nothing is
+ # running at all.
+ try:
+ notebook_limiter.use(team_id=team_id, notebook_short_id=notebook_short_id, task_id=run_id)
+ except ConcurrencyLimitExceeded as exc:
+ if not _reclaim_dead_members(notebook_limiter, _notebook_key(team_id, notebook_short_id), team_id):
+ raise NotebookRunBusy(
+ "This notebook already has a cell running. Wait for it to finish, then run this one."
+ ) from exc
+ try:
+ notebook_limiter.use(team_id=team_id, notebook_short_id=notebook_short_id, task_id=run_id)
+ except ConcurrencyLimitExceeded as retry_exc:
+ # Another dispatch reclaimed and took it in the same moment. That one is real.
+ raise NotebookRunBusy(
+ "This notebook already has a cell running. Wait for it to finish, then run this one."
+ ) from retry_exc
+
+ try:
+ team_limiter.use(team_id=team_id, task_id=run_id)
+ except ConcurrencyLimitExceeded as exc:
+ if _reclaim_dead_members(team_limiter, _team_key(team_id), team_id):
+ try:
+ team_limiter.use(team_id=team_id, task_id=run_id)
+ return
+ except ConcurrencyLimitExceeded:
+ pass
+ # The notebook slot is already ours, so give it back rather than holding a notebook
+ # hostage over a ceiling the caller never got past.
+ _release(notebook_limiter, _notebook_key(team_id, notebook_short_id), run_id)
+ raise TeamRunCapacityFull(
+ "This project is running as many notebook cells as it can at once. Try again shortly."
+ ) from exc
+
+
+def _reclaim_dead_members(limiter: RateLimit, key: str, team_id: int) -> bool:
+ """Drop slot members whose run is demonstrably over; return whether any went.
+
+ Two conditions, both needed. A member has to be old enough that its holder would have
+ written its run row by now, or a dispatch still inside that gap would look abandoned. And
+ its run must not be in flight, judged by the rows rather than by the slot.
+
+ The row lookup is by primary key over at most a ceiling's worth of ids, so it stays indexed
+ even for the team ceiling, where counting a whole team's runs would not be.
+ """
+ try:
+ entries = limiter.redis_client.zrange(key, 0, -1, withscores=True)
+ except Exception:
+ # No evidence means no eviction: refuse rather than clear a slot on a failed read.
+ return False
+ now = time.time()
+ settled = [
+ (member.decode() if isinstance(member, bytes) else str(member), float(score))
+ for member, score in entries
+ if limiter.ttl - (float(score) - now) >= _SLOT_CONFIRM_GRACE_SECONDS
+ ]
+ if not settled:
+ return False
+
+ active = _active_run_ids(team_id, [member for member, _ in settled])
+ reclaimed = False
+ for member, score in settled:
+ if member not in active and _evict_if_unchanged(limiter, key, member, score):
+ reclaimed = True
+ return reclaimed
+
+
+def _active_run_ids(team_id: int, run_ids: list[str]) -> set[str]:
+ """Which of `run_ids` are still genuinely in flight.
+
+ Bounded by `_RUN_ACTIVE_WINDOW_SECONDS` rather than trusting RUNNING alone: a direct run
+ only turns terminal when a client polls it, and nothing sweeps one server-side, so a row
+ left RUNNING would otherwise hold its slot for good.
+ """
+ try:
+ rows = (
+ NotebookNodeRun.objects.for_team(team_id)
+ .filter(
+ id__in=run_ids,
+ status=NotebookNodeRun.Status.RUNNING,
+ updated_at__gte=timezone.now() - timedelta(seconds=_RUN_ACTIVE_WINDOW_SECONDS),
+ )
+ .values_list("id", flat=True)
+ )
+ except (DjangoValidationError, ValueError):
+ # A member that is not a uuid cannot name a run, so nothing here is active.
+ return set()
+ return {str(row_id) for row_id in rows}
+
+
+def _evict_if_unchanged(limiter: RateLimit, key: str, member: str, score: float) -> bool:
+ """Remove `member` only while it still holds `score`. Returns whether it went."""
+ try:
+ return bool(limiter.redis_client.eval(_EVICT_IF_UNCHANGED, 1, key, member, repr(score)))
+ except Exception:
+ return False
+
+
+def renew_run_slots(team_id: int, notebook_short_id: str, run_id: str) -> None:
+ """Push both slots' expiry out while the run is demonstrably still working.
+
+ A slot has to outlast the run holding it, and no fixed TTL does: a python cell materializes
+ one input per referenced upstream node, in sequence, each with its own 11 minute deadline.
+ Left to expire, the ceiling stops being a concurrency limit and becomes a rate — a caller
+ can start a fresh batch every TTL while the previous ones still run, and keep an unbounded
+ number in flight. The gap between two signs of life is one materialization, which is well
+ inside either TTL, so renewing on each one is enough.
+
+ `xx=True` so this only ever moves a member that is already there. A late fetch for a run
+ whose slot was released must not put it back and hold capacity until the TTL.
+ """
+ _renew(_get_notebook_limiter(), _notebook_key(team_id, notebook_short_id), run_id)
+ _renew(_get_team_limiter(), _team_key(team_id), run_id)
+
+
+def _renew(limiter: RateLimit, key: str, run_id: str) -> None:
+ # Best effort, like releasing: a missed renewal costs the run its slot, not its result.
+ with suppress(Exception):
+ limiter.redis_client.zadd(key, {run_id: time.time() + limiter.ttl}, xx=True)
+
+
+def release_run_slots(team_id: int, notebook_short_id: str, run_id: str) -> None:
+ """Give both slots back. Idempotent, and safe for a run that never took one.
+
+ Releasing is a Redis set-member removal, so releasing twice, or releasing a run that was
+ refused before it ever held a slot, does nothing.
+ """
+ _release(_get_notebook_limiter(), _notebook_key(team_id, notebook_short_id), run_id)
+ _release(_get_team_limiter(), _team_key(team_id), run_id)
+
+
+def _release(limiter: RateLimit, key: str, run_id: str) -> None:
+ # Best effort: a run that finished matters more than the slot bookkeeping, and the TTL
+ # already covers a release that never lands.
+ with suppress(Exception):
+ limiter.release(ConcurrencySlot(running_tasks_key=key, task_id=run_id))
diff --git a/products/notebooks/backend/sql_v2_data_plane.py b/products/notebooks/backend/sql_v2_data_plane.py
index b08397a14ce0..f5abd5f983c1 100644
--- a/products/notebooks/backend/sql_v2_data_plane.py
+++ b/products/notebooks/backend/sql_v2_data_plane.py
@@ -145,7 +145,7 @@ def notebook_sql_v2_data_plane(request: HttpRequest) -> HttpResponse:
# another, and without this the watchdog would count that whole sequence against a single
# budget and fail a cell that is working correctly.
if claims.run_id:
- touch_run_progress(claims.team_id, claims.run_id)
+ touch_run_progress(claims.team_id, claims.notebook_short_id, claims.run_id)
team = Team.objects.get(id=claims.team_id)
user = User.objects.filter(id=claims.user_id).first() if claims.user_id else None
diff --git a/products/notebooks/backend/sql_v2_runs.py b/products/notebooks/backend/sql_v2_runs.py
index 44b5a84b8ec9..5b2f32d2995c 100644
--- a/products/notebooks/backend/sql_v2_runs.py
+++ b/products/notebooks/backend/sql_v2_runs.py
@@ -16,6 +16,7 @@ from django.utils import timezone
import structlog
from products.notebooks.backend.models import NotebookNodeRun
+from products.notebooks.backend.sql_v2_concurrency import release_run_slots, renew_run_slots
from products.notebooks.backend.sql_v2_metrics import OUTCOME_TIMED_OUT, outcome_for_status, record_node_run_terminal
logger = structlog.get_logger(__name__)
@@ -63,12 +64,16 @@ def finish_node_run(
# 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"))
+ # Released whether or not this call won: the run is terminal either way, and giving a slot
+ # back twice removes an absent set member, which does nothing. Holding it on the losing
+ # path would keep a notebook blocked until the slot's TTL.
+ release_run_slots(run.team_id, run.notebook.short_id, str(run.id))
if updated:
record_node_run_terminal(run, outcome or outcome_for_status(status))
return bool(updated)
-def touch_run_progress(team_id: int, run_id: str) -> None:
+def touch_run_progress(team_id: int, notebook_short_id: str, run_id: str) -> None:
"""Record that the kernel is still working on `run_id`, resetting its watchdog clock.
Called from the data plane, which is the kernel's only way back to PostHog during a run:
@@ -80,6 +85,10 @@ def touch_run_progress(team_id: int, run_id: str) -> None:
watchdog already finished. Best effort: the run's progress matters less than the query
the sandbox is waiting on, so a failure here must never fail the fetch.
"""
+ # The same sign of life keeps the run's concurrency slots alive. Without it a long cell's
+ # slot expires while it works, and the ceiling degrades from "ten at once" to "ten every
+ # TTL" — a caller could hold an unbounded number by starting a batch each time one lapses.
+ renew_run_slots(team_id, notebook_short_id, run_id)
try:
NotebookNodeRun.objects.for_team(team_id).filter(id=run_id, status=NotebookNodeRun.Status.RUNNING).update(
updated_at=timezone.now()
diff --git a/products/notebooks/backend/test/test_sql_v2.py b/products/notebooks/backend/test/test_sql_v2.py
index 337543c77539..bef461b32827 100644
--- a/products/notebooks/backend/test/test_sql_v2.py
+++ b/products/notebooks/backend/test/test_sql_v2.py
@@ -2,6 +2,7 @@ import io
import os
import json
import math
+import time
import tarfile
import datetime
import tempfile
@@ -9,6 +10,7 @@ import threading
import urllib.error
import email.message
import urllib.request
+from datetime import timedelta
from http.server import ThreadingHTTPServer
from types import SimpleNamespace
from typing import Any
@@ -21,12 +23,14 @@ from django.conf import settings
from django.core import signing
from django.core.cache import cache
from django.test import SimpleTestCase, override_settings
+from django.utils import timezone
from parameterized import parameterized
from posthog.hogql import ast
from posthog.hogql.parser import parse_select
+from posthog import redis
from posthog.clickhouse.client.execute_async import QueryNotFoundError
from posthog.constants import AvailableFeature
from posthog.models.organization import OrganizationMembership
@@ -35,6 +39,7 @@ from posthog.models.user import User
from posthog.models.utils import UUIDT
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.sandbox.kernel import (
@@ -71,6 +76,7 @@ from products.notebooks.backend.sql_v2_direct import (
notebook_direct_query_id,
sync_direct_run,
)
+from products.notebooks.backend.sql_v2_runs import finish_node_run, touch_run_progress
from products.notebooks.backend.temporal.sql_v2 import (
SQLV2RunInput,
dispatch_sql_v2_run_activity,
@@ -441,6 +447,185 @@ class TestSQLV2Run(APIBaseTest):
mock_start.assert_not_called()
self.assertFalse(KernelRuntime.objects.filter(team=self.team).exists())
+ def _age_slot(self, run_id: str) -> None:
+ """Backdate a held slot so it reads as old enough to have been abandoned.
+
+ The set's score is the member's expiry, so moving it earlier ages the member.
+ """
+ key = sql_v2_concurrency._notebook_key(self.team.id, self.notebook.short_id)
+ 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.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
+ # state in one browser tab. An API caller — which is what the MCP cell tools are — could
+ # dispatch as many as it liked, and each SQL run is a real ClickHouse query.
+ first = self.client.post(self.run_url, data={"node_id": "n1", "code": "select 1"}, format="json")
+ self.assertEqual(first.status_code, 200)
+
+ # 409, not 429: the MCP client retries every 429 with backoff and then replaces the
+ # body with its own rate-limit message, so a 429 would hide this detail from an agent.
+ second = self.client.post(self.run_url, data={"node_id": "n2", "code": "select 2"}, format="json")
+ self.assertEqual(second.status_code, 409, second.content)
+ self.assertIn("already has a cell running", second.json()["detail"])
+ # A refused dispatch must write nothing: an agent retrying into a full ceiling would
+ # otherwise leave a row per attempt on the table that grows fastest.
+ self.assertEqual(NotebookNodeRun.objects.for_team(self.team.id).filter(node_id="n2").count(), 0)
+
+ # Finishing the first run hands the slot back. Without this the notebook would stay
+ # blocked until the slot's TTL, which is far worse than the problem being fixed.
+ run = NotebookNodeRun.objects.for_team(self.team.id).get(id=first.json()["run_id"])
+ finish_node_run(run, NotebookNodeRun.Status.DONE, error=None)
+
+ 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.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
+ ):
+ # Both release sites need a client still watching, so an agent that dispatches a cell
+ # and walks away leaves the slot held. Without recovery the notebook would refuse every
+ # later cell until the slot's TTL, which is hours. The run rows are the truth.
+ first = self.client.post(self.run_url, data={"node_id": "n1", "code": "select 1"}, format="json")
+ self.assertEqual(first.status_code, 200)
+ # The run ends without anything releasing the slot, exactly as a lost client leaves it.
+ NotebookNodeRun.objects.for_team(self.team.id).filter(id=first.json()["run_id"]).update(
+ status=NotebookNodeRun.Status.DONE
+ )
+ self._age_slot(first.json()["run_id"])
+
+ 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.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
+ # dispatch arriving in that gap sees a held slot with no row behind it. Reading that as
+ # a leak would clear a live slot and admit a second run — losing the ceiling in exactly
+ # the parallel-dispatch case it exists for. A fresh slot is trusted on its age alone.
+ first = self.client.post(self.run_url, data={"node_id": "n1", "code": "select 1"}, format="json")
+ self.assertEqual(first.status_code, 200)
+ # Stand in for the gap: the slot is held and no RUNNING row backs it.
+ NotebookNodeRun.objects.for_team(self.team.id).filter(id=first.json()["run_id"]).update(
+ status=NotebookNodeRun.Status.DONE
+ )
+
+ second = self.client.post(self.run_url, data={"node_id": "n2", "code": "select 2"}, format="json")
+ self.assertEqual(second.status_code, 409, second.content)
+
+ def test_a_second_reclaimer_cannot_wipe_the_slot_the_first_just_took(self) -> None:
+ # The interleave that used to break the ceiling. Two callers both see the same stale
+ # member S and both decide it is dead. A retires S and takes the slot; B, still holding
+ # its own view of S, then tries to retire it too. Clearing the whole key at that point
+ # removed A's brand-new member and let B in as well, so a ceiling of one ran two cells.
+ limiter = sql_v2_concurrency._get_notebook_limiter()
+ key = sql_v2_concurrency._notebook_key(self.team.id, "racenb")
+ client = redis.get_client()
+ client.delete(key)
+ stale_score = time.time() + sql_v2_concurrency._NOTEBOOK_SLOT_TTL_SECONDS - 7200
+ client.zadd(key, {"stale-holder": stale_score})
+
+ # A retires the dead holder and claims the slot.
+ self.assertTrue(sql_v2_concurrency._evict_if_unchanged(limiter, key, "stale-holder", stale_score))
+ client.zadd(key, {"caller-a": time.time() + sql_v2_concurrency._NOTEBOOK_SLOT_TTL_SECONDS})
+
+ # B acts on the view it took before A moved. It must not disturb the live holder.
+ self.assertFalse(sql_v2_concurrency._evict_if_unchanged(limiter, key, "stale-holder", stale_score))
+ self.assertEqual(client.zrange(key, 0, -1), [b"caller-a"])
+
+ def test_a_reclaim_cannot_evict_a_member_that_changed_underneath_it(self) -> None:
+ # The same guarantee stated the other way: a score read before the holder renewed, or
+ # before a new dispatch replaced it, must not authorise removing what is there now.
+ limiter = sql_v2_concurrency._get_notebook_limiter()
+ key = sql_v2_concurrency._notebook_key(self.team.id, "renewnb")
+ client = redis.get_client()
+ client.delete(key)
+ observed_score = time.time() + 100
+ client.zadd(key, {"holder": observed_score})
+ # The holder renews, or another dispatch takes the slot, after the score was read.
+ client.zadd(key, {"holder": observed_score + 500})
+
+ 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.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
+ # node, in sequence, each with its own deadline. If the slot lapses underneath it, the
+ # team ceiling stops being "ten at once" and becomes "ten every TTL", which a caller can
+ # ride to hold an unbounded number. Every data-plane fetch has to push the expiry out.
+ first = self.client.post(self.run_url, data={"node_id": "n1", "code": "select 1"}, format="json")
+ self.assertEqual(first.status_code, 200)
+ run_id = first.json()["run_id"]
+ team_key = sql_v2_concurrency._team_key(self.team.id)
+ client = redis.get_client()
+ # Wind the slot to the edge of expiry, as a long-running cell would.
+ client.zadd(team_key, {run_id: time.time() + 5})
+
+ touch_run_progress(self.team.id, self.notebook.short_id, run_id)
+
+ renewed = dict(client.zrange(team_key, 0, -1, withscores=True))[run_id.encode()]
+ self.assertGreater(renewed, time.time() + sql_v2_concurrency._TEAM_SLOT_TTL_SECONDS - 60)
+
+ def test_progress_never_resurrects_a_released_slot(self) -> None:
+ # A fetch can land after the run finished and its slot was handed back. Re-adding the
+ # member there would hold team capacity until the TTL for a run that is already over.
+ team_key = sql_v2_concurrency._team_key(self.team.id)
+ client = redis.get_client()
+ client.delete(team_key)
+
+ touch_run_progress(self.team.id, self.notebook.short_id, "a-run-that-holds-nothing")
+
+ 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.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
+ # one server-side. Left RUNNING for good, it would block its notebook for good — a
+ # permanent outage rather than a wait — so a row past every watchdog budget must stop
+ # counting as in flight.
+ first = self.client.post(self.run_url, data={"node_id": "n1", "code": "select 1"}, format="json")
+ self.assertEqual(first.status_code, 200)
+ run_id = first.json()["run_id"]
+ # Still RUNNING, but last touched long past every lane's budget.
+ NotebookNodeRun.objects.for_team(self.team.id).filter(id=run_id).update(
+ updated_at=timezone.now() - timedelta(hours=2)
+ )
+ self._age_slot(run_id)
+
+ 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.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
+ # per-notebook limiter used the team key by mistake, the team ceiling would effectively
+ # be 1 and this would fail.
+ self.assertEqual(
+ self.client.post(self.run_url, data={"node_id": "n1", "code": "select 1"}, format="json").status_code, 200
+ )
+ other = Notebook.objects.create(team=self.team, short_id="nbrun02")
+ response = self.client.post(
+ f"/api/projects/{self.team.id}/notebooks/{other.short_id}/sql_v2/run/",
+ data={"node_id": "n1", "code": "select 1"},
+ format="json",
+ )
+ self.assertEqual(response.status_code, 200, response.content)
+
@patch("products.notebooks.backend.sql_v2_direct.enqueue_process_query_task")
@patch("products.notebooks.backend.presentation.views.notebook.is_sql_v2_enabled", return_value=True)
def test_direct_enqueue_threads_user_and_private_query_id(self, _mock_enabled, mock_enqueue):
diff --git a/products/notebooks/frontend/generated/api.ts b/products/notebooks/frontend/generated/api.ts
index 4b2e66e929ef..5161a5ad8d1f 100644
--- a/products/notebooks/frontend/generated/api.ts
+++ b/products/notebooks/frontend/generated/api.ts
@@ -454,7 +454,7 @@ export const getNotebooksSqlV2RunCreateUrl = (projectId: string, shortId: string
}
/**
- * Dispatch an asynchronous run of a notebook SQL or Python cell. Returns a run_id immediately; poll the run result endpoint until the status is terminal. Flag-gated (revamped-py-notebooks).
+ * Dispatch an asynchronous run of a notebook SQL or Python cell. Returns a run_id immediately; poll the run result endpoint until the status is terminal. One run at a time per notebook. Flag-gated (revamped-py-notebooks).
*/
export const notebooksSqlV2RunCreate = async (
projectId: string,
diff --git a/products/notebooks/frontend/generated/api.zod.ts b/products/notebooks/frontend/generated/api.zod.ts
index a751f1b74d57..f8e73396255c 100644
--- a/products/notebooks/frontend/generated/api.zod.ts
+++ b/products/notebooks/frontend/generated/api.zod.ts
@@ -642,7 +642,7 @@ export const NotebooksKernelStopCreateBody = /* @__PURE__ */ zod.object({
})
/**
- * Dispatch an asynchronous run of a notebook SQL or Python cell. Returns a run_id immediately; poll the run result endpoint until the status is terminal. Flag-gated (revamped-py-notebooks).
+ * Dispatch an asynchronous run of a notebook SQL or Python cell. Returns a run_id immediately; poll the run result endpoint until the status is terminal. One run at a time per notebook. Flag-gated (revamped-py-notebooks).
*/
export const notebooksSqlV2RunCreateBodyNodeTypeDefault = `hogql`
export const notebooksSqlV2RunCreateBodyOutputNameDefault = ``