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.

chore(evals): run notebook python and duckdb cells in the eval harness (#79690)

Sinan Kucukkoseler5075f5ad0857
diff --git a/products/notebooks/evals/__init__.py b/products/notebooks/evals/__init__.py
new file mode 100644
index 000000000000..bbe6ab2c0173
--- /dev/null
+++ b/products/notebooks/evals/__init__.py
@@ -0,0 +1,5 @@
+"""Sandboxed agent evals for the notebook MCP tools.
+
+Discovered by the shared harness (``hogli evals notebooks``); see
+``products/posthog_ai/eval_harness/README.md``.
+"""
diff --git a/products/notebooks/evals/eval_notebook_cells.py b/products/notebooks/evals/eval_notebook_cells.py
new file mode 100644
index 000000000000..56b62d083976
--- /dev/null
+++ b/products/notebooks/evals/eval_notebook_cells.py
@@ -0,0 +1,75 @@
+"""Eval cases for authoring notebook cells over MCP.
+
+Both lanes a cell run can take are graded here, because they fail in different places:
+a SQL cell rides the direct HogQL lane and never provisions anything, while a python
+cell dispatches a Temporal workflow that provisions the notebook kernel sandbox.
+
+To run one case:
+ hogli evals eval_notebook_cells --eval sql_cell_report
+"""
+
+from __future__ import annotations
+
+from products.notebooks.evals.scorers import CellRunsCompleted, NotebookCreated
+from products.notebooks.evals.seeders import seed_case_team
+from products.posthog_ai.eval_harness.base import SandboxedPublicEval
+from products.posthog_ai.eval_harness.config import SandboxedEvalCase
+from products.posthog_ai.eval_harness.harness.context import EvalContext
+from products.posthog_ai.eval_harness.scorers import RequiredToolCall
+
+
+async def eval_notebook_cells(ctx: EvalContext) -> None:
+ cases: list[SandboxedEvalCase] = [
+ SandboxedEvalCase(
+ # Cheapest possible kernel-lane check: no query, no dataframe, no dependency
+ # between cells. When this passes and the cases below fail, the sandbox is fine
+ # and the agent's analysis is what broke.
+ name="python_cell_arithmetic",
+ prompt=("Create a notebook called 'Kernel smoke test'. Add a Python cell that prints the result of 1 + 2."),
+ expected={
+ "notebook_created": {},
+ "cell_runs_completed": {"node_types": ["python"]},
+ },
+ setup=seed_case_team,
+ ),
+ SandboxedEvalCase(
+ name="sql_cell_report",
+ prompt=(
+ "Create a notebook called 'Signup momentum'. Add a SQL cell that returns weekly counts "
+ "of `signed_up` events over the last 8 weeks, and finish with a short markdown summary "
+ "of what the numbers show."
+ ),
+ expected={
+ "notebook_created": {},
+ "cell_runs_completed": {"node_types": ["hogql"]},
+ },
+ setup=seed_case_team,
+ ),
+ SandboxedEvalCase(
+ name="python_cell_from_dataframe",
+ prompt=(
+ "Create a notebook called 'Signup momentum'. Add a SQL cell that returns weekly counts "
+ "of `signed_up` events over the last 8 weeks, then add a Python cell that reads that "
+ "cell's dataframe and computes the week-over-week percentage change. Finish with a short "
+ "markdown summary naming the week that grew the most."
+ ),
+ expected={
+ "notebook_created": {},
+ # Both lanes: the SQL cell proves the direct path, the python cell proves the
+ # kernel sandbox was provisioned, ran the code, and reported back.
+ "cell_runs_completed": {"node_types": ["hogql", "python"]},
+ },
+ setup=seed_case_team,
+ ),
+ ]
+
+ await SandboxedPublicEval(
+ experiment_name="sandboxed-notebook-cells-cli",
+ cases=cases,
+ scorers=[
+ RequiredToolCall({"notebooks-add-cell"}),
+ NotebookCreated(),
+ CellRunsCompleted(),
+ ],
+ ctx=ctx,
+ )
diff --git a/products/notebooks/evals/scorers.py b/products/notebooks/evals/scorers.py
new file mode 100644
index 000000000000..af3dd9b6c97b
--- /dev/null
+++ b/products/notebooks/evals/scorers.py
@@ -0,0 +1,147 @@
+"""Scorers for the notebook evals.
+
+These grade the notebook the agent left behind, not the transcript that describes it.
+A cell run that is dispatched and one that finishes look nearly identical in the log —
+the tool returns ``status: running`` either way — and it is the finished run whose
+result the notebook renders, so the run rows are the honest source.
+
+Reading the ORM means running async: the engine dispatches every scorer through
+``eval_async``, and the base class's sync branch would execute Django ORM calls on the
+event loop, which Django's async-safety guard rejects.
+"""
+
+from __future__ import annotations
+
+import asyncio
+from typing import Any
+
+from products.notebooks.backend.markdown_conversion import MARKDOWN_NOTEBOOK_NODE_TYPE
+from products.notebooks.backend.models import Notebook, NotebookNodeRun
+from products.posthog_ai.eval_harness.scorers import AsyncOnlyScorerMixin
+from products.posthog_ai.eval_harness.scorers.contract import Score, Scorer
+
+__all__ = ["CellRunsCompleted", "NotebookCreated"]
+
+
+def _seeded_team_id(output: dict | None) -> int | None:
+ seed = (output or {}).get("seed")
+ team_id = seed.get("team_id") if isinstance(seed, dict) else None
+ return team_id if isinstance(team_id, int) else None
+
+
+def _spec(expected: dict | None, name: str) -> dict | None:
+ if not isinstance(expected, dict):
+ return None
+ spec = expected.get(name)
+ return spec if isinstance(spec, dict) else None
+
+
+def _markdown_body(content: Any) -> str | None:
+ """The markdown of a ``ph-markdown-notebook`` document, or None for legacy rich text."""
+ if not isinstance(content, dict):
+ return None
+ nodes = content.get("content")
+ if not isinstance(nodes, list) or not nodes:
+ return None
+ first = nodes[0]
+ if not isinstance(first, dict) or first.get("type") != MARKDOWN_NOTEBOOK_NODE_TYPE:
+ return None
+ attrs = first.get("attrs")
+ if not isinstance(attrs, dict):
+ return None
+ markdown = attrs.get("markdown")
+ return markdown if isinstance(markdown, str) and markdown else None
+
+
+class NotebookCreated(AsyncOnlyScorerMixin, Scorer):
+ """Binary: does the case's team hold a markdown notebook the agent created?
+
+ Opt in with ``expected = {"notebook_created": {}}``.
+
+ Markdown is what the whole new flow produces, so a notebook that came back as
+ legacy rich text (``markdown`` unset on its single document node) fails rather
+ than counting — that is the clobbering regression, not a near miss.
+ """
+
+ def _name(self) -> str:
+ return "notebook_created"
+
+ async def _run_eval_async(self, output: Any, expected: Any = None, **kwargs: Any) -> Score:
+ if _spec(expected, self._name()) is None:
+ return Score(name=self._name(), score=None, metadata={"reason": f"No {self._name()} key on case"})
+ team_id = _seeded_team_id(output)
+ if team_id is None:
+ return Score(name=self._name(), score=0.0, metadata={"reason": "No seed.team_id — case needs a seeder"})
+
+ notebooks = await asyncio.to_thread(self._read_notebooks, team_id)
+ if not notebooks:
+ return Score(name=self._name(), score=0.0, metadata={"reason": "No notebook in the team"})
+ markdown = [n for n in notebooks if n["is_markdown"]]
+ if not markdown:
+ return Score(
+ name=self._name(),
+ score=0.0,
+ metadata={"reason": "Notebook exists but is not a markdown document", "notebooks": notebooks},
+ )
+ return Score(name=self._name(), score=1.0, metadata={"notebooks": markdown})
+
+ @staticmethod
+ def _read_notebooks(team_id: int) -> list[dict[str, Any]]:
+ return [
+ {
+ "short_id": notebook.short_id,
+ "title": notebook.title,
+ "is_markdown": _markdown_body(notebook.content) is not None,
+ }
+ for notebook in Notebook.objects.filter(team_id=team_id, deleted=False)
+ ]
+
+
+class CellRunsCompleted(AsyncOnlyScorerMixin, Scorer):
+ """Binary: did every required kind of cell reach a completed run?
+
+ ``expected = {"cell_runs_completed": {"node_types": ["hogql", "python"]}}``
+
+ ``hogql`` runs take the direct lane and never touch a sandbox; ``python`` and
+ ``duckdb`` runs go out to the notebook kernel. Naming both is what separates "the
+ agent wrote a python cell" from "the kernel actually ran it", and the observed
+ statuses land in the metadata so a failure says which of the two happened.
+ """
+
+ def _name(self) -> str:
+ return "cell_runs_completed"
+
+ async def _run_eval_async(self, output: Any, expected: Any = None, **kwargs: Any) -> Score:
+ spec = _spec(expected, self._name())
+ if spec is None:
+ return Score(name=self._name(), score=None, metadata={"reason": f"No {self._name()} spec on case"})
+ required = [t for t in spec.get("node_types", []) if isinstance(t, str) and t]
+ if not required:
+ return Score(name=self._name(), score=None, metadata={"reason": "Missing 'node_types' on spec"})
+ team_id = _seeded_team_id(output)
+ if team_id is None:
+ return Score(name=self._name(), score=0.0, metadata={"reason": "No seed.team_id — case needs a seeder"})
+
+ runs = await asyncio.to_thread(self._read_runs, team_id)
+ completed = {run["node_type"] for run in runs if run["status"] == NotebookNodeRun.Status.DONE}
+ missing = [node_type for node_type in required if node_type not in completed]
+ if missing:
+ return Score(
+ name=self._name(),
+ score=0.0,
+ metadata={
+ "reason": "No completed run for every required cell type",
+ "missing_node_types": missing,
+ "runs": runs,
+ },
+ )
+ return Score(name=self._name(), score=1.0, metadata={"runs": runs})
+
+ @staticmethod
+ def _read_runs(team_id: int) -> list[dict[str, Any]]:
+ return [
+ {"node_type": node_type, "status": status, "error": error}
+ for node_type, status, error in NotebookNodeRun.objects.for_team(team_id)
+ .order_by("created_at")
+ .values_list("node_type", "status", "error")
+ ]
diff --git a/products/notebooks/evals/seeders.py b/products/notebooks/evals/seeders.py
new file mode 100644
index 000000000000..b9822feeb8a2
--- /dev/null
+++ b/products/notebooks/evals/seeders.py
@@ -0,0 +1,22 @@
+"""Seeder hooks for the notebook eval cases.
+
+The seeder contract takes no per-case parameters, so each seeded state gets its own
+function. Every one of them returns ``team_id``: it is the only channel a scorer has
+for reaching the case's own team, and the notebook scorers grade the documents and run
+rows the agent left there rather than what the transcript claims.
+"""
+
+from __future__ import annotations
+
+from typing import Any
+
+from products.tasks.backend.facade.agents import CustomPromptSandboxContext
+
+
+def seed_case_team(context: CustomPromptSandboxContext) -> dict[str, Any]:
+ """Seed nothing; hand the scorers the case's team so they can read the end state.
+
+ For cases where the agent creates the notebook itself, Hedgebox is already the
+ whole fixture.
+ """
+ return {"team_id": context.team_id}
diff --git a/products/notebooks/plan/notebooks_mcp_evals_plan.md b/products/notebooks/plan/notebooks_mcp_evals_plan.md
new file mode 100644
index 000000000000..1f701fcbca4c
--- /dev/null
+++ b/products/notebooks/plan/notebooks_mcp_evals_plan.md
@@ -0,0 +1,225 @@
+# Offline evals for markdown notebooks over MCP
+
+How to add agent evals for notebook creation and editing through the MCP tools, using the existing eval harness.
+
+## 1. How evals work in this repo
+
+Everything runs on the standalone harness in `products/posthog_ai/eval_harness/`, not pytest.
+`hogli evals` boots shared infrastructure once (test DB, Django live server, LLM gateway, MCP server, Temporal, personhog), then runs every selected suite concurrently with Braintrust as the eval engine.
+
+Two suite kinds:
+
+| Kind | Marker | Per case | Infra |
+| ------------------- | --------------------------------- | ------------------------------------------------------------------ | ----------------------------- |
+| sandboxed (default) | none | the real coding agent in a real sandbox, talking to the MCP server | everything |
+| one-shot | `SUITE_KIND = SuiteKind.ONE_SHOT` | one in-process model call | test DB, personhog, demo data |
+
+Notebook MCP evals are **sandboxed**: the thing under test is an agent driving real tools against real state, which a one-shot call cannot exercise.
+
+Facts that shape the design:
+
+- Suites are discovered by convention. Product-owned suites live in `products/<product>/evals/` (plural), so ours is `products/notebooks/evals/eval_*.py`, suite id `notebooks/<module>::<fn>`.
+- A suite is one Braintrust experiment. `experiment_name` is the history key, so renaming it resets cross-run comparison.
+- Every case gets its own org/team/user cloned from a master Hedgebox team. Cases never see each other's state. The seeded user is "Karen Smith".
+- The Hedgebox dataset is byte-for-byte reproducible under a fixed seed, so assert shapes and relative date ranges, never absolute counts.
+- Case fields: `name`, `prompt`, `expected` (keyed by scorer `_name()`), `metadata`, `setup` (the seeder).
+- Whatever the seeder returns lands in `output["seed"]`, which is the only channel scorers have for seeded IDs.
+- The harness adds `ExitCodeZero` to every experiment; suites must not declare it.
+- Sandboxed evals are **not** in CI. `.github/workflows/ci-ai.yml` only runs the older `ee/hogai/eval/ci` pytest tree behind an `evals-ready` label. These run on demand, locally or on Modal.
+
+## 2. The surface under test
+
+Behind `revamped-py-notebooks`, the notebook tool set is:
+
+| Tool | Kind | Notes |
+| ------------------------------------------------------------------------------------------------------------------- | ------------ | ---------------------------------------------------------------------------------------------------------------------------------------- |
+| `notebooks-create-markdown` | hand-written | title + optional prose. Explicitly refuses to carry cells |
+| `notebooks-add-cell` | hand-written | `sql` / `python` / `markdown` / `saved_insight` / `component`. sql and python dispatch a run and write the result back into the document |
+| `notebooks-update-cell` | hand-written | edit code and re-run, or omit code to re-run as-is. Returns `stale_dependents` |
+| `notebooks-delete-cell` | hand-written | |
+| `notebook-edit` | hand-written | markdown string replacement (`old_markdown` / `new_markdown` / `replace_all`) |
+| `notebooks-get` | generated | title, markdown, cells, `depends_on`/`dependents`, derived stale status |
+| `notebooks-list-frames`, `notebooks-configure-compute`, `notebooks-run-cell-result`, `notebooks-run-cell-interrupt` | generated | kernel-side |
+
+With the flag **off** the legacy set is registered instead (`notebooks-create`, `notebooks-retrieve`, `notebooks-partial-update`), and the markdown tools disappear.
+The two sets are mutually exclusive, which matters for the harness change below.
+
+## 3. Environment blockers, verified
+
+**a. The markdown tools reach the eval MCP server through a flag override.**
+Tool filtering gates the whole markdown set on `revamped-py-notebooks` (see `services/mcp/tests/unit/tool-filtering.test.ts`), and the eval MCP server sets that flag in `FEATURE_FLAG_OVERRIDES` (`harness/services.py`). Without it the tools are not registered at all.
+Note the side effect: it also removes `notebooks-create` / `notebooks-retrieve` from the eval tool list, so a legacy-notebook eval needs a different lever.
+
+**b. Django-side gating is already satisfied.**
+`harness/lifecycle.py` patches `posthoganalytics.feature_enabled` to return `True` for the whole run, so the flag-gated SQLV2 endpoints answer normally.
+
+**c. Both cell lanes run, docker only.**
+A pure-HogQL run takes the direct lane (`enqueue_direct_run` in `presentation/views/notebook.py`), which rides the async query manager. The harness runs with `TEST=1`, where Celery is eager, so the query executes inline and no sandbox is involved.
+Python and DuckDB runs call `start_sql_v2_run_workflow`, which needs the notebook Temporal workflows registered and a kernel sandbox. The harness now does both (see [Notebook kernel sandboxes](../../posthog_ai/eval_harness/README.md#notebook-kernel-sandboxes)); before that change the run sat at `running` until its poll window expired.
+
+The kernel lane is docker-only: the notebook kernel reads its backend straight off `SANDBOX_PROVIDER`, and the modal provider sets that to `MODAL_EVALS`, which is not a `KernelRuntime.Backend` value. Run python or duckdb cases with `--provider docker`; SQL-only cases work on either provider.
+
+**d. Scopes are fine.** The sandbox context defaults to `"full"` MCP scopes (`custom_prompt_internals.py`), which includes `notebook:write`.
+
+**e. End-state scoring is possible but must be async.**
+Braintrust's base `_run_eval_async` calls `_run_eval_sync` directly on the event loop, so a scorer doing sync ORM work trips Django's async guard. A DB-reading scorer subclasses `AsyncOnlyScorerMixin, Scorer` and does its work in `asyncio.to_thread`. The pattern already exists (`DuplicateUniqueFlagKey` in `products/posthog_ai/evals/experiments/scorers.py`).
+The seeder must return `team_id` for this to work at all.
+
+## 4. Use-case selection
+
+Ground it in what the tools actually do in practice rather than what feels comprehensive.
+Check the MCP analytics for the notebook tools before picking cases (`query-mcp-tool-stats` and `query-mcp-tool-failures` per tool, or the MCP analytics UI). What that showed when this plan was written:
+
+- `notebook-edit` carries by far the highest error rate of the editing tools, and most of its failures are opaque `internal` — what a thrown `Error` looks like in telemetry, meaning `old_markdown` was not found or not unique. Highest-value target, and the one with a real failure signature to reproduce.
+- `notebooks-add-cell` is barely used yet. Evals here lock behavior in before it scales, rather than fixing a fire.
+- The legacy `notebooks-partial-update` fails mostly on HTTP 409 version conflicts.
+
+Selection principles worth keeping:
+
+- One case per behavior you could plausibly regress, not one case per tool.
+- Prefer cases where a wrong answer is cheap to detect and expensive in production (clobbering a document, losing cell results, rebuilding an insight that already exists).
+- Include at least one case where the correct behavior is _not_ calling a tool, and one where the tool rejects the first attempt and the agent must recover. Those catch prompt regressions that success-only cases miss.
+
+### Proposed cases
+
+**Suite 0: `eval_notebook_cells`** (shipped — the lane check)
+
+Two cases, both creating a notebook from scratch: `sql_cell_report` proves the direct lane, `python_cell_from_dataframe` proves the kernel lane end to end (sandbox provisioned, code run, result written back). `CellRunsCompleted` grades the `NotebookNodeRun` rows rather than the transcript, because a dispatched run and a finished one look the same in the log.
+
+**Suite A: `eval_notebook_authoring`** (create from an analysis request)
+
+| Case | Prompt shape | What it grades |
+| -------------------------- | ---------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------- |
+| `create_signup_report` | "Create a notebook called X showing weekly `signed_up` counts over the last 8 weeks, with a short summary" | uses `notebooks-create-markdown`, adds a SQL cell that completes, titles it, adds prose |
+| `multi_cell_dependency` | two related SQL steps where the second reads the first's dataframe | dataframe naming, `refs`, dependency order |
+| `embed_saved_insight` | "Put our 'Weekly signups' insight in a notebook" | reuses the seeded insight via a `saved_insight` cell instead of rewriting the SQL |
+| `component_hogql_rejected` | phrasing that tempts a `component` cell with a HogQL source | the tool rejects it; agent recovers to `cell_type: sql` |
+
+**Suite B: `eval_notebook_editing`** (change an existing notebook without breaking it)
+
+| Case | Prompt shape | What it grades |
+| --------------------- | --------------------------------------------------- | --------------------------------------------------------------------------------------------------------- |
+| `local_prose_edit` | "Reword the intro section of notebook X" | edits only the target span; every other section and both cells survive with their `runId`/`result` intact |
+| `insert_cell_after` | "Add a breakdown cell right after the signups cell" | uses `after_node_id` rather than appending at the end |
+| `delete_one_cell` | "Drop the file-size cell" | deletes exactly one cell |
+| `refresh_stale_cells` | seeded notebook where an upstream cell changed | reads `notebooks-get`, re-runs stale cells in dependency order with `notebooks-update-cell` and no `code` |
+
+Eight sandboxed cases is a sensible first suite. Each case is a full agent run, so cost scales linearly and a 20-case suite gets slow to iterate on.
+
+## 5. Data generation
+
+Hedgebox gives you events, insights, dashboards, and flags, but no notebooks. Editing and orientation cases therefore need a seeder.
+
+Follow the synthesizer/seeder split that `data_warehouse` uses:
+
+- `products/notebooks/evals/synthesizer.py` — pure, Django-free, deterministic. Builds the markdown document as frozen dataclasses: section anchors, cell tags with fixed `nodeId`s, dataframe names, and any planted "needle" the case must find. Unit-testable in `products/notebooks/backend/test/`, never inside the `evals/` tree.
+- `products/notebooks/evals/seeders.py` — takes `CustomPromptSandboxContext`, creates the `Notebook` row in the case's team with `content = buildMarkdownNotebookContent(markdown)` equivalent, and (for staleness cases) `NotebookNodeRun` rows so `notebooks-get` reports realistic run state.
+- `products/notebooks/evals/constants.py` — every literal shared by the prompt, the `expected` payload, and the scorers. Titles, anchor strings, node IDs, dataframe names. This is what stops prompt and scorer from drifting apart.
+
+Seeder contract details that bite:
+
+- Synchronous `def seed_x(context) -> dict[str, Any]`. The harness calls it via `asyncio.to_thread`; never make it async.
+- No per-case parameters. Case-specific state means a dedicated seeder function, not a knob on a shared one.
+- Return everything a scorer needs, including `team_id` and the notebook `short_id`. For editing cases also return `markdown_before` so a scorer can diff against it.
+- A seeder exception marks the case an infra error, excluded from averages, so a broken seeder never reads as an agent regression.
+
+For the authoring suite, the seeder is optional: Hedgebox already ships the "Weekly signups" insight that `embed_saved_insight` needs. A tiny seeder that just returns `{"team_id": ...}` is still worth it, because it unlocks end-state scoring.
+
+## 6. Scoring
+
+Stack three layers. Weight the deterministic ones as the backbone and use judges only where the question is genuinely qualitative.
+
+### Layer 1: tool trajectory, from the agent log
+
+Deterministic `Scorer` subclasses reading `LogParser.cached(output["raw_log"], ...)`. Reuse the generics first (`RequiredToolCall`, `NoToolCall`, `LastToolCallNot`, and `CalledTargetTool` from `cli_mcp/scorers.py`). Notebook-specific additions:
+
+- `UsedMarkdownNotebookFlow` — created through `notebooks-create-markdown`, not by hand-assembling a document.
+- `CellsTitled` — every successful sql/python `add-cell` carried a non-empty `title`. The tool description demands it and PR #75471 exists because agents skip it.
+- `ReusedSavedInsight` — a `saved_insight` cell with the seeded short_id, and no SQL cell duplicating the same query.
+- `RanCellsInDependencyOrder` — for update chains, each upstream re-run precedes its dependents' re-runs.
+- `RecoveredFromToolRejection` — the rejected shape was attempted, then a correct call succeeded. Generalizes `RecoveredToCorrectTool`.
+
+### Layer 2: end state, from the database
+
+This is the layer that actually catches the production failure, and it is new for this repo. Async scorers (`AsyncOnlyScorerMixin, Scorer` + `asyncio.to_thread`) that read the notebook back from Postgres using `seed["team_id"]` and `seed["notebook_short_id"]`:
+
+- `NotebookIsMarkdown` — content is still a single `ph-markdown-notebook` node, not clobbered into legacy rich text.
+- `PreservedUnrelatedContent` — every anchor from `seed["markdown_before"]` except the edit target is still present, and every pre-existing cell tag still carries its `nodeId`, `runId`, and `result` props. Direct counter to the clobbering failure.
+- `CellRunSucceeded` — the `NotebookNodeRun` rows for added cells are `DONE` with a non-empty envelope. Catches "wrote a cell that looks right and errors".
+
+`system.notebooks` also exposes a `markdown` column via HogQL, but a direct ORM read from the scorer is simpler and avoids a query round trip.
+
+### Layer 3: LLM judge, for quality
+
+`JudgedScorer` subclasses implementing `_prepare` only:
+
+- `NotebookAnswersQuestion` — given the final markdown, does the notebook actually answer the prompt: right metric, right window, a chart present, prose that a reader can skim.
+- `CellTitlesAreDescriptive` — titles say what the cell shows, not that it is SQL.
+
+Judges get the final markdown from the same DB read, so they are async by construction.
+
+### Scoring discipline
+
+- `score=None` means "this check does not apply to this case" and is dropped from the aggregate. `0.0` means the agent got it wrong, and also covers broken-judge and missing-input paths that must not vanish silently.
+- Count only successful tool calls (`is_error=False`). The agent is allowed to attempt and fail.
+- One implemented branch per scorer, never both `_run_eval_sync` and `_run_eval_async`.
+- Keep `expected` payloads keyed by scorer name so one scorer list can span the whole suite.
+
+## 7. Layout
+
+```text
+products/notebooks/evals/
+ __init__.py
+ constants.py # shared literals: titles, anchors, node ids, dataframe names
+ synthesizer.py # pure deterministic markdown document builder
+ seeders.py # ORM installation into the per-case team [shipped]
+ scorers.py # trajectory + end-state + judge scorers [shipped]
+ eval_notebook_cells.py # both run lanes [shipped]
+ eval_notebook_authoring.py
+ eval_notebook_editing.py
+```
+
+No `conftest.py` and no `pytest` import in that tree. Unit tests for the synthesizer go under `products/notebooks/backend/test/`.
+
+Suite skeleton:
+
+```python
+from products.posthog_ai.eval_harness.base import SandboxedPublicEval
+from products.posthog_ai.eval_harness.config import SandboxedEvalCase
+from products.posthog_ai.eval_harness.harness.context import EvalContext
+
+
+async def eval_notebook_editing(ctx: EvalContext) -> None:
+ await SandboxedPublicEval(
+ experiment_name="sandboxed-notebooks-editing-cli",
+ cases=[...],
+ scorers=[...],
+ ctx=ctx,
+ )
+```
+
+Use `SandboxedPublicEval` unless a prompt or seed should not leave the machine; public gets you a Braintrust URL and cross-run history. Keep the `-cli` suffix so the naming lines up with the other MCP suites.
+
+## 8. Rollout order
+
+1. ~~Enable `revamped-py-notebooks` in the eval MCP server, register the notebook Temporal workflows, and reclaim kernel sandboxes.~~ Done, with `eval_notebook_cells` as the case that proves it.
+2. Add `eval_notebook_authoring` — the discrimination cases (reuse a saved insight, recover from the component+HogQL rejection) on trajectory scorers.
+3. Add the document seeder plus `PreservedUnrelatedContent`, then `eval_notebook_editing`.
+4. Add judges last. They are the noisiest layer and the easiest to over-fit.
+5. Once stable, run with `--trials 3` to see variance before treating any score as a baseline.
+
+Commands:
+
+```bash
+hogli evals --list | grep notebooks # confirm discovery, import-checks the modules
+hogli evals eval_notebook_cells --eval python_cell_from_dataframe --provider docker
+hogli evals notebooks --provider docker # whole domain; docker because of the kernel lane
+```
+
+Run from a flox shell. Read the transcript path printed on the final line, then the per-case `<case>.jsonl` and `<case>.summary.txt` in the experiment's agent-log directory. The score alone will not tell you why a case failed.
+
+## 9. Open decisions
+
+- **Kernel lane on modal.** Docker-only today, which caps python-cell cases at four concurrent sandboxes. Lifting it means teaching the notebook kernel that `MODAL_EVALS` is a modal backend, which is production code changed for an eval's benefit — worth it only if the python suite grows past what docker can hold.
+- **Legacy notebook tools.** Enabling the flag hides them, so any eval of `notebooks-create` / `notebooks-partial-update` (the 409-conflict path, which has real error volume) needs a per-suite flag lever rather than a process-wide env var.
+- **Judge model cost.** Judges run per case per scorer. Two judges across eight cases is fine; ten is not.
diff --git a/products/posthog_ai/eval_harness/README.md b/products/posthog_ai/eval_harness/README.md
index 11412cf161ca..353b2c4f70c6 100644
--- a/products/posthog_ai/eval_harness/README.md
+++ b/products/posthog_ai/eval_harness/README.md
@@ -95,6 +95,7 @@ Use Docker for small smoke tests or when remote access is unavailable.
**docker** (default) runs sandboxes as local containers, so a Docker daemon must be reachable.
Each container defaults to 16 GB, so host RAM is what bounds concurrency: the default cap is 4, and raising `--max-sandboxes` needs a big host.
+A case running notebook python or duckdb cells holds a second container on top of that (see [Notebook kernel sandboxes](#notebook-kernel-sandboxes)), which the sandbox cap does not count.
Every docker run verifies the `posthog-sandbox-base` image is fresh before any case starts: it rebuilds when `@posthog/agent` has published a newer version than the one baked into the image, or when the Dockerfile changed since the image was built.
An unchanged image passes the check in under a second, and even a rebuild is mostly layer-cached — only the npm install layer onward re-runs when the agent version moved.
@@ -121,6 +122,25 @@ Each case waits for its workflow to terminate the sandbox, then runs a tag-scope
When the whole run ends, the harness sweeps the Modal app again for its own leftover sandboxes, so a crashed or interrupted run doesn't leave sandboxes billing until their TTL.
The sweep is scoped to this run's own tasks (matched by the `task_id` sandbox tag), so a second eval run sharing the same Modal app keeps its sandboxes.
+## Notebook kernel sandboxes
+
+A notebook SQL cell whose refs are all HogQL runs on the direct lane — the async query manager, no sandbox — and needs nothing beyond the live server.
+A python or duckdb cell instead dispatches the notebook Temporal workflow, which provisions a **second** sandbox for the case: the notebook kernel, ~2 GB alongside the agent's 16 GB.
+
+The harness supports that lane on **docker only**.
+The notebook kernel resolves its backend straight from `SANDBOX_PROVIDER`, and the modal provider sets that to `MODAL_EVALS`, which is not one of `KernelRuntime.Backend`'s values — the port map and liveness checks both miss, and the kernel never comes up.
+Run suites with python or duckdb cells as `--provider docker`; SQL-only suites are unaffected and run anywhere.
+
+Three things make the lane work, all automatic:
+
+- The eval Temporal worker registers the notebook workflows next to the tasks ones, and `GENERAL_PURPOSE_TASK_QUEUE` (where notebook runs dispatch) points at the same per-process queue, so one worker serves both.
+- `SANDBOX_API_URL` already points the sandbox at the Django live server, which is where the kernel posts its result callback and reads the data plane.
+- The docker provider builds the notebook image during startup. Left to first use it would build inside a Temporal activity with a five-minute budget, and a cold build overruns it.
+
+Kernel sandboxes are reclaimed by the harness, not by a TTL — the docker backend ignores `SandboxConfig.ttl_seconds`.
+Each case destroys its own before releasing its sandbox slot, and the run sweeps the eval database for stragglers at both ends.
+`--keep-sandbox-containers` preserves kernel containers the same way it preserves agent ones.
+
## Concurrency
Every selected suite runs concurrently on one event loop, and a global semaphore bounds the number of live sandboxes across all of them.
diff --git a/products/posthog_ai/eval_harness/base.py b/products/posthog_ai/eval_harness/base.py
index 2524970be904..eebf82de608c 100644
--- a/products/posthog_ai/eval_harness/base.py
+++ b/products/posthog_ai/eval_harness/base.py
@@ -13,6 +13,7 @@ from .acp_log import ParsedLog, parse_log
from .config import AgentArtifacts, BaseEvalCase, SandboxedEvalCase
from .engines.base import EvalEngine
from .engines.types import CaseHooks, CaseSpec, ExperimentResult, ExperimentSpec, SpanKind
+from .harness.kernel_sandboxes import reclaim_kernels
from .log_sink import append_case_scores, build_case_dir, write_case_logs
from .runner import EvalCaseResult, run_eval_case
from .scorers import ExitCodeZero, wrap_scorers
@@ -377,10 +378,20 @@ class _SandboxedEvalRun(_BaseEvalRun):
raise
# Start the agent budget after team setup, so neither semaphore wait
# nor the ClickHouse copy can consume it.
- result = await asyncio.wait_for(
- run_eval_case(eval_case, sandbox_context, provider=self._provider_strategy),
- timeout=ctx.per_case_timeout_seconds,
- )
+ try:
+ result = await asyncio.wait_for(
+ run_eval_case(eval_case, sandbox_context, provider=self._provider_strategy),
+ timeout=ctx.per_case_timeout_seconds,
+ )
+ finally:
+ # Still inside the slot: a notebook python or duckdb cell provisions a
+ # kernel sandbox of its own, and nothing else reclaims it. A timed-out
+ # case is exactly the one most likely to have left one running. One
+ # indexed query for every case that never touched a notebook.
+ await reclaim_kernels(
+ sandbox_context.team_id,
+ keep=self._provider_strategy is not None and self._provider_strategy.keeps_sandboxes(),
+ )
return result, seed_result
async def _post_process(
diff --git a/products/posthog_ai/eval_harness/harness/AGENTS.md b/products/posthog_ai/eval_harness/harness/AGENTS.md
index b9c81969c04a..1d19acf1ceeb 100644
--- a/products/posthog_ai/eval_harness/harness/AGENTS.md
+++ b/products/posthog_ai/eval_harness/harness/AGENTS.md
@@ -92,6 +92,12 @@ Bootstrap registers teardown on an `ExitStack` as each resource comes up, so a f
After any change, a Ctrl-C mid-run must leave no listeners on 18000 / 13308 / 18787 / 15051 / 15052, no `task-sandbox-*` containers, no Temporal dev server, and no Tailscale Funnel mappings left enabled on 443 / 8443 / 10000.
+A case can also own a sandbox the harness never created: a notebook python or duckdb cell provisions the notebook kernel through the notebook Temporal workflow.
+Nothing upstream reclaims it — the docker backend ignores `SandboxConfig.ttl_seconds`, and the sweeps below match agent containers by task id, which a kernel container's name never carries.
+`kernel_sandboxes.release_kernels` is what reclaims them, from three places: once at startup (a prior interrupted run's rows survive in the reused test database), per case inside the sandbox slot so the memory is free before the next case takes it, and once at the end of the run.
+It is scoped by team per case and unscoped for the sweeps, which is safe only because the eval test database holds nothing but this harness's own teams.
+Keep those calls on the stack that still holds the provider settings overrides, or the sandbox class resolves differently than it did at create time.
+
Three layers tear a case's sandbox down, outermost last:
- Every case signals its `ProcessTaskWorkflow` with a terminal status and waits for the workflow result, which includes the workflow's own `cleanup_sandbox` call.
diff --git a/products/posthog_ai/eval_harness/harness/kernel_sandboxes.py b/products/posthog_ai/eval_harness/harness/kernel_sandboxes.py
new file mode 100644
index 000000000000..2ebb8de00b7f
--- /dev/null
+++ b/products/posthog_ai/eval_harness/harness/kernel_sandboxes.py
@@ -0,0 +1,85 @@
+"""Reclaiming the notebook kernel sandboxes a case leaves behind.
+
+A notebook python or duckdb cell run dispatches through the notebook Temporal
+workflow, which provisions a **second** sandbox for the case — the notebook kernel —
+alongside the agent sandbox the harness manages itself. Nothing else reclaims it
+here: the docker backend ignores ``SandboxConfig.ttl_seconds``, and the harness's own
+sweeps match agent containers by task id, which a kernel container's name
+(``notebook-kernel-<short_id>-<hex>``) never carries. Left alone, every python case
+would hold its kernel container for the rest of the run.
+
+The eval test database only ever holds this harness's own teams, so an unscoped sweep
+here can never touch a dev-stack kernel: those rows live in the development database.
+
+``release_kernels`` is synchronous ORM and provider work; ``reclaim_kernels`` is the
+async wrapper every caller in the harness actually uses.
+"""
+
+from __future__ import annotations
+
+import asyncio
+import logging
+
+from products.notebooks.backend.models import KernelRuntime
+from products.tasks.backend.facade.sandbox import get_sandbox_class_for_backend
+
+logger = logging.getLogger(__name__)
+
+_RELEASABLE_STATUSES = (
+ KernelRuntime.Status.STARTING,
+ KernelRuntime.Status.RUNNING,
+ KernelRuntime.Status.ERROR,
+)
+"""Statuses that can still own a live sandbox. A row already marked stopped, timed out,
+or discarded had its sandbox destroyed by whoever set that status."""
+
+
+def release_kernels(team_id: int | None = None) -> int:
+ """Destroy the kernel sandboxes recorded for ``team_id``, or for every team when ``None``.
+
+ Returns the number of runtimes actually released. A row whose sandbox could not be
+ destroyed keeps its status, so the end-of-run sweep gets a second attempt at it —
+ a container that survived a transient provider failure would otherwise hold its
+ memory for the rest of the run with nothing left to reclaim it.
+ """
+ runtimes = KernelRuntime.objects.filter(status__in=_RELEASABLE_STATUSES).exclude(sandbox_id__isnull=True)
+ if team_id is not None:
+ runtimes = runtimes.filter(team_id=team_id)
+
+ released = 0
+ for runtime in runtimes:
+ if not runtime.sandbox_id:
+ continue
+ try:
+ sandbox_class = get_sandbox_class_for_backend(runtime.backend)
+ sandbox_class.get_by_id(runtime.sandbox_id).destroy()
+ except Exception:
+ logger.warning(
+ "Could not destroy notebook kernel sandbox %s (team %d)",
+ runtime.sandbox_id,
+ runtime.team_id,
+ exc_info=True,
+ )
+ continue
+ runtime.status = KernelRuntime.Status.STOPPED
+ runtime.save(update_fields=["status"])
+ released += 1
+ return released
+
+
+async def reclaim_kernels(team_id: int | None = None, *, keep: bool = False) -> None:
+ """Release kernel sandboxes off the event loop, without ever failing the caller.
+
+ ``keep`` honors a run that deliberately preserves sandboxes for inspection. A
+ kernel the provider cannot reach is a leaked container, not a wrong score, so
+ every failure here is a warning.
+ """
+ if keep:
+ return
+ try:
+ released = await asyncio.to_thread(release_kernels, team_id)
+ except Exception:
+ logger.warning("Notebook kernel release failed (team_id=%s)", team_id, exc_info=True)
+ return
+ if released:
+ logger.info("Released %d notebook kernel sandbox(es) (team_id=%s)", released, team_id)
diff --git a/products/posthog_ai/eval_harness/harness/lifecycle.py b/products/posthog_ai/eval_harness/harness/lifecycle.py
index cc7f5ac49abd..12aa951c12a2 100644
--- a/products/posthog_ai/eval_harness/harness/lifecycle.py
+++ b/products/posthog_ai/eval_harness/harness/lifecycle.py
@@ -27,6 +27,7 @@ from .demo_data import SandboxedDemoData, ensure_demo_ready
from .discovery import EvalSuite, discover_suites
from .django_env import EvalDatabase
from .env_preflight import validate_eval_env
+from .kernel_sandboxes import reclaim_kernels
from .live_server import EvalLiveServer
from .ports import DJANGO_LIVE_PORT
from .providers import PreflightError, SandboxProviderStrategy, build_provider
@@ -254,6 +255,10 @@ class SandboxedEvalHarness:
TEMPORAL_CLIENT_KEY=None,
# Keep eval workflows off any dev worker already polling the normal tasks queue.
TASKS_TASK_QUEUE=temporal_task_queue(),
+ # Notebook kernel runs dispatch onto the general-purpose queue. Pointing it at
+ # the same per-process queue lets the single eval worker serve both, and keeps
+ # those workflows off a dev worker the same way.
+ GENERAL_PURPOSE_TASK_QUEUE=temporal_task_queue(),
**self.provider.settings_overrides(),
)
@@ -269,6 +274,10 @@ class SandboxedEvalHarness:
worker = TemporalWorkerThread()
worker.start()
stack.callback(worker.stop)
+ # A run interrupted before its own sweep leaves kernel rows behind in the
+ # reused test database; reclaim those containers now rather than at the end.
+ await self._sweep_notebook_kernels()
+ stack.push_async_callback(self._sweep_notebook_kernels)
ctx = self._build_context(required, reporter)
@@ -284,6 +293,17 @@ class SandboxedEvalHarness:
results = await asyncio.gather(*(self._run_suite(suite, ctx) for suite in suites))
return results
+ async def _sweep_notebook_kernels(self) -> None:
+ """Sweep every notebook kernel sandbox recorded in the eval database.
+
+ A python or duckdb notebook cell provisions a kernel sandbox next to the case's
+ agent sandbox, and docker ignores the sandbox TTL. Each case reclaims its own
+ before it frees its slot; this catches whatever a crash or a timeout left behind.
+ Registered on the stack that still holds the provider settings overrides, so the
+ sandbox class resolves the same way it did when the kernel was created.
+ """
+ await reclaim_kernels(keep=self.provider is not None and self.provider.keeps_sandboxes())
+
def _build_context(self, required: frozenset[Infra], reporter: ProgressReporter) -> EvalContext:
if Infra.DEMO_DATA in required and self._demo_data is None:
raise RuntimeError("_bootstrap() must run before the eval context is built")
diff --git a/products/posthog_ai/eval_harness/harness/providers.py b/products/posthog_ai/eval_harness/harness/providers.py
index 0206cf3ff603..413b868b4e03 100644
--- a/products/posthog_ai/eval_harness/harness/providers.py
+++ b/products/posthog_ai/eval_harness/harness/providers.py
@@ -162,6 +162,15 @@ class SandboxProviderStrategy(ABC):
"""Per-sandbox max lifetime, or ``None`` to keep ``SANDBOX_TTL_SECONDS``."""
return None
+ def keeps_sandboxes(self) -> bool:
+ """Whether this run deliberately leaves sandboxes behind for inspection.
+
+ Covers the sandboxes the harness does not create itself — notebook kernels —
+ so a debugging flag that preserves a case's agent container preserves the
+ kernel container the same case provisioned.
+ """
+ return False
+
def cleanup_case(self, task_id: str) -> None: # noqa: B027 — optional hook; only providers whose per-case teardown can lag override it
"""Per-case teardown run after each case settles, on top of the workflow's own cleanup."""
@@ -197,9 +206,17 @@ class DockerProviderStrategy(SandboxProviderStrategy):
# stale image can't break the whole run. Imported here because it pulls in Django.
from products.tasks.backend.logic.services.docker_sandbox import ( # noqa: PLC0415 — Django import, kept off the harness import path
ensure_fresh_base_image,
+ ensure_template_image,
+ )
+ from products.tasks.backend.logic.services.sandbox import ( # noqa: PLC0415 — Django import, kept off the harness import path
+ SandboxTemplate,
)
ensure_fresh_base_image(force=self.rebuild_image)
+ # The notebook kernel image is otherwise built on first use, inside a Temporal
+ # activity with a 5-minute budget — a cold build blows through it, and the run's
+ # first python cell fails on a timeout instead of on anything real.
+ ensure_template_image(SandboxTemplate.NOTEBOOK_BASE)
def settings_overrides(self) -> dict[str, Any]:
# Docker containers reach the host via host.docker.internal.
@@ -210,6 +227,9 @@ class DockerProviderStrategy(SandboxProviderStrategy):
"SANDBOX_MCP_URL": f"http://host.docker.internal:{MCP_PORT}/mcp",
}
+ def keeps_sandboxes(self) -> bool:
+ return self.keep_containers
+
def cleanup_case(self, task_id: str) -> None:
# Belt-and-braces on top of the workflow's own shutdown: its cleanup_sandbox
# can lag or be cancelled at worker shutdown, so reclaim this case's container
diff --git a/products/posthog_ai/eval_harness/harness/services.py b/products/posthog_ai/eval_harness/harness/services.py
index 0b8af7863dd5..bb740a1f9c9d 100644
--- a/products/posthog_ai/eval_harness/harness/services.py
+++ b/products/posthog_ai/eval_harness/harness/services.py
@@ -117,7 +117,12 @@ def start_mcp_server(live_server_url: str) -> Callable[[], None]:
# (honored only when NODE_ENV is explicitly development/test — set above).
# product-data-catalog gates the metric-discovery section of the execute-sql
# description; the governed-metrics evals exercise that path.
- "FEATURE_FLAG_OVERRIDES": json.dumps({"product-data-catalog": True}),
+ # revamped-py-notebooks gates the markdown notebook tools (create-markdown,
+ # add-cell, update-cell, delete-cell, get, list-frames). It also *hides* the
+ # legacy notebooks-create / notebooks-retrieve pair, which the two surfaces
+ # being mutually exclusive makes unavoidable — an eval of the legacy tools
+ # needs its own lever, not this one.
+ "FEATURE_FLAG_OVERRIDES": json.dumps({"product-data-catalog": True, "revamped-py-notebooks": True}),
}
logger.info("Starting MCP server (Hono runtime) on port %d (API: %s)", MCP_PORT, api_url)
diff --git a/products/posthog_ai/eval_harness/harness/temporal_env.py b/products/posthog_ai/eval_harness/harness/temporal_env.py
index 653f3b303380..e2625335cccd 100644
--- a/products/posthog_ai/eval_harness/harness/temporal_env.py
+++ b/products/posthog_ai/eval_harness/harness/temporal_env.py
@@ -12,6 +12,10 @@ from temporalio.testing import WorkflowEnvironment
from posthog.temporal.common.client import async_connect
from posthog.temporal.common.worker import create_worker
+from products.notebooks.backend.facade.temporal import (
+ ACTIVITIES as NOTEBOOK_ACTIVITIES,
+ WORKFLOWS as NOTEBOOK_WORKFLOWS,
+)
from products.tasks.backend.facade.temporal import (
ACTIVITIES as TASKS_ACTIVITIES,
WORKFLOWS as TASKS_WORKFLOWS,
@@ -89,6 +93,13 @@ class TemporalWorkerThread:
daemon thread so it can poll Temporal without competing with the harness's
main loop; DB access is unblocked (nothing blocks it in the harness) so
temporal activities can use the Django ORM against the test database.
+
+ It serves the notebook workflows as well as the tasks ones. In production those
+ live on ``GENERAL_PURPOSE_TASK_QUEUE`` and the tasks ones on ``TASKS_TASK_QUEUE``,
+ but ``lifecycle`` points both settings at this run's single per-process queue, so
+ one worker covers both. Without them a notebook python or duckdb cell dispatches a
+ workflow nothing ever picks up, and the run sits at ``running`` until its poll
+ window expires.
"""
def __init__(self, *, max_concurrent_workflow_tasks: int = 100, max_concurrent_activities: int = 100) -> None:
@@ -124,8 +135,8 @@ class TemporalWorkerThread:
metrics_port=0,
namespace=settings.TEMPORAL_NAMESPACE,
task_queue=settings.TASKS_TASK_QUEUE,
- workflows=TASKS_WORKFLOWS,
- activities=TASKS_ACTIVITIES, # type: ignore[arg-type]
+ workflows=TASKS_WORKFLOWS + NOTEBOOK_WORKFLOWS,
+ activities=TASKS_ACTIVITIES + NOTEBOOK_ACTIVITIES, # type: ignore[arg-type]
max_concurrent_workflow_tasks=self._max_concurrent_workflow_tasks,
max_concurrent_activities=self._max_concurrent_activities,
enable_combined_metrics_server=False,
diff --git a/products/posthog_ai/eval_harness/test/test_kernel_sandboxes.py b/products/posthog_ai/eval_harness/test/test_kernel_sandboxes.py
new file mode 100644
index 000000000000..47505ba89b3a
--- /dev/null
+++ b/products/posthog_ai/eval_harness/test/test_kernel_sandboxes.py
@@ -0,0 +1,100 @@
+from __future__ import annotations
+
+from posthog.test.base import APIBaseTest
+from unittest.mock import MagicMock, patch
+
+from parameterized import parameterized
+
+from posthog.models.team import Team
+
+from products.notebooks.backend.models import KernelRuntime
+from products.posthog_ai.eval_harness.harness.kernel_sandboxes import release_kernels
+
+RELEASABLE = [
+ (KernelRuntime.Status.STARTING,),
+ (KernelRuntime.Status.RUNNING,),
+ (KernelRuntime.Status.ERROR,),
+]
+ALREADY_RELEASED = [
+ (KernelRuntime.Status.STOPPED,),
+ (KernelRuntime.Status.TIMED_OUT,),
+ (KernelRuntime.Status.DISCARDED,),
+]
+
+
+class TestReleaseKernels(APIBaseTest):
+ def setUp(self):
+ super().setUp()
+ self.sandbox = MagicMock()
+ sandbox_class = MagicMock()
+ sandbox_class.get_by_id.return_value = self.sandbox
+ self.get_sandbox_class = patch(
+ "products.posthog_ai.eval_harness.harness.kernel_sandboxes.get_sandbox_class_for_backend",
+ return_value=sandbox_class,
+ )
+ self.get_sandbox_class.start()
+ self.addCleanup(self.get_sandbox_class.stop)
+
+ def _runtime(self, *, status: str, team: Team | None = None, sandbox_id: str = "sbx-1") -> KernelRuntime:
+ return KernelRuntime.objects.create(
+ team=team or self.team,
+ notebook_short_id="aBcD1234",
+ status=status,
+ backend=KernelRuntime.Backend.DOCKER,
+ sandbox_id=sandbox_id,
+ )
+
+ @parameterized.expand(RELEASABLE)
+ def test_destroys_and_marks_stopped(self, status: str) -> None:
+ runtime = self._runtime(status=status)
+
+ assert release_kernels(self.team.id) == 1
+
+ self.sandbox.destroy.assert_called_once()
+ runtime.refresh_from_db()
+ assert runtime.status == KernelRuntime.Status.STOPPED
+
+ @parameterized.expand(ALREADY_RELEASED)
+ def test_leaves_already_released_runtimes_alone(self, status: str) -> None:
+ runtime = self._runtime(status=status)
+
+ assert release_kernels(self.team.id) == 0
+
+ self.sandbox.destroy.assert_not_called()
+ runtime.refresh_from_db()
+ assert runtime.status == status
+
+ def test_retries_a_sandbox_that_could_not_be_destroyed(self) -> None:
+ self.sandbox.destroy.side_effect = RuntimeError("provider unreachable")
+ runtime = self._runtime(status=KernelRuntime.Status.RUNNING)
+
+ assert release_kernels(self.team.id) == 0
+
+ runtime.refresh_from_db()
+ assert runtime.status == KernelRuntime.Status.RUNNING
+
+ self.sandbox.destroy.side_effect = None
+
+ assert release_kernels(self.team.id) == 1
+
+ runtime.refresh_from_db()
+ assert runtime.status == KernelRuntime.Status.STOPPED
+
+ def test_scoping_by_team_spares_a_concurrent_case(self) -> None:
+ other_team = Team.objects.create(organization=self.organization, name="other case")
+ mine = self._runtime(status=KernelRuntime.Status.RUNNING)
+ theirs = self._runtime(status=KernelRuntime.Status.RUNNING, team=other_team, sandbox_id="sbx-2")
+
+ assert release_kernels(self.team.id) == 1
+
+ mine.refresh_from_db()
+ theirs.refresh_from_db()
+ assert mine.status == KernelRuntime.Status.STOPPED
+ assert theirs.status == KernelRuntime.Status.RUNNING
+
+ def test_unscoped_sweep_releases_every_team(self) -> None:
+ other_team = Team.objects.create(organization=self.organization, name="other case")
+ self._runtime(status=KernelRuntime.Status.RUNNING)
+ self._runtime(status=KernelRuntime.Status.RUNNING, team=other_team, sandbox_id="sbx-2")
+
+ assert release_kernels() == 2
diff --git a/products/tasks/backend/logic/services/docker_sandbox.py b/products/tasks/backend/logic/services/docker_sandbox.py
index d0ed7a1d52f2..54acb82555f4 100644
--- a/products/tasks/backend/logic/services/docker_sandbox.py
+++ b/products/tasks/backend/logic/services/docker_sandbox.py
@@ -1392,3 +1392,13 @@ def ensure_fresh_base_image(*, force: bool = False) -> None:
labels={_AGENT_VERSION_LABEL: latest or "unknown"},
force=True,
)
+
+
+def ensure_template_image(template: SandboxTemplate) -> str:
+ """Build ``template``'s image if it is missing, and return its name.
+
+ Sandbox creation does this itself, but a cold build can take minutes — longer than
+ the budget of whatever is provisioning the sandbox. Callers that know a template is
+ coming can pay that cost up front instead. A present image returns immediately.
+ """
+ return DockerSandbox._ensure_image_exists(template)