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): record kernel sandbox starts, ends, and price (#100062)

Sinan Kucukkoseler7aa84333c9c9
diff --git a/products/notebooks/backend/facade/kernel_sandbox_usage.py b/products/notebooks/backend/facade/kernel_sandbox_usage.py
new file mode 100644
index 000000000000..87dfc4998d28
--- /dev/null
+++ b/products/notebooks/backend/facade/kernel_sandbox_usage.py
@@ -0,0 +1,9 @@
+"""
+Facade re-export for notebook kernel sandbox usage events.
+
+The kernel status endpoint can be the first code path that notices a sandbox has ended, so it
+records that end. Presentation may only reach in-product code through this package, so the
+recorder stays in `kernel_sandbox_usage` and is re-exported here.
+"""
+
+from ..kernel_sandbox_usage import record_sandbox_ended_by_id as record_sandbox_ended_by_id
diff --git a/products/notebooks/backend/kernel_runtime.py b/products/notebooks/backend/kernel_runtime.py
index 43e38fab177a..cb627acd1470 100644
--- a/products/notebooks/backend/kernel_runtime.py
+++ b/products/notebooks/backend/kernel_runtime.py
@@ -7,7 +7,7 @@ import base64
import signal
from contextlib import suppress
from dataclasses import dataclass
-from datetime import datetime
+from datetime import datetime, timedelta
from typing import Any
from django.conf import settings
@@ -24,6 +24,7 @@ from posthog.models import Team, User
from posthog.redis import get_client
from products.notebooks.backend.compute_pricing import get_default_compute_preset
+from products.notebooks.backend.kernel_sandbox_usage import record_sandbox_ended, record_sandbox_started
from products.notebooks.backend.models import KernelRuntime, Notebook
from products.tasks.backend.facade.sandbox import (
SandboxBase,
@@ -210,6 +211,7 @@ def build_notebook_sandbox_config(notebook: Notebook) -> SandboxConfig:
cpu_cores=default_preset.cpu_cores,
memory_gb=default_preset.memory_gb,
ttl_seconds=NOTEBOOK_KERNEL_TTL_SECONDS,
+ metadata={"team_id": str(notebook.team_id), "product": "notebooks"},
)
if notebook.kernel_cpu_cores:
sandbox_config.cpu_cores = notebook.kernel_cpu_cores
@@ -630,13 +632,16 @@ class KernelRuntimeService:
def _shutdown_handle(self, handle: _KernelHandle, *, status: str) -> None:
if handle.backend in (KernelRuntime.Backend.MODAL, KernelRuntime.Backend.DOCKER):
+ destroyed = False
if handle.sandbox_id:
try:
sandbox_class = self._get_sandbox_class(handle.backend)
sandbox_class.get_by_id(handle.sandbox_id).destroy()
+ destroyed = True
except Exception:
logger.warning("notebook_kernel_sandbox_destroy_failed", kernel_runtime_id=str(handle.runtime.id))
self._touch_runtime(handle, status_override=status)
+ record_sandbox_ended(handle.runtime, reason=status, sandbox_still_running=not destroyed)
return
self._touch_runtime(handle, status_override=status)
@@ -688,13 +693,20 @@ class KernelRuntimeService:
def _discard_active_runtime(self, notebook: Notebook, user: User | None, backend: str) -> None:
active_statuses = [KernelRuntime.Status.STARTING, KernelRuntime.Status.RUNNING]
- KernelRuntime.objects.filter(
+ active_runtimes = KernelRuntime.objects.filter(
team_id=notebook.team_id,
notebook_short_id=notebook.short_id,
user=user if isinstance(user, User) else None,
status__in=active_statuses,
backend=backend,
- ).update(status=KernelRuntime.Status.DISCARDED, last_used_at=timezone.now())
+ )
+ for runtime in list(active_runtimes):
+ moved = KernelRuntime.objects.filter(pk=runtime.pk, status__in=active_statuses).update(
+ status=KernelRuntime.Status.DISCARDED, last_used_at=timezone.now()
+ )
+ if moved:
+ # Discarding a row does not destroy its sandbox, so the sandbox keeps running until its TTL.
+ record_sandbox_ended(runtime, reason=KernelRuntime.Status.DISCARDED, sandbox_still_running=True)
def _get_backend(self, *, require_credentials: bool = False) -> str | None:
provider = getattr(settings, "SANDBOX_PROVIDER", None)
@@ -720,6 +732,7 @@ class KernelRuntimeService:
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)
+ provision_requested_at = timezone.now()
try:
sandbox = sandbox_class.create(sandbox_config)
except Exception as err:
@@ -727,14 +740,21 @@ class KernelRuntimeService:
self._mark_runtime_error(runtime, f"Failed to provision sandbox: {detail}")
raise
+ runtime.ttl_expires_at = provision_requested_at + timedelta(seconds=sandbox_config.ttl_seconds)
+ runtime.save(update_fields=["ttl_expires_at"])
+ record_sandbox_started(runtime, sandbox_id=sandbox.id, ttl_seconds=sandbox_config.ttl_seconds)
+
try:
kernel_pid = self._start_kernel_process(sandbox, connection_file)
self._wait_for_kernel_ready(sandbox, connection_file)
self._bootstrap_kernel(sandbox, connection_file, notebook, user)
except Exception as err:
self._mark_runtime_error(runtime, "Failed to start kernel in sandbox")
+ destroyed = False
with suppress(Exception):
sandbox.destroy()
+ destroyed = True
+ record_sandbox_ended(runtime, reason=KernelRuntime.Status.ERROR, sandbox_still_running=not destroyed)
raise RuntimeError("Failed to start kernel in sandbox") from err
runtime.kernel_id = kernel_id
@@ -1101,16 +1121,19 @@ class KernelRuntimeService:
sandbox = sandbox_class.get_by_id(runtime.sandbox_id)
except Exception:
self._mark_runtime_error(runtime, "Sandbox not found")
+ record_sandbox_ended(runtime, reason=KernelRuntime.Status.ERROR, sandbox_still_running=True)
return None
if sandbox.get_status() != SandboxStatus.RUNNING:
self._mark_runtime_error(runtime, "Sandbox is not running")
+ record_sandbox_ended(runtime, reason=KernelRuntime.Status.ERROR, sandbox_still_running=False)
return None
try:
self._wait_for_kernel_ready(sandbox, runtime.connection_file or "")
except Exception:
self._mark_runtime_error(runtime, "Kernel not ready in sandbox")
+ record_sandbox_ended(runtime, reason=KernelRuntime.Status.ERROR, sandbox_still_running=True)
return None
handle = _KernelHandle(
diff --git a/products/notebooks/backend/kernel_sandbox_usage.py b/products/notebooks/backend/kernel_sandbox_usage.py
new file mode 100644
index 000000000000..0801a51b84f1
--- /dev/null
+++ b/products/notebooks/backend/kernel_sandbox_usage.py
@@ -0,0 +1,172 @@
+"""Usage events for notebook kernel sandboxes: one when a sandbox starts, and one when it ends.
+
+Modal exports metrics for each sandbox, but those metrics carry no team and no size. These events
+carry both, so product analytics can count sandboxes, add up sandbox-hours, and estimate the price
+of the compute per team.
+"""
+
+from __future__ import annotations
+
+from datetime import datetime
+from typing import Any
+from uuid import UUID
+
+from django.utils import timezone
+
+import structlog
+
+from posthog.event_usage import report_user_or_team_action
+from posthog.models import Team
+
+from products.notebooks.backend.compute_pricing import find_matching_preset, get_compute_rates
+from products.notebooks.backend.models import KernelRuntime
+
+logger = structlog.get_logger(__name__)
+
+KERNEL_SANDBOX_STARTED_EVENT = "notebook kernel sandbox started"
+KERNEL_SANDBOX_ENDED_EVENT = "notebook kernel sandbox ended"
+
+CUSTOM_COMPUTE_PRESET = "custom"
+
+
+def estimated_runtime_seconds(
+ *,
+ created_at: datetime,
+ ended_at: datetime,
+ ttl_expires_at: datetime,
+ sandbox_still_running: bool,
+) -> float:
+ # The provider kills a sandbox at its TTL at the latest, whatever PostHog does. A sandbox that
+ # PostHog stopped tracking without destroying it keeps running until that deadline.
+ end = ttl_expires_at if sandbox_still_running else min(ended_at, ttl_expires_at)
+ return max((end - created_at).total_seconds(), 0.0)
+
+
+def record_sandbox_started(runtime: KernelRuntime, *, sandbox_id: str, ttl_seconds: int) -> None:
+ """Report that the provider created a sandbox for `runtime`.
+
+ Call it as soon as the provider returns the sandbox, because the sandbox costs money from
+ that moment even if the kernel inside it never starts. Never raises, because telemetry must
+ not fail a kernel start.
+ """
+ try:
+ properties: dict[str, Any] = {
+ **_shape_properties(runtime),
+ "kernel_runtime_id": str(runtime.id),
+ "sandbox_id": sandbox_id,
+ "notebook_short_id": runtime.notebook_short_id,
+ "ttl_seconds": ttl_seconds,
+ "provision_seconds": round(max((timezone.now() - runtime.created_at).total_seconds(), 0.0), 3),
+ }
+ _report(runtime, KERNEL_SANDBOX_STARTED_EVENT, properties)
+ except Exception:
+ logger.exception("notebook_kernel_sandbox_started_report_failed", kernel_runtime_id=str(runtime.id))
+
+
+def record_sandbox_ended(runtime: KernelRuntime, *, reason: str, sandbox_still_running: bool) -> None:
+ """Stamp the end of the sandbox behind `runtime` and report it, at most once.
+
+ A stop, a dead handle, a discard and the status poll can each notice the same end, in
+ different processes. The conditional update lets only the first of them claim it, so a
+ sandbox is never counted twice. Rows without `ttl_expires_at` started before this
+ instrumentation existed and have no start event, so they are skipped. Never raises.
+ """
+ if runtime.ended_at is not None:
+ return
+ try:
+ runtime.refresh_from_db(fields=["created_at", "ended_at", "ttl_expires_at"])
+ if runtime.ended_at is not None or runtime.ttl_expires_at is None:
+ return
+
+ # Build the event before the claim, so that a failure here leaves the end unclaimed for the
+ # next path that notices it.
+ ended_at = timezone.now()
+ properties = _ended_properties(runtime, ended_at, reason=reason, sandbox_still_running=sandbox_still_running)
+ team = Team.objects.filter(pk=runtime.team_id).first()
+ user = runtime.user
+
+ claimed = KernelRuntime.objects.filter(pk=runtime.pk, ended_at__isnull=True).update(ended_at=ended_at)
+ if not claimed:
+ return
+ runtime.ended_at = ended_at
+ try:
+ report_user_or_team_action(KERNEL_SANDBOX_ENDED_EVENT, properties, user=user, team=team)
+ except Exception:
+ KernelRuntime.objects.filter(pk=runtime.pk, ended_at=ended_at).update(ended_at=None)
+ runtime.ended_at = None
+ raise
+ except Exception:
+ logger.exception("notebook_kernel_sandbox_ended_report_failed", kernel_runtime_id=str(runtime.id))
+
+
+def record_sandbox_ended_by_id(
+ kernel_runtime_id: UUID, *, team_id: int, user_id: int | None, reason: str, sandbox_still_running: bool
+) -> None:
+ """Record the end of a sandbox for a caller that holds only the runtime id.
+
+ The facade accepts ids and not model rows, so the kernel status endpoint uses this function. The
+ lookup also filters on the team and the user, so a caller can only end a runtime that it owns. The
+ lookup skips a row that has already ended, so a status poll on an ended runtime costs one query.
+ Never raises.
+ """
+ try:
+ if user_id is None:
+ runtime = KernelRuntime.objects.filter(
+ pk=kernel_runtime_id, team_id=team_id, user=None, ended_at__isnull=True
+ ).first()
+ else:
+ runtime = KernelRuntime.objects.filter(
+ pk=kernel_runtime_id, team_id=team_id, user_id=user_id, ended_at__isnull=True
+ ).first()
+ except Exception:
+ logger.exception("notebook_kernel_sandbox_ended_report_failed", kernel_runtime_id=str(kernel_runtime_id))
+ return
+ if runtime is not None:
+ record_sandbox_ended(runtime, reason=reason, sandbox_still_running=sandbox_still_running)
+
+
+def _ended_properties(
+ runtime: KernelRuntime, ended_at: datetime, *, reason: str, sandbox_still_running: bool
+) -> dict[str, Any]:
+ assert runtime.ttl_expires_at is not None
+ runtime_seconds = estimated_runtime_seconds(
+ created_at=runtime.created_at,
+ ended_at=ended_at,
+ ttl_expires_at=runtime.ttl_expires_at,
+ sandbox_still_running=sandbox_still_running,
+ )
+ shape = _shape_properties(runtime)
+ hourly_price = shape["hourly_price_usd"]
+ return {
+ **shape,
+ "kernel_runtime_id": str(runtime.id),
+ "notebook_short_id": runtime.notebook_short_id,
+ "ended_reason": reason,
+ "sandbox_still_running": sandbox_still_running,
+ "tracked_seconds": round(max((ended_at - runtime.created_at).total_seconds(), 0.0), 3),
+ "estimated_runtime_seconds": round(runtime_seconds, 3),
+ "estimated_price_usd": (round(runtime_seconds / 3600 * hourly_price, 4) if hourly_price is not None else None),
+ }
+
+
+def _shape_properties(runtime: KernelRuntime) -> dict[str, Any]:
+ cpu_cores = runtime.provisioned_cpu_cores
+ memory_gb = runtime.provisioned_memory_gb
+ preset = find_matching_preset(cpu_cores=cpu_cores, memory_gb=memory_gb)
+ hourly_price = None
+ if runtime.backend == KernelRuntime.Backend.MODAL and cpu_cores is not None and memory_gb is not None:
+ hourly_price = get_compute_rates().hourly_price(cpu_cores=cpu_cores, memory_gb=memory_gb)
+ return {
+ "backend": runtime.backend,
+ "cpu_cores": cpu_cores,
+ "memory_gb": memory_gb,
+ "compute_preset": preset.key if preset else CUSTOM_COMPUTE_PRESET,
+ "hourly_price_usd": hourly_price,
+ }
+
+
+def _report(runtime: KernelRuntime, event: str, properties: dict[str, Any]) -> None:
+ # Resolve the runtime's own team. With team=None, report_user_or_team_action attributes the
+ # event to the user's currently active project, which can differ from the notebook's project.
+ team = Team.objects.filter(pk=runtime.team_id).first()
+ report_user_or_team_action(event, properties, user=runtime.user, team=team)
diff --git a/products/notebooks/backend/migrations/0021_kernelruntime_sandbox_end.py b/products/notebooks/backend/migrations/0021_kernelruntime_sandbox_end.py
new file mode 100644
index 000000000000..f7cf6d11904c
--- /dev/null
+++ b/products/notebooks/backend/migrations/0021_kernelruntime_sandbox_end.py
@@ -0,0 +1,25 @@
+# Generated by Django 5.2.17 on 2026-09-14 10:53
+
+from django.db import migrations, models
+
+
+class Migration(migrations.Migration):
+ dependencies = [
+ (
+ "notebooks",
+ "0020_alter_kernelruntime_team_alter_kernelruntime_user_and_more",
+ ),
+ ]
+
+ operations = [
+ migrations.AddField(
+ model_name="kernelruntime",
+ name="ended_at",
+ field=models.DateTimeField(blank=True, null=True),
+ ),
+ migrations.AddField(
+ model_name="kernelruntime",
+ name="ttl_expires_at",
+ field=models.DateTimeField(blank=True, null=True),
+ ),
+ ]
diff --git a/products/notebooks/backend/migrations/max_migration.txt b/products/notebooks/backend/migrations/max_migration.txt
index f90ecdac735f..ef54ccdc4a32 100644
--- a/products/notebooks/backend/migrations/max_migration.txt
+++ b/products/notebooks/backend/migrations/max_migration.txt
@@ -1 +1 @@
-0020_alter_kernelruntime_team_alter_kernelruntime_user_and_more
+0021_kernelruntime_sandbox_end
diff --git a/products/notebooks/backend/models.py b/products/notebooks/backend/models.py
index ae3ecff4ef29..830e3fe38cd1 100644
--- a/products/notebooks/backend/models.py
+++ b/products/notebooks/backend/models.py
@@ -194,6 +194,8 @@ class KernelRuntime(UUIDTModel):
# before this was captured.
provisioned_cpu_cores = models.FloatField(null=True, blank=True)
provisioned_memory_gb = models.FloatField(null=True, blank=True)
+ ended_at = models.DateTimeField(null=True, blank=True)
+ ttl_expires_at = models.DateTimeField(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.py
index a531b799d660..ab3120d0b969 100644
--- a/products/notebooks/backend/presentation/views/notebook.py
+++ b/products/notebooks/backend/presentation/views/notebook.py
@@ -71,6 +71,7 @@ from products.notebooks.backend.facade.compute_pricing import (
get_compute_rates,
)
from products.notebooks.backend.facade.contracts import NotebookRunBusy, TeamRunCapacityFull
+from products.notebooks.backend.facade.kernel_sandbox_usage import record_sandbox_ended_by_id
from products.notebooks.backend.facade.sql_v2 import acquire_run_slots, release_run_slots
from products.notebooks.backend.facade.widgets import (
WidgetConflictError,
@@ -1258,6 +1259,7 @@ class NotebookViewSet(TeamAndOrgViewSetMixin, AccessControlViewSetMixin, ForbidD
cpu_cores = sandbox_config.cpu_cores
status = runtime.status if runtime else KernelRuntime.Status.STOPPED
+ sandbox_still_running = False
if (
runtime
and runtime.sandbox_id
@@ -1274,6 +1276,7 @@ class NotebookViewSet(TeamAndOrgViewSetMixin, AccessControlViewSetMixin, ForbidD
status = KernelRuntime.Status.STOPPED
except Exception:
status = KernelRuntime.Status.STOPPED
+ sandbox_still_running = True
if runtime and status == KernelRuntime.Status.STOPPED:
if (
@@ -1288,6 +1291,13 @@ class NotebookViewSet(TeamAndOrgViewSetMixin, AccessControlViewSetMixin, ForbidD
if runtime.status != status:
runtime.status = status
runtime.save(update_fields=["status"])
+ record_sandbox_ended_by_id(
+ runtime.id,
+ team_id=runtime.team_id,
+ user_id=runtime.user_id,
+ reason=status,
+ sandbox_still_running=sandbox_still_running,
+ )
# 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.
diff --git a/products/notebooks/backend/sql_v2_observability.md b/products/notebooks/backend/sql_v2_observability.md
index 297ca72fd487..ca961c67d822 100644
--- a/products/notebooks/backend/sql_v2_observability.md
+++ b/products/notebooks/backend/sql_v2_observability.md
@@ -60,6 +60,27 @@ the streaming path returns a result set (`result_bytes`, `result_rows`), while t
`query_kind` (`Select` vs `Insert`) is what separates them.
The Prometheus `posthog_notebooks_frame_object_bytes` histogram is the mode-independent view of the same thing, but only on the success path.
+## Kernel sandbox usage events
+
+Modal's own metrics count notebook sandboxes, but they carry no team, no size, and no price.
+Two events from `kernel_sandbox_usage.py` carry those, so product analytics can show sandbox starts, sandbox-hours, and an estimated price per team.
+
+| Event | Fires when | Main properties |
+| --------------------------------- | ---------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------- |
+| `notebook kernel sandbox started` | The provider returns a new sandbox, before the kernel starts inside it | `backend`, `cpu_cores`, `memory_gb`, `compute_preset`, `hourly_price_usd`, `ttl_seconds`, `provision_seconds` |
+| `notebook kernel sandbox ended` | PostHog stops tracking the sandbox: a stop, a failure, a discard, or the status poll finding it gone | `ended_reason`, `sandbox_still_running`, `tracked_seconds`, `estimated_runtime_seconds`, `estimated_price_usd` |
+
+`KernelRuntime` stores `ttl_expires_at`, the time the provider kills the sandbox at the latest, and `ended_at`.
+Several paths can notice the same end, and a conditional update on `ended_at` lets only the first one report it.
+
+Read the estimates with these rules:
+
+- **The price is the rate card, not Modal's charge.** `hourly_price_usd` and `estimated_price_usd` use the rates in `compute_pricing.py`, which set the price shown to users. Docker sandboxes have no price.
+- **A sandbox that nothing destroyed costs its full lifetime.** A discard, a kernel that does not answer, or a failed destroy leaves the sandbox running. The event then sets `sandbox_still_running` and runs the estimate to `ttl_expires_at`.
+- **A sandbox found gone ends when PostHog finds it, but never after its TTL.** A sandbox that crashed early and was found late counts longer than it ran.
+- **A sandbox that dies while nobody watches has no end event** until a later stop, reuse, or status poll notices it.
+- **Rows from before these columns existed** have no `ttl_expires_at`, so they report no end event.
+
## Node-run instrumentation (closes gap 1)
Every terminal transition of a `NotebookNodeRun` — the sandbox callback, the direct-lane finish, dispatch failures, and interrupts — reports once through `sql_v2_metrics.record_node_run_terminal`, emitting three sinks:
diff --git a/products/notebooks/backend/test/test_kernel_runtime.py b/products/notebooks/backend/test/test_kernel_runtime.py
index 5441d8917c4f..71e2d61e6da2 100644
--- a/products/notebooks/backend/test/test_kernel_runtime.py
+++ b/products/notebooks/backend/test/test_kernel_runtime.py
@@ -2,10 +2,11 @@ from __future__ import annotations
import json
from dataclasses import dataclass
+from datetime import timedelta
from typing import Any
from posthog.test.base import BaseTest
-from unittest.mock import patch
+from unittest.mock import MagicMock, patch
from django.test import override_settings
from django.utils import timezone
@@ -119,6 +120,7 @@ class TestKernelRuntimeService(BaseTest):
assert sandbox_config.template.value == "notebook_base"
assert sandbox_config.name == f"notebook-kernel-{notebook.short_id}"
+ assert sandbox_config.metadata == {"team_id": str(self.team.id), "product": "notebooks"}
for key, value in expected.items():
assert getattr(sandbox_config, key) == value
@@ -194,6 +196,43 @@ class TestKernelRuntimeService(BaseTest):
with self.assertRaisesMessage(RuntimeError, "Modal credentials are required to start notebook kernels"):
service._get_backend(require_credentials=True)
+ @parameterized.expand([("destroyed", False), ("destroy_failed", True)])
+ @patch("products.notebooks.backend.kernel_sandbox_usage.report_user_or_team_action")
+ def test_shutdown_reports_whether_the_sandbox_still_runs(
+ self, _name: str, destroy_fails: bool, mock_report: MagicMock
+ ) -> None:
+ notebook = Notebook.objects.create(team=self.team)
+ runtime = 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,
+ sandbox_id="sb-notebook-kernel",
+ provisioned_cpu_cores=1,
+ provisioned_memory_gb=2,
+ )
+ KernelRuntime.objects.filter(pk=runtime.pk).update(ttl_expires_at=runtime.created_at + timedelta(hours=1))
+ sandbox = MagicMock()
+ if destroy_fails:
+ sandbox.destroy.side_effect = RuntimeError("provider unavailable")
+ sandbox_class = MagicMock()
+ sandbox_class.get_by_id.return_value = sandbox
+ service = KernelRuntimeService()
+
+ with (
+ patch.object(service, "_acquire_lock", return_value=_DummyLock()),
+ patch.object(service, "_get_sandbox_class", return_value=sandbox_class),
+ ):
+ assert service.shutdown_kernel(notebook, self.user)
+
+ mock_report.assert_called_once()
+ event, properties = mock_report.call_args[0]
+ assert event == "notebook kernel sandbox ended"
+ assert properties["ended_reason"] == KernelRuntime.Status.STOPPED
+ assert properties["sandbox_still_running"] is destroy_fails
+
def test_execute_filters_invalid_variable_names(self) -> None:
service = KernelRuntimeService()
notebook = Notebook.objects.create(team=self.team)
diff --git a/products/notebooks/backend/test/test_kernel_sandbox_usage.py b/products/notebooks/backend/test/test_kernel_sandbox_usage.py
new file mode 100644
index 000000000000..14c05d98df37
--- /dev/null
+++ b/products/notebooks/backend/test/test_kernel_sandbox_usage.py
@@ -0,0 +1,93 @@
+from datetime import UTC, datetime, timedelta
+
+import time_machine
+from posthog.test.base import BaseTest
+from unittest.mock import MagicMock, patch
+
+from django.test import SimpleTestCase
+
+from parameterized import parameterized
+
+from products.notebooks.backend.compute_pricing import get_compute_rates
+from products.notebooks.backend.kernel_sandbox_usage import (
+ KERNEL_SANDBOX_ENDED_EVENT,
+ estimated_runtime_seconds,
+ record_sandbox_ended,
+ record_sandbox_ended_by_id,
+)
+from products.notebooks.backend.models import KernelRuntime
+
+
+class TestEstimatedRuntimeSeconds(SimpleTestCase):
+ @parameterized.expand(
+ [
+ ("destroyed_before_its_ttl", 600, False, 600),
+ ("left_running_costs_until_its_ttl", 600, True, 3600),
+ ("noticed_gone_after_its_ttl", 7200, False, 3600),
+ ]
+ )
+ def test_estimated_runtime_seconds(
+ self, _name: str, ended_after_seconds: int, sandbox_still_running: bool, expected_seconds: int
+ ) -> None:
+ created_at = datetime(2026, 9, 1, 12, 0, tzinfo=UTC)
+ seconds = estimated_runtime_seconds(
+ created_at=created_at,
+ ended_at=created_at + timedelta(seconds=ended_after_seconds),
+ ttl_expires_at=created_at + timedelta(hours=1),
+ sandbox_still_running=sandbox_still_running,
+ )
+ self.assertEqual(seconds, expected_seconds)
+
+
+class TestRecordSandboxEnded(BaseTest):
+ def _modal_runtime_with_an_hour_ttl(self) -> KernelRuntime:
+ runtime = KernelRuntime.objects.create(
+ team=self.team,
+ user=self.user,
+ notebook_short_id="abc123",
+ status=KernelRuntime.Status.RUNNING,
+ backend=KernelRuntime.Backend.MODAL,
+ provisioned_cpu_cores=1,
+ provisioned_memory_gb=2,
+ )
+ KernelRuntime.objects.filter(pk=runtime.pk).update(ttl_expires_at=runtime.created_at + timedelta(hours=1))
+ runtime.refresh_from_db()
+ return runtime
+
+ @patch("products.notebooks.backend.kernel_sandbox_usage.report_user_or_team_action")
+ def test_an_end_noticed_twice_is_reported_once(self, mock_report: MagicMock) -> None:
+ runtime = self._modal_runtime_with_an_hour_ttl()
+ copy_in_another_process = KernelRuntime.objects.get(pk=runtime.pk)
+
+ with time_machine.travel(runtime.created_at + timedelta(minutes=30), tick=False):
+ record_sandbox_ended(runtime, reason=KernelRuntime.Status.STOPPED, sandbox_still_running=False)
+ record_sandbox_ended(
+ copy_in_another_process, reason=KernelRuntime.Status.TIMED_OUT, sandbox_still_running=False
+ )
+
+ mock_report.assert_called_once()
+ event, properties = mock_report.call_args[0]
+ self.assertEqual(event, KERNEL_SANDBOX_ENDED_EVENT)
+ self.assertEqual(properties["ended_reason"], KernelRuntime.Status.STOPPED)
+ self.assertEqual(properties["estimated_runtime_seconds"], 1800)
+ hourly_price = get_compute_rates().hourly_price(cpu_cores=1, memory_gb=2)
+ self.assertEqual(properties["estimated_price_usd"], round(0.5 * hourly_price, 4))
+
+ @patch("products.notebooks.backend.kernel_sandbox_usage.report_user_or_team_action")
+ def test_an_end_whose_event_fails_is_reported_by_the_next_path(self, mock_report: MagicMock) -> None:
+ mock_report.side_effect = [RuntimeError("capture queue unavailable"), None]
+ runtime = self._modal_runtime_with_an_hour_ttl()
+
+ record_sandbox_ended(runtime, reason=KernelRuntime.Status.STOPPED, sandbox_still_running=False)
+ record_sandbox_ended_by_id(
+ runtime.id,
+ team_id=self.team.id,
+ user_id=self.user.id,
+ reason=KernelRuntime.Status.TIMED_OUT,
+ sandbox_still_running=False,
+ )
+
+ self.assertEqual(mock_report.call_count, 2)
+ self.assertEqual(mock_report.call_args[0][1]["ended_reason"], KernelRuntime.Status.TIMED_OUT)
+ runtime.refresh_from_db()
+ self.assertIsNotNone(runtime.ended_at)