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): cap a notebook at 50 cells (#88451)

Sinan Kucukkoselerf75fc4c1e203
diff --git a/ee/hogai/tools/create_notebook/tool.py b/ee/hogai/tools/create_notebook/tool.py
index 10150ec716d8..43b1391f3c34 100644
--- a/ee/hogai/tools/create_notebook/tool.py
+++ b/ee/hogai/tools/create_notebook/tool.py
@@ -5,6 +5,7 @@ from pydantic import BaseModel, Field
from posthog.schema import ArtifactContentType, ArtifactSource, AssistantTool, AssistantToolCallMessage
+from products.notebooks.backend.facade.contracts import NotebookCellLimitExceeded
from products.notebooks.backend.facade.widget_catalog import format_notebook_widget_catalog_for_agents
from ee.hogai.tool import MaxTool, ToolMessagesArtifact
@@ -168,6 +169,13 @@ class CreateNotebookTool(MaxTool):
"so it was not changed.",
None,
)
+ except NotebookCellLimitExceeded as err:
+ # Deterministic: the same save fails again, so say so rather than letting the
+ # model spend turns retrying it.
+ return (
+ f"Error: {err} The notebook was not changed, so do not retry this save.",
+ None,
+ )
# Build response message
if save_to_notebook or is_already_saved:
diff --git a/products/notebooks/backend/facade/contracts.py b/products/notebooks/backend/facade/contracts.py
index fc0c068dc24a..2a80949f4d5d 100644
--- a/products/notebooks/backend/facade/contracts.py
+++ b/products/notebooks/backend/facade/contracts.py
@@ -18,6 +18,15 @@ from uuid import UUID
from pydantic.dataclasses import dataclass
+class NotebookCellLimitExceeded(Exception):
+ """Raised when a write would grow a notebook past its cell ceiling.
+
+ Lives here rather than beside the validator because it crosses the product boundary:
+ Max writes notebooks through the facade, and its tool has to catch this to tell the
+ model the notebook is full instead of retrying the save.
+ """
+
+
@dataclass(frozen=True)
class NotebookData:
"""A notebook's persisted state, as other products read it."""
diff --git a/products/notebooks/backend/logic.py b/products/notebooks/backend/logic.py
index aa8319051684..6efa0fb1fb9b 100644
--- a/products/notebooks/backend/logic.py
+++ b/products/notebooks/backend/logic.py
@@ -19,6 +19,7 @@ from asgiref.sync import sync_to_async
from products.access_control.backend.facade.user_access_control import UserAccessControl
from .models import Notebook, ResourceNotebook
+from .sql_v2_state import validate_cell_count
def _base_queryset(team_id: int, *, include_deleted: bool = False) -> Any:
@@ -67,6 +68,10 @@ async def aupdate_notebook_content(
notebook = await aget_notebook(team_id, short_id, include_deleted=True)
if notebook is None:
return None
+ # Enforced here rather than only at the HTTP layer: this writer bypasses the serializer
+ # entirely (it is a queryset update, so no save() hook or signal fires either), and it is
+ # how Max saves a notebook. A ceiling only the API respects is not a ceiling.
+ validate_cell_count(notebook.content, content)
await Notebook.objects.filter(pk=notebook.pk).aupdate(
content=content,
title=title,
@@ -89,6 +94,11 @@ async def aupsert_notebook(
content: dict[str, Any],
text_content: str | None = None,
) -> tuple[Notebook, bool]:
+ # Checked before the upsert, not after: aget_or_create would otherwise have already
+ # written the over-limit row by the time the ceiling rejected it. Like the rest of this
+ # writer, the read and the write are not atomic — the path has no version CAS at all.
+ existing = await aget_notebook(team_id, short_id, include_deleted=True)
+ validate_cell_count(existing.content if existing is not None else None, content)
notebook, created = await Notebook.objects.aget_or_create(
team_id=team_id,
short_id=short_id,
diff --git a/products/notebooks/backend/presentation/views/notebook.py b/products/notebooks/backend/presentation/views/notebook.py
index 3318b18830e5..ba3b03b3a7b8 100644
--- a/products/notebooks/backend/presentation/views/notebook.py
+++ b/products/notebooks/backend/presentation/views/notebook.py
@@ -93,7 +93,11 @@ from products.notebooks.backend.sql_v2_serializers import (
NotebookSQLV2RunStatusResponseSerializer,
NotebookSQLV2StateResponseSerializer,
)
-from products.notebooks.backend.sql_v2_state import build_notebook_cell_state
+from products.notebooks.backend.sql_v2_state import (
+ NotebookCellLimitExceeded,
+ build_notebook_cell_state,
+ validate_cell_count,
+)
from products.notebooks.backend.temporal.client import start_sql_v2_run_workflow
from products.notebooks.backend.temporal.sql_v2 import SQLV2RunInput
from products.tasks.backend.facade.exceptions import SandboxProvisionError
@@ -383,6 +387,12 @@ class NotebookSerializer(NotebookMinimalSerializer):
def validate_content(self, value: Any) -> Any:
if not isinstance(value, dict):
return value
+ # self.instance is set on update and None on create, so a new notebook is measured
+ # against an empty document and an edit against what it currently holds.
+ try:
+ validate_cell_count(self.instance.content if self.instance else None, value)
+ except NotebookCellLimitExceeded as err:
+ raise serializers.ValidationError(str(err))
try:
return normalize_notebook_query_nodes(value)
except InvalidNotebookQueryError as err:
@@ -1678,6 +1688,14 @@ class NotebookViewSet(TeamAndOrgViewSetMixin, AccessControlViewSetMixin, ForbidD
current_version=locked_notebook.version,
)
else:
+ # Checked against the locked row rather than in the serializer, so two saves
+ # racing to add a cell cannot both read the same under-limit count and pass.
+ # This is the path the MCP cell tools write through, so it is the one an agent
+ # adding cells in a loop actually meets.
+ try:
+ validate_cell_count(locked_notebook.content, submitted_content)
+ except NotebookCellLimitExceeded as err:
+ raise serializers.ValidationError(str(err))
annotated_content = annotate_python_nodes(submitted_content)
diff = markdown_collab.build_markdown_update_diff(locked_notebook.content, annotated_content)
result = markdown_collab.submit_markdown_update(
diff --git a/products/notebooks/backend/sql_v2_state.py b/products/notebooks/backend/sql_v2_state.py
index 5074008fbbfb..68e51764d98c 100644
--- a/products/notebooks/backend/sql_v2_state.py
+++ b/products/notebooks/backend/sql_v2_state.py
@@ -16,6 +16,7 @@ from typing import Any
from posthog.hogql import ast
from posthog.hogql.parser import parse_select
+from products.notebooks.backend.facade.contracts import NotebookCellLimitExceeded
from products.notebooks.backend.models import NotebookNodeRun
from products.notebooks.backend.python_analysis import analyze_python_globals
from products.notebooks.backend.sql_v2_references import _TableReferenceCollector, resolve_sql_v2_references
@@ -26,6 +27,14 @@ from products.notebooks.backend.util import (
)
_CELL_TAGS = {"SQLV2": "sql", "PythonV2": "python", "Query": "saved_insight"}
+
+# The most cells one notebook may hold. A cell is the expensive unit: a SQL or Python cell is a
+# ClickHouse query or a sandbox execution, and the MCP tools let an agent add one and run it in
+# the same call, in a loop, with nothing between it and storage. Counted the way `extract_cells`
+# counts, so this ceiling and what the API reports as a cell are the same number.
+MAX_NOTEBOOK_CELLS = 50
+
+__all__ = ["NotebookCellLimitExceeded"]
_DATAFRAME_NAME = re.compile(r"^[A-Za-z_][A-Za-z0-9_]*$")
_CODE_PREVIEW_CHARS = 8_000
@@ -68,6 +77,22 @@ def extract_cells(content: Any) -> list[NotebookCellState]:
return cells
+def validate_cell_count(previous_content: Any, next_content: Any) -> None:
+ """Refuse a save that grows a notebook past the cell ceiling.
+
+ Only growth is refused. A notebook already over the ceiling — written before this existed,
+ or by a path that predates it — stays editable, so its owner can delete cells down instead
+ of finding every save rejected. A save that leaves the count unchanged always passes.
+ """
+ next_count = len(extract_cells(next_content))
+ if next_count <= MAX_NOTEBOOK_CELLS or next_count <= len(extract_cells(previous_content)):
+ return
+ raise NotebookCellLimitExceeded(
+ f"This notebook is at its limit of {MAX_NOTEBOOK_CELLS} cells. "
+ "Delete a cell before adding another, or start a new notebook for the next step."
+ )
+
+
def _referenced_names(cell: NotebookCellState, candidates: set[str]) -> set[str]:
if not candidates or not cell.code.strip():
return set()
diff --git a/products/notebooks/backend/test/test_facade.py b/products/notebooks/backend/test/test_facade.py
index 2061701ee626..2a7194ab81b5 100644
--- a/products/notebooks/backend/test/test_facade.py
+++ b/products/notebooks/backend/test/test_facade.py
@@ -8,7 +8,9 @@ from products.access_control.backend.facade.user_access_control import UserAcces
from products.notebooks.backend import logic
from products.notebooks.backend.analytics import NotebookCreationSource
from products.notebooks.backend.facade import api, content
+from products.notebooks.backend.facade.contracts import NotebookCellLimitExceeded
from products.notebooks.backend.models import Notebook, ResourceNotebook
+from products.notebooks.backend.sql_v2_state import MAX_NOTEBOOK_CELLS
def _create_account(team):
@@ -192,6 +194,46 @@ class TestNotebooksFacadeAsync(BaseTest):
self.assertEqual(data.text_content, "updated")
self.assertEqual(data.version, notebook.version + 1)
+ def _cells_doc(self, count: int) -> dict:
+ markdown = "\n\n".join(
+ f'<SQLV2 nodeId="s{index}" code="select {index}" returnVariable="df{index}" />' for index in range(count)
+ )
+ return {
+ "type": "doc",
+ "content": [{"type": "ph-markdown-notebook", "attrs": {"nodeId": "md", "markdown": markdown}}],
+ }
+
+ @pytest.mark.asyncio
+ async def test_aupdate_notebook_content_refuses_growth_past_the_cell_ceiling(self):
+ # This writer is a queryset update, so it fires no serializer, no save() hook, and no
+ # signal. Max saves notebooks through it, so a ceiling enforced only at the API layer
+ # would not apply to anything Max writes.
+ await Notebook.objects.acreate(team=self.team, short_id="cap001", title="t", content=self._cells_doc(0))
+ with self.assertRaises(NotebookCellLimitExceeded):
+ await api.aupdate_notebook_content(
+ self.team.id,
+ "cap001",
+ content=self._cells_doc(MAX_NOTEBOOK_CELLS + 1),
+ title="t",
+ text_content="",
+ last_modified_by_id=self.user.id,
+ )
+
+ @pytest.mark.asyncio
+ async def test_aupsert_notebook_refuses_the_ceiling_without_writing_a_partial_row(self):
+ # The check has to run before aget_or_create: after it, the over-limit notebook is
+ # already stored by the time the ceiling rejects it.
+ with self.assertRaises(NotebookCellLimitExceeded):
+ await api.aupsert_notebook(
+ self.team.id,
+ "cap002",
+ created_by_id=self.user.id,
+ last_modified_by_id=self.user.id,
+ title="t",
+ content=self._cells_doc(MAX_NOTEBOOK_CELLS + 1),
+ )
+ self.assertFalse(await Notebook.objects.filter(team=self.team, short_id="cap002").aexists())
+
@pytest.mark.asyncio
async def test_acan_user_edit_notebook_creator(self):
notebook = await Notebook.objects.acreate(team=self.team, title="t", created_by=self.user)
diff --git a/products/notebooks/backend/test/test_sql_v2_state.py b/products/notebooks/backend/test/test_sql_v2_state.py
index 3fb0c7197385..36a2ba1995cb 100644
--- a/products/notebooks/backend/test/test_sql_v2_state.py
+++ b/products/notebooks/backend/test/test_sql_v2_state.py
@@ -10,7 +10,14 @@ from rest_framework import status
from products.notebooks.backend.models import Notebook, NotebookNodeRun
from products.notebooks.backend.sql_v2_references import resolve_sql_v2_references
-from products.notebooks.backend.sql_v2_state import build_dependency_edges, build_notebook_cell_state, extract_cells
+from products.notebooks.backend.sql_v2_state import (
+ MAX_NOTEBOOK_CELLS,
+ NotebookCellLimitExceeded,
+ build_dependency_edges,
+ build_notebook_cell_state,
+ extract_cells,
+ validate_cell_count,
+)
def markdown_content(markdown: str) -> dict[str, Any]:
@@ -71,6 +78,67 @@ class TestCellExtractionAndEdges(SimpleTestCase):
assert cells[2].depends_on == ["s"]
+def cells_markdown(count: int) -> dict[str, Any]:
+ return markdown_content(
+ "\n\n".join(
+ f'<SQLV2 nodeId="s{index}" code="select {index}" returnVariable="df{index}" />' for index in range(count)
+ )
+ )
+
+
+class TestCellCountLimit(SimpleTestCase):
+ @parameterized.expand(
+ [
+ ("under", MAX_NOTEBOOK_CELLS - 1, True),
+ ("at_the_limit", MAX_NOTEBOOK_CELLS, True),
+ ("over", MAX_NOTEBOOK_CELLS + 1, False),
+ ]
+ )
+ def test_growth_is_refused_past_the_ceiling(self, _name: str, next_count: int, allowed: bool) -> None:
+ # Without a ceiling an agent adds cells in a loop, and every SQL or Python cell it adds
+ # is a query or a sandbox execution. Nothing else bounds that.
+ if allowed:
+ validate_cell_count(None, cells_markdown(next_count))
+ return
+ with self.assertRaises(NotebookCellLimitExceeded):
+ validate_cell_count(None, cells_markdown(next_count))
+
+ @parameterized.expand([("unchanged", 0), ("shrinking", -1)])
+ def test_a_notebook_already_over_the_ceiling_stays_editable(self, _name: str, delta: int) -> None:
+ # Notebooks written before the ceiling existed must not become unsavable, or their owner
+ # cannot delete cells down to get under it.
+ over = MAX_NOTEBOOK_CELLS + 5
+ validate_cell_count(cells_markdown(over), cells_markdown(over + delta))
+
+ def test_a_notebook_already_over_the_ceiling_still_cannot_grow(self) -> None:
+ over = MAX_NOTEBOOK_CELLS + 5
+ with self.assertRaises(NotebookCellLimitExceeded):
+ validate_cell_count(cells_markdown(over), cells_markdown(over + 1))
+
+
+class TestCellLimitEndpointWiring(APIBaseTest):
+ def test_markdown_save_refuses_a_notebook_over_the_cell_ceiling(self) -> None:
+ # The wiring guard for the unit cases above: this endpoint is what the MCP cell tools
+ # and the editor both write through, so a refactor that stops calling the validator
+ # would leave every SimpleTestCase green and still ship an uncapped endpoint.
+ notebook = Notebook.objects.create(team=self.team, short_id="nbcap01", content=cells_markdown(0), version=0)
+ response = self.client.post(
+ f"/api/environments/{self.team.id}/notebooks/{notebook.short_id}/collab/markdown_save/",
+ {
+ "client_id": "c1",
+ "version": notebook.version,
+ "content": cells_markdown(MAX_NOTEBOOK_CELLS + 1),
+ "text_content": "",
+ },
+ format="json",
+ )
+ assert response.status_code == status.HTTP_400_BAD_REQUEST, response.content
+ assert str(MAX_NOTEBOOK_CELLS) in response.content.decode()
+
+ notebook.refresh_from_db()
+ assert len(extract_cells(notebook.content)) == 0
+
+
class TestNotebookCellState(APIBaseTest):
def _notebook(self, markdown: str) -> Notebook:
return Notebook.objects.create(team=self.team, created_by=self.user, content=markdown_content(markdown))
diff --git a/services/mcp/schema/tool-definitions-all.json b/services/mcp/schema/tool-definitions-all.json
index 8a6ca14dd913..21ebbb171f8f 100644
--- a/services/mcp/schema/tool-definitions-all.json
+++ b/services/mcp/schema/tool-definitions-all.json
@@ -8034,7 +8034,7 @@
}
},
"notebooks-add-cell": {
- "description": "Add a cell to a markdown notebook. SQL and Python cells run immediately: the call waits up to ~45s and returns the result — columns, a capped row preview, stdout/stderr (a Python cell's logs and tracebacks), and error — so you can look at the output and decide the next step (fix, or proceed). If the status comes back 'running', poll notebooks-run-cell-result with the run_id. A cell that reads other cells' dataframes references them by dataframe_name; those cells must have completed a run first, so add cells in dependency order. SQL cells are always HogQL: queries against PostHog or data warehouse tables run on ClickHouse, and a SQL cell that references a Python-created dataframe runs on the notebook's local engine automatically — any local dataframe is queryable by name, same syntax. The first Python cell can take longer while the notebook's sandbox kernel starts. Run analysis Python here rather than in a runtime the user can't see — dataframe work, statistics, clustering, forecasting, plotting — so the code and its output stay visible and re-runnable beside the result; the sandbox has pandas, numpy, scipy, scikit-learn, and matplotlib. component cells add other node types: Query, Image, Embed, Latex, FeatureFlag, Survey, Experiment, Person, Cohort, Recording, RecordingPlaylist. Pass a short title on every cell you add, describing what that cell shows — it renders in the cell header and is what a reader skims instead of the code.",
+ "description": "Add a cell to a markdown notebook. SQL and Python cells run immediately: the call waits up to ~45s and returns the result — columns, a capped row preview, stdout/stderr (a Python cell's logs and tracebacks), and error — so you can look at the output and decide the next step (fix, or proceed). If the status comes back 'running', poll notebooks-run-cell-result with the run_id. A cell that reads other cells' dataframes references them by dataframe_name; those cells must have completed a run first, so add cells in dependency order. SQL cells are always HogQL: queries against PostHog or data warehouse tables run on ClickHouse, and a SQL cell that references a Python-created dataframe runs on the notebook's local engine automatically — any local dataframe is queryable by name, same syntax. The first Python cell can take longer while the notebook's sandbox kernel starts. Run analysis Python here rather than in a runtime the user can't see — dataframe work, statistics, clustering, forecasting, plotting — so the code and its output stay visible and re-runnable beside the result; the sandbox has pandas, numpy, scipy, scikit-learn, and matplotlib. component cells add other node types: Query, Image, Embed, Latex, FeatureFlag, Survey, Experiment, Person, Cohort, Recording, RecordingPlaylist. Pass a short title on every cell you add, describing what that cell shows — it renders in the cell header and is what a reader skims instead of the code. A notebook holds at most 50 cells; past that the call fails, so start a new notebook rather than retrying.",
"category": "Notebooks",
"feature": "notebooks",
"summary": "Add a cell to a notebook; SQL/Python cells run immediately.",
diff --git a/services/mcp/schema/tool-definitions.json b/services/mcp/schema/tool-definitions.json
index c28ec84ee3eb..dbd9cec02428 100644
--- a/services/mcp/schema/tool-definitions.json
+++ b/services/mcp/schema/tool-definitions.json
@@ -302,7 +302,7 @@
}
},
"notebooks-add-cell": {
- "description": "Add a cell to a markdown notebook. SQL and Python cells run immediately: the call waits up to ~45s and returns the result — columns, a capped row preview, stdout/stderr (a Python cell's logs and tracebacks), and error — so you can look at the output and decide the next step (fix, or proceed). If the status comes back 'running', poll notebooks-run-cell-result with the run_id. A cell that reads other cells' dataframes references them by dataframe_name; those cells must have completed a run first, so add cells in dependency order. SQL cells are always HogQL: queries against PostHog or data warehouse tables run on ClickHouse, and a SQL cell that references a Python-created dataframe runs on the notebook's local engine automatically — any local dataframe is queryable by name, same syntax. The first Python cell can take longer while the notebook's sandbox kernel starts. Run analysis Python here rather than in a runtime the user can't see — dataframe work, statistics, clustering, forecasting, plotting — so the code and its output stay visible and re-runnable beside the result; the sandbox has pandas, numpy, scipy, scikit-learn, and matplotlib. component cells add other node types: Query, Image, Embed, Latex, FeatureFlag, Survey, Experiment, Person, Cohort, Recording, RecordingPlaylist. Pass a short title on every cell you add, describing what that cell shows — it renders in the cell header and is what a reader skims instead of the code.",
+ "description": "Add a cell to a markdown notebook. SQL and Python cells run immediately: the call waits up to ~45s and returns the result — columns, a capped row preview, stdout/stderr (a Python cell's logs and tracebacks), and error — so you can look at the output and decide the next step (fix, or proceed). If the status comes back 'running', poll notebooks-run-cell-result with the run_id. A cell that reads other cells' dataframes references them by dataframe_name; those cells must have completed a run first, so add cells in dependency order. SQL cells are always HogQL: queries against PostHog or data warehouse tables run on ClickHouse, and a SQL cell that references a Python-created dataframe runs on the notebook's local engine automatically — any local dataframe is queryable by name, same syntax. The first Python cell can take longer while the notebook's sandbox kernel starts. Run analysis Python here rather than in a runtime the user can't see — dataframe work, statistics, clustering, forecasting, plotting — so the code and its output stay visible and re-runnable beside the result; the sandbox has pandas, numpy, scipy, scikit-learn, and matplotlib. component cells add other node types: Query, Image, Embed, Latex, FeatureFlag, Survey, Experiment, Person, Cohort, Recording, RecordingPlaylist. Pass a short title on every cell you add, describing what that cell shows — it renders in the cell header and is what a reader skims instead of the code. A notebook holds at most 50 cells; past that the call fails, so start a new notebook rather than retrying.",
"category": "Notebooks",
"feature": "notebooks",
"summary": "Add a cell to a notebook; SQL/Python cells run immediately.",