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): cancel direct sql runs instead of only abandoning the row (#73895)

Sinan Kucukkoseler8cae44e8897b
diff --git a/frontend/src/scenes/notebooks/Nodes/NotebookNodeSQLV2.tsx b/frontend/src/scenes/notebooks/Nodes/NotebookNodeSQLV2.tsx
index 520e92a2fa92..af72db31b4ea 100644
--- a/frontend/src/scenes/notebooks/Nodes/NotebookNodeSQLV2.tsx
+++ b/frontend/src/scenes/notebooks/Nodes/NotebookNodeSQLV2.tsx
@@ -347,7 +347,7 @@ const Settings = ({
hasResult: !!attributes.result,
getContent: () => notebookLogic.values.content ?? null,
})
- const { isRunning, isInterrupting, operationBlockReason, activeRunLane } = useValues(dataLogic)
+ const { isRunning, isInterrupting, operationBlockReason } = useValues(dataLogic)
const { runQuery, interruptRun } = useActions(dataLogic)
return (
@@ -361,9 +361,7 @@ const Settings = ({
runQueryLoading={isRunning}
runQueryDisabledReason={operationBlockReason ?? undefined}
runQueryTooltip="Run SQL query"
- // Direct (no-sandbox) runs cannot be cancelled — there is no kernel to signal;
- // they finish on their own bounded schedule. Stop applies to kernel-lane runs only.
- onCancelQuery={activeRunLane === 'kernel' ? interruptRun : undefined}
+ onCancelQuery={interruptRun}
cancelQueryLoading={isInterrupting}
/>
)
diff --git a/frontend/src/scenes/notebooks/Nodes/notebookNodeSQLV2Logic.test.ts b/frontend/src/scenes/notebooks/Nodes/notebookNodeSQLV2Logic.test.ts
index 00605f785f46..3604200dc571 100644
--- a/frontend/src/scenes/notebooks/Nodes/notebookNodeSQLV2Logic.test.ts
+++ b/frontend/src/scenes/notebooks/Nodes/notebookNodeSQLV2Logic.test.ts
@@ -178,14 +178,12 @@ describe('notebookNodeSQLV2Logic', () => {
mount()
logic.actions.runQuery('select 1')
await expectLogic(logic).toFinishAllListeners()
- expect(logic.values.activeRunLane).toEqual('direct')
expect(notebookSettingsLogic.findMounted()?.values.showKernelInfo).toBe(false)
expect(logic.values.pendingKernelStart).toBe(false)
expect(toastSpy).not.toHaveBeenCalled()
logic.actions.runQuery('select * from new_events', { new_events: { node_id: 'py', kind: 'local' } })
await expectLogic(logic).toFinishAllListeners()
- expect(logic.values.activeRunLane).toEqual('kernel')
expect(notebookSettingsLogic.findMounted()?.values.showKernelInfo).toBe(true)
expect(logic.values.pendingKernelStart).toBe(true)
expect(toastSpy).toHaveBeenCalledWith(expect.stringContaining('Starting a compute sandbox'))
diff --git a/frontend/src/scenes/notebooks/Nodes/notebookNodeSQLV2Logic.ts b/frontend/src/scenes/notebooks/Nodes/notebookNodeSQLV2Logic.ts
index 4f3efbfba067..7a36683c50d0 100644
--- a/frontend/src/scenes/notebooks/Nodes/notebookNodeSQLV2Logic.ts
+++ b/frontend/src/scenes/notebooks/Nodes/notebookNodeSQLV2Logic.ts
@@ -85,10 +85,6 @@ export type NotebookNodeSQLV2DirectRows = {
rows: (string | number | null)[][]
}
-// Which execution lane the node's current run took: 'direct' runs on ClickHouse with no
-// sandbox (no Stop affordance, client-side paging); 'kernel' runs in the sandbox.
-export type SqlV2RunLane = 'direct' | 'kernel'
-
export interface RunQueryOptions {
nodeType?: 'hogql' | 'python'
outputName?: string
@@ -118,7 +114,6 @@ export interface notebookNodeSQLV2LogicValues {
staleNodeIds: Record<string, true> // notebookNodeStalenessLogic
activeOperation: NotebookOperation | null // notebookOperationsLogic
isBusy: boolean // notebookOperationsLogic
- activeRunLane: SqlV2RunLane | null
directRows: NotebookNodeSQLV2DirectRows | null
isInterrupting: boolean
isRunning: boolean
@@ -190,9 +185,6 @@ export interface notebookNodeSQLV2LogicActions {
opts: RunQueryOptions
refs: Record<string, SqlV2RunRef>
}
- setActiveRunLane: (activeRunLane: SqlV2RunLane) => {
- activeRunLane: SqlV2RunLane
- }
setDirectRows: (directRows: NotebookNodeSQLV2DirectRows | null) => {
directRows: NotebookNodeSQLV2DirectRows | null
}
@@ -288,7 +280,6 @@ export const notebookNodeSQLV2Logic = kea<notebookNodeSQLV2LogicType>([
setPageLoading: (pageLoading: boolean) => ({ pageLoading }),
resetPaging: true,
setDirectRows: (directRows: NotebookNodeSQLV2DirectRows | null) => ({ directRows }),
- setActiveRunLane: (activeRunLane: SqlV2RunLane) => ({ activeRunLane }),
setPendingKernelStart: (pendingKernelStart: boolean) => ({ pendingKernelStart }),
}),
reducers({
@@ -360,12 +351,6 @@ export const notebookNodeSQLV2Logic = kea<notebookNodeSQLV2LogicType>([
runQuery: () => null,
},
],
- activeRunLane: [
- null as SqlV2RunLane | null,
- {
- setActiveRunLane: (_, { activeRunLane }) => activeRunLane,
- },
- ],
// A kernel-lane run was submitted while no kernel was known to be up: the backend is
// provisioning the sandbox; drives the "Starting compute sandbox…" caption.
pendingKernelStart: [
@@ -487,12 +472,11 @@ export const notebookNodeSQLV2Logic = kea<notebookNodeSQLV2LogicType>([
}
// Which lane will this run take? Mirrors the backend's routing: python always
// needs the kernel; SQL needs it only when it reads a local (python-made) frame.
- // The backend stays authoritative — this only drives the Stop affordance and
- // the kernel panel, never dispatch.
+ // The backend stays authoritative — this only drives the kernel panel, never
+ // dispatch.
const isKernelLane =
opts.nodeType === 'python' ||
extractDuckSqlTables(code).some((name) => refs[name]?.kind === 'local')
- actions.setActiveRunLane(isKernelLane ? 'kernel' : 'direct')
if (isKernelLane) {
// The backend provisions the sandbox itself when none is running; open the
// kernel panel so the user can watch it come up instead of guessing.
diff --git a/products/notebooks/backend/presentation/views/notebook.py b/products/notebooks/backend/presentation/views/notebook.py
index dbdbacf7fd26..15127773f453 100644
--- a/products/notebooks/backend/presentation/views/notebook.py
+++ b/products/notebooks/backend/presentation/views/notebook.py
@@ -72,7 +72,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 enqueue_direct_run, sync_direct_run
+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,
@@ -1268,11 +1268,14 @@ class NotebookViewSet(TeamAndOrgViewSetMixin, AccessControlViewSetMixin, ForbidD
return Response({"status": run.status})
if run.node_type == NotebookNodeRun.NodeType.HOGQL:
- # A direct (hogql) run has no kernel to signal and no cancellation — the query
- # runs to its bounded completion. Mark the row abandoned; the guarded update
- # yields to a completion that already landed, and sync_direct_run's own guard
- # can never overwrite this interrupt afterwards.
- finish_node_run(run, NotebookNodeRun.Status.INTERRUPTED, error="Run stopped.")
+ # A direct (hogql) run has no kernel to signal, so stop it at the query manager
+ # instead. Mark the row abandoned first so the stop is durable even if the
+ # cancellation below is slow or fails; the guarded update yields to a completion
+ # that already landed, and sync_direct_run's own guard can never overwrite this
+ # interrupt afterwards. Only the caller that won the transition has a live query
+ # to stop, because a run that finished on its own has nothing left running.
+ if finish_node_run(run, NotebookNodeRun.Status.INTERRUPTED, error="Run stopped."):
+ cancel_direct_run(run)
return Response({"status": run.status})
try:
diff --git a/products/notebooks/backend/sql_v2_direct.py b/products/notebooks/backend/sql_v2_direct.py
index 6f34bc070ff4..2e77cbf0ca4a 100644
--- a/products/notebooks/backend/sql_v2_direct.py
+++ b/products/notebooks/backend/sql_v2_direct.py
@@ -23,7 +23,12 @@ from posthog.hogql import ast
from posthog.hogql.errors import ExposedHogQLError
from posthog.hogql.parser import parse_select
-from posthog.clickhouse.client.execute_async import QueryNotFoundError, enqueue_process_query_task, get_query_status
+from posthog.clickhouse.client.execute_async import (
+ QueryNotFoundError,
+ cancel_query,
+ enqueue_process_query_task,
+ get_query_status,
+)
from posthog.clickhouse.query_tagging import Feature, Product, tags_context
from products.notebooks.backend.models import NotebookNodeRun
@@ -145,6 +150,20 @@ def enqueue_direct_run(team: "Team", user: "User | None", run: NotebookNodeRun)
)
+def cancel_direct_run(run: NotebookNodeRun) -> None:
+ """Stop a direct (hogql) run's query: revoke it if still queued, else KILL it on ClickHouse.
+
+ Best effort. The run row is already terminal by the time this is called, so a cancellation
+ that fails must not turn the user's Stop into an error: the query then runs to its own
+ bounded completion and its result is discarded, because the interrupted row is the one
+ `sync_direct_run` and the result poll read.
+ """
+ try:
+ cancel_query(run.team_id, notebook_direct_query_id(str(run.id)))
+ except Exception:
+ logger.exception("notebook_direct_run_cancel_failed", run_id=str(run.id), team_id=run.team_id)
+
+
def _query_status_timings(status: Any) -> dict[str, float]:
"""Decompose a completed QueryStatus into phase timings for the run envelope.
diff --git a/products/notebooks/backend/sql_v2_result_delivery.md b/products/notebooks/backend/sql_v2_result_delivery.md
index a7c80eed2fe9..c1bd5d89aeca 100644
--- a/products/notebooks/backend/sql_v2_result_delivery.md
+++ b/products/notebooks/backend/sql_v2_result_delivery.md
@@ -38,11 +38,14 @@ state.
endpoint surfaces it like a `done` envelope. When no kernel is reachable the
endpoint marks the run `interrupted` itself, so a user can always break out of
a RUNNING-forever row (the kernel lane has no backend watchdog). For
- **direct (hogql) runs** there is nothing to signal and no cancellation: the
- endpoint marks the row abandoned immediately (the query runs to its bounded
- completion; the guarded poll transition can't overwrite the interrupt), and the
- UI hides Stop for these runs. Real cancellation (`cancel_query`: Celery revoke
- plus CH KILL) is a one-call upgrade if long queries warrant it.
+ **direct (hogql) runs** there is no kernel to signal, so the endpoint marks the
+ row abandoned itself (the guarded poll transition can't overwrite the interrupt)
+ and then stops the query at the async manager: `cancel_query` revokes a
+ still-queued Celery task, otherwise it KILLs the query on ClickHouse under the
+ run's derived query id. That cancellation is best effort, because the row is
+ already terminal: a cluster that refuses the KILL just leaves the query running
+ to its bounded completion with its result discarded. Stop is offered for both
+ lanes.
Chosen because the result is a **single terminal value**, not a live event stream.
Polling a durable row is simpler than SSE and inherently resilient to connection
diff --git a/products/notebooks/backend/test/test_sql_v2.py b/products/notebooks/backend/test/test_sql_v2.py
index 5e339276ff4b..5d85d22dae15 100644
--- a/products/notebooks/backend/test/test_sql_v2.py
+++ b/products/notebooks/backend/test/test_sql_v2.py
@@ -1179,11 +1179,17 @@ class TestSQLV2RunInterrupt(APIBaseTest):
self.assertIn("detail", response.json())
self.assertEqual(self._reload_run().status, NotebookNodeRun.Status.RUNNING)
+ @parameterized.expand([("query_cancelled", None), ("cancellation_failed", Exception("cluster unreachable"))])
@patch("products.notebooks.backend.presentation.views.notebook.is_sql_v2_enabled", return_value=True)
@patch("products.notebooks.backend.sql_v2.requests.post")
- def test_direct_sql_run_interrupt_marks_without_kernel(self, mock_post, _mock_enabled):
- # A direct (hogql) run has no kernel to signal: interrupt marks the row abandoned
- # immediately, even when a live kernel exists for this user.
+ @patch("products.notebooks.backend.sql_v2_direct.cancel_query")
+ def test_direct_sql_run_interrupt_stops_the_query_without_a_kernel(
+ self, _name, cancel_error, mock_cancel_query, mock_post, _mock_enabled
+ ):
+ # A direct (hogql) run has no kernel to signal: interrupt marks the row abandoned and
+ # stops the query at the manager, even when a live kernel exists for this user. A failed
+ # cancellation must not turn the user's Stop into an error.
+ mock_cancel_query.side_effect = cancel_error
self._create_runtime()
with team_scope(self.team.id):
sql_run = NotebookNodeRun.objects.create(
@@ -1199,6 +1205,8 @@ class TestSQLV2RunInterrupt(APIBaseTest):
self.assertEqual(response.status_code, 200)
self.assertEqual(response.json()["status"], NotebookNodeRun.Status.INTERRUPTED)
mock_post.assert_not_called()
+ # The private derived id, not the run id: that is what the query was enqueued under.
+ mock_cancel_query.assert_called_once_with(self.team.id, notebook_direct_query_id(str(sql_run.id)))
reloaded = NotebookNodeRun.objects.for_team(self.team.id).get(id=sql_run.id)
self.assertEqual(reloaded.status, NotebookNodeRun.Status.INTERRUPTED)
self.assertTrue(reloaded.error)