:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
feat(notebooks): expose each sql cell's chart in the notebook state (#109343)
Sinan Kucukkoseler2a6db4babc36
diff --git a/products/notebooks/backend/sql_v2_serializers.py b/products/notebooks/backend/sql_v2_serializers.pyindex 7077824efccf..c6e63ba6ca0a 100644--- a/products/notebooks/backend/sql_v2_serializers.py+++ b/products/notebooks/backend/sql_v2_serializers.py@@ -429,6 +429,31 @@ class NotebookCellLastRunSerializer(serializers.Serializer):error = serializers.CharField(required=False, allow_null=True, help_text="Error message when the run failed.")+class NotebookCellVisualizationSerializer(serializers.Serializer):+ display = serializers.CharField(+ help_text="Chart type the cell opens on, a chart display value such as 'ActionsBar' or 'ActionsLineGraph'."+ )+ x_axis = serializers.CharField(+ allow_null=True,+ help_text=(+ "Column on the X axis. Null means the chart picks it: the first date column, or the first column the Y "+ "series do not use when there is no date column."+ ),+ )+ y_axis = serializers.ListField(+ child=serializers.CharField(),+ allow_null=True,+ help_text=(+ "Columns plotted as Y series. Null means the chart picks them: every numeric column. An empty list "+ "means the author removed every series, so the chart plots nothing."+ ),+ )+ series_breakdown = serializers.CharField(+ allow_null=True,+ help_text="Column that splits the Y series into one series per value, or null.",+ )++class NotebookCellStateSerializer(serializers.Serializer):node_id = serializers.CharField(help_text="Durable cell identity, used by the cell run and edit endpoints.")cell_type = serializers.CharField(@@ -477,6 +502,14 @@ class NotebookCellStateSerializer(serializers.Serializer):last_run = NotebookCellLastRunSerializer(required=False, allow_null=True, help_text="Summary of the most recent run; null when never run.")+ visualization = NotebookCellVisualizationSerializer(+ required=False,+ allow_null=True,+ help_text=(+ "SQL cells only: the chart the cell opens on, set in the editor or with the visualization parameter of "+ "notebooks-add-cell. Null when the cell opens on its results table."+ ),+ )class NotebookKernelStateSerializer(serializers.Serializer):diff --git a/products/notebooks/backend/sql_v2_state.py b/products/notebooks/backend/sql_v2_state.pyindex 9b90a36f80cb..882a1637fcd8 100644--- a/products/notebooks/backend/sql_v2_state.py+++ b/products/notebooks/backend/sql_v2_state.py@@ -18,6 +18,8 @@ from typing import Anyfrom posthog.hogql import astfrom posthog.hogql.parser import parse_select+from posthog.dataclasses import frozen+from products.notebooks.backend.facade.contracts import NotebookCellLimitExceededfrom products.notebooks.backend.models import NotebookNodeRunfrom products.notebooks.backend.python_analysis import analyze_python_globals@@ -55,6 +57,14 @@ _DATAFRAME_NAME = re.compile(r"^[A-Za-z_][A-Za-z0-9_]*$")_CODE_PREVIEW_CHARS = 8_000+@frozen+class CellVisualization:+ display: str+ x_axis: str | None+ y_axis: tuple[str, ...] | None+ series_breakdown: str | None++# Built in stages: `build_dependency_edges` fills the graph edges, `annotate_run_state` the run# status, and `_merge_prose_cells` the document span.@dataclass(frozen=False)@@ -74,6 +84,7 @@ class NotebookCellState:last_run: dict[str, Any] | None = Nonestart: int = 0end: int = 0+ visualization: CellVisualization | None = Nonedef _code_from_query_prop(value: Any) -> str:@@ -84,25 +95,64 @@ def _code_from_query_prop(value: Any) -> str:HogQLQuery, or wrapped in a data-table or visualization node. The editor renders allthree, so a whole-notebook run has to plan all three rather than silently skip them."""- if isinstance(value, str):- text = value.strip()- if not text:- return ""- if not text.startswith("{"):- # Anything else a string prop can hold is the SQL itself.- return text- try:- value = json.loads(text)- except ValueError:- return ""- if not isinstance(value, dict):+ if isinstance(value, str) and not value.strip().startswith("{"):+ # Anything else a string prop can hold is the SQL itself.+ return value.strip()+ query = _query_prop_object(value)+ if query is None:return ""- source = value if value.get("kind") == "HogQLQuery" else value.get("source")+ source = query if query.get("kind") == "HogQLQuery" else query.get("source")if isinstance(source, dict) and source.get("kind") == "HogQLQuery" and isinstance(source.get("query"), str):return source["query"]return ""+def _query_prop_object(value: Any) -> dict[str, Any] | None:+ if isinstance(value, str):+ try:+ value = json.loads(value)+ except ValueError:+ return None+ return value if isinstance(value, dict) else None+++# Mirrors the SQLV2 node, which opens on the chart only when `outputTab` says so and draws a line+# chart when `vizQuery` names no display.+_DEFAULT_CHART_DISPLAY = "ActionsLineGraph"+++def _axis_column(axis: Any) -> str | None:+ column = axis.get("column") if isinstance(axis, dict) else None+ return column if isinstance(column, str) and column else None+++def _visualization_from_props(props: dict[str, Any]) -> CellVisualization | None:+ output_tab, viz_query = props.get("outputTab"), props.get("vizQuery")+ code = props.get("code")+ if not (isinstance(code, str) and code.strip()):+ # Mirrors the editor's `getSqlV2PropsFromQueryProp`: a cell without `code` whose `query`+ # is a visualization node opens on that chart, whatever `outputTab` and `vizQuery` hold.+ query = _query_prop_object(props.get("query"))+ if query and query.get("kind") == "DataVisualizationNode" and _code_from_query_prop(query).strip():+ output_tab, viz_query = "visualization", query+ if output_tab != "visualization":+ return None+ viz_query = viz_query if isinstance(viz_query, dict) else {}+ chart_settings = viz_query.get("chartSettings")+ chart_settings = chart_settings if isinstance(chart_settings, dict) else {}+ display = viz_query.get("display")+ y_axis = chart_settings.get("yAxis")+ breakdown = chart_settings.get("seriesBreakdownColumn")+ return CellVisualization(+ display=display if isinstance(display, str) and display else _DEFAULT_CHART_DISPLAY,+ x_axis=_axis_column(chart_settings.get("xAxis")),+ # The chart picks the Y series only when `yAxis` is absent. An empty list records that the+ # author removed every series, so the chart plots nothing, and the two must not merge.+ y_axis=tuple(column for column in map(_axis_column, y_axis) if column) if isinstance(y_axis, list) else None,+ series_breakdown=breakdown if isinstance(breakdown, str) and breakdown else None,+ )++def extract_cells(content: Any) -> list[NotebookCellState]:markdown = _get_markdown_notebook_markdown(content)if markdown is None:@@ -133,6 +183,7 @@ def extract_cells(content: Any) -> list[NotebookCellState]:code=code if isinstance(code, str) else "",connection_id=connection_id if isinstance(connection_id, str) and connection_id else None,send_raw_query=props.get("sendRawQuery") is True,+ visualization=_visualization_from_props(props) if tag_name == "SQLV2" else None,))used_names: set[str] = set()diff --git a/products/notebooks/backend/test/test_sql_v2_state.py b/products/notebooks/backend/test/test_sql_v2_state.pyindex 198a5a62ed07..b50a1da66833 100644--- a/products/notebooks/backend/test/test_sql_v2_state.py+++ b/products/notebooks/backend/test/test_sql_v2_state.py@@ -15,6 +15,7 @@ from products.notebooks.backend.sql_v2_references import resolve_sql_v2_referencfrom products.notebooks.backend.sql_v2_state import (MAX_ADDRESSABLE_PROSE_BLOCKS,MAX_NOTEBOOK_CELLS,+ CellVisualization,NotebookCellLimitExceeded,build_dependency_edges,build_notebook_cell_state,@@ -40,6 +41,43 @@ def markdown_content(markdown: str) -> dict[str, Any]:class TestCellExtractionAndEdges(SimpleTestCase):+ @parameterized.expand(+ [+ (+ "chart tab with axes",+ 'outputTab="visualization" vizQuery={{"kind":"DataVisualizationNode","display":"ActionsBar",'+ '"chartSettings":{"xAxis":{"column":"month"},"yAxis":[{"column":"orgs"}],'+ '"seriesBreakdownColumn":"region"}}}',+ CellVisualization(display="ActionsBar", x_axis="month", y_axis=("orgs",), series_breakdown="region"),+ ),+ (+ "chart tab without a stored chart",+ 'outputTab="visualization"',+ CellVisualization(display="ActionsLineGraph", x_axis=None, y_axis=None, series_breakdown=None),+ ),+ (+ "every series removed",+ 'outputTab="visualization" vizQuery={{"kind":"DataVisualizationNode","chartSettings":{"yAxis":[]}}}',+ CellVisualization(display="ActionsLineGraph", x_axis=None, y_axis=(), series_breakdown=None),+ ),+ (+ "results tab keeps a stored chart hidden",+ 'outputTab="results" vizQuery={{"kind":"DataVisualizationNode","display":"ActionsBar"}}',+ None,+ ),+ ("no output tab", 'code="select 1"', None),+ (+ "chart held in the legacy query prop",+ 'query={{"kind":"DataVisualizationNode","display":"ActionsPie",'+ '"source":{"kind":"HogQLQuery","query":"select 1"}}}',+ CellVisualization(display="ActionsPie", x_axis=None, y_axis=None, series_breakdown=None),+ ),+ ]+ )+ def test_sql_cell_visualization(self, _name: str, props: str, expected: CellVisualization | None) -> None:+ cells = extract_cells(markdown_content(f'<SQLV2 nodeId="s" returnVariable="df" {props} />'))+ assert cells[0].visualization == expected+@parameterized.expand([(case["name"], case["markdown"], case["owners"])@@ -486,7 +524,8 @@ class TestNotebookCellState(APIBaseTest):@patch("products.notebooks.backend.presentation.views.notebook.is_sql_v2_enabled", return_value=True)def test_state_endpoint_returns_cells_and_kernel(self, _mock_enabled) -> None:notebook = self._notebook(- '<SQLV2 nodeId="s" code="select 1" returnVariable="df" />\n\n'+ '<SQLV2 nodeId="s" code="select 1" returnVariable="df" outputTab="visualization" '+ 'vizQuery={{"kind":"DataVisualizationNode","display":"ActionsBar","chartSettings":{"yAxis":[{"column":"n"}]}}} />\n\n''<PythonV2 nodeId="p" code="x = df.head()" returnVariable="x" />\n\n\n'"<!--ph:phb-note-->\nFirst paragraph.\n\nSecond paragraph.")@@ -508,5 +547,12 @@ class TestNotebookCellState(APIBaseTest):assert by_node["p"]["status"] == "never_run"assert by_node["p"]["depends_on"] == ["s"]assert by_node["phb-note"]["code"] == "First paragraph.\n\nSecond paragraph."+ assert by_node["s"]["visualization"] == {+ "display": "ActionsBar",+ "x_axis": None,+ "y_axis": ["n"],+ "series_breakdown": None,+ }+ assert by_node["p"]["visualization"] is Noneassert by_node["s"]["last_run"]["run_id"]assert data["markdown"][by_node["s"]["start"] : by_node["s"]["end"]].startswith('<SQLV2 nodeId="s"')diff --git a/products/notebooks/frontend/generated/api.schemas.ts b/products/notebooks/frontend/generated/api.schemas.tsindex 5bcb712a7042..3afd8ddf88cc 100644--- a/products/notebooks/frontend/generated/api.schemas.ts+++ b/products/notebooks/frontend/generated/api.schemas.ts@@ -1300,6 +1300,26 @@ export interface NotebookCellLastRunApi {error?: string | null}+export interface NotebookCellVisualizationApi {+ /** Chart type the cell opens on, a chart display value such as 'ActionsBar' or 'ActionsLineGraph'. */+ display: string+ /**+ * Column on the X axis. Null means the chart picks it: the first date column, or the first column the Y series do not use when there is no date column.+ * @nullable+ */+ x_axis: string | null+ /**+ * Columns plotted as Y series. Null means the chart picks them: every numeric column. An empty list means the author removed every series, so the chart plots nothing.+ * @nullable+ */+ y_axis: string[] | null+ /**+ * Column that splits the Y series into one series per value, or null.+ * @nullable+ */+ series_breakdown: string | null+}+export interface NotebookCellStateApi {/** Durable cell identity, used by the cell run and edit endpoints. */node_id: string@@ -1321,6 +1341,8 @@ export interface NotebookCellStateApi {dependents: string[]/** Summary of the most recent run; null when never run. */last_run?: NotebookCellLastRunApi | null+ /** SQL cells only: the chart the cell opens on, set in the editor or with the visualization parameter of notebooks-add-cell. Null when the cell opens on its results table. */+ visualization?: NotebookCellVisualizationApi | null}export interface NotebookSQLV2StateResponseApi {diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.tsindex 1a84c441dd86..da00a52c14b8 100644--- a/services/mcp/src/api/generated.ts+++ b/services/mcp/src/api/generated.ts@@ -66678,6 +66678,26 @@ export namespace Schemas {error?: string | null;}+ export interface NotebookCellVisualization {+ /** Chart type the cell opens on, a chart display value such as 'ActionsBar' or 'ActionsLineGraph'. */+ display: string;+ /**+ * Column on the X axis. Null means the chart picks it: the first date column, or the first column the Y series do not use when there is no date column.+ * @nullable+ */+ x_axis: string | null;+ /**+ * Columns plotted as Y series. Null means the chart picks them: every numeric column. An empty list means the author removed every series, so the chart plots nothing.+ * @nullable+ */+ y_axis: string[] | null;+ /**+ * Column that splits the Y series into one series per value, or null.+ * @nullable+ */+ series_breakdown: string | null;+ }+export interface NotebookCellState {/** Durable cell identity, used by the cell run and edit endpoints. */node_id: string;@@ -66699,6 +66719,8 @@ export namespace Schemas {dependents: string[];/** Summary of the most recent run; null when never run. */last_run?: NotebookCellLastRun | null;+ /** SQL cells only: the chart the cell opens on, set in the editor or with the visualization parameter of notebooks-add-cell. Null when the cell opens on its results table. */+ visualization?: NotebookCellVisualization | null;}export interface NotebookCollabCursor {