:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
fix(notebooks): reject and auto-correct malformed ph-query nodes (#59801)
Sam Penningtonc042fb772fd7
diff --git a/posthog/api/test/notebooks/test_notebook.py b/posthog/api/test/notebooks/test_notebook.pyindex 7bab03b4d984..3f0ac26d1aa7 100644--- a/posthog/api/test/notebooks/test_notebook.py+++ b/posthog/api/test/notebooks/test_notebook.py@@ -193,6 +193,98 @@ class TestNotebooks(APIBaseTest, QueryMatchingTest):assert response.status_code == status.HTTP_200_OKassert response.json()["short_id"] == notebook["short_id"]+ def test_create_notebook_unwraps_insight_viz_node_wrapping_sql_chart(self) -> None:+ # Real-world bug: AI agents constructing notebook JSON via the MCP API have wrapped+ # SQL charts in an InsightVizNode shell. The notebook then renders blank because the+ # frontend treats it as an insight viz and chokes on the inner DataVisualizationNode.+ # The server should auto-unwrap to the correct top-level DataVisualizationNode.+ bad_content = {+ "type": "doc",+ "content": [+ {+ "type": "ph-query",+ "attrs": {+ "nodeId": "n1",+ "query": {+ "kind": "InsightVizNode",+ "source": {+ "kind": "DataVisualizationNode",+ "source": {"kind": "HogQLQuery", "query": "SELECT 1"},+ "display": "ActionsBar",+ },+ },+ },+ },+ ],+ }+ response = self.client.post(+ f"/api/projects/{self.team.id}/notebooks",+ data={"content": bad_content},+ )+ assert response.status_code == status.HTTP_201_CREATED+ stored_query = response.json()["content"]["content"][0]["attrs"]["query"]+ assert stored_query == {+ "kind": "DataVisualizationNode",+ "source": {"kind": "HogQLQuery", "query": "SELECT 1"},+ "display": "ActionsBar",+ }++ def test_create_notebook_rejects_insight_viz_wrapping_unknown_kind(self) -> None:+ bad_content = {+ "type": "doc",+ "content": [+ {+ "type": "ph-query",+ "attrs": {+ "nodeId": "n1",+ "query": {+ "kind": "InsightVizNode",+ "source": {"kind": "DefinitelyNotAQuery"},+ },+ },+ },+ ],+ }+ response = self.client.post(+ f"/api/projects/{self.team.id}/notebooks",+ data={"content": bad_content},+ )+ assert response.status_code == status.HTTP_400_BAD_REQUEST+ body = response.json()+ assert body["attr"] == "content"+ assert "DefinitelyNotAQuery" in body["detail"]++ def test_update_notebook_normalizes_invalid_query_node(self) -> None:+ create = self.client.post(f"/api/projects/{self.team.id}/notebooks", data={})+ short_id = create.json()["short_id"]+ version = create.json()["version"]++ bad_content = {+ "type": "doc",+ "content": [+ {+ "type": "ph-query",+ "attrs": {+ "nodeId": "n1",+ "query": {+ "kind": "InsightVizNode",+ "source": {"kind": "HogQLQuery", "query": "SELECT 1"},+ },+ },+ },+ ],+ }+ response = self.client.patch(+ f"/api/projects/{self.team.id}/notebooks/{short_id}",+ {"content": bad_content, "version": version},+ )+ assert response.status_code == status.HTTP_200_OK+ stored_query = response.json()["content"]["content"][0]["attrs"]["query"]+ assert stored_query == {+ "kind": "DataVisualizationNode",+ "source": {"kind": "HogQLQuery", "query": "SELECT 1"},+ }+def test_python_node_static_analysis(self) -> None:content = {"type": "doc",diff --git a/products/notebooks/backend/api/notebook.py b/products/notebooks/backend/api/notebook.pyindex f884dd20ce23..c69981264c91 100644--- a/products/notebooks/backend/api/notebook.py+++ b/products/notebooks/backend/api/notebook.py@@ -46,6 +46,7 @@ from products.notebooks.backend.collab import submit_stepsfrom products.notebooks.backend.kernel_runtime import build_notebook_sandbox_config, get_kernel_runtimefrom products.notebooks.backend.models import KernelRuntime, Notebookfrom products.notebooks.backend.python_analysis import analyze_python_globals, annotate_python_nodes+from products.notebooks.backend.query_validation import InvalidNotebookQueryError, normalize_notebook_query_nodesfrom products.tasks.backend.services.sandbox import SandboxStatusfrom products.tasks.backend.temporal.exceptions import SandboxProvisionError@@ -269,6 +270,14 @@ class NotebookSerializer(NotebookMinimalSerializer):return updated_notebook+ def validate_content(self, value: Any) -> Any:+ if not isinstance(value, dict):+ return value+ try:+ return normalize_notebook_query_nodes(value)+ except InvalidNotebookQueryError as err:+ raise serializers.ValidationError(str(err))+class NotebookKernelExecuteSerializer(serializers.Serializer):code = serializers.CharField(allow_blank=True)@@ -340,6 +349,14 @@ class NotebookCollabSaveSerializer(serializers.Serializer):required=False, allow_null=True, help_text="ProseMirror cursor head position after applying steps.")+ def validate_content(self, value: Any) -> Any:+ if not isinstance(value, dict):+ return value+ try:+ return normalize_notebook_query_nodes(value)+ except InvalidNotebookQueryError as err:+ raise serializers.ValidationError(str(err))+def _format_hogql_response_payload(response: Any) -> dict[str, Any]:if hasattr(response, "model_dump"):diff --git a/products/notebooks/backend/query_validation.py b/products/notebooks/backend/query_validation.pynew file mode 100644index 000000000000..fe21b217bfac--- /dev/null+++ b/products/notebooks/backend/query_validation.py@@ -0,0 +1,161 @@+from typing import Any++import structlog++logger = structlog.get_logger(__name__)+++PH_QUERY_NODE_TYPE = "ph-query"++# Kinds the frontend's NotebookNodeQuery accepts as a top-level `attrs.query`.+# Anything else inside a ph-query node is almost certainly a programmatic mistake — an AI+# agent producing notebook content via the MCP API has no Pydantic guard between it and+# storage, so we apply one here.+_VALID_TOP_LEVEL_QUERY_KINDS = frozenset(+ {+ "DataVisualizationNode",+ "DataTableNode",+ "SavedInsightNode",+ "InsightVizNode",+ }+)++# Source kinds that an InsightVizNode is actually allowed to wrap (matches the Pydantic+# schema at posthog/schema.py — InsightVizNode.source).+_VALID_INSIGHT_VIZ_SOURCE_KINDS = frozenset(+ {+ "TrendsQuery",+ "FunnelsQuery",+ "RetentionQuery",+ "PathsQuery",+ "StickinessQuery",+ "LifecycleQuery",+ "WebStatsTableQuery",+ "WebOverviewQuery",+ }+)+++class InvalidNotebookQueryError(ValueError):+ """Raised when a ph-query node carries a query shape we can't safely store.++ The message is exposed to the API caller (and therefore to AI agents constructing+ notebook content), so it must spell out the expected shape clearly enough for the+ caller to fix on retry.+ """+++def normalize_notebook_query_nodes(content: Any) -> Any:+ """Walk a ProseMirror notebook document and validate every ph-query node.++ For known, recoverable LLM mistakes (e.g. wrapping a SQL chart in an InsightVizNode)+ we auto-correct in place and log. For anything else that fails validation, we raise+ InvalidNotebookQueryError so the write is rejected with a helpful message.++ The function is structure-preserving: it returns a new tree with corrections applied,+ leaves nodes that aren't ph-query untouched, and is a no-op if `content` is not a dict.+ """+ if not isinstance(content, dict):+ return content++ def walk(node: Any) -> Any:+ if not isinstance(node, dict):+ return node++ if node.get("type") == PH_QUERY_NODE_TYPE:+ attrs = node.get("attrs")+ if isinstance(attrs, dict) and "query" in attrs:+ normalized_query = _normalize_query(attrs["query"])+ if normalized_query is not attrs["query"]:+ node = {**node, "attrs": {**attrs, "query": normalized_query}}++ children = node.get("content")+ if isinstance(children, list):+ node = {**node, "content": [walk(child) for child in children]}++ return node++ return walk(content)+++def _normalize_query(query: Any) -> Any:+ if not isinstance(query, dict):+ return query++ kind = query.get("kind")+ if not isinstance(kind, str):+ # No kind — likely a legacy or hand-crafted node. Leave it alone; older notebooks+ # may rely on the frontend's tolerant handling and we don't want to break them.+ return query++ if kind == "InsightVizNode":+ return _normalize_insight_viz_node(query)++ if kind == "DataVisualizationNode":+ return _normalize_data_visualization_node(query)++ if kind not in _VALID_TOP_LEVEL_QUERY_KINDS:+ # Other QuerySchema kinds (HogQLQuery, EventsQuery, ...) can be used as a top-level+ # `attrs.query` in some legacy notebooks, so we don't reject — but we also don't+ # try to auto-fix.+ return query++ return query+++def _normalize_insight_viz_node(query: dict[str, Any]) -> dict[str, Any]:+ source = query.get("source")+ if not isinstance(source, dict):+ raise InvalidNotebookQueryError(+ "ph-query node has an InsightVizNode without a `source`. "+ "InsightVizNode.source must be a TrendsQuery, FunnelsQuery, RetentionQuery, "+ "PathsQuery, StickinessQuery, LifecycleQuery, WebStatsTableQuery, or WebOverviewQuery."+ )++ source_kind = source.get("kind")++ if source_kind == "DataVisualizationNode":+ # This is the bug we keep seeing from AI agents: a SQL chart got wrapped in an+ # InsightVizNode (which is only valid for product-analytics insights). The inner+ # DataVisualizationNode is already the correct top-level shape, so unwrap it.+ logger.warning(+ "notebook_query_auto_unwrapped_insight_viz_node",+ reason="InsightVizNode wrapping DataVisualizationNode",+ )+ return _normalize_data_visualization_node(source)++ if source_kind == "HogQLQuery":+ # Same shape of mistake, one level up: agent wrapped a raw HogQLQuery in an+ # InsightVizNode. The correct shell for a SQL chart is DataVisualizationNode.+ logger.warning(+ "notebook_query_auto_rewrapped_hogql_query",+ reason="InsightVizNode wrapping HogQLQuery",+ )+ return {"kind": "DataVisualizationNode", "source": source}++ if source_kind not in _VALID_INSIGHT_VIZ_SOURCE_KINDS:+ raise InvalidNotebookQueryError(+ f"ph-query node has an InsightVizNode wrapping `{source_kind}`, which is not "+ "a valid insight source. InsightVizNode.source must be one of: "+ f"{', '.join(sorted(_VALID_INSIGHT_VIZ_SOURCE_KINDS))}."+ )++ return query+++def _normalize_data_visualization_node(query: dict[str, Any]) -> dict[str, Any]:+ source = query.get("source")+ if not isinstance(source, dict):+ raise InvalidNotebookQueryError(+ "ph-query node has a DataVisualizationNode without a `source`. "+ "DataVisualizationNode.source must be a HogQLQuery."+ )++ source_kind = source.get("kind")+ if source_kind != "HogQLQuery":+ raise InvalidNotebookQueryError(+ f"ph-query node has a DataVisualizationNode wrapping `{source_kind}`, which "+ "is not a valid SQL chart source. DataVisualizationNode.source must be a HogQLQuery."+ )++ return querydiff --git a/products/notebooks/backend/test/test_query_validation.py b/products/notebooks/backend/test/test_query_validation.pynew file mode 100644index 000000000000..8f17f7e4435b--- /dev/null+++ b/products/notebooks/backend/test/test_query_validation.py@@ -0,0 +1,149 @@+from typing import Any++import pytest++from parameterized import parameterized++from products.notebooks.backend.query_validation import InvalidNotebookQueryError, normalize_notebook_query_nodes++HOGQL_SOURCE: dict[str, Any] = {"kind": "HogQLQuery", "query": "SELECT 1"}+VALID_DATA_VIZ: dict[str, Any] = {+ "kind": "DataVisualizationNode",+ "source": HOGQL_SOURCE,+ "display": "ActionsBar",+}+VALID_INSIGHT_VIZ: dict[str, Any] = {+ "kind": "InsightVizNode",+ "source": {"kind": "TrendsQuery", "series": []},+}+++def _wrap(query: dict | None) -> dict[str, Any]:+ attrs: dict[str, Any] = {"nodeId": "n1"}+ if query is not None:+ attrs["query"] = query+ return {+ "type": "doc",+ "content": [{"type": "ph-query", "attrs": attrs}],+ }+++def _extract_query(doc: dict[str, Any]) -> dict | None:+ return doc["content"][0]["attrs"].get("query")+++class TestNormalizeNotebookQueryNodes:+ def test_returns_non_dict_input_unchanged(self) -> None:+ assert normalize_notebook_query_nodes(None) is None+ assert normalize_notebook_query_nodes("plain") == "plain"+ assert normalize_notebook_query_nodes([1, 2, 3]) == [1, 2, 3]++ def test_passes_through_doc_without_ph_query_nodes(self) -> None:+ doc = {"type": "doc", "content": [{"type": "paragraph", "content": [{"type": "text", "text": "hi"}]}]}+ assert normalize_notebook_query_nodes(doc) == doc++ def test_passes_through_ph_query_without_query_attr(self) -> None:+ doc = {"type": "doc", "content": [{"type": "ph-query", "attrs": {"nodeId": "x"}}]}+ assert normalize_notebook_query_nodes(doc) == doc++ def test_passes_through_valid_data_visualization_node(self) -> None:+ doc = _wrap(VALID_DATA_VIZ)+ assert _extract_query(normalize_notebook_query_nodes(doc)) == VALID_DATA_VIZ++ def test_passes_through_valid_insight_viz_node(self) -> None:+ doc = _wrap(VALID_INSIGHT_VIZ)+ assert _extract_query(normalize_notebook_query_nodes(doc)) == VALID_INSIGHT_VIZ++ def test_unwraps_insight_viz_node_wrapping_data_visualization_node(self) -> None:+ # The exact bug observed in notebook wUll: AI agent wrapped a SQL chart in an+ # InsightVizNode shell. The inner DataVisualizationNode is the correct shape.+ bad = {"kind": "InsightVizNode", "source": VALID_DATA_VIZ}+ result = _extract_query(normalize_notebook_query_nodes(_wrap(bad)))+ assert result == VALID_DATA_VIZ++ def test_rewraps_insight_viz_node_wrapping_hogql_query(self) -> None:+ bad = {"kind": "InsightVizNode", "source": HOGQL_SOURCE}+ result = _extract_query(normalize_notebook_query_nodes(_wrap(bad)))+ assert result == {"kind": "DataVisualizationNode", "source": HOGQL_SOURCE}++ def test_rejects_insight_viz_node_wrapping_unknown_kind(self) -> None:+ bad = {"kind": "InsightVizNode", "source": {"kind": "MadeUpQuery"}}+ with pytest.raises(InvalidNotebookQueryError, match="MadeUpQuery"):+ normalize_notebook_query_nodes(_wrap(bad))++ def test_rejects_insight_viz_node_without_source(self) -> None:+ bad = {"kind": "InsightVizNode"}+ with pytest.raises(InvalidNotebookQueryError, match="without a `source`"):+ normalize_notebook_query_nodes(_wrap(bad))++ def test_rejects_data_visualization_node_with_non_hogql_source(self) -> None:+ bad = {"kind": "DataVisualizationNode", "source": {"kind": "TrendsQuery"}}+ with pytest.raises(InvalidNotebookQueryError, match="TrendsQuery"):+ normalize_notebook_query_nodes(_wrap(bad))++ def test_rejects_data_visualization_node_without_source(self) -> None:+ bad = {"kind": "DataVisualizationNode"}+ with pytest.raises(InvalidNotebookQueryError, match="without a `source`"):+ normalize_notebook_query_nodes(_wrap(bad))++ @parameterized.expand(+ [+ ("SavedInsightNode", {"kind": "SavedInsightNode", "shortId": "abc"}),+ ("DataTableNode", {"kind": "DataTableNode", "source": {"kind": "EventsQuery"}}),+ # Bare data node kinds — legacy notebooks set these directly as the top-level query.+ ("HogQLQuery", HOGQL_SOURCE),+ ("EventsQuery", {"kind": "EventsQuery", "select": ["*"]}),+ ]+ )+ def test_passes_through_other_known_kinds(self, _name: str, query: dict) -> None:+ assert _extract_query(normalize_notebook_query_nodes(_wrap(query))) == query++ def test_passes_through_query_without_kind(self) -> None:+ # Older notebooks may have hand-crafted query attrs without a discriminator.+ doc = _wrap({"foo": "bar"})+ assert _extract_query(normalize_notebook_query_nodes(doc)) == {"foo": "bar"}++ def test_walks_nested_content(self) -> None:+ bad = {"kind": "InsightVizNode", "source": VALID_DATA_VIZ}+ nested = {+ "type": "doc",+ "content": [+ {+ "type": "bulletList",+ "content": [+ {+ "type": "listItem",+ "content": [+ {"type": "ph-query", "attrs": {"nodeId": "deep", "query": bad}},+ ],+ },+ ],+ },+ ],+ }+ result = normalize_notebook_query_nodes(nested)+ deep_node = result["content"][0]["content"][0]["content"][0]+ assert deep_node["attrs"]["query"] == VALID_DATA_VIZ++ def test_does_not_mutate_input(self) -> None:+ bad = {"kind": "InsightVizNode", "source": VALID_DATA_VIZ}+ doc = _wrap(bad)+ original_query = doc["content"][0]["attrs"]["query"]+ normalize_notebook_query_nodes(doc)+ # Original object reference unchanged+ assert doc["content"][0]["attrs"]["query"] is original_query+ assert doc["content"][0]["attrs"]["query"]["kind"] == "InsightVizNode"++ def test_multiple_ph_query_nodes_handled_independently(self) -> None:+ bad = {"kind": "InsightVizNode", "source": VALID_DATA_VIZ}+ doc = {+ "type": "doc",+ "content": [+ {"type": "ph-query", "attrs": {"nodeId": "a", "query": bad}},+ {"type": "paragraph"},+ {"type": "ph-query", "attrs": {"nodeId": "b", "query": VALID_INSIGHT_VIZ}},+ ],+ }+ result = normalize_notebook_query_nodes(doc)+ assert result["content"][0]["attrs"]["query"] == VALID_DATA_VIZ+ assert result["content"][2]["attrs"]["query"] == VALID_INSIGHT_VIZdiff --git a/products/notebooks/mcp/tools.yaml b/products/notebooks/mcp/tools.yamlindex 7e9c27373a91..61e802859811 100644--- a/products/notebooks/mcp/tools.yaml+++ b/products/notebooks/mcp/tools.yaml@@ -50,6 +50,14 @@ tools:description: >Create a new notebook. Provide a title and content. Content is a JSON object representing the notebook'srich text document structure (ProseMirror-based). Returns the created notebook with its short_id.++ Embedded charts use `{type: "ph-query", attrs: {nodeId, query}}` nodes. The `query` object must be one of:+ (a) `{kind: "DataVisualizationNode", source: {kind: "HogQLQuery", query: "SELECT ..."}, display:+ "ActionsBar", chartSettings: {...}}` for SQL charts — do NOT wrap this in an InsightVizNode; (b) `{kind:+ "InsightVizNode", source: <TrendsQuery | FunnelsQuery | RetentionQuery | PathsQuery | StickinessQuery |+ LifecycleQuery>}` for product-analytics insights; or (c) `{kind: "SavedInsightNode", shortId: "..."}` to+ embed a saved insight. The server rejects other shapes and auto-corrects the common `InsightVizNode`+ wrapping a SQL chart.exclude_params:- _create_in_foldernotebooks-destroy:diff --git a/services/mcp/schema/generated-tool-definitions.json b/services/mcp/schema/generated-tool-definitions.jsonindex 64c2f3b67352..1ff091d97ce4 100644--- a/services/mcp/schema/generated-tool-definitions.json+++ b/services/mcp/schema/generated-tool-definitions.json@@ -3941,7 +3941,7 @@}},"notebooks-create": {- "description": "Create a new notebook. Provide a title and content. Content is a JSON object representing the notebook's rich text document structure (ProseMirror-based). Returns the created notebook with its short_id.",+ "description": "Create a new notebook. Provide a title and content. Content is a JSON object representing the notebook's rich text document structure (ProseMirror-based). Returns the created notebook with its short_id.\nEmbedded charts use `{type: \"ph-query\", attrs: {nodeId, query}}` nodes. The `query` object must be one of: (a) `{kind: \"DataVisualizationNode\", source: {kind: \"HogQLQuery\", query: \"SELECT ...\"}, display: \"ActionsBar\", chartSettings: {...}}` for SQL charts — do NOT wrap this in an InsightVizNode; (b) `{kind: \"InsightVizNode\", source: <TrendsQuery | FunnelsQuery | RetentionQuery | PathsQuery | StickinessQuery | LifecycleQuery>}` for product-analytics insights; or (c) `{kind: \"SavedInsightNode\", shortId: \"...\"}` to embed a saved insight. The server rejects other shapes and auto-corrects the common `InsightVizNode` wrapping a SQL chart.","category": "Notebooks","feature": "notebooks","summary": "Create notebook",diff --git a/services/mcp/schema/tool-definitions-all.json b/services/mcp/schema/tool-definitions-all.jsonindex f0d1a71c5a72..266b1747203f 100644--- a/services/mcp/schema/tool-definitions-all.json+++ b/services/mcp/schema/tool-definitions-all.json@@ -4270,7 +4270,7 @@}},"notebooks-create": {- "description": "Create a new notebook. Provide a title and content. Content is a JSON object representing the notebook's rich text document structure (ProseMirror-based). Returns the created notebook with its short_id.",+ "description": "Create a new notebook. Provide a title and content. Content is a JSON object representing the notebook's rich text document structure (ProseMirror-based). Returns the created notebook with its short_id.\nEmbedded charts use `{type: \"ph-query\", attrs: {nodeId, query}}` nodes. The `query` object must be one of: (a) `{kind: \"DataVisualizationNode\", source: {kind: \"HogQLQuery\", query: \"SELECT ...\"}, display: \"ActionsBar\", chartSettings: {...}}` for SQL charts — do NOT wrap this in an InsightVizNode; (b) `{kind: \"InsightVizNode\", source: <TrendsQuery | FunnelsQuery | RetentionQuery | PathsQuery | StickinessQuery | LifecycleQuery>}` for product-analytics insights; or (c) `{kind: \"SavedInsightNode\", shortId: \"...\"}` to embed a saved insight. The server rejects other shapes and auto-corrects the common `InsightVizNode` wrapping a SQL chart.","category": "Notebooks","feature": "notebooks","summary": "Create notebook",