: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): price a sandbox at the managed warehouse compute rates (#91021)
Sinan Kucukkoseler9bf3f6838e86
diff --git a/products/notebooks/backend/compute_pricing.py b/products/notebooks/backend/compute_pricing.pynew file mode 100644index 000000000000..d6a68a81ec97--- /dev/null+++ b/products/notebooks/backend/compute_pricing.py@@ -0,0 +1,112 @@+from __future__ import annotations++from posthog.dataclasses import frozen+from posthog.utils import get_instance_region++# A notebook sandbox costs its CPU rate plus its memory rate, for every hour it stays alive.+# The rates match managed warehouse compute, so the same sandbox shape costs the same in both+# products. They price what a sandbox reserves, not what it uses, because the reservation is+# what we hold for the user.+_US_CPU_RATE_PER_CORE_HOUR = 0.20+_US_MEMORY_RATE_PER_GB_HOUR = 0.025++# The EU region runs 15% above the US region.+_EU_RATE_MULTIPLIER = 1.15+++@frozen+class ComputeRates:+ cpu_per_core_hour: float+ memory_per_gb_hour: float++ def hourly_price(self, *, cpu_cores: float, memory_gb: float) -> float:+ return round(cpu_cores * self.cpu_per_core_hour + memory_gb * self.memory_per_gb_hour, 4)+++@frozen+class ComputeShape:+ """The cpu and memory a sandbox runs on, which is all the rates need to price it."""++ cpu_cores: float+ memory_gb: float+++@frozen+class ComputePreset:+ key: str+ name: str+ description: str+ cpu_cores: float+ memory_gb: float+++_US_RATES = ComputeRates(+ cpu_per_core_hour=_US_CPU_RATE_PER_CORE_HOUR,+ memory_per_gb_hour=_US_MEMORY_RATE_PER_GB_HOUR,+)+_EU_RATES = ComputeRates(+ cpu_per_core_hour=round(_US_CPU_RATE_PER_CORE_HOUR * _EU_RATE_MULTIPLIER, 5),+ memory_per_gb_hour=round(_US_MEMORY_RATE_PER_GB_HOUR * _EU_RATE_MULTIPLIER, 5),+)++# A preset only saves the user the sizing decision, because the two rates price any shape they+# pick. The shapes step apart far enough that a user who outgrows one knows which to take next.+COMPUTE_PRESETS: tuple[ComputePreset, ...] = (+ ComputePreset(+ key="small",+ name="Small",+ description="Exploring data and working with small dataframes.",+ cpu_cores=1,+ memory_gb=2,+ ),+ ComputePreset(+ key="balanced",+ name="Balanced",+ description="Most analysis work.",+ cpu_cores=4,+ memory_gb=8,+ ),+ ComputePreset(+ key="large",+ name="Large",+ description="Large joins and cells that run for a while.",+ cpu_cores=8,+ memory_gb=16,+ ),+ ComputePreset(+ key="high_memory",+ name="High memory",+ description="Dataframes that run out of memory on the other presets.",+ cpu_cores=8,+ memory_gb=32,+ ),+)++DEFAULT_COMPUTE_PRESET_KEY = "small"+++def get_compute_rates(region: str | None = None) -> ComputeRates:+ """The rates that apply to this instance. Anything that is not EU is priced at US rates."""+ resolved_region = region if region is not None else get_instance_region()+ return _EU_RATES if resolved_region == "EU" else _US_RATES+++def get_default_compute_preset() -> ComputePreset:+ return get_compute_preset(DEFAULT_COMPUTE_PRESET_KEY)+++def get_compute_preset(key: str) -> ComputePreset:+ for preset in COMPUTE_PRESETS:+ if preset.key == key:+ return preset+ raise ValueError(f"Unknown compute preset: {key}")+++def find_matching_preset(*, cpu_cores: float | None, memory_gb: float | None) -> ComputePreset | None:+ """The preset a sandbox shape came from, or None when the user tuned it themselves."""+ if cpu_cores is None or memory_gb is None:+ return None+ for preset in COMPUTE_PRESETS:+ if abs(preset.cpu_cores - cpu_cores) < 1e-6 and abs(preset.memory_gb - memory_gb) < 1e-6:+ return preset+ return Nonediff --git a/products/notebooks/backend/facade/compute_pricing.py b/products/notebooks/backend/facade/compute_pricing.pynew file mode 100644index 000000000000..11ebc3c556a0--- /dev/null+++ b/products/notebooks/backend/facade/compute_pricing.py@@ -0,0 +1,15 @@+"""+Facade re-exports for notebook sandbox compute pricing.++The kernel endpoints quote what a sandbox costs, so the HTTP surface needs the rates, the+presets, and the shape-to-preset lookup. Presentation may only reach in-product code through+this package, so the rate table stays in `compute_pricing` and is re-exported here.+"""++from ..compute_pricing import (+ COMPUTE_PRESETS as COMPUTE_PRESETS,+ DEFAULT_COMPUTE_PRESET_KEY as DEFAULT_COMPUTE_PRESET_KEY,+ ComputeShape as ComputeShape,+ find_matching_preset as find_matching_preset,+ get_compute_rates as get_compute_rates,+)diff --git a/products/notebooks/backend/kernel_runtime.py b/products/notebooks/backend/kernel_runtime.pyindex c280de4d91da..7af3aa8099e9 100644--- a/products/notebooks/backend/kernel_runtime.py+++ b/products/notebooks/backend/kernel_runtime.py@@ -22,6 +22,7 @@ from posthog.hogql.query import execute_hogql_queryfrom posthog.models import Team, Userfrom posthog.redis import get_client+from products.notebooks.backend.compute_pricing import get_default_compute_presetfrom products.notebooks.backend.models import KernelRuntime, Notebookfrom products.tasks.backend.facade.sandbox import (SandboxBase,@@ -235,11 +236,12 @@ class KernelRuntimeSession:def build_notebook_sandbox_config(notebook: Notebook) -> SandboxConfig:+ default_preset = get_default_compute_preset()sandbox_config = SandboxConfig(name=f"notebook-kernel-{notebook.short_id}",template=SandboxTemplate.NOTEBOOK_BASE,- cpu_cores=1,- memory_gb=2,+ cpu_cores=default_preset.cpu_cores,+ memory_gb=default_preset.memory_gb,ttl_seconds=NOTEBOOK_KERNEL_TTL_SECONDS,)if notebook.kernel_cpu_cores:@@ -779,6 +781,11 @@ class KernelRuntimeService:connection_file = f"/tmp/jupyter/kernel-{runtime.id}.json"kernel_id = f"kernel-{runtime.id}"sandbox_config = build_notebook_sandbox_config(notebook)+ # Record the shape this sandbox gets, so the price can describe what is running rather+ # than what the notebook is configured for. The two diverge until a restart.+ runtime.provisioned_cpu_cores = sandbox_config.cpu_cores+ runtime.provisioned_memory_gb = sandbox_config.memory_gb+ runtime.save(update_fields=["provisioned_cpu_cores", "provisioned_memory_gb"])sandbox_class = self._get_sandbox_class(backend)try:sandbox = sandbox_class.create(sandbox_config)diff --git a/products/notebooks/backend/migrations/0017_kernelruntime_provisioned_cpu_cores_and_more.py b/products/notebooks/backend/migrations/0017_kernelruntime_provisioned_cpu_cores_and_more.pynew file mode 100644index 000000000000..8d1c60dcb976--- /dev/null+++ b/products/notebooks/backend/migrations/0017_kernelruntime_provisioned_cpu_cores_and_more.py@@ -0,0 +1,22 @@+# Generated by Django 5.2.17 on 2026-09-01 14:51++from django.db import migrations, models+++class Migration(migrations.Migration):+ dependencies = [+ ("notebooks", "0016_generatedwidgetversion_security_review_findings_and_more"),+ ]++ operations = [+ migrations.AddField(+ model_name="kernelruntime",+ name="provisioned_cpu_cores",+ field=models.FloatField(blank=True, null=True),+ ),+ migrations.AddField(+ model_name="kernelruntime",+ name="provisioned_memory_gb",+ field=models.FloatField(blank=True, null=True),+ ),+ ]diff --git a/products/notebooks/backend/migrations/max_migration.txt b/products/notebooks/backend/migrations/max_migration.txtindex b0ae6f0238b8..36ffd37f26de 100644--- a/products/notebooks/backend/migrations/max_migration.txt+++ b/products/notebooks/backend/migrations/max_migration.txt@@ -1 +1 @@-0016_generatedwidgetversion_security_review_findings_and_more+0017_kernelruntime_provisioned_cpu_cores_and_morediff --git a/products/notebooks/backend/models.py b/products/notebooks/backend/models.pyindex 61e7cecb0cb0..deb0e3314bdf 100644--- a/products/notebooks/backend/models.py+++ b/products/notebooks/backend/models.py@@ -188,6 +188,12 @@ class KernelRuntime(UUIDTModel):# arrive out of order, so a slow older callback must not overwrite a newer snapshot. Runs# are created before dispatch, so created_at orders them the same way the kernel ran them.frames_run_created_at = models.DateTimeField(null=True, blank=True)+ # The shape this sandbox was actually provisioned with. The notebook holds the configured+ # shape, which a live kernel does not adopt until it restarts, so pricing the running sandbox+ # needs the size recorded here rather than derived from the notebook. Null on rows created+ # before this was captured.+ provisioned_cpu_cores = models.FloatField(null=True, blank=True)+ provisioned_memory_gb = models.FloatField(null=True, blank=True)class Meta:db_table = "posthog_kernelruntime"diff --git a/products/notebooks/backend/presentation/views/notebook.py b/products/notebooks/backend/presentation/views/notebook.pyindex 938ae677ac6f..9a7558dc8ef2 100644--- a/products/notebooks/backend/presentation/views/notebook.py+++ b/products/notebooks/backend/presentation/views/notebook.py@@ -64,6 +64,13 @@ from products.notebooks.backend.analytics import (notebook_node_count,)from products.notebooks.backend.collab import submit_steps+from products.notebooks.backend.facade.compute_pricing import (+ COMPUTE_PRESETS,+ DEFAULT_COMPUTE_PRESET_KEY,+ ComputeShape,+ find_matching_preset,+ get_compute_rates,+)from products.notebooks.backend.facade.contracts import NotebookRunBusy, TeamRunCapacityFullfrom products.notebooks.backend.facade.sql_v2 import acquire_run_slots, release_run_slotsfrom products.notebooks.backend.facade.widgets import (@@ -122,6 +129,7 @@ from products.notebooks.backend.sql_v2_references import (from products.notebooks.backend.sql_v2_runs import expire_stale_kernel_run, finish_node_runfrom products.notebooks.backend.sql_v2_serializers import (MAX_VARIABLES_PER_NOTEBOOK,+ NotebookComputeOptionsResponseSerializer,NotebookKernelConfigResponseSerializer,NotebookKernelStatusResponseSerializer,NotebookSQLV2InterruptResponseSerializer,@@ -1315,34 +1323,42 @@ class NotebookViewSet(TeamAndOrgViewSetMixin, AccessControlViewSetMixin, ForbidDruntime.status = statusruntime.save(update_fields=["status"])- return Response(- {- "backend": backend,- "status": status,- "last_used_at": runtime.last_used_at.isoformat() if runtime else None,- "last_error": runtime.last_error if runtime else None,- "runtime_id": str(runtime.id) if runtime else None,- "kernel_id": runtime.kernel_id if runtime else None,- "kernel_pid": runtime.kernel_pid if runtime else None,- "sandbox_id": runtime.sandbox_id if runtime else None,- # Journey 7: what a SQL node can currently SELECT from. Gated twice. On the- # live-checked status, not runtime.status — the row above is the latest by- # last_used_at regardless of state, and a dead kernel's frames are not- # SELECT-able. And on query access, because these are column names and types- # derived from the user's data: notebook access alone gates liveness (which is- # all this endpoint used to return), but not schema. The rest of SQLV2 draws- # that line already; this keeps the endpoint's existing surface ungated.- "frames": (- (runtime.frames or [])- if runtime and status == KernelRuntime.Status.RUNNING and self._has_query_access()- else []- ),- "cpu_cores": cpu_cores,- "memory_gb": sandbox_config.memory_gb,- "disk_size_gb": sandbox_config.disk_size_gb,- "idle_timeout_seconds": sandbox_config.ttl_seconds,- }+ # A running sandbox keeps the shape it started with, so price that rather than the+ # notebook's configuration. They differ between a resize and the restart that applies it.+ is_live = status in (KernelRuntime.Status.RUNNING, KernelRuntime.Status.STARTING)+ priced = self._priced_shape(+ runtime if is_live else None,+ ComputeShape(cpu_cores=cpu_cores, memory_gb=sandbox_config.memory_gb),)+ payload = {+ "backend": backend,+ "status": status,+ "last_used_at": runtime.last_used_at.isoformat() if runtime else None,+ "last_error": runtime.last_error if runtime else None,+ "runtime_id": str(runtime.id) if runtime else None,+ "kernel_id": runtime.kernel_id if runtime else None,+ "kernel_pid": runtime.kernel_pid if runtime else None,+ "sandbox_id": runtime.sandbox_id if runtime else None,+ # Journey 7: what a SQL node can currently SELECT from. Gated twice. On the+ # live-checked status, not runtime.status — the row above is the latest by+ # last_used_at regardless of state, and a dead kernel's frames are not+ # SELECT-able. And on query access, because these are column names and types+ # derived from the user's data: notebook access alone gates liveness (which is+ # all this endpoint used to return), but not schema. The rest of SQLV2 draws+ # that line already; this keeps the endpoint's existing surface ungated.+ "frames": (+ (runtime.frames or [])+ if runtime and status == KernelRuntime.Status.RUNNING and self._has_query_access()+ else []+ ),+ "cpu_cores": cpu_cores,+ "memory_gb": sandbox_config.memory_gb,+ "disk_size_gb": sandbox_config.disk_size_gb,+ "idle_timeout_seconds": sandbox_config.ttl_seconds,+ "hourly_price": get_compute_rates().hourly_price(cpu_cores=priced.cpu_cores, memory_gb=priced.memory_gb),+ "preset_key": self._preset_key_for(priced.cpu_cores, priced.memory_gb),+ }+ return Response(NotebookKernelStatusResponseSerializer(payload).data)@extend_schema(request=NotebookKernelConfigSerializer,@@ -1358,6 +1374,10 @@ class NotebookViewSet(TeamAndOrgViewSetMixin, AccessControlViewSetMixin, ForbidDserializer.is_valid(raise_exception=True)notebook = self._get_notebook_for_kernel()update_fields = []+ # A sandbox takes its size at provision time, so a live one keeps the old shape until it+ # restarts. Capture the shape before the write as the fallback baseline for the restart+ # decision, used when no runtime has recorded the running shape.+ shape_before = build_notebook_sandbox_config(notebook)if "cpu_cores" in serializer.validated_data:notebook.kernel_cpu_cores = serializer.validated_data["cpu_cores"]@@ -1372,18 +1392,139 @@ class NotebookViewSet(TeamAndOrgViewSetMixin, AccessControlViewSetMixin, ForbidDif notebook.pk:notebook.save(update_fields=update_fields)- return Response(- {- "cpu_cores": notebook.kernel_cpu_cores,- "memory_gb": notebook.kernel_memory_gb,- "idle_timeout_seconds": notebook.kernel_idle_timeout_seconds,- "restart_required": KernelRuntime.objects.filter(- team_id=self.team_id,- notebook_short_id=notebook.short_id,- status__in=(KernelRuntime.Status.RUNNING, KernelRuntime.Status.STARTING),- ).exists(),- }+ # Price the shape the next sandbox will actually get, so a notebook that leaves one knob+ # unset is still quoted against the default that fills it in.+ configured = build_notebook_sandbox_config(notebook)+ # Scoped to the requester, like kernel_status: runtimes are per user, and restarting on a+ # collaborator's row would provision a paid sandbox for whoever called this while leaving+ # that collaborator on the old shape.+ config_user = self._current_user()+ live_runtime = (+ KernelRuntime.objects.filter(+ team_id=self.team_id,+ notebook_short_id=notebook.short_id,+ user=config_user if isinstance(config_user, User) else None,+ status__in=(KernelRuntime.Status.RUNNING, KernelRuntime.Status.STARTING),+ )+ .order_by("-last_used_at")+ .first()+ )+ # A RUNNING row can outlive its sandbox, and restarting on a stale one would turn a+ # config-only call into new paid compute. Confirm the sandbox before acting on the row.+ kernel_is_live = live_runtime is not None and self._sandbox_is_running(notebook, config_user, live_runtime)+ # Compare the desired shape against what the running sandbox was provisioned with, not just+ # this request's change, so a retry after a failed restart still triggers one. Fall back to+ # the pre-write config when no runtime has recorded a shape.+ running = self._priced_shape(+ live_runtime,+ ComputeShape(cpu_cores=shape_before.cpu_cores, memory_gb=shape_before.memory_gb),+ )+ shape_changed = (+ abs(running.cpu_cores - configured.cpu_cores) > 1e-6 or abs(running.memory_gb - configured.memory_gb) > 1e-6+ )++ # Restart on a resize so the quoted price describes the sandbox that is actually running.+ # Only on a resize: a restart discards every materialized dataframe, which is too much to+ # spend on an idle-timeout change that a live sandbox cannot pick up anyway.+ restarted = False+ if kernel_is_live and shape_changed:+ try:+ get_kernel_runtime(notebook, config_user).restart()+ restarted = True+ except (SandboxProvisionError, RuntimeError):+ logger.exception("notebook_kernel_config_restart_failed", notebook_short_id=notebook.short_id)+ # The configuration stays saved: it is what the next sandbox gets. Status prices+ # the runtime's own shape while one is alive, so a failed restart no longer makes+ # the panel quote a sandbox nobody is on.++ # Price the same thing status prices, so the field does not mean the running sandbox on+ # one endpoint and the configuration on the other. After a restart this is the new+ # sandbox; after a failed one it is the old sandbox still serving the notebook.+ priced_runtime = (+ KernelRuntime.objects.filter(+ team_id=self.team_id,+ notebook_short_id=notebook.short_id,+ user=config_user if isinstance(config_user, User) else None,+ status__in=(KernelRuntime.Status.RUNNING, KernelRuntime.Status.STARTING),+ )+ .order_by("-last_used_at")+ .first()+ )+ priced = self._priced_shape(+ priced_runtime,+ ComputeShape(cpu_cores=configured.cpu_cores, memory_gb=configured.memory_gb),)+ config_payload = {+ "cpu_cores": notebook.kernel_cpu_cores,+ "memory_gb": notebook.kernel_memory_gb,+ "idle_timeout_seconds": notebook.kernel_idle_timeout_seconds,+ "restarted": restarted,+ "restart_required": kernel_is_live and not restarted,+ "hourly_price": get_compute_rates().hourly_price(cpu_cores=priced.cpu_cores, memory_gb=priced.memory_gb),+ "preset_key": self._preset_key_for(priced.cpu_cores, priced.memory_gb),+ }+ return Response(NotebookKernelConfigResponseSerializer(config_payload).data)++ def _priced_shape(self, runtime: KernelRuntime | None, fallback: ComputeShape) -> ComputeShape:+ """The shape hourly_price describes: what a live sandbox runs, else what the next one gets.++ Both kernel endpoints price through this so the field means one thing. A runtime from+ before the shape was recorded reads as unknown and falls back.+ """+ if runtime and runtime.provisioned_cpu_cores is not None and runtime.provisioned_memory_gb is not None:+ return ComputeShape(cpu_cores=runtime.provisioned_cpu_cores, memory_gb=runtime.provisioned_memory_gb)+ return fallback++ def _sandbox_is_running(self, notebook: Notebook, user: Any, runtime: KernelRuntime) -> bool:+ """Whether the runtime row still has a sandbox behind it, the check kernel_status makes."""+ if not runtime.sandbox_id or runtime.backend not in (+ KernelRuntime.Backend.MODAL,+ KernelRuntime.Backend.DOCKER,+ ):+ return False+ try:+ service = get_kernel_runtime(notebook, user).service+ sandbox = service._get_sandbox_class(runtime.backend).get_by_id(runtime.sandbox_id)+ return sandbox.get_status() == SandboxStatus.RUNNING+ except Exception:+ return False++ @staticmethod+ def _preset_key_for(cpu_cores: float | None, memory_gb: float | None) -> str | None:+ preset = find_matching_preset(cpu_cores=cpu_cores, memory_gb=memory_gb)+ return preset.key if preset else None++ @extend_schema(+ responses={200: NotebookComputeOptionsResponseSerializer},+ description=(+ "Compute rates, presets, and the sizes the kernel config endpoint accepts. Static per region, "+ "so a client can fetch it once and price any shape a user picks."+ ),+ )+ @action(methods=["GET"], url_path="kernel/compute_options", detail=False, required_scopes=["notebook:read"])+ def kernel_compute_options(self, request: Request, **kwargs) -> Response:+ rates = get_compute_rates()+ options_payload = {+ "currency": "USD",+ "cpu_rate_per_core_hour": rates.cpu_per_core_hour,+ "memory_rate_per_gb_hour": rates.memory_per_gb_hour,+ "default_preset_key": DEFAULT_COMPUTE_PRESET_KEY,+ "presets": [+ {+ "key": preset.key,+ "name": preset.name,+ "description": preset.description,+ "cpu_cores": preset.cpu_cores,+ "memory_gb": preset.memory_gb,+ "hourly_price": rates.hourly_price(cpu_cores=preset.cpu_cores, memory_gb=preset.memory_gb),+ }+ for preset in COMPUTE_PRESETS+ ],+ "allowed_cpu_cores": ALLOWED_KERNEL_CPU_CORES,+ "allowed_memory_gb": ALLOWED_KERNEL_MEMORY_GB,+ "allowed_idle_timeout_seconds": ALLOWED_KERNEL_IDLE_TIMEOUT_SECONDS,+ }+ return Response(NotebookComputeOptionsResponseSerializer(options_payload).data)@action(methods=["POST"], url_path="kernel/execute", detail=True)def kernel_execute(self, request: Request, **kwargs):@@ -1749,7 +1890,38 @@ class NotebookViewSet(TeamAndOrgViewSetMixin, AccessControlViewSetMixin, ForbidDfinish_node_run(run, NotebookNodeRun.Status.FAILED, error="Failed to start run.")return Response({"detail": "Failed to start run."}, status=503)- return Response({"run_id": str(run.id)})+ # Whether this run has to build a sandbox, decided here rather than inferred by a client+ # from a kernel status poll that can be ten seconds old. That cache could stay silent+ # through a sandbox that timed out between polls, which is the one case worth disclosing.+ uses_sandbox = plan.node_type != "hogql"+ live_runtime = (+ KernelRuntime.objects.filter(+ team_id=self.team_id,+ notebook_short_id=notebook.short_id,+ user=user if isinstance(user, User) else None,+ status__in=(KernelRuntime.Status.RUNNING, KernelRuntime.Status.STARTING),+ )+ .order_by("-last_used_at")+ .first()+ if uses_sandbox+ else None+ )+ starts_sandbox = uses_sandbox and not (+ live_runtime is not None and self._sandbox_is_running(notebook, user, live_runtime)+ )+ sandbox_config = build_notebook_sandbox_config(notebook) if starts_sandbox else None+ run_payload = {+ "run_id": str(run.id),+ "starts_sandbox": starts_sandbox,+ # Only a modal sandbox is charged, so a docker kernel carries no price to disclose.+ "sandbox_hourly_price": (+ get_compute_rates().hourly_price(cpu_cores=sandbox_config.cpu_cores, memory_gb=sandbox_config.memory_gb)+ if sandbox_config is not None+ and get_kernel_runtime(notebook, user).service._get_backend() == KernelRuntime.Backend.MODAL+ else None+ ),+ }+ return Response(NotebookSQLV2RunResponseSerializer(run_payload).data)@extend_schema(parameters=[diff --git a/products/notebooks/backend/sql_v2_serializers.py b/products/notebooks/backend/sql_v2_serializers.pyindex 47cde3a7e8ed..76716cb317e0 100644--- a/products/notebooks/backend/sql_v2_serializers.py+++ b/products/notebooks/backend/sql_v2_serializers.py@@ -326,6 +326,20 @@ class NotebookSQLV2RunResponseSerializer(serializers.Serializer):run_id = serializers.UUIDField(help_text="Identifier of the dispatched run. Poll the run result endpoint with it until the status is terminal.")+ starts_sandbox = serializers.BooleanField(+ help_text=(+ "True when this run has to provision a sandbox because none is live for the caller, checked here "+ "rather than inferred from a client's cached kernel status. Tell the user what that costs."+ )+ )+ sandbox_hourly_price = serializers.FloatField(+ required=False,+ allow_null=True,+ help_text=(+ "What the sandbox this run provisions costs per hour in USD. Null when the run needs no new "+ "sandbox, or when the backend is not charged."+ ),+ )class NotebookSQLV2RunStatusResponseSerializer(serializers.Serializer):@@ -484,6 +498,49 @@ class NotebookKernelStatusResponseSerializer(serializers.Serializer):idle_timeout_seconds = serializers.IntegerField(required=False, allow_null=True, help_text="Seconds of inactivity before the sandbox shuts down.")+ hourly_price = serializers.FloatField(+ help_text=(+ "What this sandbox shape costs per hour in USD while it is alive, at this region's rates. "+ "Charged on the sandbox's lifetime, not on how much of it a cell uses. Resizing through the "+ "kernel config endpoint restarts a live kernel, so this tracks the running sandbox."+ )+ )+ preset_key = serializers.CharField(+ required=False,+ allow_null=True,+ help_text=(+ "Compute preset for the shape hourly_price describes: the running sandbox while a kernel is "+ "live, otherwise the configured shape. Null when that shape was tuned by hand and matches no preset."+ ),+ )+++class NotebookComputePresetSerializer(serializers.Serializer):+ key = serializers.CharField(help_text="Stable identifier for the preset, e.g. 'balanced'.")+ name = serializers.CharField(help_text="Preset name as a person reads it, e.g. 'Balanced'.")+ description = serializers.CharField(help_text="What this preset suits, in one sentence.")+ cpu_cores = serializers.FloatField(help_text="CPU cores the preset provisions.")+ memory_gb = serializers.FloatField(help_text="Memory in GB the preset provisions.")+ hourly_price = serializers.FloatField(help_text="What this preset costs per hour in USD while it is alive.")+++class NotebookComputeOptionsResponseSerializer(serializers.Serializer):+ currency = serializers.CharField(help_text="Currency of every price in this response. Always 'USD'.")+ cpu_rate_per_core_hour = serializers.FloatField(help_text="Price of one CPU core for one hour, in USD.")+ memory_rate_per_gb_hour = serializers.FloatField(help_text="Price of one GB of memory for one hour, in USD.")+ default_preset_key = serializers.CharField(+ help_text="Preset a sandbox starts with when the notebook sets no compute config."+ )+ presets = NotebookComputePresetSerializer(many=True, help_text="Sandbox shapes offered as one-click options.")+ allowed_cpu_cores = serializers.ListField(+ child=serializers.FloatField(), help_text="CPU core counts the kernel config endpoint accepts."+ )+ allowed_memory_gb = serializers.ListField(+ child=serializers.FloatField(), help_text="Memory sizes in GB the kernel config endpoint accepts."+ )+ allowed_idle_timeout_seconds = serializers.ListField(+ child=serializers.IntegerField(), help_text="Idle timeouts in seconds the kernel config endpoint accepts."+ )class NotebookKernelConfigResponseSerializer(serializers.Serializer):@@ -496,12 +553,31 @@ class NotebookKernelConfigResponseSerializer(serializers.Serializer):idle_timeout_seconds = serializers.IntegerField(required=False, allow_null=True, help_text="Configured idle timeout in seconds; null means the default.")+ restarted = serializers.BooleanField(+ help_text=(+ "True when this call restarted a live kernel to apply a new size. Restarting discards every "+ "materialized dataframe, so cells that referenced one must run again."+ )+ )restart_required = serializers.BooleanField(help_text=(- "True when a kernel is currently active: config applies at sandbox provision time, so the "- "running kernel keeps its old resources until restarted (restarting loses materialized dataframes)."+ "True when a kernel is live and this call did not restart it, so the running sandbox may not "+ "match the saved config. A resize restarts the kernel and reports False on success, or True if "+ "that restart fails. An idle-timeout change and a no-op on a live kernel also report True."+ )+ )+ hourly_price = serializers.FloatField(+ help_text=(+ "What this sandbox shape costs per hour in USD while it is alive, at this region's rates. It "+ "tracks the running sandbox while a kernel is live, otherwise the configured shape. After a "+ "failed resize this stays the running sandbox's rate, not the size that failed to apply."))+ preset_key = serializers.CharField(+ required=False,+ allow_null=True,+ help_text="Compute preset the configured shape matches, or null when it was tuned by hand.",+ )class NotebookSQLV2InterruptResponseSerializer(serializers.Serializer):diff --git a/products/notebooks/backend/test/test_compute_pricing.py b/products/notebooks/backend/test/test_compute_pricing.pynew file mode 100644index 000000000000..c44c0bde6fd3--- /dev/null+++ b/products/notebooks/backend/test/test_compute_pricing.py@@ -0,0 +1,374 @@+from posthog.test.base import APIBaseTest+from unittest.mock import MagicMock, patch++from django.test import SimpleTestCase++from parameterized import parameterized++from posthog.models import User++from products.notebooks.backend.compute_pricing import (+ COMPUTE_PRESETS,+ DEFAULT_COMPUTE_PRESET_KEY,+ find_matching_preset,+ get_compute_rates,+ get_default_compute_preset,+)+from products.notebooks.backend.kernel_runtime import build_notebook_sandbox_config+from products.notebooks.backend.models import KernelRuntime, Notebook+++class TestComputePricing(SimpleTestCase):+ @parameterized.expand(+ [+ ("us_default_sandbox", "US", 1, 2, 0.25),+ ("us_balanced", "US", 4, 8, 1.00),+ ("us_high_memory", "US", 8, 32, 2.40),+ ("us_memory_only_shape", "US", 1, 64, 1.80),+ ("eu_carries_the_uplift", "EU", 4, 8, 1.15),+ ("dev_is_priced_as_us", "DEV", 4, 8, 1.00),+ ]+ )+ def test_hourly_price_sums_the_two_rates(+ self, _name: str, region: str, cpu_cores: float, memory_gb: float, expected: float+ ) -> None:+ rates = get_compute_rates(region)++ assert rates.hourly_price(cpu_cores=cpu_cores, memory_gb=memory_gb) == expected++ @parameterized.expand([("US",), ("EU",)])+ def test_every_preset_is_priced_at_the_region_rates(self, region: str) -> None:+ rates = get_compute_rates(region)++ for preset in COMPUTE_PRESETS:+ expected = round(+ preset.cpu_cores * rates.cpu_per_core_hour + preset.memory_gb * rates.memory_per_gb_hour, 4+ )+ assert rates.hourly_price(cpu_cores=preset.cpu_cores, memory_gb=preset.memory_gb) == expected++ @parameterized.expand(+ [+ ("exact_preset_shape", 4, 8, "balanced"),+ ("tuned_shape_matches_nothing", 6, 8, None),+ ("unset_cpu_matches_nothing", None, 8, None),+ ]+ )+ def test_find_matching_preset(+ self, _name: str, cpu_cores: float | None, memory_gb: float | None, expected_key: str | None+ ) -> None:+ preset = find_matching_preset(cpu_cores=cpu_cores, memory_gb=memory_gb)++ assert (preset.key if preset else None) == expected_key+++class TestComputeOptionsEndpoint(APIBaseTest):+ def test_returns_presets_priced_at_the_instance_rates(self) -> None:+ response = self.client.get(f"/api/projects/{self.team.id}/notebooks/kernel/compute_options/")++ assert response.status_code == 200, response.json()+ payload = response.json()+ rates = get_compute_rates()+ assert payload["cpu_rate_per_core_hour"] == rates.cpu_per_core_hour+ assert payload["default_preset_key"] == DEFAULT_COMPUTE_PRESET_KEY+ assert [preset["key"] for preset in payload["presets"]] == [preset.key for preset in COMPUTE_PRESETS]+ for quoted, preset in zip(payload["presets"], COMPUTE_PRESETS):+ assert quoted["hourly_price"] == rates.hourly_price(cpu_cores=preset.cpu_cores, memory_gb=preset.memory_gb)++ def test_offered_preset_shapes_are_all_configurable(self) -> None:+ response = self.client.get(f"/api/projects/{self.team.id}/notebooks/kernel/compute_options/")++ payload = response.json()+ for preset in payload["presets"]:+ assert preset["cpu_cores"] in payload["allowed_cpu_cores"]+ assert preset["memory_gb"] in payload["allowed_memory_gb"]++ def test_status_quotes_the_shape_the_notebook_will_get(self) -> None:+ notebook = Notebook.objects.create(team=self.team, created_by=self.user, kernel_cpu_cores=4, kernel_memory_gb=8)++ response = self.client.get(+ f"/api/projects/{self.team.id}/notebooks/{notebook.short_id}/kernel/status/",+ )++ assert response.status_code == 200, response.json()+ payload = response.json()+ assert payload["hourly_price"] == get_compute_rates().hourly_price(cpu_cores=4, memory_gb=8)+ assert payload["preset_key"] == "balanced"++ def test_config_quotes_the_default_for_knobs_the_notebook_leaves_unset(self) -> None:+ notebook = Notebook.objects.create(team=self.team, created_by=self.user)+ default_preset = get_default_compute_preset()++ response = self.client.post(+ f"/api/projects/{self.team.id}/notebooks/{notebook.short_id}/kernel/config/",+ {"idle_timeout_seconds": 1800},+ )++ assert response.status_code == 200, response.json()+ payload = response.json()+ assert payload["cpu_cores"] is None+ assert payload["hourly_price"] == get_compute_rates().hourly_price(+ cpu_cores=default_preset.cpu_cores, memory_gb=default_preset.memory_gb+ )+ assert payload["preset_key"] == DEFAULT_COMPUTE_PRESET_KEY++ def _live_kernel(self, notebook: Notebook) -> KernelRuntime:+ return KernelRuntime.objects.create(+ team=self.team,+ notebook=notebook,+ notebook_short_id=notebook.short_id,+ user=self.user,+ status=KernelRuntime.Status.RUNNING,+ backend=KernelRuntime.Backend.MODAL,+ provisioned_cpu_cores=notebook.kernel_cpu_cores,+ provisioned_memory_gb=notebook.kernel_memory_gb,+ )++ @patch(+ "products.notebooks.backend.presentation.views.notebook.NotebookViewSet._sandbox_is_running",+ return_value=True,+ )+ @patch("products.notebooks.backend.presentation.views.notebook.get_kernel_runtime")+ def test_a_resize_restarts_the_live_kernel(self, mock_runtime: MagicMock, _alive: MagicMock) -> None:+ notebook = Notebook.objects.create(team=self.team, created_by=self.user, kernel_cpu_cores=1, kernel_memory_gb=2)+ self._live_kernel(notebook)++ response = self.client.post(+ f"/api/projects/{self.team.id}/notebooks/{notebook.short_id}/kernel/config/",+ {"cpu_cores": 4, "memory_gb": 8},+ )++ assert response.status_code == 200, response.json()+ mock_runtime.return_value.restart.assert_called_once()+ payload = response.json()+ assert payload["restarted"] is True+ # The quote now describes the sandbox that is actually running.+ assert payload["restart_required"] is False++ @patch(+ "products.notebooks.backend.presentation.views.notebook.NotebookViewSet._sandbox_is_running",+ return_value=True,+ )+ @patch("products.notebooks.backend.presentation.views.notebook.get_kernel_runtime")+ def test_an_idle_timeout_change_leaves_the_kernel_alone(self, mock_runtime: MagicMock, _alive: MagicMock) -> None:+ # A restart discards every materialized dataframe, which is far too much to spend on a+ # setting a live sandbox cannot pick up anyway.+ notebook = Notebook.objects.create(team=self.team, created_by=self.user, kernel_cpu_cores=4, kernel_memory_gb=8)+ self._live_kernel(notebook)++ response = self.client.post(+ f"/api/projects/{self.team.id}/notebooks/{notebook.short_id}/kernel/config/",+ {"idle_timeout_seconds": 1800},+ )++ assert response.status_code == 200, response.json()+ mock_runtime.return_value.restart.assert_not_called()+ payload = response.json()+ assert payload["restarted"] is False+ assert payload["restart_required"] is True++ @patch("products.notebooks.backend.presentation.views.notebook.get_kernel_runtime")+ def test_a_resize_with_no_live_kernel_starts_nothing(self, mock_runtime: MagicMock) -> None:+ notebook = Notebook.objects.create(team=self.team, created_by=self.user, kernel_cpu_cores=1, kernel_memory_gb=2)++ response = self.client.post(+ f"/api/projects/{self.team.id}/notebooks/{notebook.short_id}/kernel/config/",+ {"cpu_cores": 4, "memory_gb": 8},+ )++ assert response.status_code == 200, response.json()+ mock_runtime.return_value.restart.assert_not_called()+ assert response.json()["restarted"] is False++ @patch(+ "products.notebooks.backend.presentation.views.notebook.NotebookViewSet._sandbox_is_running",+ return_value=True,+ )+ @patch("products.notebooks.backend.presentation.views.notebook.get_kernel_runtime")+ def test_a_collaborators_kernel_is_not_restarted(self, mock_runtime: MagicMock, _alive: MagicMock) -> None:+ # Runtimes are per user. Restarting on someone else's row would provision a paid sandbox+ # for the caller and leave the collaborator on the old shape.+ other = User.objects.create_and_join(self.organization, "[email protected]", None)+ notebook = Notebook.objects.create(team=self.team, created_by=self.user, kernel_cpu_cores=1, kernel_memory_gb=2)+ runtime = self._live_kernel(notebook)+ runtime.user = other+ runtime.save(update_fields=["user"])++ response = self.client.post(+ f"/api/projects/{self.team.id}/notebooks/{notebook.short_id}/kernel/config/",+ {"cpu_cores": 4, "memory_gb": 8},+ )++ assert response.status_code == 200, response.json()+ mock_runtime.return_value.restart.assert_not_called()+ assert response.json()["restarted"] is False++ @patch(+ "products.notebooks.backend.presentation.views.notebook.NotebookViewSet._sandbox_is_running",+ return_value=False,+ )+ @patch("products.notebooks.backend.presentation.views.notebook.get_kernel_runtime")+ def test_a_stale_running_row_does_not_provision_compute(self, mock_runtime: MagicMock, _alive: MagicMock) -> None:+ # A RUNNING row can outlive its sandbox. Acting on it would turn a config-only call into+ # new paid compute.+ notebook = Notebook.objects.create(team=self.team, created_by=self.user, kernel_cpu_cores=1, kernel_memory_gb=2)+ self._live_kernel(notebook)++ response = self.client.post(+ f"/api/projects/{self.team.id}/notebooks/{notebook.short_id}/kernel/config/",+ {"cpu_cores": 4, "memory_gb": 8},+ )++ assert response.status_code == 200, response.json()+ mock_runtime.return_value.restart.assert_not_called()+ assert response.json()["restarted"] is False++ @patch(+ "products.notebooks.backend.presentation.views.notebook.NotebookViewSet._sandbox_is_running",+ return_value=True,+ )+ @patch("products.notebooks.backend.presentation.views.notebook.get_kernel_runtime")+ def test_a_failed_restart_keeps_the_shape_that_is_running(self, mock_runtime: MagicMock, _alive: MagicMock) -> None:+ # The write has to precede the restart because the restart reads it. When the restart does+ # not happen, the old sandbox is still running, so the row has to go back or every later+ # status prices a shape nobody is on.+ mock_runtime.return_value.restart.side_effect = RuntimeError("lock timeout")+ notebook = Notebook.objects.create(team=self.team, created_by=self.user, kernel_cpu_cores=1, kernel_memory_gb=2)+ self._live_kernel(notebook)++ response = self.client.post(+ f"/api/projects/{self.team.id}/notebooks/{notebook.short_id}/kernel/config/",+ {"cpu_cores": 8, "memory_gb": 16},+ )++ assert response.status_code == 200, response.json()+ payload = response.json()+ assert payload["restarted"] is False+ assert payload["restart_required"] is True+ # This response prices the same thing status does: the sandbox still serving the notebook,+ # not the size that failed to apply.+ assert payload["hourly_price"] == get_compute_rates().hourly_price(cpu_cores=1, memory_gb=2)++ # The requested size is kept: it is what the next sandbox gets.+ notebook.refresh_from_db()+ assert notebook.kernel_cpu_cores == 8+ assert notebook.kernel_memory_gb == 16++ # But status prices the sandbox that is actually running, which is where the old bug+ # became permanent — every poll quoted the shape that failed to apply.+ status_payload = self.client.get(+ f"/api/projects/{self.team.id}/notebooks/{notebook.short_id}/kernel/status/"+ ).json()+ assert status_payload["hourly_price"] == get_compute_rates().hourly_price(cpu_cores=1, memory_gb=2)++ @patch(+ "products.notebooks.backend.presentation.views.notebook.NotebookViewSet._sandbox_is_running",+ return_value=True,+ )+ @patch("products.notebooks.backend.presentation.views.notebook.get_kernel_runtime")+ def test_a_failed_resize_retries_on_an_identical_second_request(+ self, mock_runtime: MagicMock, _alive: MagicMock+ ) -> None:+ # A transient restart failure leaves the sandbox on the old shape. Re-sending the same size+ # has to attempt the restart again, or the resize is wedged until the sandbox idles out.+ mock_runtime.return_value.restart.side_effect = [RuntimeError("lock timeout"), None]+ notebook = Notebook.objects.create(team=self.team, created_by=self.user, kernel_cpu_cores=1, kernel_memory_gb=2)+ self._live_kernel(notebook)++ first = self.client.post(+ f"/api/projects/{self.team.id}/notebooks/{notebook.short_id}/kernel/config/",+ {"cpu_cores": 8, "memory_gb": 16},+ )+ assert first.status_code == 200, first.json()+ assert first.json()["restarted"] is False++ second = self.client.post(+ f"/api/projects/{self.team.id}/notebooks/{notebook.short_id}/kernel/config/",+ {"cpu_cores": 8, "memory_gb": 16},+ )+ assert second.status_code == 200, second.json()+ assert second.json()["restarted"] is True+ assert mock_runtime.return_value.restart.call_count == 2++ def test_status_prices_the_running_sandbox_not_the_configuration(self) -> None:+ # The notebook is configured for a bigger shape than the live sandbox was built with,+ # which is the state a resize leaves until a restart applies it.+ notebook = Notebook.objects.create(team=self.team, created_by=self.user, kernel_cpu_cores=1, kernel_memory_gb=2)+ runtime = self._live_kernel(notebook)+ notebook.kernel_cpu_cores = 8+ notebook.kernel_memory_gb = 16+ notebook.save(update_fields=["kernel_cpu_cores", "kernel_memory_gb"])++ payload = self.client.get(f"/api/projects/{self.team.id}/notebooks/{notebook.short_id}/kernel/status/").json()++ assert runtime.provisioned_cpu_cores == 1+ assert payload["hourly_price"] == get_compute_rates().hourly_price(cpu_cores=1, memory_gb=2)+ assert payload["preset_key"] == "small"++ def test_status_prices_the_configuration_when_nothing_is_running(self) -> None:+ # With no live sandbox the configured shape is what the next one costs, so quote that.+ notebook = Notebook.objects.create(+ team=self.team, created_by=self.user, kernel_cpu_cores=8, kernel_memory_gb=16+ )++ payload = self.client.get(f"/api/projects/{self.team.id}/notebooks/{notebook.short_id}/kernel/status/").json()++ assert payload["hourly_price"] == get_compute_rates().hourly_price(cpu_cores=8, memory_gb=16)++ @patch("products.notebooks.backend.presentation.views.notebook.start_sql_v2_run_workflow")+ @patch("products.notebooks.backend.presentation.views.notebook.is_sql_v2_enabled", return_value=True)+ @patch(+ "products.notebooks.backend.presentation.views.notebook.NotebookViewSet._sandbox_is_running",+ return_value=True,+ )+ def test_a_run_reusing_a_live_sandbox_discloses_nothing(+ self, _flag: MagicMock, _alive: MagicMock, _workflow: MagicMock+ ) -> None:+ notebook = Notebook.objects.create(team=self.team, created_by=self.user, kernel_cpu_cores=1, kernel_memory_gb=2)+ self._live_kernel(notebook)++ response = self.client.post(+ f"/api/projects/{self.team.id}/notebooks/{notebook.short_id}/sql_v2/run/",+ {"node_id": "n1", "code": "print(1)", "node_type": "python"},+ )++ assert response.status_code == 200, response.json()+ assert response.json()["starts_sandbox"] is False++ @patch("products.notebooks.backend.presentation.views.notebook.is_sql_v2_enabled", return_value=True)+ @patch("products.notebooks.backend.presentation.views.notebook.start_sql_v2_run_workflow")+ def test_a_run_with_no_live_sandbox_discloses_the_start(self, _flag: MagicMock, _workflow: MagicMock) -> None:+ # The client used to answer this from a kernel poll up to ten seconds old, which stayed+ # silent through a sandbox that timed out between polls.+ notebook = Notebook.objects.create(team=self.team, created_by=self.user, kernel_cpu_cores=1, kernel_memory_gb=2)++ response = self.client.post(+ f"/api/projects/{self.team.id}/notebooks/{notebook.short_id}/sql_v2/run/",+ {"node_id": "n1", "code": "print(1)", "node_type": "python"},+ )++ assert response.status_code == 200, response.json()+ assert response.json()["starts_sandbox"] is True++ @patch("products.notebooks.backend.presentation.views.notebook.is_sql_v2_enabled", return_value=True)+ @patch("products.notebooks.backend.presentation.views.notebook.enqueue_direct_run")+ def test_a_pure_hogql_run_never_discloses_a_sandbox(self, _flag: MagicMock, _direct: MagicMock) -> None:+ notebook = Notebook.objects.create(team=self.team, created_by=self.user)++ response = self.client.post(+ f"/api/projects/{self.team.id}/notebooks/{notebook.short_id}/sql_v2/run/",+ {"node_id": "n1", "code": "select 1", "node_type": "hogql"},+ )++ assert response.status_code == 200, response.json()+ payload = response.json()+ assert payload["starts_sandbox"] is False+ assert payload["sandbox_hourly_price"] is None++ def test_a_new_sandbox_gets_the_default_preset_shape(self) -> None:+ notebook = Notebook.objects.create(team=self.team, created_by=self.user)+ default_preset = get_default_compute_preset()++ sandbox_config = build_notebook_sandbox_config(notebook)++ assert sandbox_config.cpu_cores == default_preset.cpu_cores+ assert sandbox_config.memory_gb == default_preset.memory_gbdiff --git a/products/notebooks/frontend/generated/api.schemas.ts b/products/notebooks/frontend/generated/api.schemas.tsindex 793c1d9ffcef..0f1faeb3ac3f 100644--- a/products/notebooks/frontend/generated/api.schemas.ts+++ b/products/notebooks/frontend/generated/api.schemas.ts@@ -318,8 +318,17 @@ export interface NotebookKernelConfigResponseApi {* @nullable*/idle_timeout_seconds?: number | null- /** True when a kernel is currently active: config applies at sandbox provision time, so the running kernel keeps its old resources until restarted (restarting loses materialized dataframes). */+ /** True when this call restarted a live kernel to apply a new size. Restarting discards every materialized dataframe, so cells that referenced one must run again. */+ restarted: boolean+ /** True when a kernel is live and this call did not restart it, so the running sandbox may not match the saved config. A resize restarts the kernel and reports False on success, or True if that restart fails. An idle-timeout change and a no-op on a live kernel also report True. */restart_required: boolean+ /** What this sandbox shape costs per hour in USD while it is alive, at this region's rates. It tracks the running sandbox while a kernel is live, otherwise the configured shape. After a failed resize this stays the running sandbox's rate, not the size that failed to apply. */+ hourly_price: number+ /**+ * Compute preset the configured shape matches, or null when it was tuned by hand.+ * @nullable+ */+ preset_key?: string | null}export interface NotebookSQLV2FrameApi {@@ -392,6 +401,13 @@ export interface NotebookKernelStatusResponseApi {* @nullable*/idle_timeout_seconds?: number | null+ /** What this sandbox shape costs per hour in USD while it is alive, at this region's rates. Charged on the sandbox's lifetime, not on how much of it a cell uses. Resizing through the kernel config endpoint restarts a live kernel, so this tracks the running sandbox. */+ hourly_price: number+ /**+ * Compute preset for the shape hourly_price describes: the running sandbox while a kernel is live, otherwise the configured shape. Null when that shape was tuned by hand and matches no preset.+ * @nullable+ */+ preset_key?: string | null}/**@@ -460,6 +476,13 @@ export interface NotebookSQLV2RunRequestApi {export interface NotebookSQLV2RunResponseApi {/** Identifier of the dispatched run. Poll the run result endpoint with it until the status is terminal. */run_id: string+ /** True when this run has to provision a sandbox because none is live for the caller, checked here rather than inferred from a client's cached kernel status. Tell the user what that costs. */+ starts_sandbox: boolean+ /**+ * What the sandbox this run provisions costs per hour in USD. Null when the run needs no new sandbox, or when the backend is not charged.+ * @nullable+ */+ sandbox_hourly_price?: number | null}export interface NotebookSQLV2MediaApi {@@ -1016,6 +1039,40 @@ export interface WidgetVersionPageApi {next_offset: number | null}+export interface NotebookComputePresetApi {+ /** Stable identifier for the preset, e.g. 'balanced'. */+ key: string+ /** Preset name as a person reads it, e.g. 'Balanced'. */+ name: string+ /** What this preset suits, in one sentence. */+ description: string+ /** CPU cores the preset provisions. */+ cpu_cores: number+ /** Memory in GB the preset provisions. */+ memory_gb: number+ /** What this preset costs per hour in USD while it is alive. */+ hourly_price: number+}++export interface NotebookComputeOptionsResponseApi {+ /** Currency of every price in this response. Always 'USD'. */+ currency: string+ /** Price of one CPU core for one hour, in USD. */+ cpu_rate_per_core_hour: number+ /** Price of one GB of memory for one hour, in USD. */+ memory_rate_per_gb_hour: number+ /** Preset a sandbox starts with when the notebook sets no compute config. */+ default_preset_key: string+ /** Sandbox shapes offered as one-click options. */+ presets: NotebookComputePresetApi[]+ /** CPU core counts the kernel config endpoint accepts. */+ allowed_cpu_cores: number[]+ /** Memory sizes in GB the kernel config endpoint accepts. */+ allowed_memory_gb: number[]+ /** Idle timeouts in seconds the kernel config endpoint accepts. */+ allowed_idle_timeout_seconds: number[]+}+export type NotebooksListParams = {/*** Filter for notebooks that match a provided filter.diff --git a/products/notebooks/frontend/generated/api.ts b/products/notebooks/frontend/generated/api.tsindex f835fd80c3e8..704f92b57ffa 100644--- a/products/notebooks/frontend/generated/api.ts+++ b/products/notebooks/frontend/generated/api.ts@@ -12,6 +12,7 @@ import type {NotebookApi,NotebookCollabPresenceApi,NotebookCollabSaveApi,+ NotebookComputeOptionsResponseApi,NotebookKernelConfigApi,NotebookKernelConfigResponseApi,NotebookKernelStatusResponseApi,@@ -751,6 +752,23 @@ export const notebooksAllActivityRetrieve = async (projectId: string, options?:})}+export const getNotebooksKernelComputeOptionsRetrieveUrl = (projectId: string) => {+ return `/api/projects/${projectId}/notebooks/kernel/compute_options/`+}++/**+ * Compute rates, presets, and the sizes the kernel config endpoint accepts. Static per region, so a client can fetch it once and price any shape a user picks.+ */+export const notebooksKernelComputeOptionsRetrieve = async (+ projectId: string,+ options?: RequestInit+): Promise<NotebookComputeOptionsResponseApi> => {+ return apiMutator<NotebookComputeOptionsResponseApi>(getNotebooksKernelComputeOptionsRetrieveUrl(projectId), {+ ...options,+ method: 'GET',+ })+}+export const getNotebooksRecordingCommentsRetrieveUrl = (projectId: string) => {return `/api/projects/${projectId}/notebooks/recording_comments/`}diff --git a/products/notebooks/mcp/tools.yaml b/products/notebooks/mcp/tools.yamlindex 76fc3765f758..b0e207b202ec 100644--- a/products/notebooks/mcp/tools.yaml+++ b/products/notebooks/mcp/tools.yaml@@ -118,6 +118,9 @@ tools:notebooks-hogql-execute-create:operation: notebooks_hogql_execute_createenabled: false+ notebooks-kernel-compute-options-retrieve:+ operation: notebooks_kernel_compute_options_retrieve+ enabled: falsenotebooks-kernel-dataframe-retrieve:operation: notebooks_kernel_dataframe_retrieveenabled: falsediff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.tsindex b26fa35be280..19d8e17b585e 100644--- a/services/mcp/src/api/generated.ts+++ b/services/mcp/src/api/generated.ts@@ -51947,6 +51947,40 @@ export namespace Schemas {cursor_head?: number | null;}+ export interface NotebookComputePreset {+ /** Stable identifier for the preset, e.g. 'balanced'. */+ key: string;+ /** Preset name as a person reads it, e.g. 'Balanced'. */+ name: string;+ /** What this preset suits, in one sentence. */+ description: string;+ /** CPU cores the preset provisions. */+ cpu_cores: number;+ /** Memory in GB the preset provisions. */+ memory_gb: number;+ /** What this preset costs per hour in USD while it is alive. */+ hourly_price: number;+ }++ export interface NotebookComputeOptionsResponse {+ /** Currency of every price in this response. Always 'USD'. */+ currency: string;+ /** Price of one CPU core for one hour, in USD. */+ cpu_rate_per_core_hour: number;+ /** Price of one GB of memory for one hour, in USD. */+ memory_rate_per_gb_hour: number;+ /** Preset a sandbox starts with when the notebook sets no compute config. */+ default_preset_key: string;+ /** Sandbox shapes offered as one-click options. */+ presets: NotebookComputePreset[];+ /** CPU core counts the kernel config endpoint accepts. */+ allowed_cpu_cores: number[];+ /** Memory sizes in GB the kernel config endpoint accepts. */+ allowed_memory_gb: number[];+ /** Idle timeouts in seconds the kernel config endpoint accepts. */+ allowed_idle_timeout_seconds: number[];+ }+export interface NotebookKernelConfig {/** CPU cores for the notebook's sandbox kernel; must be a supported option. */cpu_cores?: number;@@ -51972,8 +52006,17 @@ export namespace Schemas {* @nullable*/idle_timeout_seconds?: number | null;- /** True when a kernel is currently active: config applies at sandbox provision time, so the running kernel keeps its old resources until restarted (restarting loses materialized dataframes). */+ /** True when this call restarted a live kernel to apply a new size. Restarting discards every materialized dataframe, so cells that referenced one must run again. */+ restarted: boolean;+ /** True when a kernel is live and this call did not restart it, so the running sandbox may not match the saved config. A resize restarts the kernel and reports False on success, or True if that restart fails. An idle-timeout change and a no-op on a live kernel also report True. */restart_required: boolean;+ /** What this sandbox shape costs per hour in USD while it is alive, at this region's rates. It tracks the running sandbox while a kernel is live, otherwise the configured shape. After a failed resize this stays the running sandbox's rate, not the size that failed to apply. */+ hourly_price: number;+ /**+ * Compute preset the configured shape matches, or null when it was tuned by hand.+ * @nullable+ */+ preset_key?: string | null;}export interface NotebookKernelState {@@ -52066,6 +52109,13 @@ export namespace Schemas {* @nullable*/idle_timeout_seconds?: number | null;+ /** What this sandbox shape costs per hour in USD while it is alive, at this region's rates. Charged on the sandbox's lifetime, not on how much of it a cell uses. Resizing through the kernel config endpoint restarts a live kernel, so this tracks the running sandbox. */+ hourly_price: number;+ /**+ * Compute preset for the shape hourly_price describes: the running sandbox while a kernel is live, otherwise the configured shape. Null when that shape was tuned by hand and matches no preset.+ * @nullable+ */+ preset_key?: string | null;}export interface NotebookMarkdownSave {@@ -52228,6 +52278,13 @@ export namespace Schemas {export interface NotebookSQLV2RunResponse {/** Identifier of the dispatched run. Poll the run result endpoint with it until the status is terminal. */run_id: string;+ /** True when this run has to provision a sandbox because none is live for the caller, checked here rather than inferred from a client's cached kernel status. Tell the user what that costs. */+ starts_sandbox: boolean;+ /**+ * What the sandbox this run provisions costs per hour in USD. Null when the run needs no new sandbox, or when the backend is not charged.+ * @nullable+ */+ sandbox_hourly_price?: number | null;}export interface NotebookSQLV2RunStatusResponse {