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): bake the sqlv2 kernel into the notebook sandbox image (#82636)

Sinan Kucukkoselera0f2d3277b54
diff --git a/.github/workflows/cd-sandbox-base-image.yml b/.github/workflows/cd-sandbox-base-image.yml
index 8c8ef1d26968..bb3a84a1a0c4 100644
--- a/.github/workflows/cd-sandbox-base-image.yml
+++ b/.github/workflows/cd-sandbox-base-image.yml
@@ -11,6 +11,9 @@ on:
- 'products/tasks/backend/sandbox/images/**'
- 'products/*/skills/**'
- 'products/posthog_ai/scripts/**'
+ # The notebook image bakes this package and stamps its content hash.
+ - 'products/notebooks/backend/sandbox/kernel/**'
+ - 'products/notebooks/backend/kernel_package.py'
workflow_dispatch:
jobs:
@@ -44,6 +47,8 @@ jobs:
- 'products/tasks/backend/sandbox/images/**'
- 'products/*/skills/**'
- 'products/posthog_ai/scripts/**'
+ - 'products/notebooks/backend/sandbox/kernel/**'
+ - 'products/notebooks/backend/kernel_package.py'
build_skills:
needs: changes
diff --git a/products/notebooks/backend/kernel_package.py b/products/notebooks/backend/kernel_package.py
index f927580458ca..47656922c411 100644
--- a/products/notebooks/backend/kernel_package.py
+++ b/products/notebooks/backend/kernel_package.py
@@ -1,12 +1,24 @@
-"""Builds the deployable tarball of the in-sandbox kernel package.
+"""Packages the in-sandbox kernel so it can reach the sandbox two ways.
-The `kernel/` package ships into the sandbox as `nb_kernel/`: `ensure_sql_v2_server`
-writes the tarball, extracts it, and launches `python -m nb_kernel.server`. The
-content hash doubles as the server version — /health reports it, and a mismatch
-with the running server triggers a redeploy (the dev loop needs no image rebuild).
+The `kernel/` package runs in the sandbox as `nb_kernel/`. The notebook sandbox
+image bakes it under `BAKED_PACKAGE_ROOT` and stamps its content hash into
+`BAKED_VERSION_PATH`, so `ensure_sql_v2_server` launches it in place. When that
+stamp does not match the hash the backend expects, the same modules go over the
+control plane as a tarball instead. That covers a kernel edit no image build has
+picked up: every edit in the dev loop, and the window in production between
+merging a kernel change and its image reaching the registry.
+
+The content hash doubles as the server version, so /health reports it and a
+mismatch triggers a redeploy.
+
+Running this module as a script prints the hash, and `--baked-root` prints the
+directory the image bakes into. The image build calls it both ways, so the paths
+and the hash have one definition rather than a copy in the Dockerfile that can
+drift out of step with this one.
"""
import io
+import sys
import hashlib
import tarfile
from functools import lru_cache
@@ -14,6 +26,12 @@ from pathlib import Path
SANDBOX_PACKAGE_NAME = "nb_kernel"
+# Where Dockerfile.sandbox-notebook bakes the package. The modules land in
+# `<root>/nb_kernel/`, mirroring the tarball layout, so one PYTHONPATH and one
+# `-m nb_kernel.server` launch serve both roots.
+BAKED_PACKAGE_ROOT = "/opt/nb_kernel_pkg"
+BAKED_VERSION_PATH = f"{BAKED_PACKAGE_ROOT}/VERSION"
+
_KERNEL_DIR = Path(__file__).parent / "sandbox" / "kernel"
@@ -40,3 +58,8 @@ def kernel_package_bytes_and_hash() -> tuple[bytes, str]:
def kernel_package_hash() -> str:
return kernel_package_bytes_and_hash()[1]
+
+
+if __name__ == "__main__":
+ _answer = BAKED_PACKAGE_ROOT if "--baked-root" in sys.argv[1:] else kernel_package_hash()
+ sys.stdout.write(f"{_answer}\n")
diff --git a/products/notebooks/backend/sandbox/kernel/__init__.py b/products/notebooks/backend/sandbox/kernel/__init__.py
index 5f07164ae41a..066dc4dee2a9 100644
--- a/products/notebooks/backend/sandbox/kernel/__init__.py
+++ b/products/notebooks/backend/sandbox/kernel/__init__.py
@@ -1,10 +1,12 @@
"""The in-sandbox SQLV2 kernel-server, as a real package.
-Nothing here may import Django or posthog — this code is tarred up by
-`kernel_package.py`, written into the notebook sandbox, extracted as the
-`nb_kernel` package, and launched there (`python -m nb_kernel.server`). It may
-only use the stdlib plus the libraries baked into the notebook sandbox image
-(`Dockerfile.sandbox-notebook`): pyarrow, duckdb, pandas, jupyter_client.
+Nothing here may import Django or posthog. This code runs in the notebook sandbox
+as the `nb_kernel` package (`python -m nb_kernel.server`), reaching it either baked
+into the sandbox image or uploaded as a tarball by `kernel_package.py`. It may only
+use the stdlib plus the libraries baked into the notebook sandbox image
+(`Dockerfile.sandbox-notebook`): pyarrow, duckdb, pandas, jupyter_client. The image
+build imports every module here to hold that rule, so a new third-party import
+fails the build rather than the next cold start.
Intra-package imports must stay relative so the code works under both names
(`products.notebooks.backend.kernel` in tests, `nb_kernel` in the sandbox).
diff --git a/products/notebooks/backend/sql_v2.py b/products/notebooks/backend/sql_v2.py
index c9100c7ed574..70f0bf29cf08 100644
--- a/products/notebooks/backend/sql_v2.py
+++ b/products/notebooks/backend/sql_v2.py
@@ -24,7 +24,12 @@ import posthoganalytics
from posthog.models.user import User
-from products.notebooks.backend.kernel_package import SANDBOX_PACKAGE_NAME, kernel_package_bytes_and_hash
+from products.notebooks.backend.kernel_package import (
+ BAKED_PACKAGE_ROOT,
+ BAKED_VERSION_PATH,
+ SANDBOX_PACKAGE_NAME,
+ kernel_package_bytes_and_hash,
+)
from products.notebooks.backend.models import KernelRuntime, Notebook, NotebookNodeRun
from products.tasks.backend.facade.sandbox import SandboxBase, get_sandbox_class_for_backend
@@ -262,32 +267,73 @@ def _wait_for_server_ready(server_url: str, connect_token: str | None, expected_
raise RuntimeError("SQLV2 kernel-server did not become ready")
+# Stop a previous server via its PID file — never pkill by our own name: the
+# pattern would match this very launch command's shell and kill it mid-deploy.
+# The pkill lines only clear pre-package servers (distinct names, safe to
+# match) from sandboxes that predate the PID file; drop them once those age out.
+_STOP_PREVIOUS_SERVER = (
+ f"kill $(cat {_SERVER_PID_PATH} 2>/dev/null) 2>/dev/null || true; "
+ "pkill -f '[n]b_sql_v2_kernel_server' 2>/dev/null; pkill -f '[n]b_data_v2_kernel_server' 2>/dev/null; "
+)
+# Echoed by the baked launch so the caller can tell it ran from a matching image
+# rather than exiting early on a stale stamp.
+_BAKED_LAUNCH_MARKER = "nb_kernel_baked_ok"
+
+
+def _launch_server(package_root: str, port: int, version: str) -> str:
+ """Shell that backgrounds the kernel-server out of `package_root` and records its PID.
+
+ `< /dev/null` detaches the server from the exec's pipes so `execute` returns.
+ The backgrounded launch must stay a single simple command (PYTHONPATH= prefix,
+ no `cd X && …`) — a compound list backgrounds a wrapper subshell, so `$!`
+ would record the wrapper's PID and the next redeploy would kill nothing.
+ Prefer the notebook venv python (has pyarrow).
+ """
+ return (
+ 'PY=/opt/notebook-venv/bin/python3; [ -x "$PY" ] || PY=python3; '
+ f'PYTHONPATH={package_root} nohup "$PY" -m {SANDBOX_PACKAGE_NAME}.server '
+ f"--port {port} --secret-file {_SECRET_PATH} --version {version} "
+ f"> {_SERVER_LOG_PATH} 2>&1 < /dev/null & echo $! > {_SERVER_PID_PATH}"
+ )
+
+
+def _launch_baked_kernel_server(sandbox: SandboxBase, port: int, version: str) -> bool:
+ """Launch the package the image baked in, unless its stamp predates `version`.
+
+ Returns False on a stale stamp, having stopped the old server but started no
+ new one, so the caller falls back to the tarball. The version is a hex digest,
+ so it needs no shell quoting beyond the comparison's own quotes.
+ """
+ command = (
+ _STOP_PREVIOUS_SERVER
+ + f'[ "$(cat {BAKED_VERSION_PATH} 2>/dev/null)" = "{version}" ] || exit 0; '
+ + _launch_server(BAKED_PACKAGE_ROOT, port, version)
+ + f"; echo {_BAKED_LAUNCH_MARKER}"
+ )
+ result = sandbox.execute(command, timeout_seconds=30)
+ return _BAKED_LAUNCH_MARKER in result.stdout
+
+
def _deploy_kernel_server(sandbox: SandboxBase, runtime: KernelRuntime, package: bytes, version: str) -> None:
- """Write the kernel package + secret into the sandbox and (re)launch the server.
+ """Write the secret into the sandbox and (re)launch the kernel-server.
This is the only place the control plane (write_file/execute) is used, exactly
as Code bootstraps its agent-server. Per-run dispatch is a plain authed POST.
+
+ The image bakes the package, so the usual path is one execute that launches it
+ in place. Uploading the tarball is the fallback for a kernel edit no image build
+ has picked up yet, which keeps a merged kernel fix from waiting on an image.
"""
port = _CONTAINER_PORT_BY_BACKEND.get(runtime.backend, 47821)
sandbox.write_file(_SECRET_PATH, kernel_server_secret(str(runtime.id)).encode())
+ if _launch_baked_kernel_server(sandbox, port, version):
+ return
+
sandbox.write_file(_TARBALL_PATH, package)
- # Stop a previous server via its PID file — never pkill by our own name: the
- # pattern would match this very launch command's shell and kill it mid-deploy.
- # The pkill lines only clear pre-package servers (distinct names, safe to
- # match) from sandboxes that predate the PID file; drop them once those age out.
- # `< /dev/null` detaches the server from the exec's pipes so `execute` returns.
- # The backgrounded launch must stay a single simple command (PYTHONPATH= prefix,
- # no `cd X && …`) — a compound list backgrounds a wrapper subshell, so `$!`
- # would record the wrapper's PID and the next redeploy would kill nothing.
- # Prefer the notebook venv python (has pyarrow).
launch = (
- f"kill $(cat {_SERVER_PID_PATH} 2>/dev/null) 2>/dev/null || true; "
- "pkill -f '[n]b_sql_v2_kernel_server' 2>/dev/null; pkill -f '[n]b_data_v2_kernel_server' 2>/dev/null; "
- f"rm -rf {_PACKAGE_ROOT} && mkdir -p {_PACKAGE_ROOT} && tar -xzf {_TARBALL_PATH} -C {_PACKAGE_ROOT} && "
- 'PY=/opt/notebook-venv/bin/python3; [ -x "$PY" ] || PY=python3; '
- f'PYTHONPATH={_PACKAGE_ROOT} nohup "$PY" -m {SANDBOX_PACKAGE_NAME}.server '
- f"--port {port} --secret-file {_SECRET_PATH} --version {version} "
- f"> {_SERVER_LOG_PATH} 2>&1 < /dev/null & echo $! > {_SERVER_PID_PATH}"
+ _STOP_PREVIOUS_SERVER
+ + f"rm -rf {_PACKAGE_ROOT} && mkdir -p {_PACKAGE_ROOT} && tar -xzf {_TARBALL_PATH} -C {_PACKAGE_ROOT} && "
+ + _launch_server(_PACKAGE_ROOT, port, version)
)
sandbox.execute(launch, timeout_seconds=30)
@@ -296,8 +342,9 @@ def ensure_sql_v2_server(notebook: Notebook, user: User | None) -> KernelRuntime
"""Ensure the in-sandbox kernel-server is running the current package version.
Idempotent — a healthy server at the expected version is reused as-is; a stale
- or unreachable one is redeployed from the freshly built tarball (this is the
- dev loop: edit `kernel/`, next run redeploys, no image rebuild).
+ or unreachable one is redeployed, from the image's baked package when that
+ matches and from the freshly built tarball when it does not (this is the dev
+ loop: edit `kernel/`, next run redeploys, no image rebuild).
"""
runtime = _find_running_runtime(notebook, user)
if runtime is None:
diff --git a/products/notebooks/backend/sql_v2_kernel_architecture.md b/products/notebooks/backend/sql_v2_kernel_architecture.md
index c55c64a3afec..fae8fb712ffa 100644
--- a/products/notebooks/backend/sql_v2_kernel_architecture.md
+++ b/products/notebooks/backend/sql_v2_kernel_architecture.md
@@ -156,10 +156,14 @@ products/notebooks/kernel/ # or backend/kernel_src/ — sandbox-side co
└── envelope.py # envelope construction shared by executor/bootstrap
```
-Dependencies (`jupyter_client`, `pyarrow`, `duckdb`, `pandas`, `requests`) are already in `Dockerfile.sandbox-notebook`; no new image deps needed. Delivery:
+Dependencies (`jupyter_client`, `pyarrow`, `duckdb`, `pandas`, `requests`) are already in `Dockerfile.sandbox-notebook`; no new image deps needed. Delivery runs on two paths, both landing on the same `python -m nb_kernel.server --port … --secret-file … --version …` launch:
-- **Prod**: bake the package into the sandbox image (like Code's agent-server), launched as `python -m …kernel.server --port … --secret-file …`.
-- **Dev / iteration**: keep the `write_file` bootstrap in `ensure_sql_v2_server`, but upload a tarball of the package keyed by content hash; `/health` reports the hash, and a mismatch triggers re-upload + restart. Editing kernel code then needs no image rebuild.
+- **Baked (the normal path)**: `Dockerfile.sandbox-notebook` copies the package to `/opt/nb_kernel_pkg/nb_kernel/` and stamps its content hash into `/opt/nb_kernel_pkg/VERSION`. `_launch_baked_kernel_server` compares that stamp against the hash the backend expects and launches in place when they agree. No upload, no extract.
+- **Tarball (the fallback)**: when the stamp disagrees, the backend uploads the package as a tarball and launches from `/tmp/nb_kernel_pkg` instead. This covers both the dev loop (edit `kernel/`, next run redeploys, no image rebuild) and the window in production between merging a kernel change and its image reaching the registry. A merged kernel fix therefore never waits on an image build.
+
+`kernel_package.py` owns both the destination and the hash: the image build calls it for the bake path (`--baked-root`) and for the stamp, so the Dockerfile holds no second copy of either. A stale stamp is not an outage, only a lost optimization, because the deploy degrades to the tarball path it used before.
+
+`/health` reports the running hash either way, which is what drives the redeploy decision in `ensure_sql_v2_server`. Editing `products/notebooks/backend/sandbox/kernel/**` rebuilds the image through `cd-sandbox-base-image.yml`.
Because the package is plain Python with no Django imports, it gets normal unit tests in CI (auth round-trip, envelope building, run_node against a real in-process DuckDB, data-plane client against a stub Arrow server).
diff --git a/products/notebooks/backend/test/test_sql_v2.py b/products/notebooks/backend/test/test_sql_v2.py
index 19bdb579ef91..f0e515c88475 100644
--- a/products/notebooks/backend/test/test_sql_v2.py
+++ b/products/notebooks/backend/test/test_sql_v2.py
@@ -929,17 +929,25 @@ class TestSQLV2RunOnAConnection(APIBaseTest):
class _RecordingSandbox:
- """Stands in for the docker/Modal sandbox: records control-plane calls."""
+ """Stands in for the docker/Modal sandbox: records control-plane calls.
- def __init__(self):
+ `baked_version` stands in for the stamp the image carries. It defaults to None,
+ which is an image with no baked package at all, so the probe reports nothing and
+ the deploy falls back to the tarball.
+ """
+
+ def __init__(self, baked_version: str | None = None):
self.files: dict[str, bytes] = {}
self.commands: list[str] = []
+ self.baked_version = baked_version
def write_file(self, path: str, payload: bytes) -> None:
self.files[path] = payload
- def execute(self, command: str, timeout_seconds: int | None = None) -> None:
+ def execute(self, command: str, timeout_seconds: int | None = None):
self.commands.append(command)
+ launched_baked = self.baked_version is not None and f'= "{self.baked_version}"' in command
+ return SimpleNamespace(stdout="nb_kernel_baked_ok\n" if launched_baked else "", exit_code=0)
def get_connect_credentials(self):
return SimpleNamespace(url="http://localhost:45678", token="connect-tok")
@@ -987,21 +995,46 @@ class TestSQLV2EnsureServer(APIBaseTest):
package, _version = kernel_package_bytes_and_hash()
self.assertEqual(self.sandbox.files["/tmp/nb_kernel.tar.gz"], package)
self.assertEqual(self.sandbox.files["/tmp/nb_sql_v2_secret"], kernel_server_secret(str(runtime.id)).encode())
- self.assertEqual(len(self.sandbox.commands), 1)
self.assertEqual(result.server_url, "http://localhost:45678")
self.assertEqual(result.server_connect_token, "connect-tok")
- def test_launch_command_shape_regressions(self):
+ def test_image_without_the_current_package_still_gets_a_server(self):
+ # The baked probe stops the old server before it reads the stamp, so a miss that
+ # skipped the tarball would leave the sandbox with no server running at all.
+ self._create_runtime(server_url="http://localhost:1")
+ self.sandbox.baked_version = "an-older-image"
+ self._ensure(reported_version="some-old-version")
+ self.assertIn("/tmp/nb_kernel.tar.gz", self.sandbox.files)
+ self.assertIn("PYTHONPATH=/tmp/nb_kernel_pkg", self.sandbox.commands[-1])
+
+ def test_matching_image_launches_in_place_without_the_tarball(self):
+ # The upload and the tar extract are what baking the package removes. Losing the
+ # short-circuit costs a control-plane round trip on every cold start, and nothing
+ # at runtime shows it: both paths start an identical server.
+ self._create_runtime(server_url="http://localhost:1")
+ self.sandbox.baked_version = kernel_package_bytes_and_hash()[1]
+ self._ensure(reported_version="some-old-version")
+ self.assertNotIn("/tmp/nb_kernel.tar.gz", self.sandbox.files)
+ self.assertEqual(len(self.sandbox.commands), 1)
+ launch = self.sandbox.commands[0]
+ self.assertIn("PYTHONPATH=/opt/nb_kernel_pkg", launch)
+ self.assertNotIn("tar -xzf", launch)
+
+ @parameterized.expand([("baked", kernel_package_bytes_and_hash()[1]), ("tarball", None)])
+ def test_launch_command_shape_regressions(self, _name: str, baked_version: str | None):
# Two bugs shipped from this one string: pkill -f of our own module name matches
# the launch command's shell and kills the deploy; and backgrounding a compound
# command records a wrapper subshell PID so later redeploys kill nothing.
self._create_runtime(server_url="http://localhost:1")
+ self.sandbox.baked_version = baked_version
self._ensure(reported_version="some-old-version")
- launch = self.sandbox.commands[0]
+ launch = self.sandbox.commands[-1]
self.assertNotRegex(launch, r"pkill[^;&]*[^\[]nb_kernel")
self.assertIn("echo $! > /tmp/nb_kernel_server.pid", launch)
# The backgrounded segment must be a single simple command (no cd &&-chain).
- backgrounded = launch.rsplit(";", 1)[-1].split("&")[0]
+ nohup_segments = [segment for segment in launch.split(";") if "nohup" in segment]
+ self.assertEqual(len(nohup_segments), 1)
+ backgrounded = nohup_segments[0].split("&")[0]
self.assertNotIn("&&", backgrounded)
self.assertIn("nb_kernel.server", backgrounded)
diff --git a/products/tasks/backend/logic/services/modal_sandbox.py b/products/tasks/backend/logic/services/modal_sandbox.py
index 15429d953e83..8d97ba36fbc0 100644
--- a/products/tasks/backend/logic/services/modal_sandbox.py
+++ b/products/tasks/backend/logic/services/modal_sandbox.py
@@ -258,6 +258,10 @@ LOCAL_MODAL_DOCKERFILES = {
LOCAL_MODAL_INSTALL_SKILLS_SCRIPT = Path("products/tasks/backend/sandbox/images/install-skills.sh")
LOCAL_MODAL_GIT_GUARD_SCRIPT = Path("products/tasks/backend/sandbox/images/git-guard.sh")
LOCAL_MODAL_GH_GUARD_SCRIPT = Path("products/tasks/backend/sandbox/images/gh-guard.sh")
+# The notebook image bakes the notebooks SQLV2 kernel and stamps its content hash,
+# so a local build context needs the package and the module that computes the hash.
+LOCAL_MODAL_NOTEBOOK_KERNEL_MODULE = Path("products/notebooks/backend/kernel_package.py")
+LOCAL_MODAL_NOTEBOOK_KERNEL_DIR = Path("products/notebooks/backend/sandbox/kernel")
_image_ref_cache: TTLCache = TTLCache(maxsize=3, ttl=300)
@@ -612,6 +616,18 @@ def _prepare_local_modal_build_context(template: SandboxTemplate) -> tuple[str,
LocalSkillsCache(base_dir).ensure_built()
populate_skills_directory(context_dir / LOCAL_BUILT_SKILLS_PATH, base_dir=base_dir)
+ elif template == SandboxTemplate.NOTEBOOK_BASE:
+ destination_kernel_module_path = context_dir / LOCAL_MODAL_NOTEBOOK_KERNEL_MODULE
+ destination_kernel_module_path.parent.mkdir(parents=True, exist_ok=True)
+ shutil.copy2(base_dir / LOCAL_MODAL_NOTEBOOK_KERNEL_MODULE, destination_kernel_module_path)
+ # A checkout that ran the tests locally has bytecode here, and this context
+ # bypasses .dockerignore, so drop it rather than bake it into the image.
+ shutil.copytree(
+ base_dir / LOCAL_MODAL_NOTEBOOK_KERNEL_DIR,
+ context_dir / LOCAL_MODAL_NOTEBOOK_KERNEL_DIR,
+ ignore=shutil.ignore_patterns("__pycache__"),
+ )
+
elif template == SandboxTemplate.STREAMLIT_BASE:
# Copy all sibling files (streamlit_auth_proxy.py, etc.)
# needed by COPY instructions in the Dockerfile
diff --git a/products/tasks/backend/logic/services/test_modal_sandbox.py b/products/tasks/backend/logic/services/test_modal_sandbox.py
index d17355b3f5dc..b81e80736ea5 100644
--- a/products/tasks/backend/logic/services/test_modal_sandbox.py
+++ b/products/tasks/backend/logic/services/test_modal_sandbox.py
@@ -1,3 +1,6 @@
+import shutil
+from pathlib import Path
+
import pytest
from unittest.mock import MagicMock
@@ -8,10 +11,13 @@ from products.tasks.backend.constants import (
)
from products.tasks.backend.logic.services.modal_sandbox import (
DEFAULT_MODAL_APP_NAME,
+ LOCAL_MODAL_NOTEBOOK_KERNEL_DIR,
+ LOCAL_MODAL_NOTEBOOK_KERNEL_MODULE,
NOTEBOOK_MODAL_APP_NAME,
SELF_DRIVING_MODAL_APP_NAME,
STREAMLIT_MODAL_APP_NAME,
ModalSandbox,
+ _prepare_local_modal_build_context,
)
from products.tasks.backend.logic.services.sandbox import (
SELF_DRIVING_ORIGIN_PRODUCTS,
@@ -211,3 +217,20 @@ class TestSelfDrivingWorkloadMapping:
# The set is held as strings to keep the sandbox layer model-free, so a renamed or
# removed OriginProduct would otherwise silently drop that product out of the fleet.
assert SELF_DRIVING_ORIGIN_PRODUCTS <= {choice.value for choice in Task.OriginProduct}
+
+
+class TestLocalModalBuildContext:
+ def test_notebook_context_carries_the_baked_kernel_package(self):
+ # DEBUG builds the notebook image from this trimmed context, not the repo root, so a
+ # Dockerfile COPY whose source is missing here fails the build and no notebook
+ # sandbox starts. The registry path in production never exercises it.
+ _prepare_local_modal_build_context.cache_clear()
+ _dockerfile_path, context_dir = _prepare_local_modal_build_context(SandboxTemplate.NOTEBOOK_BASE)
+ try:
+ root = Path(context_dir)
+ assert (root / LOCAL_MODAL_NOTEBOOK_KERNEL_MODULE).is_file()
+ assert (root / LOCAL_MODAL_NOTEBOOK_KERNEL_DIR / "server.py").is_file()
+ assert not (root / LOCAL_MODAL_NOTEBOOK_KERNEL_DIR / "__pycache__").exists()
+ finally:
+ shutil.rmtree(context_dir, ignore_errors=True)
+ _prepare_local_modal_build_context.cache_clear()
diff --git a/products/tasks/backend/sandbox/images/Dockerfile.sandbox-notebook b/products/tasks/backend/sandbox/images/Dockerfile.sandbox-notebook
index 53594108094d..9daa974934dd 100644
--- a/products/tasks/backend/sandbox/images/Dockerfile.sandbox-notebook
+++ b/products/tasks/backend/sandbox/images/Dockerfile.sandbox-notebook
@@ -136,4 +136,23 @@ RUN python3 --version && \
node --version && \
npm --version
+# Bake the notebooks SQLV2 kernel package. The backend launches it from here when
+# the stamp matches the package hash it expects, and uploads the same modules as a
+# tarball when it does not, so a kernel edit never waits on an image build.
+# kernel_package.py supplies both the destination and the stamp, so this image and
+# the backend cannot drift apart on where the package lives or how its hash is
+# derived. This stays last because it invalidates on every kernel edit and the pip
+# layer above is expensive to rebuild. The import check enforces the package's rule
+# that it may only use libraries this image already carries.
+COPY products/notebooks/backend/kernel_package.py /tmp/nb_kernel_build/kernel_package.py
+COPY products/notebooks/backend/sandbox/kernel/ /tmp/nb_kernel_build/sandbox/kernel/
+RUN ROOT="$(python3 /tmp/nb_kernel_build/kernel_package.py --baked-root)" && \
+ mkdir -p "$ROOT" && \
+ cp -R /tmp/nb_kernel_build/sandbox/kernel "$ROOT/nb_kernel" && \
+ python3 /tmp/nb_kernel_build/kernel_package.py > "$ROOT/VERSION" && \
+ rm -rf /tmp/nb_kernel_build && \
+ test -s "$ROOT/VERSION" && \
+ PYTHONPATH="$ROOT" python3 -c \
+ "import nb_kernel.server, nb_kernel.executor, nb_kernel.bootstrap, nb_kernel.result_store"
+
CMD ["/bin/bash"]