: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.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
feat(notebooks): let users interrupt a running SQLV2 cell (#70168)
Sinan Kucukkoseler824a99513dbc
diff --git a/frontend/src/lib/api.ts b/frontend/src/lib/api.tsindex 35e6a14df1ad..70b4c90fbe5b 100644--- a/frontend/src/lib/api.ts+++ b/frontend/src/lib/api.ts@@ -4902,11 +4902,17 @@ const api = {): Promise<{ run_id: string }> {return await new ApiRequest().notebook(notebookId).withAction('sql_v2/run').create({ data })},+ async sqlV2RunInterrupt(+ notebookId: NotebookType['short_id'],+ runId: string+ ): Promise<{ status: string; detail?: string }> {+ return await new ApiRequest().notebook(notebookId).withAction(`sql_v2/runs/${runId}/interrupt`).create()+ },async sqlV2RunResult(notebookId: NotebookType['short_id'],runId: string): Promise<{- status: 'running' | 'done' | 'failed'+ status: 'running' | 'done' | 'failed' | 'interrupted'result: {columns?: string[]types?: [string, string][]diff --git a/frontend/src/scenes/data-warehouse/editor/QueryWindow.tsx b/frontend/src/scenes/data-warehouse/editor/QueryWindow.tsxindex cea3906ad044..5769e375a61c 100644--- a/frontend/src/scenes/data-warehouse/editor/QueryWindow.tsx+++ b/frontend/src/scenes/data-warehouse/editor/QueryWindow.tsx@@ -50,6 +50,9 @@ interface QueryWindowProps {runQueryLoading?: booleanrunQueryDisabledReason?: stringrunQueryTooltip?: string+ /** With onRunQuery: flips the button to Cancel while runQueryLoading, mirroring the native cancel. */+ onCancelQuery?: () => void+ cancelQueryLoading?: booleanonShareTab?: () => void/** Whether the query pane's code editor may grab focus on mount. Defaults to true. */autoFocusQueryPane?: boolean@@ -67,6 +70,8 @@ export function QueryWindow({runQueryLoading,runQueryDisabledReason,runQueryTooltip,+ onCancelQuery,+ cancelQueryLoading,onShareTab,autoFocusQueryPane,}: QueryWindowProps): JSX.Element {@@ -231,6 +236,8 @@ export function QueryWindow({runQueryLoading={runQueryLoading}runQueryDisabledReason={runQueryDisabledReason}runQueryTooltip={runQueryTooltip}+ onCancelQuery={onCancelQuery}+ cancelQueryLoading={cancelQueryLoading}/><CollapsedConnectionSelector tabId={tabId} mode={mode} /><LemonDivider vertical />@@ -378,11 +385,15 @@ function RunButton({runQueryLoading,runQueryDisabledReason,runQueryTooltip,+ onCancelQuery,+ cancelQueryLoading,}: {onRunQuery?: () => voidrunQueryLoading?: booleanrunQueryDisabledReason?: stringrunQueryTooltip?: string+ onCancelQuery?: () => void+ cancelQueryLoading?: boolean}): JSX.Element {const { runQuery, runSubquery } = useActions(sqlEditorLogic)const { cancelQuery } = useActions(dataNodeLogic)@@ -391,9 +402,14 @@ function RunButton({const isUsingIndices = metadata?.isUsingIndices === 'yes'const isRunning = onRunQuery ? !!runQueryLoading : responseLoading+ // The external-run path shows a cancel affordance only when a canceller is provided.+ const showCancel = isRunning && (!onRunQuery || !!onCancelQuery)const [iconColor, tooltipContent] = useMemo(() => {if (onRunQuery) {+ if (isRunning && onCancelQuery) {+ return ['var(--success)', 'Stop the running query']+ }return ['var(--success)', runQueryTooltip ?? 'Run query']}@@ -410,7 +426,16 @@ function RunButton({: undefinedreturn ['var(--warning)', tooltip]- }, [metadata, isUsingIndices, queryInput, isSourceQueryLastRun, onRunQuery, runQueryTooltip])+ }, [+ metadata,+ isUsingIndices,+ queryInput,+ isSourceQueryLastRun,+ onRunQuery,+ runQueryTooltip,+ isRunning,+ onCancelQuery,+ ])const sideAction = useMemo(() =>@@ -446,7 +471,7 @@ function RunButton({<Shortcutname="SQLEditorRun"keybind={[keyBinds.run]}- intent={isRunning && !onRunQuery ? 'Cancel query' : 'Run query'}+ intent={showCancel ? 'Cancel query' : 'Run query'}interaction="click"scope={Scene.SQLEditor}>@@ -454,7 +479,12 @@ function RunButton({data-attr="sql-editor-run-button"onClick={() => {if (onRunQuery) {- if (!runQueryLoading) {+ if (runQueryLoading) {+ // Guard against double submission: one cancel request at a time.+ if (onCancelQuery && !cancelQueryLoading) {+ onCancelQuery()+ }+ } else {onRunQuery()}} else if (responseLoading) {@@ -463,15 +493,15 @@ function RunButton({runQuery()}}}- icon={isRunning && !onRunQuery ? <IconCancel /> : <IconPlayFilled color={iconColor} />}+ icon={showCancel ? <IconCancel /> : <IconPlayFilled color={iconColor} />}type="primary"size="small"tooltip={tooltipContent}sideAction={sideAction}- loading={isRunning && !!onRunQuery}+ loading={onRunQuery ? (onCancelQuery ? !!cancelQueryLoading : isRunning) : false}disabledReason={runQueryDisabledReason}>- {isRunning && !onRunQuery ? 'Cancel' : 'Run'}+ {showCancel ? 'Cancel' : 'Run'}</LemonButton></Shortcut>)diff --git a/frontend/src/scenes/data-warehouse/editor/SQLEditor.tsx b/frontend/src/scenes/data-warehouse/editor/SQLEditor.tsxindex d9591a35c7fb..7bd3a3111063 100644--- a/frontend/src/scenes/data-warehouse/editor/SQLEditor.tsx+++ b/frontend/src/scenes/data-warehouse/editor/SQLEditor.tsx@@ -65,6 +65,9 @@ interface SQLEditorProps {runQueryLoading?: booleanrunQueryDisabledReason?: stringrunQueryTooltip?: string+ /** With onRunQuery: flips the run button to Cancel while runQueryLoading. */+ onCancelQuery?: () => void+ cancelQueryLoading?: booleanonShareTab?: () => voidqueryPaneDefaultHeight?: number/** Whether the query pane's code editor may grab focus on mount. Defaults to true. */@@ -82,6 +85,8 @@ export function SQLEditor({runQueryLoading,runQueryDisabledReason,runQueryTooltip,+ onCancelQuery,+ cancelQueryLoading,onShareTab,queryPaneDefaultHeight,autoFocusQueryPane,@@ -253,6 +258,8 @@ export function SQLEditor({runQueryLoading={runQueryLoading}runQueryDisabledReason={runQueryDisabledReason}runQueryTooltip={runQueryTooltip}+ onCancelQuery={onCancelQuery}+ cancelQueryLoading={cancelQueryLoading}onShareTab={onShareTab}autoFocusQueryPane={autoFocusQueryPane}/>diff --git a/frontend/src/scenes/notebooks/Nodes/NotebookNodePythonV2.tsx b/frontend/src/scenes/notebooks/Nodes/NotebookNodePythonV2.tsxindex d5a724566389..2c4fe7955da7 100644--- a/frontend/src/scenes/notebooks/Nodes/NotebookNodePythonV2.tsx+++ b/frontend/src/scenes/notebooks/Nodes/NotebookNodePythonV2.tsx@@ -3,6 +3,7 @@ import { useMemo, useRef } from 'react'import { IconCornerDownRight, IconPlayFilled } from '@posthog/icons'+import { IconCancel } from 'lib/lemon-ui/icons'import { LemonButton } from 'lib/lemon-ui/LemonButton'import { CodeEditorResizeable } from 'lib/monaco/CodeEditorResizable'import { createPostHogWidgetNode } from 'scenes/notebooks/Nodes/NodeWrapper'@@ -169,8 +170,8 @@ const Settings = ({runId: attributes.runId ?? null,hasResult: !!attributes.result,})- const { isRunning, operationBlockReason } = useValues(dataLogic)- const { runQuery } = useActions(dataLogic)+ const { isRunning, isInterrupting, operationBlockReason } = useValues(dataLogic)+ const { runQuery, interruptRun } = useActions(dataLogic)const run = (): void => {// Guard here (not just on the button) so Cmd+Enter can't fire a second run mid-flight —@@ -197,17 +198,26 @@ const Settings = ({className="flex w-full shrink-0 flex-row items-center gap-2 border-t border-b bg-white py-1 pl-2 pr-2 dark:bg-black"onClick={(event) => event.stopPropagation()}>+ {/* Run flips to Cancel while the cell runs, mirroring the SQL editor's affordance. */}<LemonButtondata-attr="notebook-python-v2-run-button"size="small"type="primary"- icon={<IconPlayFilled color="var(--success)" />}- onClick={() => run()}- loading={isRunning}+ icon={isRunning ? <IconCancel /> : <IconPlayFilled color="var(--success)" />}+ onClick={() => {+ if (isRunning) {+ if (!isInterrupting) {+ interruptRun()+ }+ } else {+ run()+ }+ }}+ loading={isInterrupting}disabledReason={operationBlockReason ?? undefined}- tooltip="Run Python (⌘⏎)"+ tooltip={isRunning ? 'Stop the running cell' : 'Run Python (⌘⏎)'}>- Run+ {isRunning ? 'Cancel' : 'Run'}</LemonButton></div><div className="min-h-0 flex-1">diff --git a/frontend/src/scenes/notebooks/Nodes/NotebookNodeSQLV2.tsx b/frontend/src/scenes/notebooks/Nodes/NotebookNodeSQLV2.tsxindex c9b420eb63c9..8d6f0a84af83 100644--- a/frontend/src/scenes/notebooks/Nodes/NotebookNodeSQLV2.tsx+++ b/frontend/src/scenes/notebooks/Nodes/NotebookNodeSQLV2.tsx@@ -263,8 +263,8 @@ const Settings = ({runId: attributes.runId ?? null,hasResult: !!attributes.result,})- const { isRunning, operationBlockReason } = useValues(dataLogic)- const { runQuery } = useActions(dataLogic)+ const { isRunning, isInterrupting, operationBlockReason } = useValues(dataLogic)+ const { runQuery, interruptRun } = useActions(dataLogic)return (<NotebookCodeSQLEditorSettings@@ -277,6 +277,8 @@ const Settings = ({runQueryLoading={isRunning}runQueryDisabledReason={operationBlockReason ?? undefined}runQueryTooltip="Run SQL (v2) query"+ onCancelQuery={interruptRun}+ cancelQueryLoading={isInterrupting}/>)}diff --git a/frontend/src/scenes/notebooks/Nodes/components/NotebookSQLEditor.tsx b/frontend/src/scenes/notebooks/Nodes/components/NotebookSQLEditor.tsxindex 6244d73ca893..9021f8eaab55 100644--- a/frontend/src/scenes/notebooks/Nodes/components/NotebookSQLEditor.tsx+++ b/frontend/src/scenes/notebooks/Nodes/components/NotebookSQLEditor.tsx@@ -398,6 +398,8 @@ export function NotebookCodeSQLEditorSettings<T extends { code: string }>({runQueryLoading,runQueryDisabledReason,runQueryTooltip,+ onCancelQuery,+ cancelQueryLoading,}: NotebookNodeAttributeProperties<T> & {tabIdSuffix: string/** Called with the live editor text — `attributes.code` can lag it by a Tiptap round-trip. */@@ -405,6 +407,9 @@ export function NotebookCodeSQLEditorSettings<T extends { code: string }>({runQueryLoading?: booleanrunQueryDisabledReason?: stringrunQueryTooltip?: string+ /** With onRunQuery: flips the run button to Cancel while runQueryLoading. */+ onCancelQuery?: () => void+ cancelQueryLoading?: boolean}): JSX.Element {const tabId = useMemo(() => getNotebookSqlEditorTabId(attributes.nodeId, tabIdSuffix),@@ -452,6 +457,8 @@ export function NotebookCodeSQLEditorSettings<T extends { code: string }>({runQueryLoading={runQueryLoading}runQueryDisabledReason={runQueryDisabledReason}runQueryTooltip={runQueryTooltip}+ onCancelQuery={onCancelQuery}+ cancelQueryLoading={cancelQueryLoading}queryPaneDefaultHeight={EMBEDDED_SQL_EDITOR_EDIT_DEFAULT_HEIGHT}/></div>diff --git a/frontend/src/scenes/notebooks/Nodes/notebookNodeSQLV2Logic.test.ts b/frontend/src/scenes/notebooks/Nodes/notebookNodeSQLV2Logic.test.tsindex d612da2f5815..fc3334d52bb3 100644--- a/frontend/src/scenes/notebooks/Nodes/notebookNodeSQLV2Logic.test.ts+++ b/frontend/src/scenes/notebooks/Nodes/notebookNodeSQLV2Logic.test.ts@@ -186,6 +186,58 @@ describe('notebookNodeSQLV2Logic', () => {expect(logic.values.isRunning).toBe(false)})+ it('surfaces an interrupted run with its partial output', async () => {+ // Journey 9: a stopped cell must still show what it printed before the interrupt,+ // with a notice instead of polling forever or rendering a bare failure.+ resultSpy.mockResolvedValue({+ status: 'interrupted',+ result: { columns: [], first_page: [], row_count: 0, stdout: 'partial output' },+ error: 'Run interrupted.',+ })+ mount({ runId: 'r1', hasResult: false })+ await expectLogic(logic).toFinishAllListeners()+ expect(updateAttributes).toHaveBeenCalledWith({+ result: expect.objectContaining({ stdout: 'partial output' }),+ })+ expect(logic.values.runError).toBe('Run interrupted.')+ expect(logic.values.isRunning).toBe(false)+ expect(logic.values.isInterrupting).toBe(false)+ })++ it('interruptRun posts the active run to the interrupt endpoint and stays pending', async () => {+ const interruptSpy = jest.spyOn(api.notebooks, 'sqlV2RunInterrupt').mockResolvedValue({ status: 'running' })+ mount({ runId: 'r1', hasResult: false })+ await expectLogic(logic).toDispatchActions(['startPolling'])+ logic.actions.interruptRun()+ await expectLogic(logic).toFinishAllListeners()+ expect(interruptSpy).toHaveBeenCalledWith('nb1', 'r1')+ // The terminal state arrives via the poll; until then the Cancel button stays pending.+ expect(logic.values.isInterrupting).toBe(true)+ })++ it('an interrupt that stopped nothing resets the cancel button for a retry', async () => {+ jest.spyOn(api.notebooks, 'sqlV2RunInterrupt').mockResolvedValue({+ status: 'running',+ detail: 'The run has not reached the kernel yet. Try again in a moment.',+ })+ mount({ runId: 'r1', hasResult: false })+ await expectLogic(logic).toDispatchActions(['startPolling'])+ logic.actions.interruptRun()+ await expectLogic(logic).toFinishAllListeners()+ expect(logic.values.isInterrupting).toBe(false)+ expect(logic.values.isRunning).toBe(true)+ })++ it('a failed interrupt request resets the cancel button', async () => {+ jest.spyOn(api.notebooks, 'sqlV2RunInterrupt').mockRejectedValue(new Error('network down'))+ mount({ runId: 'r1', hasResult: false })+ await expectLogic(logic).toDispatchActions(['startPolling'])+ logic.actions.interruptRun()+ await expectLogic(logic).toFinishAllListeners()+ expect(logic.values.isInterrupting).toBe(false)+ expect(logic.values.isRunning).toBe(true)+ })+it('surfaces a run dispatch failure as an error', async () => {runSpy.mockRejectedValue(new Error('network down'))mount()diff --git a/frontend/src/scenes/notebooks/Nodes/notebookNodeSQLV2Logic.ts b/frontend/src/scenes/notebooks/Nodes/notebookNodeSQLV2Logic.tsindex 71731d33f9a8..103b6ef4f2c5 100644--- a/frontend/src/scenes/notebooks/Nodes/notebookNodeSQLV2Logic.ts+++ b/frontend/src/scenes/notebooks/Nodes/notebookNodeSQLV2Logic.ts@@ -96,6 +96,8 @@ export const notebookNodeSQLV2Logic = kea<notebookNodeSQLV2LogicType>([startPolling: (runId: string) => ({ runId }),pollResult: (runId: string) => ({ runId }),stopPolling: true,+ interruptRun: true,+ setIsInterrupting: (isInterrupting: boolean) => ({ isInterrupting }),setIsRunning: (isRunning: boolean) => ({ isRunning }),setRunError: (runError: string | null) => ({ runError }),setPage: (page: number) => ({ page }),@@ -122,6 +124,17 @@ export const notebookNodeSQLV2Logic = kea<notebookNodeSQLV2LogicType>([setRunError: (_, { runError }) => runError,},],+ // The interrupt POST (or the wait for its effect) is in flight; guards the Cancel+ // button against double submission; any terminal poll state resets it.+ isInterrupting: [+ false,+ {+ interruptRun: () => true,+ setIsInterrupting: (_, { isInterrupting }) => isInterrupting,+ stopPolling: () => false,+ runQuery: () => false,+ },+ ],page: [1,{@@ -280,24 +293,30 @@ export const notebookNodeSQLV2Logic = kea<notebookNodeSQLV2LogicType>([if (runId !== cache.activeRunId) {return}+ const envelopeResult: NotebookNodeSQLV2Result | null = result+ ? {+ columns: result.columns ?? [],+ types: result.types ?? [],+ row_count: result.row_count ?? 0,+ first_page: result.first_page ?? [],+ has_more: result.has_more ?? false,+ stdout: result.stdout ?? '',+ stderr: result.stderr ?? '',+ media: result.media ?? [],+ }+ : nullif (status === 'done') {- props.updateAttributes({- result: result- ? {- columns: result.columns ?? [],- types: result.types ?? [],- row_count: result.row_count ?? 0,- first_page: result.first_page ?? [],- has_more: result.has_more ?? false,- stdout: result.stdout ?? '',- stderr: result.stderr ?? '',- media: result.media ?? [],- }- : null,- })+ props.updateAttributes({ result: envelopeResult })// A fresh envelope replaces whatever page the user had drilled into.actions.resetPaging()actions.stopPolling()+ } else if (status === 'interrupted') {+ // A user-requested stop: the envelope still carries whatever stdout,+ // stderr, and figures the cell produced before the interrupt landed.+ props.updateAttributes({ result: envelopeResult })+ actions.setRunError(error ?? 'Run interrupted.')+ actions.resetPaging()+ actions.stopPolling()} else if (status === 'failed') {actions.setRunError(error ?? 'Run failed')actions.stopPolling()@@ -313,6 +332,26 @@ export const notebookNodeSQLV2Logic = kea<notebookNodeSQLV2LogicType>([cache.pollInFlight = false}},+ interruptRun: async () => {+ const runId = cache.activeRunId ?? props.runId+ if (!runId || !values.isRunning) {+ actions.setIsInterrupting(false)+ return+ }+ try {+ const response = await api.notebooks.sqlV2RunInterrupt(props.notebookShortId, runId)+ if (response.detail) {+ // Nothing was stopped (e.g. the run hasn't reached the kernel yet), so+ // let the user retry instead of wedging the button in loading.+ lemonToast.info(response.detail)+ actions.setIsInterrupting(false)+ }+ // Otherwise stay interrupting until the poll observes the terminal state.+ } catch (error: any) {+ actions.setIsInterrupting(false)+ lemonToast.error(error?.detail || error?.message || 'Failed to stop the run')+ }+ },stopPolling: () => {cache.disposables.dispose('pollResult')actions.setIsRunning(false)diff --git a/products/notebooks/backend/migrations/0011_alter_notebooknoderun_status.py b/products/notebooks/backend/migrations/0011_alter_notebooknoderun_status.pynew file mode 100644index 000000000000..fcdffa25b6a5--- /dev/null+++ b/products/notebooks/backend/migrations/0011_alter_notebooknoderun_status.py@@ -0,0 +1,26 @@+# Generated by Django 5.2.14 on 2026-07-10 21:34++from django.db import migrations, models+++class Migration(migrations.Migration):+ dependencies = [+ ("notebooks", "0010_notebooknoderun_node_type"),+ ]++ operations = [+ migrations.AlterField(+ model_name="notebooknoderun",+ name="status",+ field=models.CharField(+ choices=[+ ("running", "running"),+ ("done", "done"),+ ("failed", "failed"),+ ("interrupted", "interrupted"),+ ],+ default="running",+ max_length=20,+ ),+ ),+ ]diff --git a/products/notebooks/backend/migrations/max_migration.txt b/products/notebooks/backend/migrations/max_migration.txtindex be3b4447a6c4..8a8c2c3c87c4 100644--- a/products/notebooks/backend/migrations/max_migration.txt+++ b/products/notebooks/backend/migrations/max_migration.txt@@ -1 +1 @@-0010_notebooknoderun_node_type+0011_alter_notebooknoderun_statusdiff --git a/products/notebooks/backend/models.py b/products/notebooks/backend/models.pyindex 89fb50ccdccb..beeae0599c1c 100644--- a/products/notebooks/backend/models.py+++ b/products/notebooks/backend/models.py@@ -190,6 +190,9 @@ class NotebookNodeRun(TeamScopedRootMixin, UUIDModel):RUNNING = "running", "running"DONE = "done", "done"FAILED = "failed", "failed"+ # A user-requested stop (Journey 9); unlike FAILED, the envelope's captured+ # stdout/stderr still surface to the UI.+ INTERRUPTED = "interrupted", "interrupted"class NodeType(models.TextChoices):HOGQL = "hogql", "hogql"diff --git a/products/notebooks/backend/presentation/views/notebook.py b/products/notebooks/backend/presentation/views/notebook.pyindex 359c55261b4b..61a333e872d7 100644--- a/products/notebooks/backend/presentation/views/notebook.py+++ b/products/notebooks/backend/presentation/views/notebook.py@@ -66,6 +66,7 @@ from products.notebooks.backend.sql_v2 import (SQLV2KernelNotRunning,SQLV2PageError,fetch_sql_v2_page,+ interrupt_sql_v2_run,is_sql_v2_enabled,sql_v2_page_lock_key,)@@ -1092,10 +1093,13 @@ class NotebookViewSet(TeamAndOrgViewSetMixin, AccessControlViewSetMixin, ForbidDif run is None:raise Http404()+ # Interrupted runs keep their envelope too: the walkthrough (Journey 9) promises the+ # captured stdout/stderr arrive with the final envelope even when the user stopped it.+ has_result = run.status in (NotebookNodeRun.Status.DONE, NotebookNodeRun.Status.INTERRUPTED)return Response({"status": run.status,- "result": run.envelope if run.status == NotebookNodeRun.Status.DONE else None,+ "result": run.envelope if has_result else None,"error": run.error or None,})@@ -1185,6 +1189,71 @@ class NotebookViewSet(TeamAndOrgViewSetMixin, AccessControlViewSetMixin, ForbidDreturn Response(page)+ @extend_schema(exclude=True)+ @action(+ methods=["POST"],+ url_path="sql_v2/runs/(?P<run_id>[^/.]+)/interrupt",+ detail=True,+ required_scopes=["notebook:write"],+ )+ def sql_v2_run_interrupt(self, request: Request, run_id: str | None = None, **kwargs):+ # A control call, not a data read: it stops a run, so it needs notebook write access+ # but neither query scope nor the RBAC query gate (no analytics rows flow either way).+ # The terminal state still arrives through the normal callback -> run row -> poll.+ user = self._current_user()+ if not (settings.DEBUG or is_sql_v2_enabled(user)) or run_id is None:+ raise Http404()++ notebook = self._get_notebook_for_kernel()+ try:+ run = NotebookNodeRun.objects.for_team(self.team_id).filter(id=run_id, notebook=notebook).first()+ except DjangoValidationError: # malformed run_id (not a UUID)+ raise Http404()+ if run is None:+ raise Http404()+ if run.status != NotebookNodeRun.Status.RUNNING:+ # Already terminal: idempotent noop; the client just reads the outcome.+ return Response({"status": run.status})++ try:+ known = interrupt_sql_v2_run(notebook, user if isinstance(user, User) else None, run)+ except SQLV2KernelNotRunning:+ # Kernels are currently per user, so in a shared notebook the run may be+ # executing on a collaborator's kernel this user cannot reach. Don't mark a+ # possibly-live run terminal in that case.+ other_kernel_running = (+ KernelRuntime.objects.filter(+ team_id=notebook.team_id,+ notebook_short_id=notebook.short_id,+ status__in=(KernelRuntime.Status.RUNNING, KernelRuntime.Status.STARTING),+ )+ .exclude(user=user if isinstance(user, User) else None)+ .exists()+ )+ if other_kernel_running:+ return Response(+ {+ "detail": "This run is executing on another collaborator's kernel and can't be stopped from here."+ },+ status=409,+ )+ # No reachable kernel anywhere: the callback can never arrive, so this is the+ # user's escape hatch out of a stuck RUNNING row. A late callback (e.g. the+ # sandbox comes back) simply overwrites with the real outcome.+ run.status = NotebookNodeRun.Status.INTERRUPTED+ run.error = "Kernel is not reachable, so the run was stopped."+ run.save(update_fields=["status", "error", "updated_at"])+ return Response({"status": run.status})++ if not known:+ # Dispatch still in flight (Temporal) or the run just finished: nothing was+ # stopped; the client keeps polling and the user can retry.+ return Response(+ {"status": run.status, "detail": "The run has not reached the kernel yet. Try again in a moment."},+ status=202,+ )+ return Response({"status": run.status}, status=202)+@extend_schema(request=NotebookCollabSaveSerializer)@action(methods=["POST"], url_path="collab/save", detail=True, required_scopes=["notebook:write"])def collab_save(self, request: Request, **kwargs):diff --git a/products/notebooks/backend/sandbox/kernel/bootstrap.py b/products/notebooks/backend/sandbox/kernel/bootstrap.pyindex f1422b18c575..a491b4b68bc5 100644--- a/products/notebooks/backend/sandbox/kernel/bootstrap.py+++ b/products/notebooks/backend/sandbox/kernel/bootstrap.py@@ -122,6 +122,16 @@ class KernelSession:# setting error_in_exec, and they must not masquerade as a successful empty run.error = execution.error_in_exec or execution.error_before_execif error is not None:+ # A SIGINT (the /interrupt path) surfaces as KeyboardInterrupt inside run_cell;+ # it is a user-requested stop, not a failure, and the captured output still ships.+ if isinstance(error, KeyboardInterrupt):+ return envelope.from_python_execution(+ status="interrupted",+ stdout=stdout,+ stderr=stderr,+ error=envelope.INTERRUPTED_MESSAGE,+ media=media,+ )return envelope.from_python_execution(status="error",stdout=stdout,diff --git a/products/notebooks/backend/sandbox/kernel/data_plane.py b/products/notebooks/backend/sandbox/kernel/data_plane.pyindex 0bd49a255ac8..dec5529f7a5b 100644--- a/products/notebooks/backend/sandbox/kernel/data_plane.py+++ b/products/notebooks/backend/sandbox/kernel/data_plane.py@@ -11,6 +11,7 @@ only third-party dependency is pyarrow (present in the sandbox image).import osimport jsonimport time+import threadingimport urllib.errorimport urllib.requestfrom typing import Any@@ -28,20 +29,37 @@ class DataPlaneError(Exception):"""A query the data plane rejected or failed to run; message is user-facing."""+class DataPlaneInterrupted(DataPlaneError):+ """The run's cancel event fired while waiting on the data plane."""++def fetch_query_page(- url: str, token: str, query: str, limit: int, offset: int = 0+ url: str,+ token: str,+ query: str,+ limit: int,+ offset: int = 0,+ cancel_event: "threading.Event | None" = None,) -> tuple[list[str], list[tuple[Any, ...]], list[list[str]]]:"""Run `query` through the data plane; return (columns, rows, types) of the capped page."""- return _table_to_rows_and_types(_request_table(url, token, query, limit, offset))---def materialize_query_to_file(url: str, token: str, query: str, dest_path: str, limit: int, offset: int = 0) -> int:+ return _table_to_rows_and_types(_request_table(url, token, query, limit, offset, cancel_event))+++def materialize_query_to_file(+ url: str,+ token: str,+ query: str,+ dest_path: str,+ limit: int,+ offset: int = 0,+ cancel_event: "threading.Event | None" = None,+) -> int:"""Fetch the full result of `query` and write it as a local Arrow IPC file for a Python/DuckDB node.Returns the row count. The file is written to a temp name and renamed on success so a tornwrite (e.g. a mid-stream failure) never leaves a half-frame the kernel could read."""- table = _request_table(url, token, query, limit, offset)+ table = _request_table(url, token, query, limit, offset, cancel_event)temp_path = f"{dest_path}.partial"with pa.OSFile(temp_path, "wb") as sink:with pa.ipc.new_file(sink, table.schema) as writer:@@ -50,8 +68,16 @@ def materialize_query_to_file(url: str, token: str, query: str, dest_path: str,return table.num_rows-def _request_table(url: str, token: str, query: str, limit: int, offset: int) -> "pa.Table":+def _check_cancelled(cancel_event: "threading.Event | None") -> None:+ if cancel_event is not None and cancel_event.is_set():+ raise DataPlaneInterrupted("Run interrupted.")+++def _request_table(+ url: str, token: str, query: str, limit: int, offset: int, cancel_event: "threading.Event | None" = None+) -> "pa.Table":"""POST the query and (once the async manager finishes) return the raw Arrow table."""+ _check_cancelled(cancel_event)request = urllib.request.Request(url,data=json.dumps({"query": query, "limit": limit, "offset": offset}).encode(),@@ -76,14 +102,15 @@ def _request_table(url: str, token: str, query: str, limit: int, offset: int) ->query_id = body.get("query_id")if not query_id:raise DataPlaneError("Data plane did not accept the query")- return _poll_for_table(f"{url.rstrip('/')}/{query_id}/", token)+ return _poll_for_table(f"{url.rstrip('/')}/{query_id}/", token, cancel_event)-def _poll_for_table(status_url: str, token: str) -> "pa.Table":+def _poll_for_table(status_url: str, token: str, cancel_event: "threading.Event | None" = None) -> "pa.Table":request = urllib.request.Request(status_url, headers={"Authorization": f"Bearer {token}"}, method="GET")deadline = time.monotonic() + _POLL_DEADLINE_SECONDSinterval = _POLL_INITIAL_INTERVAL_SECONDSwhile time.monotonic() < deadline:+ _check_cancelled(cancel_event)try:# status_url is the backend's own data-plane endpoint from the signed run payload, not user input.# nosemgrep: python.lang.security.audit.dynamic-urllib-use-detected.dynamic-urllib-use-detected@@ -97,7 +124,11 @@ def _poll_for_table(status_url: str, token: str) -> "pa.Table":raise DataPlaneError(f"Could not reach the data plane: {exc.reason}") from excexcept pa.ArrowInvalid as exc:raise DataPlaneError(f"Invalid Arrow response from the data plane: {exc}") from exc- time.sleep(interval)+ # An Event.wait doubles as an interruptible sleep: a cancel fires mid-interval.+ if cancel_event is not None:+ cancel_event.wait(interval)+ else:+ time.sleep(interval)interval = min(interval * 1.5, _POLL_MAX_INTERVAL_SECONDS)raise DataPlaneError("Timed out waiting for the query to finish")diff --git a/products/notebooks/backend/sandbox/kernel/envelope.py b/products/notebooks/backend/sandbox/kernel/envelope.pyindex 62065a561dd6..1dafabc88ed6 100644--- a/products/notebooks/backend/sandbox/kernel/envelope.py+++ b/products/notebooks/backend/sandbox/kernel/envelope.py@@ -54,6 +54,18 @@ def from_error(message: str) -> dict[str, Any]:return {"status": "error", "error": message}+INTERRUPTED_MESSAGE = "Run interrupted."+++def as_interrupted(result: dict[str, Any]) -> dict[str, Any]:+ """Rewrite a non-ok envelope as the interrupted outcome, keeping any captured output.++ The underlying error is almost always the interrupt itself (KeyboardInterrupt, an+ aborted data-plane wait), so the user-facing message is the interrupt, not the symptom.+ """+ return {**result, "status": "interrupted", "error": INTERRUPTED_MESSAGE}++def from_python_execution(*,status: str,diff --git a/products/notebooks/backend/sandbox/kernel/executor.py b/products/notebooks/backend/sandbox/kernel/executor.pyindex d78849da90bf..ffa42c414edf 100644--- a/products/notebooks/backend/sandbox/kernel/executor.py+++ b/products/notebooks/backend/sandbox/kernel/executor.py@@ -48,13 +48,23 @@ class KernelExecutor:self._km: KernelManager | None = Noneself._kc: Any = Noneself._lock = threading.Lock()+ # The run currently executing a cell in the kernel, so an interrupt for a queued or+ # already-finished run can never SIGINT somebody else's cell. Written while holding+ # _lock; read lock-free from the HTTP handler thread (a stale read is benign; the+ # worst case is a missed/late SIGINT, and the cancel event still stops the run).+ self._active_run_id: str | None = None- def run_kernel_node(self, payload: dict[str, Any]) -> dict[str, Any]:+ def run_kernel_node(self, payload: dict[str, Any], cancel_event: threading.Event | None = None) -> dict[str, Any]:with self._lock: # a kernel has one namespace — concurrent runs are meaningless+ # Cancelled while queued behind another run: never touch the kernel.+ if cancel_event is not None and cancel_event.is_set():+ return envelope.from_python_execution(status="interrupted", error=envelope.INTERRUPTED_MESSAGE)try:self._ensure_kernel()- inputs = self._materialize_inputs(payload)+ inputs = self._materialize_inputs(payload, cancel_event)return self._invoke_run_node(payload, inputs)+ except data_plane.DataPlaneInterrupted:+ return envelope.from_python_execution(status="interrupted", error=envelope.INTERRUPTED_MESSAGE)except data_plane.DataPlaneError as exc:return envelope.from_python_execution(status="error", error=str(exc))except Exception as exc: # noqa: BLE001 — a run must always yield a callback envelope@@ -64,6 +74,13 @@ class KernelExecutor:if self._km is not None:self._km.interrupt_kernel()+ def interrupt_for_run(self, run_id: str) -> bool:+ """SIGINT the kernel only if `run_id` is the run executing a cell right now."""+ if run_id and run_id == self._active_run_id and self._km is not None:+ self._km.interrupt_kernel()+ return True+ return False+def restart(self) -> None:with self._lock:if self._km is not None:@@ -98,10 +115,14 @@ class KernelExecutor:if status != "ok":raise RuntimeError("failed to initialize the kernel session")- def _materialize_inputs(self, payload: dict[str, Any]) -> list[dict[str, Any]]:+ def _materialize_inputs(+ self, payload: dict[str, Any], cancel_event: threading.Event | None = None+ ) -> list[dict[str, Any]]:"""Fetch each HogQL input to a local Arrow file; return the kernel-facing input specs (paths only)."""kernel_inputs: list[dict[str, Any]] = []for spec in payload.get("inputs") or []:+ if cancel_event is not None and cancel_event.is_set():+ raise data_plane.DataPlaneInterrupted("Run interrupted.")name = spec["name"]if spec.get("kind") == "local":kernel_inputs.append({"name": name, "kind": "local"})@@ -121,6 +142,7 @@ class KernelExecutor:spec["query"],frame_path,limit=_MATERIALIZE_ROW_CAP,+ cancel_event=cancel_event,)kernel_inputs.append({"name": name, "kind": "hogql", "path": frame_path})return kernel_inputs@@ -150,12 +172,17 @@ class KernelExecutor:if os.path.exists(envelope_path):os.remove(envelope_path)- status = self._execute(- "import json as __j\n"- f"with open({payload_path!r}) as __f:\n __payload = __j.load(__f)\n"- "__envelope = _ph.run_node(__payload)\n"- f"with open({envelope_path!r}, 'w') as __f:\n __j.dump(__envelope, __f)\n"- )+ # Only while the cell is actually executing may an interrupt SIGINT the kernel.+ self._active_run_id = run_id+ try:+ status = self._execute(+ "import json as __j\n"+ f"with open({payload_path!r}) as __f:\n __payload = __j.load(__f)\n"+ "__envelope = _ph.run_node(__payload)\n"+ f"with open({envelope_path!r}, 'w') as __f:\n __j.dump(__envelope, __f)\n"+ )+ finally:+ self._active_run_id = Noneif status != "ok" or not os.path.exists(envelope_path):return envelope.from_python_execution(status="error", error="The kernel did not return a result (it may have crashed — try re-running)."diff --git a/products/notebooks/backend/sandbox/kernel/runner.py b/products/notebooks/backend/sandbox/kernel/runner.pyindex bb491fed4424..bf29bbd9c441 100644--- a/products/notebooks/backend/sandbox/kernel/runner.py+++ b/products/notebooks/backend/sandbox/kernel/runner.py@@ -34,6 +34,28 @@ _MAX_CACHED_RESULTS = 20_result_cache: OrderedDict[str, dict[str, Any]] = OrderedDict()_result_cache_lock = threading.Lock()+# run_id -> {event, kernel}, registered for the lifetime of the run's execute_run call.+# /interrupt sets the event (cancels queued runs and data-plane waits) and SIGINTs the+# kernel only when the run is a kernel node actually executing a cell.+_cancel_states: dict[str, dict[str, Any]] = {}+_cancel_states_lock = threading.Lock()+++def request_interrupt(run_id: str) -> bool:+ """Handle an /interrupt for `run_id`; return whether the run was known (still in flight)."""+ with _cancel_states_lock:+ state = _cancel_states.get(run_id)+ if state is None:+ return False+ state["event"].set()+ if state["kernel"]:+ # Deferred so a pure-HogQL interrupt never imports jupyter_client (heavy, sandbox-only);+ # for a kernel-node run the module is already loaded, since the run itself imported it.+ from . import executor # noqa: PLC0415 — keeps jupyter_client off the server import path++ executor.get_executor().interrupt_for_run(run_id)+ return True+def execute_run(payload: dict[str, Any]) -> None:"""Entry point for a /run request, invoked on a background thread.@@ -42,26 +64,46 @@ def execute_run(payload: dict[str, Any]) -> None:runs in the ipykernel (materialize inputs, run code); a pure-HogQL display nodestays a capped data-plane fetch and never touches the kernel."""+ run_id = str(payload.get("run_id") or "")node = payload.get("node") or {}- if node.get("type") in ("python", "duckdb"):- result = _run_kernel_node(payload)- else:- result = _build_envelope(payload)+ is_kernel_node = node.get("type") in ("python", "duckdb")+ cancel_event = threading.Event()+ with _cancel_states_lock:+ # A retried /run for a run still in flight must not clobber its cancel state (the+ # interrupt would target the retry, and the first thread's exit would unregister it).+ # The in-flight thread owns the run and delivers its callback; drop the duplicate.+ if run_id in _cancel_states:+ logger.warning("nb_kernel ignoring duplicate /run for in-flight run %s", run_id)+ return+ _cancel_states[run_id] = {"event": cancel_event, "kernel": is_kernel_node}+ try:+ # Interrupt-caused failures are labeled at the source (DataPlaneInterrupted, a+ # SIGINT'd cell), so a real failure that merely raced the cancel keeps its error —+ # and a completed run stays ok: the result is real.+ if is_kernel_node:+ result = _run_kernel_node(payload, cancel_event)+ else:+ result = _build_envelope(payload, cancel_event)+ finally:+ with _cancel_states_lock:+ _cancel_states.pop(run_id, None)_post_callback(payload["callback_url"], payload["callback_token"], result)-def _run_kernel_node(payload: dict[str, Any]) -> dict[str, Any]:+def _run_kernel_node(payload: dict[str, Any], cancel_event: threading.Event) -> dict[str, Any]:# Deferred so the server startup path never imports jupyter_client (heavy, sandbox-only).from . import executor # noqa: PLC0415 — keeps jupyter_client off the server import pathtry:- return executor.get_executor().run_kernel_node(payload)+ return executor.get_executor().run_kernel_node(payload, cancel_event)except Exception as exc: # noqa: BLE001 — a run must always produce a callback envelopelogger.exception("nb_kernel kernel node run failed")return envelope.from_error(f"Node failed in the sandbox: {exc}")-def _fetch_capped_page(payload: dict[str, Any], limit: int, offset: int) -> dict[str, Any]:+def _fetch_capped_page(+ payload: dict[str, Any], limit: int, offset: int, cancel_event: threading.Event | None = None+) -> dict[str, Any]:"""Fetch limit+1 rows through the data plane; the extra row only signals has_more."""# Deferred so a broken pyarrow install degrades to a per-run error envelope# instead of preventing the server from starting.@@ -73,6 +115,7 @@ def _fetch_capped_page(payload: dict[str, Any], limit: int, offset: int) -> dictpayload["code"],limit=limit + 1,offset=offset,+ cancel_event=cancel_event,)has_more = len(rows) > limitreturn {"columns": columns, "rows": rows[:limit], "types": types, "has_more": has_more}@@ -108,13 +151,13 @@ def _cached_page(run_id: str, offset: int, limit: int) -> dict[str, Any] | None:}-def _build_envelope(payload: dict[str, Any]) -> dict[str, Any]:+def _build_envelope(payload: dict[str, Any], cancel_event: threading.Event | None = None) -> dict[str, Any]:from . import data_plane # noqa: PLC0415 — see _fetch_capped_pagepage_limit = int(payload.get("page_limit") or _DEFAULT_PAGE_LIMIT)cache_limit = max(int(payload.get("cache_limit") or _DEFAULT_CACHE_LIMIT), page_limit)try:- result = _fetch_capped_page(payload, limit=cache_limit, offset=0)+ result = _fetch_capped_page(payload, limit=cache_limit, offset=0, cancel_event=cancel_event)rows = envelope.json_safe_rows(result["rows"])run_id = str(payload.get("run_id") or "")if run_id:@@ -125,6 +168,8 @@ def _build_envelope(payload: dict[str, Any]) -> dict[str, Any]:result["types"],has_more=result["has_more"] or len(rows) > page_limit,)+ except data_plane.DataPlaneInterrupted:+ return envelope.as_interrupted(envelope.from_error(envelope.INTERRUPTED_MESSAGE))except data_plane.DataPlaneError as exc:return envelope.from_error(str(exc))except Exception as exc: # noqa: BLE001 — any failure must still produce a callbackdiff --git a/products/notebooks/backend/sandbox/kernel/server.py b/products/notebooks/backend/sandbox/kernel/server.pyindex 854172c46999..1872dfdd4252 100644--- a/products/notebooks/backend/sandbox/kernel/server.py+++ b/products/notebooks/backend/sandbox/kernel/server.py@@ -20,7 +20,7 @@ from http.server import BaseHTTPRequestHandler, ThreadingHTTPServerfrom typing import Anyfrom .auth import verify_command_token-from .runner import execute_run, fetch_page+from .runner import execute_run, fetch_page, request_interruptDEFAULT_PORT = 47821@@ -52,16 +52,16 @@ class KernelServerHandler(BaseHTTPRequestHandler):self._respond(202, {"accepted": True})returnif self.path == "/interrupt":- self._handle_interrupt()+ self._handle_interrupt(payload)returnself._handle_page(payload)- def _handle_interrupt(self) -> None:- # Deferred so the server startup path never imports jupyter_client (sandbox-only).- from . import executor # noqa: PLC0415 — keeps jupyter_client off the server import path-- executor.get_executor().interrupt()- self._respond(200, {"interrupted": True})+ def _handle_interrupt(self, payload: dict[str, Any]) -> None:+ # Run-scoped: cancels the run's queued/waiting phases via its cancel event and+ # SIGINTs the kernel only when this run is the cell executing right now. An+ # unknown run (already finished, or not yet delivered) is an idempotent noop.+ known = request_interrupt(str(payload.get("run_id") or ""))+ self._respond(200, {"interrupted": known, "known": known})def _handle_page(self, payload: dict[str, Any]) -> None:from . import data_plane, result_store # noqa: PLC0415 — keep pyarrow off the server startup pathdiff --git a/products/notebooks/backend/sql_v2.py b/products/notebooks/backend/sql_v2.pyindex 52abe98586fd..8d8981f2c50e 100644--- a/products/notebooks/backend/sql_v2.py+++ b/products/notebooks/backend/sql_v2.py@@ -59,6 +59,8 @@ _SERVER_READY_TIMEOUT_SECONDS = 15_RUN_POST_TIMEOUT_SECONDS = 10# A page fetch holds a web worker for the whole kernel -> data plane -> CH round trip._PAGE_POST_TIMEOUT_SECONDS = 60+# An interrupt only sets a cancel event and sends a SIGINT in the sandbox: near-instant.+_INTERRUPT_POST_TIMEOUT_SECONDS = 5# Safety-net TTL for the per-user page-fetch lock: sized just past the POST timeout so a# worker killed before its finally-release can't wedge the user's paging for long.PAGE_LOCK_TTL_SECONDS = _PAGE_POST_TIMEOUT_SECONDS + 10@@ -360,6 +362,38 @@ def fetch_sql_v2_page(notebook: Notebook, user: User | None, run: NotebookNodeRureturn response.json()+def interrupt_sql_v2_run(notebook: Notebook, user: User | None, run: NotebookNodeRun) -> bool:+ """Ask the kernel-server to interrupt a run; return whether the kernel knew the run.++ False means the run never reached the kernel (dispatch still in flight) or already+ finished there; the caller decides how to surface that. Raises SQLV2KernelNotRunning+ when no reachable kernel exists at all, in which case the run's callback can never+ arrive and the caller may mark the run terminal itself.+ """+ runtime = _find_running_runtime(notebook, user)+ if runtime is None or not runtime.server_url:+ raise SQLV2KernelNotRunning()++ command_token = mint_command_token(kernel_server_secret(str(runtime.id)), str(run.id))+ try:+ response = requests.post(+ f"{runtime.server_url.rstrip('/')}/interrupt",+ json={"run_id": str(run.id)},+ headers=_sandbox_auth_headers(runtime.server_connect_token, command_token),+ timeout=_INTERRUPT_POST_TIMEOUT_SECONDS,+ )+ except requests.RequestException as exc:+ raise SQLV2KernelNotRunning() from exc+ if response.status_code != 200:+ raise SQLV2KernelNotRunning()+ try:+ body = response.json()+ except ValueError:+ return True+ # A pre-run-scoped kernel-server omits `known`; treat its interrupt as delivered.+ return bool(body.get("known", True))++def _kernel_error_detail(response: requests.Response) -> str:try:detail = response.json().get("error")diff --git a/products/notebooks/backend/sql_v2_callback.py b/products/notebooks/backend/sql_v2_callback.pyindex 73090de888ee..dc77474171c5 100644--- a/products/notebooks/backend/sql_v2_callback.py+++ b/products/notebooks/backend/sql_v2_callback.py@@ -82,8 +82,11 @@ def notebook_sql_v2_callback(request, run_id: str) -> JsonResponse:except NotebookNodeRun.DoesNotExist:return JsonResponse({"error": "Run not found"}, status=404)- is_ok = envelope.get("status") == "ok"- run.status = NotebookNodeRun.Status.DONE if is_ok else NotebookNodeRun.Status.FAILED+ status_by_envelope = {+ "ok": NotebookNodeRun.Status.DONE,+ "interrupted": NotebookNodeRun.Status.INTERRUPTED,+ }+ run.status = status_by_envelope.get(envelope.get("status"), NotebookNodeRun.Status.FAILED)run.envelope = enveloperun.result_id = envelope.get("result_id")run.error = envelope.get("error")diff --git a/products/notebooks/backend/sql_v2_kernel_architecture.md b/products/notebooks/backend/sql_v2_kernel_architecture.mdindex 60ccae4c6c2f..fd9da557e215 100644--- a/products/notebooks/backend/sql_v2_kernel_architecture.md+++ b/products/notebooks/backend/sql_v2_kernel_architecture.md@@ -43,14 +43,14 @@ Sandbox (Modal / Docker container)Same server, same port, same HMAC command-token auth as today (`sql_v2.mint_command_token` / `_verify_command_token`), extended:-| Route | Sync? | Purpose |-| ---------------------- | ----- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |-| `GET /health` | sync | liveness + `{version, kernel_alive}` — version drives the redeploy handshake |-| `POST /run` | 202 | enqueue a node run; result arrives via callback |-| `POST /interrupt` | sync | `KernelManager.interrupt_kernel()` (SIGINT) for the active run |-| `POST /page` | sync | one result page — bounded, no callback. A hogql run re-queries the data plane with the run’s code + LIMIT/OFFSET; a kernel run (python/duckdb) sends `result_id` and slices its `/data/results/<result_id>.arrow` frame in the server process |-| `GET /state` | sync | list materialized frames, kernel variables, DuckDB tables (Journey 7) |-| `POST /kernel/restart` | sync | recycle the ipykernel child; frames on disk survive, namespace does not |+| Route | Sync? | Purpose |+| ---------------------- | ----- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |+| `GET /health` | sync | liveness + `{version, kernel_alive}` — version drives the redeploy handshake |+| `POST /run` | 202 | enqueue a node run; result arrives via callback |+| `POST /interrupt` | sync | run-scoped stop (Journey 9): sets the run's cancel event (aborts a queued run and its data-plane waits) and SIGINTs the kernel only when that run is the executing cell. Responds `{interrupted, known}`; `known: false` = already finished or never arrived (idempotent noop) |+| `POST /page` | sync | one result page — bounded, no callback. A hogql run re-queries the data plane with the run’s code + LIMIT/OFFSET; a kernel run (python/duckdb) sends `result_id` and slices its `/data/results/<result_id>.arrow` frame in the server process |+| `GET /state` | sync | list materialized frames, kernel variables, DuckDB tables (Journey 7) |+| `POST /kernel/restart` | sync | recycle the ipykernel child; frames on disk survive, namespace does not |The command token grows a **scope** claim: `run:<run_id>` (authorizes `/run`, `/interrupt` for that run) or `kernel:<runtime_id>` (authorizes `/page`, `/state`, `/kernel/restart`). Same HMAC scheme, signed payload becomes `{scope}.{exp}`.diff --git a/products/notebooks/backend/sql_v2_result_delivery.md b/products/notebooks/backend/sql_v2_result_delivery.mdindex 2e6ba1abc21b..1ec83efe7b6d 100644--- a/products/notebooks/backend/sql_v2_result_delivery.md+++ b/products/notebooks/backend/sql_v2_result_delivery.md@@ -12,9 +12,16 @@ terminal state.by reading the `NotebookNodeRun` row (one indexed query). No held connection,no busy-loop.- **Frontend:** the node polls that endpoint (~1s) while it has a `runId` and the- run is `running`; stops on `done`/`failed`. In-progress state is derived from- the run status, so it survives remounts and reloads. The poll timer lives in- `cache.disposables` (auto-cleanup + pause on hidden tab).+ run is `running`; stops on `done`/`failed`/`interrupted`. In-progress state is+ derived from the run status, so it survives remounts and reloads. The poll timer+ lives in `cache.disposables` (auto-cleanup + pause on hidden tab).+- **Interrupt (Journey 9):** `POST .../sql_v2/runs/<run_id>/interrupt` proxies a+ run-scoped stop to the kernel-server; the terminal state (`interrupted`) still+ arrives via the callback → run row → poll, keeping one source of truth. The+ interrupted envelope carries the stdout/stderr captured before the stop, and the+ result 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 (there is no backend watchdog yet).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 connectiondiff --git a/products/notebooks/backend/sql_v2_serializers.py b/products/notebooks/backend/sql_v2_serializers.pyindex b57e5410d4b4..d1d4a62d7a72 100644--- a/products/notebooks/backend/sql_v2_serializers.py+++ b/products/notebooks/backend/sql_v2_serializers.py@@ -95,7 +95,7 @@ class NotebookSQLV2MediaSerializer(serializers.Serializer):class NotebookSQLV2EnvelopeSerializer(serializers.Serializer):- status = serializers.CharField(help_text="Run outcome: 'ok' or 'error'.")+ status = serializers.CharField(help_text="Run outcome: 'ok', 'error', or 'interrupted' (user-requested stop).")stdout = serializers.CharField(required=False,default="",diff --git a/products/notebooks/backend/test/test_kernel_bootstrap.py b/products/notebooks/backend/test/test_kernel_bootstrap.pyindex aa0083016ca2..cc8c8c90d46e 100644--- a/products/notebooks/backend/test/test_kernel_bootstrap.py+++ b/products/notebooks/backend/test/test_kernel_bootstrap.py@@ -62,6 +62,14 @@ class TestKernelSessionRunNode(SimpleTestCase):self.assertEqual(envelope["status"], "error")self.assertIn("ValueError: boom", envelope["error"])+ def test_keyboard_interrupt_surfaces_as_interrupted_with_captured_output(self):+ # A SIGINT lands in run_cell as KeyboardInterrupt: the run is `interrupted`, not a+ # red failure, and the output captured before the stop still ships in the envelope.+ envelope = self._run("print('partial output')\nraise KeyboardInterrupt")+ self.assertEqual(envelope["status"], "interrupted")+ self.assertEqual(envelope["error"], "Run interrupted.")+ self.assertIn("partial output", envelope["stdout"])+def test_syntax_error_surfaces_as_error_envelope(self):# run_cell reports compile errors via error_before_exec (error_in_exec stays None);# they must not masquerade as a successful empty run stored as DONE.diff --git a/products/notebooks/backend/test/test_sql_v2.py b/products/notebooks/backend/test/test_sql_v2.pyindex 21a022e9f62b..e5b30a19855a 100644--- a/products/notebooks/backend/test/test_sql_v2.py+++ b/products/notebooks/backend/test/test_sql_v2.py@@ -31,7 +31,11 @@ from products.notebooks.backend.sandbox.kernel import (envelope as kernel_envelope,runner as kernel_runner,)-from products.notebooks.backend.sandbox.kernel.data_plane import DataPlaneError, decode_arrow_stream+from products.notebooks.backend.sandbox.kernel.data_plane import (+ DataPlaneError,+ DataPlaneInterrupted,+ decode_arrow_stream,+)from products.notebooks.backend.sql_v2 import (SQLV2KernelNotRunning,SQLV2PageError,@@ -115,6 +119,19 @@ class TestSQLV2Callback(APIBaseTest):self.assertEqual(run.envelope["first_page"], [[42]])self.assertEqual(str(run.result_id), str(self.node_run.id))+ def test_interrupted_envelope_marks_run_interrupted(self):+ # A user-requested stop must not surface as a red FAILED run, and the captured+ # output must be stored for the UI to show.+ token = mint_callback_token(str(self.node_run.id), self.team.id)+ response = self._post(+ token, envelope={"status": "interrupted", "stdout": "partial output", "error": "Run interrupted."}+ )+ self.assertEqual(response.status_code, 200)+ run = self._reload_run()+ self.assertEqual(run.status, NotebookNodeRun.Status.INTERRUPTED)+ self.assertEqual(run.envelope["stdout"], "partial output")+ self.assertEqual(run.error, "Run interrupted.")+def test_redelivery_is_idempotent(self):token = mint_callback_token(str(self.node_run.id), self.team.id)self._post(token)@@ -701,6 +718,14 @@ class TestSQLV2RunResult(APIBaseTest):(NotebookNodeRun.Status.RUNNING, None, "", None, None),(NotebookNodeRun.Status.DONE, {"first_page": [[42]]}, "", {"first_page": [[42]]}, None),(NotebookNodeRun.Status.FAILED, None, "boom", None, "boom"),+ # An interrupted run keeps its envelope: the captured stdout/stderr must reach the UI.+ (+ NotebookNodeRun.Status.INTERRUPTED,+ {"stdout": "partial"},+ "Run interrupted.",+ {"stdout": "partial"},+ "Run interrupted.",+ ),])@patch("products.notebooks.backend.presentation.views.notebook.is_sql_v2_enabled", return_value=True)@@ -710,7 +735,7 @@ class TestSQLV2RunResult(APIBaseTest):self.assertEqual(response.status_code, 200)body = response.json()self.assertEqual(body["status"], status)- # result is only surfaced when done; error only when failed+ # result is surfaced when done or interrupted; error when failed or interruptedself.assertEqual(body["result"], expected_result)self.assertEqual(body["error"], expected_error)@@ -738,6 +763,133 @@ class TestSQLV2RunResult(APIBaseTest):self.assertEqual(self.client.get(self._url(str(run.id))).status_code, 403)+class TestSQLV2RunInterrupt(APIBaseTest):+ def setUp(self):+ super().setUp()+ self.notebook = Notebook.objects.create(team=self.team, short_id="nbint01")+ with team_scope(self.team.id):+ self.node_run = NotebookNodeRun.objects.create(+ team=self.team,+ notebook=self.notebook,+ node_id="n1",+ status=NotebookNodeRun.Status.RUNNING,+ code="select event from events",+ )++ def _url(self, run_id: str) -> str:+ return f"/api/projects/{self.team.id}/notebooks/{self.notebook.short_id}/sql_v2/runs/{run_id}/interrupt/"++ def _create_runtime(self, user=None) -> KernelRuntime:+ return KernelRuntime.objects.create(+ team=self.team,+ notebook=self.notebook,+ notebook_short_id=self.notebook.short_id,+ user=user or self.user,+ status=KernelRuntime.Status.RUNNING,+ backend=KernelRuntime.Backend.DOCKER,+ sandbox_id="sbx-1",+ server_url="http://localhost:12345",+ server_connect_token="connect-tok",+ )++ def _reload_run(self) -> NotebookNodeRun:+ return NotebookNodeRun.objects.for_team(self.team.id).get(id=self.node_run.id)++ @patch("products.notebooks.backend.presentation.views.notebook.is_sql_v2_enabled", return_value=True)+ @patch("products.notebooks.backend.sql_v2.requests.post")+ def test_interrupt_posts_run_scoped_command_to_kernel(self, mock_post, _mock_enabled):+ mock_post.return_value.status_code = 200+ mock_post.return_value.json.return_value = {"interrupted": True, "known": True}+ runtime = self._create_runtime()++ response = self.client.post(self._url(str(self.node_run.id)))++ self.assertEqual(response.status_code, 202)+ self.assertIn("/interrupt", mock_post.call_args.args[0])+ headers = mock_post.call_args.kwargs["headers"]+ self.assertEqual(headers["Authorization"], "Bearer connect-tok")+ self.assertTrue(+ kernel_auth.verify_command_token(+ kernel_server_secret(str(runtime.id)), str(self.node_run.id), headers["X-Command-Token"]+ )+ )+ # The terminal state must come from the sandbox's callback, not from this endpoint.+ self.assertEqual(self._reload_run().status, NotebookNodeRun.Status.RUNNING)++ @parameterized.expand(+ [+ (NotebookNodeRun.Status.DONE,),+ (NotebookNodeRun.Status.FAILED,),+ (NotebookNodeRun.Status.INTERRUPTED,),+ ]+ )+ @patch("products.notebooks.backend.presentation.views.notebook.is_sql_v2_enabled", return_value=True)+ @patch("products.notebooks.backend.sql_v2.requests.post")+ def test_interrupt_of_terminal_run_never_reaches_the_kernel(self, status, mock_post, _mock_enabled):+ self._create_runtime()+ self.node_run.status = status+ self.node_run.save(update_fields=["status"])++ response = self.client.post(self._url(str(self.node_run.id)))++ self.assertEqual(response.status_code, 200)+ self.assertEqual(response.json()["status"], status)+ mock_post.assert_not_called()+ self.assertEqual(self._reload_run().status, status)++ @patch("products.notebooks.backend.presentation.views.notebook.is_sql_v2_enabled", return_value=True)+ def test_unreachable_kernel_marks_run_interrupted(self, _mock_enabled):+ # No kernel means the callback can never arrive; interrupt is the user's escape+ # hatch out of a RUNNING-forever row.+ response = self.client.post(self._url(str(self.node_run.id)))++ self.assertEqual(response.status_code, 200)+ run = self._reload_run()+ self.assertEqual(run.status, NotebookNodeRun.Status.INTERRUPTED)+ self.assertTrue(run.error)++ @patch("products.notebooks.backend.presentation.views.notebook.is_sql_v2_enabled", return_value=True)+ def test_run_on_a_collaborators_kernel_is_not_marked_terminal(self, _mock_enabled):+ # Kernels are per user: another editor's kernel may still be executing this run, so+ # the requester's unreachable-kernel path must not falsely terminate a live run.+ other_user = self._create_user("[email protected]")+ self._create_runtime(user=other_user)++ response = self.client.post(self._url(str(self.node_run.id)))++ self.assertEqual(response.status_code, 409)+ self.assertEqual(self._reload_run().status, NotebookNodeRun.Status.RUNNING)++ @patch("products.notebooks.backend.presentation.views.notebook.is_sql_v2_enabled", return_value=True)+ @patch("products.notebooks.backend.sql_v2.requests.post")+ def test_run_unknown_to_the_kernel_stays_running(self, mock_post, _mock_enabled):+ # Dispatch may still be in flight (Temporal): nothing was stopped, so the run must+ # not be marked terminal and the client is told to retry.+ mock_post.return_value.status_code = 200+ mock_post.return_value.json.return_value = {"interrupted": False, "known": False}+ self._create_runtime()++ response = self.client.post(self._url(str(self.node_run.id)))++ self.assertEqual(response.status_code, 202)+ self.assertIn("detail", response.json())+ self.assertEqual(self._reload_run().status, NotebookNodeRun.Status.RUNNING)++ @patch("products.notebooks.backend.presentation.views.notebook.is_sql_v2_enabled", return_value=True)+ def test_run_from_another_notebook_is_404(self, _mock_enabled):+ # IDOR guard: a run id from a different notebook must not be interruptible (or even+ # discoverable) through this notebook's endpoint.+ other_notebook = Notebook.objects.create(team=self.team, short_id="nbint02")+ with team_scope(self.team.id):+ other_run = NotebookNodeRun.objects.create(+ team=self.team, notebook=other_notebook, node_id="n1", status=NotebookNodeRun.Status.RUNNING+ )+ response = self.client.post(self._url(str(other_run.id)))+ self.assertEqual(response.status_code, 404)+ reloaded = NotebookNodeRun.objects.for_team(self.team.id).get(id=other_run.id)+ self.assertEqual(reloaded.status, NotebookNodeRun.Status.RUNNING)++class TestSQLV2Activities(APIBaseTest):def setUp(self):super().setUp()@@ -1079,6 +1231,15 @@ class TestSQLV2KernelServerHTTP(SimpleTestCase):self.assertEqual(response.status, 200) # pages are synchronousself.assertEqual(json.loads(response.read())["rows"], [[1]])+ # /interrupt is run-scoped: the handler passes the payload's run_id through and+ # reports whether the run was known, so the backend can distinguish a delivered+ # interrupt from a noop.+ with patch.object(kernel_server, "request_interrupt", return_value=False) as mock_interrupt:+ with post("/interrupt", token=token) as response:+ self.assertEqual(response.status, 200)+ self.assertEqual(json.loads(response.read())["known"], False)+ mock_interrupt.assert_called_once_with("run-1")+with self.assertRaises(urllib.error.HTTPError) as unknown:post("/nope", token=token)self.assertEqual(unknown.exception.code, 404)@@ -1206,6 +1367,154 @@ class TestSQLV2KernelPackage(SimpleTestCase):self.assertEqual(page["has_more"], expected_has_more)self.assertEqual(len(page["rows"]), expected_rows)+ def test_interrupt_mid_fetch_delivers_an_interrupted_callback(self):+ # The registry must be live while the fetch waits: an /interrupt arriving mid-fetch+ # has to be known, abort the wait, and turn the callback into `interrupted`.+ payload = {+ "run_id": "r-int-1",+ "code": "select 1",+ "callback_url": "http://backend/cb",+ "callback_token": "cbt",+ "data_plane_url": "http://backend/dp",+ "data_plane_token": "dpt",+ }+ delivered: dict = {}+ interrupt_known: list[bool] = []++ def fetch_then_interrupted(*args, **kwargs):+ interrupt_known.append(kernel_runner.request_interrupt("r-int-1"))+ raise DataPlaneInterrupted("Run interrupted.")++ with (+ patch.object(kernel_runner, "_post_callback", side_effect=lambda url, token, env: delivered.update(env)),+ patch(+ "products.notebooks.backend.sandbox.kernel.data_plane.fetch_query_page",+ side_effect=fetch_then_interrupted,+ ),+ ):+ kernel_runner.execute_run(payload)+ self.assertEqual(interrupt_known, [True])+ self.assertEqual(delivered["status"], "interrupted")+ self.assertEqual(delivered["error"], "Run interrupted.")+ # The run must be unregistered once finished: a later interrupt is unknown.+ self.assertFalse(kernel_runner.request_interrupt("r-int-1"))++ def test_real_error_racing_the_interrupt_keeps_its_message(self):+ # A genuine failure that completes just as the user cancels must not be+ # relabeled `interrupted` — the UI would lose the actual error.+ payload = {+ "run_id": "r-int-3",+ "code": "select 1",+ "callback_url": "http://backend/cb",+ "callback_token": "cbt",+ "data_plane_url": "http://backend/dp",+ "data_plane_token": "dpt",+ }+ delivered: dict = {}++ def fail_after_interrupt(*args, **kwargs):+ kernel_runner.request_interrupt("r-int-3")+ raise DataPlaneError("no such table")++ with (+ patch.object(kernel_runner, "_post_callback", side_effect=lambda url, token, env: delivered.update(env)),+ patch(+ "products.notebooks.backend.sandbox.kernel.data_plane.fetch_query_page",+ side_effect=fail_after_interrupt,+ ),+ ):+ kernel_runner.execute_run(payload)+ self.assertEqual(delivered["status"], "error")+ self.assertEqual(delivered["error"], "no such table")++ def test_duplicate_run_for_an_in_flight_run_is_dropped(self):+ # A backend /run retry while the first thread still runs must not clobber the+ # cancel state: the duplicate posts no callback and the original stays interruptible.+ payload = {+ "run_id": "r-dup-1",+ "code": "select 1",+ "callback_url": "http://backend/cb",+ "callback_token": "cbt",+ "data_plane_url": "http://backend/dp",+ "data_plane_token": "dpt",+ }+ callbacks: list[dict] = []+ dispatched: list[bool] = []++ def fetch_with_duplicate_dispatch(*args, **kwargs):+ if not dispatched:+ dispatched.append(True)+ kernel_runner.execute_run(dict(payload)) # the retry, arriving mid-run+ self.assertTrue(kernel_runner.request_interrupt("r-dup-1")) # original still registered+ raise DataPlaneInterrupted("Run interrupted.")++ with (+ patch.object(kernel_runner, "_post_callback", side_effect=lambda url, token, env: callbacks.append(env)),+ patch(+ "products.notebooks.backend.sandbox.kernel.data_plane.fetch_query_page",+ side_effect=fetch_with_duplicate_dispatch,+ ),+ ):+ kernel_runner.execute_run(payload)+ self.assertEqual(len(callbacks), 1)+ self.assertEqual(callbacks[0]["status"], "interrupted")+ # The finished run is unregistered — a fresh retry may now run.+ self.assertFalse(kernel_runner.request_interrupt("r-dup-1"))++ def test_completed_run_stays_ok_when_the_interrupt_races_it(self):+ # An interrupt that lands as the fetch completes must not discard a real result.+ payload = {+ "run_id": "r-int-2",+ "code": "select 1",+ "callback_url": "http://backend/cb",+ "callback_token": "cbt",+ "data_plane_url": "http://backend/dp",+ "data_plane_token": "dpt",+ }+ delivered: dict = {}++ def fetch_and_interrupt(*args, **kwargs):+ kernel_runner.request_interrupt("r-int-2")+ return (["n"], [(1,)], [["n", "Int64"]])++ with (+ patch.object(kernel_runner, "_post_callback", side_effect=lambda url, token, env: delivered.update(env)),+ patch(+ "products.notebooks.backend.sandbox.kernel.data_plane.fetch_query_page",+ side_effect=fetch_and_interrupt,+ ),+ ):+ kernel_runner.execute_run(payload)+ self.assertEqual(delivered["status"], "ok")+ self.assertEqual(delivered["first_page"], [[1]])++ def test_data_plane_poll_aborts_when_the_cancel_event_fires(self):+ # Without the in-loop cancel check, an interrupted HogQL run keeps a thread polling+ # for the full 180s budget and the interrupt does nothing for SQL cells.+ from products.notebooks.backend.sandbox.kernel import data_plane as kernel_data_plane++ class _FakeResponse(io.BytesIO):+ def __init__(self, body: bytes):+ super().__init__(body)+ self.headers = {"Content-Type": "application/json"}++ def __exit__(self, *args):+ return False++ cancel_event = threading.Event()++ def fake_urlopen(request, timeout=None):+ if request.full_url.endswith("/dp"):+ return _FakeResponse(b'{"query_id": "q1"}')+ cancel_event.set() # the interrupt lands while the query is still running+ return _FakeResponse(b'{"status": "running"}')++ with patch.object(kernel_data_plane.urllib.request, "urlopen", side_effect=fake_urlopen):+ with self.assertRaises(DataPlaneInterrupted):+ kernel_data_plane.fetch_query_page(+ "http://backend/dp", "t", "select 1", limit=5, cancel_event=cancel_event+ )+def test_kernel_polls_until_the_arrow_result_arrives(self):# The kernel must follow the enqueue → poll protocol: accept the 202 query_id,# keep polling through "running" responses, and decode the eventual Arrow 200.