: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): Materialize data into files in File Storage and stream from there (#69703)
Sinan Kucukkoseler15edab62b193
diff --git a/posthog/hogql/constants.py b/posthog/hogql/constants.pyindex a5672b3bfeab..9194daa9a4a1 100644--- a/posthog/hogql/constants.py+++ b/posthog/hogql/constants.py@@ -31,6 +31,11 @@ MAX_SELECT_RETENTION_LIMIT = 100000 # 100kMAX_SELECT_HEATMAPS_LIMIT = 1000000 # 1m datapoints# Max limit for all cohort calculationsMAX_SELECT_COHORT_CALCULATION_LIMIT = 1000000000 # 1b persons+# Max limit for notebook dataframe materialization (the sandbox kernel fetching a whole frame+# over the object-storage frame store). Tier 1 of the rollout ladder in+# products/notebooks/backend/sql_v2_frame_store.md — raised toward the kernel executor's+# _MATERIALIZE_ROW_CAP (2M) on query-log evidence.+MAX_SELECT_NOTEBOOK_MATERIALIZE_LIMIT = 500000 # 500k rows# Max limit for LLM tracesMAX_SELECT_TRACES_LIMIT_EXPORT = 10000 # 10k traces# Max limit for PostHog AI queries@@ -66,6 +71,7 @@ class LimitContext(StrEnum):EXPORT = "export"COHORT_CALCULATION = "cohort_calculation"HEATMAPS = "heatmaps"+ NOTEBOOK_MATERIALIZE = "notebook_materialize"SAVED_QUERY = "saved_query"RETENTION = "retention"POSTHOG_AI = "posthog_ai"@@ -83,6 +89,8 @@ def get_max_limit_for_context(limit_context: LimitContext) -> int:return MAX_SELECT_HEATMAPS_LIMIT # 1Melif limit_context == LimitContext.COHORT_CALCULATION:return MAX_SELECT_COHORT_CALCULATION_LIMIT # 1b+ elif limit_context == LimitContext.NOTEBOOK_MATERIALIZE:+ return MAX_SELECT_NOTEBOOK_MATERIALIZE_LIMIT # 500kelif limit_context == LimitContext.RETENTION:return MAX_SELECT_RETENTION_LIMIT # 100kelif limit_context == LimitContext.SAVED_QUERY:@@ -105,6 +113,8 @@ def get_default_limit_for_context(limit_context: LimitContext) -> int:return MAX_SELECT_HEATMAPS_LIMIT # 1Melif limit_context == LimitContext.COHORT_CALCULATION:return MAX_SELECT_COHORT_CALCULATION_LIMIT # 1b+ elif limit_context == LimitContext.NOTEBOOK_MATERIALIZE:+ return MAX_SELECT_NOTEBOOK_MATERIALIZE_LIMIT # 500kelif limit_context == LimitContext.SAVED_QUERY:return sys.maxsize # Max python intelse:diff --git a/posthog/hogql/query.py b/posthog/hogql/query.pyindex fe9abcfa290c..b20b4f27af6f 100644--- a/posthog/hogql/query.py+++ b/posthog/hogql/query.py@@ -308,6 +308,7 @@ class HogQLQueryExecutor:if self.limit_context in (LimitContext.EXPORT,LimitContext.COHORT_CALCULATION,+ LimitContext.NOTEBOOK_MATERIALIZE,LimitContext.QUERY_ASYNC,LimitContext.SAVED_QUERY,LimitContext.RETENTION,@@ -462,6 +463,7 @@ class HogQLQueryExecutor:if self.limit_context in (LimitContext.EXPORT,LimitContext.COHORT_CALCULATION,+ LimitContext.NOTEBOOK_MATERIALIZE,LimitContext.QUERY_ASYNC,LimitContext.SAVED_QUERY,LimitContext.RETENTION,diff --git a/posthog/settings/object_storage.py b/posthog/settings/object_storage.pyindex 380888467a6f..9660fe0ef364 100644--- a/posthog/settings/object_storage.py+++ b/posthog/settings/object_storage.py@@ -36,6 +36,11 @@ OBJECT_STORAGE_TASKS_FOLDER = os.getenv("OBJECT_STORAGE_TASKS_FOLDER", "tasks")OBJECT_STORAGE_LEGAL_DOCUMENTS_FOLDER = os.getenv("OBJECT_STORAGE_LEGAL_DOCUMENTS_FOLDER", "legal_documents")OBJECT_STORAGE_EXTERNAL_WEB_ANALYTICS_BUCKET = os.getenv("OBJECT_STORAGE_EXTERNAL_WEB_ANALYTICS_BUCKET", "posthog")+# Notebooks SQLV2 frame store (products/notebooks/backend/sql_v2_frame_store.md): stream+# python-node frame materializations to object storage instead of the Redis JSON transport.+# Default off — rollout is env-gated per deployment on top of the product feature flag.+NOTEBOOKS_FRAME_STORE_ENABLED = get_from_env("NOTEBOOKS_FRAME_STORE_ENABLED", False, type_cast=str_to_bool)+# Query cache specific bucket - falls back to general object storage bucket if not setQUERY_CACHE_S3_BUCKET = os.getenv("QUERY_CACHE_S3_BUCKET") or OBJECT_STORAGE_BUCKETdiff --git a/posthog/temporal/common/clickhouse.py b/posthog/temporal/common/clickhouse.pyindex 5f731d7cf773..8d3a55fa9af7 100644--- a/posthog/temporal/common/clickhouse.py+++ b/posthog/temporal/common/clickhouse.py@@ -186,6 +186,13 @@ class ClickHouseTooManyBytesError(ClickHouseError):super().__init__(error_message, query, query_id)+class ClickHouseTooManyRowsOrBytesError(ClickHouseError):+ """Exception raised when a query's result exceeds max_result_rows/max_result_bytes."""++ def __init__(self, error_message, query: str | None = None, query_id: str | None = None):+ super().__init__(error_message, query, query_id)++class ClickHouseTooManySimultaneousQueriesError(ClickHouseError):"""Exception raised when ClickHouse has too many simultaneous queries running."""@@ -379,6 +386,7 @@ class ClickHouseClient:ERROR_CODE_TO_EXCEPTION: dict[str, type[ClickHouseError]] = {"ALL_REPLICAS_ARE_STALE": ClickHouseAllReplicasAreStaleError,"MEMORY_LIMIT_EXCEEDED": ClickHouseMemoryLimitExceededError,+ "TOO_MANY_ROWS_OR_BYTES": ClickHouseTooManyRowsOrBytesError,"TOO_MANY_BYTES": ClickHouseTooManyBytesError,"TOO_MANY_SIMULTANEOUS_QUERIES": ClickHouseTooManySimultaneousQueriesError,"TIMEOUT_EXCEEDED": ClickHouseQueryTimeoutError,@@ -519,7 +527,14 @@ class ClickHouseClient:raise ClickHouseClientTimeoutError(query, query_id)@contextlib.contextmanager- def post_query(self, query, *data, query_parameters, query_id) -> collections.abc.Iterator:+ def post_query(+ self,+ query,+ *data,+ query_parameters,+ query_id,+ timeout: float | tuple[float, float] | None = None,+ ) -> collections.abc.Iterator:"""POST a query to the ClickHouse HTTP interface.The context manager protocol is used to control when to release the response.@@ -532,6 +547,11 @@ class ClickHouseClient:*data: Iterable of values to include in the body of the request. For example, the tuples of VALUES for an INSERT query.query_parameters: Parameters to be formatted in the query.query_id: A query ID to pass to ClickHouse.+ timeout: Optional requests-style timeout — a (connect, read) tuple or a single+ float for both. The read timeout applies to every blocking socket read,+ including body reads while streaming the response, so a half-open connection+ raises instead of blocking the calling thread until TCP gives up. None (the+ default) preserves the historical unbounded behavior.Returns:The response received from the ClickHouse HTTP interface.@@ -565,6 +585,7 @@ class ClickHouseClient:data=request_data,stream=True,verify=False,+ timeout=timeout,)self.check_response(response, query)yield responsediff --git a/products/notebooks/backend/frame_store.py b/products/notebooks/backend/frame_store.pynew file mode 100644index 000000000000..90f5542bcb74--- /dev/null+++ b/products/notebooks/backend/frame_store.py@@ -0,0 +1,90 @@+"""Object-store handoff for materialized SQLV2 frames (sql_v2_frame_store.md, phase 1).++A Temporal worker streams a frame's ClickHouse result (raw Arrow IPC stream bytes) into+one object here; the data-plane status endpoint answers the kernel's poll with a 302 to a+short-lived presigned GET of that object. Tenant isolation is the team prefix: keys are+always built from data-plane token claims, never from request input, and presigning+refuses any key outside the requesting team's prefix.+"""++import re+from typing import IO++from django.conf import settings++from posthog.storage import object_storage++FRAMES_PREFIX = "notebooks/frames"+ARROW_STREAM_CONTENT_TYPE = "application/vnd.apache.arrow.stream"+# Long enough for the kernel's redirect-follow (and a retry or two), no more — a presigned+# URL is a bearer secret of the same class as the data-plane token.+PRESIGN_EXPIRY_SECONDS = 300++_KEY_SEGMENT_RE = re.compile(r"^[A-Za-z0-9_-]+$")+++class FrameStoreError(Exception):+ pass+++def is_enabled() -> bool:+ """The frame store is env-gated (rollout) and needs object storage to be configured."""+ return bool(settings.NOTEBOOKS_FRAME_STORE_ENABLED and settings.OBJECT_STORAGE_ENABLED)+++def team_prefix(team_id: int) -> str:+ """The per-team key prefix — the tenant isolation unit for frame objects."""+ return f"{FRAMES_PREFIX}/team_{int(team_id)}/"+++def build_frame_key(team_id: int, notebook_short_id: str, query_hash: str) -> str:+ """Build the object key for one materialized frame.++ Segments are validated defensively: they come from token claims and a server-side+ hash, but a key must never be constructible with path separators in it.+ """+ for segment in (notebook_short_id, query_hash):+ if not _KEY_SEGMENT_RE.match(segment):+ raise FrameStoreError(f"Invalid frame key segment: {segment!r}")+ return f"{team_prefix(team_id)}{notebook_short_id}/{query_hash}.arrow"+++def write_stream(key: str, fileobj: IO[bytes]) -> int:+ """Stream `fileobj` into the frame object at `key`; return the stored object's size.++ Memory is bounded by boto3's multipart part buffer, and a failed upload is aborted by+ the transfer manager — a torn stream never leaves a servable partial object. The+ post-write HEAD both confirms the object exists (an UnavailableStorage client no-ops+ writes silently) and provides the size for observability.+ """+ object_storage.write_stream(key, fileobj, extras={"ContentType": ARROW_STREAM_CONTENT_TYPE})+ head = object_storage.head_object(key)+ if head is None:+ raise FrameStoreError("Frame object was not stored")+ return int(head.get("ContentLength") or 0)+++def presign_get(key: str, team_id: int) -> str:+ """Mint a short-lived presigned GET for `key`, refusing keys outside the team's prefix.++ The caller must have verified the data-plane token for `team_id` first; this check is+ the last line keeping a poisoned stored key from ever crossing tenant boundaries.+ """+ if not key.startswith(team_prefix(team_id)):+ raise FrameStoreError("Frame key is not under the requesting team's prefix")+ url = object_storage.get_presigned_url(+ key, expiration=PRESIGN_EXPIRY_SECONDS, content_type=ARROW_STREAM_CONTENT_TYPE+ )+ if not url:+ raise FrameStoreError("Could not presign the frame object")+ return url+++def delete_frame(key: str) -> None:+ """Remove a frame object the caller itself just wrote and verified corrupt.++ Keys are deterministic per (team, notebook, user, query), so a generic failure path+ must never delete — it could destroy an object an earlier successful run's still-live+ status points at. The only legitimate caller is the writer discarding its own bytes.+ """+ object_storage.delete(key)diff --git a/products/notebooks/backend/sandbox/kernel/bootstrap.py b/products/notebooks/backend/sandbox/kernel/bootstrap.pyindex 6e18b973d0ec..a904644a92a1 100644--- a/products/notebooks/backend/sandbox/kernel/bootstrap.py+++ b/products/notebooks/backend/sandbox/kernel/bootstrap.py@@ -62,6 +62,20 @@ def _truncate_stream(text: str, cap: int = _STREAM_CAP_CHARS) -> str:return f"{text[:cap]}\n… [output truncated: exceeded {cap // 1024} KB]"+def _preview_safe_cell(value: Any) -> Any:+ """Coerce one preview cell to a JSON-encodable value (fallback path only)."""+ if value is None or isinstance(value, str | int | float | bool):+ return value+ if isinstance(value, bytes):+ return value.decode("utf-8", "replace")+ try:+ if pd.isna(value):+ return None+ except (TypeError, ValueError):+ pass # pd.isna rejects containers and some objects — fall through to str+ return str(value)++def _load_headless_pyplot() -> Any:# matplotlib is heavy and sandbox-only; keep it off the module import path (ruff TID253),# and force the Agg backend before pyplot loads so figures render without a display.@@ -288,7 +302,16 @@ class KernelSession:columns = [str(column) for column in df.columns]types = [[str(column), str(dtype)] for column, dtype in zip(df.columns, df.dtypes)]# to_json coerces numpy scalars, NaN and datetimes to JSON-native values in one pass.- rows = json.loads(df.head(limit).to_json(orient="values", date_format="iso"))+ try:+ rows = json.loads(df.head(limit).to_json(orient="values", date_format="iso"))+ except (OverflowError, UnicodeDecodeError, ValueError, TypeError):+ # Frames can carry values ujson can't encode — raw bytes from ClickHouse-native+ # binary columns, or exotic objects user code produced. The preview is+ # display-only (paging reads the Arrow frame), so degrade per cell instead of+ # failing a run whose compute succeeded.+ rows = [+ [_preview_safe_cell(cell) for cell in row] for row in df.head(limit).itertuples(index=False, name=None)+ ]# The preview is display-only (paging reads the Arrow frame), so huge cells get clipped.rows = [[diff --git a/products/notebooks/backend/sandbox/kernel/data_plane.py b/products/notebooks/backend/sandbox/kernel/data_plane.pyindex dec5529f7a5b..b78c2be55401 100644--- a/products/notebooks/backend/sandbox/kernel/data_plane.py+++ b/products/notebooks/backend/sandbox/kernel/data_plane.py@@ -19,8 +19,15 @@ from typing import Anyimport pyarrow as pa_REQUEST_TIMEOUT_SECONDS = 30-# Total budget for one query: enqueue + Celery pickup + ClickHouse execution.+# Total budget for one inline query: enqueue + Celery pickup + ClickHouse execution._POLL_DEADLINE_SECONDS = 180+# Object materialization is dispatched to a Temporal workflow whose schedule_to_close is+# 10 minutes over a 500k-row / 50GB-scan ceiling — exactly the large frames this path+# exists to carry. The client budget must cover the server budget (plus margin for the+# final poll interval), or the headline case times out client-side while the worker keeps+# producing an object nobody fetches. Sync with NotebookFrameMaterializeWorkflow's+# schedule_to_close_timeout in temporal/frame_materialize.py.+_OBJECT_POLL_DEADLINE_SECONDS = 660_POLL_INITIAL_INTERVAL_SECONDS = 0.3_POLL_MAX_INTERVAL_SECONDS = 2.0@@ -33,6 +40,30 @@ class DataPlaneInterrupted(DataPlaneError):"""The run's cancel event fired while waiting on the data plane."""+class _NoRedirectHandler(urllib.request.HTTPRedirectHandler):+ """Surface 3xx responses as HTTPError instead of auto-following.++ urllib re-sends all request headers on a redirect — including Authorization — which+ would ship the data-plane bearer token to the object-store host (and S3 rejects+ requests carrying both header auth and presigned query auth). The poll intercepts the+ 302 and fetches the presigned URL with a clean, credential-free request instead.+ """++ def redirect_request(+ self, req: Any, fp: Any, code: int, msg: str, headers: Any, newurl: str+ ) -> urllib.request.Request | None:+ return None+++_no_redirect_opener = urllib.request.build_opener(_NoRedirectHandler)+++# How much of a presigned frame URL may be surfaced for observability. The URL is a+# bearer secret; the first 30 characters cover scheme + host (which store served the+# frame) and never reach the signature query parameters.+_FRAME_SOURCE_PREVIEW_CHARS = 30++def fetch_query_page(url: str,token: str,@@ -42,7 +73,8 @@ def fetch_query_page(cancel_event: "threading.Event | None" = None,) -> tuple[list[str], list[tuple[Any, ...]], list[list[str]]]:"""Run `query` through the data plane; return (columns, rows, types) of the capped page."""- return _table_to_rows_and_types(_request_table(url, token, query, limit, offset, cancel_event))+ table, _source = _request_table(url, token, query, limit, offset, cancel_event=cancel_event)+ return _table_to_rows_and_types(table)def materialize_query_to_file(@@ -53,19 +85,24 @@ def materialize_query_to_file(limit: int,offset: int = 0,cancel_event: "threading.Event | None" = None,-) -> int:+) -> tuple[int, str | None]:"""Fetch the full result of `query` and write it as a local Arrow IPC file for a Python/DuckDB node.- Returns the row count. The file is written to a temp name and renamed on success so a torn- write (e.g. a mid-stream failure) never leaves a half-frame the kernel could read.+ Returns (row count, truncated frame-store URL preview) — the preview is set only when+ the frame actually came from a presigned object download (None on the inline fallback),+ so callers can surface which store served the frame. Requests object delivery: the poll+ answers with a 302 to a presigned object-store URL carrying the same Arrow bytes+ (falling back to the inline body when the backend's frame store is unavailable). The+ file is written to a temp name and renamed on success so a torn write (e.g. a+ mid-stream failure) never leaves a half-frame the kernel could read."""- table = _request_table(url, token, query, limit, offset, cancel_event)+ table, source = _request_table(url, token, query, limit, offset, delivery="object", cancel_event=cancel_event)temp_path = f"{dest_path}.partial"with pa.OSFile(temp_path, "wb") as sink:with pa.ipc.new_file(sink, table.schema) as writer:writer.write_table(table)os.replace(temp_path, dest_path)- return table.num_rows+ return table.num_rows, sourcedef _check_cancelled(cancel_event: "threading.Event | None") -> None:@@ -74,13 +111,27 @@ def _check_cancelled(cancel_event: "threading.Event | None") -> None:def _request_table(- url: str, token: str, query: str, limit: int, offset: int, cancel_event: "threading.Event | None" = None-) -> "pa.Table":- """POST the query and (once the async manager finishes) return the raw Arrow table."""+ url: str,+ token: str,+ query: str,+ limit: int,+ offset: int,+ delivery: str = "inline",+ cancel_event: "threading.Event | None" = None,+) -> tuple["pa.Table", str | None]:+ """POST the query and (once the async manager finishes) return the raw Arrow table.++ The second element is a truncated presigned-URL preview when the rows came from an+ object download, else None.+ """_check_cancelled(cancel_event)+ body: dict[str, Any] = {"query": query, "limit": limit, "offset": offset}+ if delivery != "inline":+ # Only sent when non-default, keeping page requests byte-identical for old backends.+ body["delivery"] = deliveryrequest = urllib.request.Request(url,- data=json.dumps({"query": query, "limit": limit, "offset": offset}).encode(),+ data=json.dumps(body).encode(),headers={"Authorization": f"Bearer {token}", "Content-Type": "application/json"},method="POST",)@@ -90,7 +141,7 @@ def _request_table(with urllib.request.urlopen(request, timeout=_REQUEST_TIMEOUT_SECONDS) as response:if _is_arrow(response):# A pre-async-manager backend answers the POST with the rows directly.- return _read_table(response)+ return _read_table(response), Nonebody = json.loads(response.read() or b"{}")except urllib.error.HTTPError as exc:raise DataPlaneError(_error_detail(exc)) from exc@@ -102,23 +153,38 @@ def _request_table(query_id = body.get("query_id")if not query_id:raise DataPlaneError("Data plane did not accept the query")- return _poll_for_table(f"{url.rstrip('/')}/{query_id}/", token, cancel_event)+ return _poll_for_table(+ f"{url.rstrip('/')}/{query_id}/", token, expect_object=delivery == "object", cancel_event=cancel_event+ )-def _poll_for_table(status_url: str, token: str, cancel_event: "threading.Event | None" = None) -> "pa.Table":+def _poll_for_table(+ status_url: str,+ token: str,+ expect_object: bool = False,+ cancel_event: "threading.Event | None" = None,+) -> tuple["pa.Table", str | None]:request = urllib.request.Request(status_url, headers={"Authorization": f"Bearer {token}"}, method="GET")- deadline = time.monotonic() + _POLL_DEADLINE_SECONDS+ # Only object-delivery polls intercept the completion 302 (a presigned frame handoff).+ # Inline polls keep urllib's transparent redirect-following, so an infrastructure+ # redirect (HTTPS upgrade, trailing-slash canonicalization) on a page fetch behaves as+ # it did before object delivery existed — no auth-header leak concern, since the target+ # is still our own data plane and inline responses carry no presigned URL.+ opener = _no_redirect_opener.open if expect_object else urllib.request.urlopen+ deadline = time.monotonic() + (_OBJECT_POLL_DEADLINE_SECONDS if expect_object else _POLL_DEADLINE_SECONDS)interval = _POLL_INITIAL_INTERVAL_SECONDSwhile time.monotonic() < deadline:_check_cancelled(cancel_event)try:# status_url is the backend's own data-plane endpoint from the signed run payload, not user input.# nosemgrep: python.lang.security.audit.dynamic-urllib-use-detected.dynamic-urllib-use-detected- with urllib.request.urlopen(request, timeout=_REQUEST_TIMEOUT_SECONDS) as response:+ with opener(request, timeout=_REQUEST_TIMEOUT_SECONDS) as response:if _is_arrow(response):- return _read_table(response)+ return _read_table(response), None# 202 — still running.except urllib.error.HTTPError as exc:+ if expect_object and exc.code == 302:+ return _fetch_presigned_table(exc.headers.get("Location") or "")raise DataPlaneError(_error_detail(exc)) from excexcept urllib.error.URLError as exc:raise DataPlaneError(f"Could not reach the data plane: {exc.reason}") from exc@@ -133,6 +199,32 @@ def _poll_for_table(status_url: str, token: str, cancel_event: "threading.Eventraise DataPlaneError("Timed out waiting for the query to finish")+def _fetch_presigned_table(presigned_url: str) -> tuple["pa.Table", str]:+ """Download the frame object from the presigned URL — deliberately credential-free.++ The URL is its own short-lived authorization; the data-plane token must never reach+ the object-store host. Range-based resume of an interrupted download is deferred.+ Returns the table plus a truncated URL preview — never the full URL, which is a+ bearer secret and must not travel beyond this fetch.+ """+ if not presigned_url:+ raise DataPlaneError("Data plane redirect carried no download URL")+ source_preview = presigned_url[:_FRAME_SOURCE_PREVIEW_CHARS]+ request = urllib.request.Request(presigned_url, method="GET")+ try:+ # The URL comes from our own backend's redirect (minted after token verification),+ # never from user input.+ # nosemgrep: python.lang.security.audit.dynamic-urllib-use-detected.dynamic-urllib-use-detected+ with urllib.request.urlopen(request, timeout=_REQUEST_TIMEOUT_SECONDS) as response:+ return _read_table(response), source_preview+ except urllib.error.HTTPError as exc:+ raise DataPlaneError(f"Frame download failed with HTTP {exc.code}") from exc+ except urllib.error.URLError as exc:+ raise DataPlaneError(f"Could not reach the frame store: {exc.reason}") from exc+ except pa.ArrowInvalid as exc:+ raise DataPlaneError(f"Invalid Arrow bytes in the frame object: {exc}") from exc++def _is_arrow(response: Any) -> bool:return "arrow" in (response.headers.get("Content-Type") or "")diff --git a/products/notebooks/backend/sandbox/kernel/executor.py b/products/notebooks/backend/sandbox/kernel/executor.pyindex ffa42c414edf..8f6a1e5aedd6 100644--- a/products/notebooks/backend/sandbox/kernel/executor.py+++ b/products/notebooks/backend/sandbox/kernel/executor.py@@ -61,8 +61,14 @@ class KernelExecutor:return envelope.from_python_execution(status="interrupted", error=envelope.INTERRUPTED_MESSAGE)try:self._ensure_kernel()- inputs = self._materialize_inputs(payload, cancel_event)- return self._invoke_run_node(payload, inputs)+ fetch_notes: list[str] = []+ inputs = self._materialize_inputs(payload, cancel_event, fetch_notes)+ result = self._invoke_run_node(payload, inputs)+ if fetch_notes:+ # Surface where each frame's bytes came from (truncated presigned host,+ # never the full URL) in the node's stdout, next to the run's own output.+ result["stdout"] = "\n".join([*fetch_notes, result.get("stdout") or ""]).strip("\n")+ return resultexcept data_plane.DataPlaneInterrupted:return envelope.from_python_execution(status="interrupted", error=envelope.INTERRUPTED_MESSAGE)except data_plane.DataPlaneError as exc:@@ -109,14 +115,17 @@ class KernelExecutor:self._inject_session()def _inject_session(self) -> None:- status = self._execute(+ status, error_detail = self._execute(f"from nb_kernel.bootstrap import KernelSession\n_ph = KernelSession(data_dir={self._data_dir!r})\n")if status != "ok":- raise RuntimeError("failed to initialize the kernel session")+ raise RuntimeError(f"failed to initialize the kernel session ({error_detail or 'no error detail'})")def _materialize_inputs(- self, payload: dict[str, Any], cancel_event: threading.Event | None = None+ self,+ payload: dict[str, Any],+ cancel_event: threading.Event | None = None,+ fetch_notes: list[str] | None = None,) -> list[dict[str, Any]]:"""Fetch each HogQL input to a local Arrow file; return the kernel-facing input specs (paths only)."""kernel_inputs: list[dict[str, Any]] = []@@ -136,7 +145,7 @@ class KernelExecutor:frame_path = os.path.join(self._frames_dir, f"{node_token}.{spec['run_id']}.arrow")if not os.path.exists(frame_path):self._evict_superseded_frames(node_token, keep=frame_path)- data_plane.materialize_query_to_file(+ _row_count, fetched_from = data_plane.materialize_query_to_file(payload["data_plane_url"],payload["data_plane_token"],spec["query"],@@ -144,6 +153,10 @@ class KernelExecutor:limit=_MATERIALIZE_ROW_CAP,cancel_event=cancel_event,)+ if fetched_from and fetch_notes is not None:+ # Only object deliveries carry a source (the inline fallback has none) —+ # this makes the frame-store path visible in the node output.+ fetch_notes.append(f"[frame store] {name} fetched from {fetched_from}…")kernel_inputs.append({"name": name, "kind": "hogql", "path": frame_path})return kernel_inputs@@ -175,7 +188,7 @@ class KernelExecutor:# Only while the cell is actually executing may an interrupt SIGINT the kernel.self._active_run_id = run_idtry:- status = self._execute(+ status, error_detail = self._execute("import json as __j\n"f"with open({payload_path!r}) as __f:\n __payload = __j.load(__f)\n""__envelope = _ph.run_node(__payload)\n"@@ -184,9 +197,12 @@ class KernelExecutor:finally:self._active_run_id = Noneif status != "ok" or not os.path.exists(envelope_path):- return envelope.from_python_execution(- status="error", error="The kernel did not return a result (it may have crashed — try re-running)."+ message = (+ f"The kernel run failed: {error_detail}"+ if error_detail+ else "The kernel did not return a result (it may have crashed — try re-running).")+ return envelope.from_python_execution(status="error", error=message)with open(envelope_path) as handle:return json.load(handle)finally:@@ -194,11 +210,13 @@ class KernelExecutor:# paging live under /data/results, so the per-run dir must not accumulate.shutil.rmtree(run_dir, ignore_errors=True)- def _execute(self, code: str) -> str:- """Run code in the kernel; return the execute_reply status ('ok'/'error').+ def _execute(self, code: str) -> tuple[str, str | None]:+ """Run code in the kernel; return (execute_reply status, error detail when not ok).- Raises if the kernel dies or the run overruns the time budget (then the cell is- interrupted so the kernel is reusable for the next run).+ The detail is the reply's exception name and value — without it a run-machinery+ failure surfaces as an unactionable "kernel did not return a result". Raises if+ the kernel dies or the run overruns the time budget (then the cell is interrupted+ so the kernel is reusable for the next run)."""msg_id = self._kc.execute(code, store_history=False, silent=True)deadline = time.monotonic() + _EXECUTE_TIMEOUT_SECONDS@@ -211,7 +229,12 @@ class KernelExecutor:continueif reply.get("parent_header", {}).get("msg_id") != msg_id:continue # a stale reply from an earlier run- return str(reply.get("content", {}).get("status") or "error")+ content = reply.get("content", {}) or {}+ reply_status = str(content.get("status") or "error")+ if reply_status == "ok":+ return reply_status, None+ detail = f"{content.get('ename') or ''}: {content.get('evalue') or ''}".strip(": ")+ return reply_status, detail or Noneself.interrupt() # overran the budget — stop the cell so the kernel stays usableraise RuntimeError("the kernel run exceeded the time limit")diff --git a/products/notebooks/backend/sql_v2_data_plane.py b/products/notebooks/backend/sql_v2_data_plane.pyindex d1fb3e991e27..f2e5321e28b3 100644--- a/products/notebooks/backend/sql_v2_data_plane.py+++ b/products/notebooks/backend/sql_v2_data_plane.py@@ -21,10 +21,11 @@ from typing import Anyfrom django.conf import settingsfrom django.core import signing-from django.http import HttpRequest, HttpResponse, JsonResponse+from django.http import HttpRequest, HttpResponse, HttpResponseRedirect, JsonResponseimport structlogfrom drf_spectacular.utils import OpenApiResponse, extend_schema+from prometheus_client import Counterfrom posthog.hogql.errors import ExposedHogQLErrorfrom posthog.hogql.parser import parse_select@@ -33,6 +34,7 @@ from posthog.clickhouse.client.execute_async import QueryNotFoundError, enqueue_from posthog.clickhouse.query_tagging import Feature, Product, tags_contextfrom posthog.models import Team, User+from products.notebooks.backend import frame_storefrom products.notebooks.backend.models import Notebookfrom products.notebooks.backend.sql_v2 import verify_data_plane_tokenfrom products.notebooks.backend.sql_v2_serializers import NotebookSQLV2DataPlaneRequestSerializer@@ -41,6 +43,11 @@ logger = structlog.get_logger(__name__)ARROW_STREAM_CONTENT_TYPE = "application/vnd.apache.arrow.stream"+FRAME_STORE_FALLBACK_COUNTER = Counter(+ "posthog_notebooks_frame_store_fallback_inline",+ "Number of object-delivery requests that fell back to the inline (Redis) path.",+)+def _rows_to_arrow_bytes(columns: list[str], rows: list[tuple[Any, ...]], types: list[list[str]] | None = None@@ -140,6 +147,40 @@ def notebook_sql_v2_data_plane(request: HttpRequest) -> HttpResponse:# nosemgrep: semgrep.rules.security.hogql-fstring-auditwrapped = f"select * from ({data['query']}\n) limit {int(data['limit'])} offset {int(data['offset'])}"+ if data["delivery"] == "object":+ if frame_store.is_enabled():+ # Whole-frame materialization: stream the result to object storage via a+ # Temporal worker; the poll answers with a 302 to a presigned URL. The+ # frame_materialize module is imported lazily — it pulls temporalio and the+ # worker ClickHouse client, which must stay off the urls.py import path.+ from products.notebooks.backend.temporal.frame_materialize import ( # noqa: PLC0415+ enqueue_frame_materialization,+ )++ try:+ with tags_context(product=Product.NOTEBOOKS, feature=Feature.QUERY, team_id=team.id):+ status = enqueue_frame_materialization(+ team=team,+ user_id=user.id if user else None,+ notebook_short_id=notebook_short_id,+ query=wrapped,+ _test_only_inline=settings.TEST,+ )+ except Exception:+ logger.exception("notebook_frame_materialize_enqueue_failed", notebook_short_id=notebook_short_id)+ return JsonResponse({"error": "Query could not be scheduled."}, status=500)+ return JsonResponse({"query_id": status.id}, status=202)+ # Degraded mode: the cell still runs over the inline (Redis) transport, clamped at+ # the async row ceiling, instead of hard-failing. Loud on purpose.+ FRAME_STORE_FALLBACK_COUNTER.inc()+ logger.warning(+ "notebook_frame_store_fallback_inline",+ notebook_short_id=notebook_short_id,+ team_id=team_id,+ frame_store_enabled=settings.NOTEBOOKS_FRAME_STORE_ENABLED,+ object_storage_enabled=settings.OBJECT_STORAGE_ENABLED,+ )+try:with tags_context(product=Product.NOTEBOOKS, feature=Feature.QUERY, team_id=team.id):status = enqueue_process_query_task(@@ -162,6 +203,7 @@ def notebook_sql_v2_data_plane(request: HttpRequest) -> HttpResponse:responses={(200, ARROW_STREAM_CONTENT_TYPE): OpenApiResponse(description="Query result as an Arrow IPC stream"),202: OpenApiResponse(description="Query is still running"),+ 302: OpenApiResponse(description="Object-delivery result; Location is a short-lived presigned download URL"),400: OpenApiResponse(description="Query failed"),401: OpenApiResponse(description="Missing or invalid data-plane token"),404: OpenApiResponse(description="Query not found or expired"),@@ -169,7 +211,9 @@ def notebook_sql_v2_data_plane(request: HttpRequest) -> HttpResponse:summary="SQLV2 data-plane query status",description=("Internal endpoint the notebook sandbox polls for an enqueued data-plane query. "- "Returns 202 while the query runs and the rows as an Arrow IPC stream once complete."+ "Returns 202 while the query runs; once complete, inline deliveries return the rows "+ "as an Arrow IPC stream and object deliveries return a 302 redirect to a presigned "+ "download URL for the same bytes."),)def notebook_sql_v2_data_plane_status(request: HttpRequest, query_id: str) -> HttpResponse:@@ -192,6 +236,19 @@ def notebook_sql_v2_data_plane_status(request: HttpRequest, query_id: str) -> Htreturn JsonResponse({"error": status.error_message or "Query execution failed."}, status=400)results: dict[str, Any] = status.results or {}++ object_key = results.get("object_key")+ if object_key:+ # Object delivery: the status carries a pointer, not rows. The token was verified+ # above; presign_get additionally refuses keys outside this team's prefix. The+ # presigned URL is a bearer secret — it must never be logged.+ try:+ presigned_url = frame_store.presign_get(str(object_key), team_id)+ except frame_store.FrameStoreError:+ logger.exception("notebook_frame_presign_failed", team_id=team_id, query_id=query_id)+ return JsonResponse({"error": "The frame download could not be prepared. Try re-running."}, status=500)+ return HttpResponseRedirect(presigned_url)+columns = [str(column) for column in (results.get("columns") or [])]types = [[str(name), str(type_name)] for name, type_name in (results.get("types") or [])]payload = _rows_to_arrow_bytes(columns, results.get("results") or [], types)diff --git a/products/notebooks/backend/sql_v2_frame_store.md b/products/notebooks/backend/sql_v2_frame_store.mdindex 1bfcfe8f46c7..27033857dd50 100644--- a/products/notebooks/backend/sql_v2_frame_store.md+++ b/products/notebooks/backend/sql_v2_frame_store.md@@ -1,7 +1,7 @@# SQLV2 frame materialization via object storageDesign notes for moving python-node frame materialization off the Redis JSON transport and onto an object-storage handoff.-Status: **proposal** — not started; materialization is deliberately clamped at 50k rows until phase 1 lands.+Status: **phase 1 shipped** (env-gated by `NOTEBOOKS_FRAME_STORE_ENABLED`, default off) — object delivery at a 500k row tier-1 ceiling (`MAX_SELECT_NOTEBOOK_MATERIALIZE_LIMIT`); the inline path remains as the degraded fallback, still clamped at 50k. Phases 2+ not started.## Problem@@ -14,12 +14,13 @@ When a python node reads an upstream SQLV2 frame, the sandbox kernel fetches theThe frame is fully copied ~5 times, and the middle copy sits in Redis — the shared cache for the whole deployment.This transport is implicitly sized by the 50k row ceiling (`MAX_SELECT_RETURNED_ROWS` under the async limit context),-so materialized frames are silently clipped at 50k rows today.+so inline materialized frames are silently clipped at 50k rows.A `LimitContext.NOTEBOOK_MATERIALIZE` context raising the ceiling to 2M (`_MATERIALIZE_ROW_CAP`) was built and then**deliberately reverted**: without a better payload transport, wide multi-hundred-thousand-row frames stress Redis(single-threaded, 512MB per-value hard cap, eviction pressure) and the workers that render/parse the JSON.-The clamp is pinned by `test_materialization_request_is_accepted_and_clipped_at_the_row_ceiling` and comes off as-part of phase 1, when the transport can carry what the limit allows.+With phase 1 the context is back, applied **only on the object path** and at a 500k tier-1 ceiling+(`MAX_SELECT_NOTEBOOK_MATERIALIZE_LIMIT`, raised toward 2M on query-log evidence); the inline path — now the+degraded fallback — keeps the 50k clamp, pinned by `test_inline_materialization_stays_clipped_at_the_row_ceiling`.## Decision sketch: durable object handoff, not live push@@ -37,8 +38,10 @@ A wins on every axis that matters here except single-transfer latency:Draining into S3 happens at datacenter speed, so CH resources are held for ~pure execution time.Draining into a Modal container is paced by public-internet throughput and the kernel's ingest —backpressure propagates into CH (memory pinned, query slot held, execution-time clock ticking).-- **Reuse.** Frames are keyed by `query_hash`; an object serves retries, kernel restarts, and unchanged upstream- queries without re-executing CH. Push has no reuse story — every delivery is a fresh execution.+- **Reuse.** Frames are keyed by `query_hash`; an object serves download retries and kernel restarts without+ re-executing CH. Cross-run reuse of an unchanged query is phase 3 — and gated on a staleness policy,+ because the key has no freshness component (see the stale-read hazard there). Push has no reuse story —+ every delivery is a fresh execution.- **Attack surface.** Pull keeps the sandbox ingress-free; push requires a new streamed-upload endpoint on thekernel server, exposed to the internet, plus a request/callback correlation protocol.@@ -72,8 +75,9 @@ Every building block already runs in production. Inventory (per deep-dive, 2026-### Relevant negativeThere is **no generic S3-backed query-result cache** — `query_cache_factory.py` only returns the Redis manager.-That cache exists to reuse identical insight queries within a TTL; the notebook flow already gets its reuse from-`query_hash`-keyed frames, so we are not duplicating (or blocked on) any platform facility.+That cache exists to reuse identical insight queries within a TTL; the notebook flow gets its reuse from+`query_hash`-keyed frames (in-flight dedup and retry re-fetch today; cross-run reuse is phase 3), so we are+not duplicating (or blocked on) any platform facility.## Security model for sandbox reads@@ -101,9 +105,10 @@ token-authed; only the bulk-bytes leg moves to object storage.- **Presigned GET discipline.** Short expiry (minutes — long enough for a resume-with-Range retry loop, no more),HTTPS-only, never logged. A presigned URL is a bearer secret of the same class as the existing command tokens;its blast radius is one object for a few minutes.-- **Write-side auth.** CH writes via its instance role (keyless, batch-exports pattern), write-scoped to the- notebooks prefix. If tighter isolation is wanted later: STS prefix-scoped credentials per run- (file-download-export pattern).+- **Write-side auth.** Phase 1: the Temporal worker writes with the standard worker-held object-storage+ credentials (`OBJECT_STORAGE_*` — no new identity). Phase 2, if CH writes directly: CH's instance role+ (keyless, batch-exports pattern), write-scoped to the notebooks prefix. If tighter isolation is wanted+ later: STS prefix-scoped credentials per run (file-download-export pattern).- **Egress.** The sandbox already makes outbound HTTPS calls to the PostHog API; fetching a presigned S3 URL addsone more allowed destination. If Modal egress policy must stay single-destination, the fallback is proxying theobject through the data-plane endpoint as a bounded stream — bytes transit Django once, but never Redis and@@ -126,19 +131,24 @@ and threads.Layered levers:- **Per-query SETTINGS (batch-exports recipe).** The staging query carries hard caps, as `internal_stage.py`- does: `max_execution_time` (modestly above the insight ceiling — frame pulls are legitimately heavier),- `max_bytes_to_read` (refuse oversized scans up front), `max_memory_usage`,- `max_bytes_before_external_sort/group_by` (spill to disk), `max_threads`, `min_insert_block_size_bytes`- (64MiB there). `max_network_bandwidth` can throttle the S3 write rate if needed.-- **Scheduler priority, not pool exile.** CH's `priority` setting lets materialization run ONLINE while- yielding CPU to interactive queries under genuine contention — dashboards get right-of-way without- sending notebooks to a worse pool.+ does. Phase 1 ships `max_execution_time` 600s (via the `NOTEBOOK_MATERIALIZE` limit context — modestly+ above the insight ceiling, frame pulls are legitimately heavier), `max_bytes_to_read` 50GB (refuse+ oversized scans up front), `max_threads` 16, and `max_result_bytes` 2GB with `result_overflow_mode=throw`+ (row/scan caps don't bound the _output_ — `repeat('x', 10000)` over 500k rows would make a ~5GB object+ from a near-zero scan; the output cap bounds object size, storage abuse, and what the kernel later decodes+ into pandas, and it throws rather than silently truncating); memory stays on the cluster profile default+ for tier 1 (the typed `MEMORY_LIMIT_EXCEEDED` handling is the backstop). Further levers if data demands:+ `max_memory_usage`, `max_bytes_before_external_sort/group_by` (spill to disk), `max_network_bandwidth`+ to throttle the S3 write rate.+- **Scheduler priority, not pool exile.** CH's `priority` setting could let materialization run ONLINE while+ yielding CPU to interactive queries under genuine contention. Phase 1 deliberately does not set it:+ everything else runs unprioritized (0), so a nonzero value would form a scheduling class of one — revisit+ if the cluster ever adopts priorities broadly.- **Tiered row ceiling.** Don't jump 50k → 2M in one step: raise to ~500k with the phase-1 transport,watch the footprint, then raise toward `_MATERIALIZE_ROW_CAP`.- **Admission control above CH.** One operation per notebook is already enforced by the operations logic;- add a per-team concurrency cap (one concurrent materialization per team initially) and a small dedicated- Celery queue so global concurrency equals worker count. The refs resolver already minimizes demand —- only frames the code actually reads are materialized.+ phase 1 adds the Redis-Lua concurrency slots (global 10, per-team 2) acquired at Temporal activity start.+ The refs resolver already minimizes demand — only frames the code actually reads are materialized.- **Dedicated ClickHouse user as the backstop.** The repo already splits traffic across CH users(`ClickHouseUser.APP` / `API`), each governed by a server-side settings profile. A materialization user getsprofile limits, QUOTAs, and `max_concurrent_queries_for_user` — a hard server-enforced ceiling no@@ -154,34 +164,74 @@ query-log exports make its CH footprint analyzable, so the knobs can be tightene## Phased plan — start basic, improve later-**Phase 0 (current state).** Materialization runs over the existing Redis transport, clipped at 50k rows.+**Phase 0.** Materialization runs over the existing Redis transport, clipped at 50k rows.Fine for the current flag-gated audience and frames up to low hundreds of thousands of rows.--**Phase 1 — swap the payload path, minimal moving parts.**-Reintroduce `LimitContext.NOTEBOOK_MATERIALIZE` together with the new transport (tiered ceiling — see-resource governance — landing eventually at `_MATERIALIZE_ROW_CAP`).-When the data-plane task runs under it, the worker streams the CH result-(`output_format="ArrowStream"`, bounded batches — data-modeling pattern) into one object,-stores the **object key** in `QueryStatus` instead of rows, and the status endpoint answers the poll with a-**302 redirect to a presigned URL**.-The kernel's `requests` client follows redirects by default and drops the `Authorization` header on cross-host-redirects, so the existing executor works nearly unchanged and the presigned URL needs no auth.-Keep the Redis path as fallback when object storage is unconfigured (dev parity, degraded mode).+Since phase 1 this path survives only as the degraded fallback (frame store disabled or unconfigured).++**Phase 1 — swap the payload path, minimal moving parts. (Shipped, env-gated by `NOTEBOOKS_FRAME_STORE_ENABLED`.)**+The kernel opts in per request with `delivery: "object"` (pages and envelope fetches stay `"inline"`).+The data plane registers a `notebook-frame:{team}:{query_hash}` dedup mapping and dispatches a Temporal+materialize workflow (`temporal/frame_materialize.py`, general-purpose queue, Redis-Lua concurrency slots+global 10 / per-team 2): the activity prints the HogQL through the guarded executor under+`LimitContext.NOTEBOOK_MATERIALIZE` (tier-1 ceiling 500k, not yet 2M), executes over the CH HTTP interface+with `FORMAT ArrowStream`, and relays the raw bytes into one multipart upload+(`frame_store.py`, key `notebooks/frames/team_{team}/{notebook}/{query_hash}.arrow`).+The **object key** lands in `QueryStatus` instead of rows, and the status endpoint answers the poll with a+**302 redirect to a presigned URL** (≤5 min, minted only after token verification, team-prefix-checked).+A frame key is a slot holding the query's current result, not an immutable blob: `query_hash` is+`sha256(user_id + wrapped query)` with no freshness component, and dedup only joins **in-flight**+materializations — a completed status is never served as a cache. Every re-run therefore re-executes against+ClickHouse and atomically overwrites the same key, which is exactly why a re-run after new events lands always+returns fresh rows in this phase (a reader holding a presign across an overwrite gets one complete object or+the other, never torn bytes).+One correction to the sketch below: the kernel's client is `urllib`, not `requests` — urllib re-sends+`Authorization` on redirects, so the client intercepts the 302 and fetches the presigned URL with a fresh,+credential-free request instead of auto-following.+Stream integrity: ClickHouse sends `200 OK` before execution finishes, so a mid-stream failure can't change+the status code — current versions deliberately break the chunked encoding (the read tears, the multipart+upload aborts), but older versions/intermediaries can close the body cleanly with exception text appended.+The worker therefore refuses to finalize unless the streamed bytes end with the Arrow end-of-stream marker+(a corrupt object at the deterministic key is deleted), and on any stream failure it recovers the real+ClickHouse error from `system.query_log` — a confirmed query-side exception is terminal (no doomed+re-scans), an unconfirmed failure stays retryable.+The Redis path stays as fallback when the frame store is disabled or unconfigured (dev parity, degraded mode).++_Rollout prerequisites (per environment, before flipping the flag on):_++- Enable `NOTEBOOKS_FRAME_STORE_ENABLED` only **after** both the web and general-purpose Temporal worker+ fleets are on the new image. Temporal accepts a `start_workflow` for a workflow type no worker has+ registered yet — so flipping the flag early produces a bounded window of hung polls that the enqueue+ rollback (which only catches a dispatch _exception_) cannot recover.+- Confirm `OBJECT_STORAGE_PUBLIC_ENDPOINT` resolves and routes **from the sandbox kernel's network** — the+ kernel fetches the presigned URL directly. An internal-only host (or the local SeaweedFS docker name)+ makes every download fail (loud, not silent).+- Provision the bucket lifecycle TTL (~24h) on the `notebooks/frames/` prefix **before** enabling.+ Successful objects are never deleted by app code, and query-text variations (even comment-only edits)+ mint new hashes, so without the lifecycle rule an authenticated user can accumulate unbounded durable+ objects. The rule is infra-owned; app-level cleanup would duplicate it poorly.+- Known degraded-mode caveat: with the flag off (the default) or object storage down, a `delivery: "object"`+ request falls back to the inline path clamped at 50k rows and the frame is silently truncated. Fine for+ frames under the clamp; a user-visible truncation signal is a follow-up before GA.Two decisions locked in for this phase:- **Format: one plain Arrow IPC stream object per frame — not Delta, not Parquet.** Delta earns its machinery- when ClickHouse re-reads a versioned, overwritten _table_ (data modeling's case). A frame is an immutable- write-once blob keyed by `query_hash`, read by pandas — an "update" is a different hash, i.e. a different- key. The executor already consumes ArrowStream from the data plane, so the sandbox-side change is just- "read the same bytes from a different host". If size matters, Arrow IPC supports LZ4/ZSTD buffer- compression without a format change; multi-file partitioning waits for phase 2, if ever.-- **The queue is the throttle.** Under worker streaming, one active task = one running CH query = one upload,- so the dedicated queue's concurrency directly bounds CH concurrency, worker memory (~100MB × concurrency),- and S3 parallelism with a single knob — no dedicated CH user needed for v1 (that stays as hardening).- Throttling moves load in time (backlog), never above the cap; the real amplification risk is impatient- re-runs, and the async manager's existing `cache_key` dedup (`get_running_query_by_cache_key`) closes it:- enqueue with `cache_key = query_hash` and duplicate in-flight materializations join the running query+ when ClickHouse re-reads a versioned, overwritten _table_ (data modeling's case). A frame key is a slot+ holding one query's current result (see above — re-runs overwrite it atomically), read once by pandas;+ versioned re-read machinery buys nothing for that flow. The executor already consumes ArrowStream from the+ data plane, so the sandbox-side change is just "read the same bytes from a different host". If size matters,+ Arrow IPC supports LZ4/ZSTD buffer compression without a format change; multi-file partitioning waits for+ phase 2, if ever.+- **An explicit concurrency limiter is the throttle.** Under worker streaming, one active task = one running+ CH query = one upload — but the materialize workflow runs on the **shared** general-purpose Temporal queue,+ so queue slots alone don't cap notebooks. The shipped throttle is the Redis-Lua concurrency limiter+ (the `process_query_task` mechanism): slots acquired at activity start, global 10 / per-team 2, bounding CH+ concurrency, worker memory, and S3 parallelism with one knob — no dedicated CH user needed for v1 (that+ stays as hardening), and a dedicated notebooks task queue stays a later infra option. Throttling moves load+ in time (retry backoff), never above the cap; the real amplification risk is impatient re-runs, and the+ async manager's `cache_key` dedup (`get_running_query_by_cache_key`) closes it: enqueue with+ `cache_key = notebook-frame:{team}:{sha256(user_id + query)}` (user-scoped, so differently-permissioned+ teammates never share a job or an object) and duplicate in-flight materializations join the running queryinstead of stacking new ones.**Phase 2 — let ClickHouse do the writing (only if the data says so).**@@ -209,11 +259,17 @@ Serve repeat materializations of an unchanged upstream query straight from the e(`query_hash` in the key makes this a HEAD check), tighten lifecycle (delete on supersede),and align the format with the local-DuckDB engine direction so materialized frames double as DuckDB-readabletables without re-encoding.+**Stale-read hazard — must be solved before the HEAD check ships:** the key has no freshness dimension, so a+bare exists-check would serve a frame materialized before newer events landed. Phase 1 stays fresh only+because it always re-executes and overwrites; cross-run reuse needs an explicit staleness input first — an+age-based reuse rule (the insight cache's target-age precedent), a data watermark, or a time bucket folded+into the key.## Open questions-- Bucket choice: reuse `OBJECT_STORAGE_BUCKET` under a `notebooks/` prefix vs a dedicated bucket- (dedicated is cleaner for lifecycle rules and IAM scoping; more infra to provision).+- ~~Bucket choice~~ — resolved in phase 1: `OBJECT_STORAGE_BUCKET` under the `notebooks/frames/` prefix+ (a dedicated bucket stays an option if lifecycle/IAM scoping demands it). The lifecycle TTL (~24h) on+ the frames prefix is an infra ticket — a bucket rule, not app code.- Does cloud CH's instance role already permit writes to the chosen bucket, or does that need infra work(batch exports suggests the pattern is established)?- Presign from SeaweedFS in local dev: verify the presigned host is reachable from the locally-run kernel.diff --git a/products/notebooks/backend/sql_v2_serializers.py b/products/notebooks/backend/sql_v2_serializers.pyindex d1d4a62d7a72..1011c89ae7f9 100644--- a/products/notebooks/backend/sql_v2_serializers.py+++ b/products/notebooks/backend/sql_v2_serializers.py@@ -85,6 +85,18 @@ class NotebookSQLV2DataPlaneRequestSerializer(serializers.Serializer):min_value=0,help_text="Number of rows to skip (applied as an outer OFFSET), for paging.",)+ delivery = serializers.ChoiceField(+ choices=["inline", "object"],+ required=False,+ default="inline",+ help_text=(+ "How the caller wants the result delivered. 'inline' (default) returns rows in the "+ "poll response body as an Arrow IPC stream — right for pages and envelope fetches. "+ "'object' streams the result to object storage and answers the poll with a 302 to a "+ "short-lived presigned download URL — for whole-frame materializations; falls back "+ "to 'inline' (clamped at the async row ceiling) when the frame store is unavailable."+ ),+ )class NotebookSQLV2MediaSerializer(serializers.Serializer):diff --git a/products/notebooks/backend/temporal/__init__.py b/products/notebooks/backend/temporal/__init__.pyindex 4bef916a4f94..4b7808a9e400 100644--- a/products/notebooks/backend/temporal/__init__.py+++ b/products/notebooks/backend/temporal/__init__.py@@ -1,3 +1,8 @@+from products.notebooks.backend.temporal.frame_materialize import (+ NotebookFrameMaterializeWorkflow,+ mark_frame_materialize_failed_activity,+ materialize_frame_activity,+)from products.notebooks.backend.temporal.sql_v2 import (NotebookSQLV2RunWorkflow,dispatch_sql_v2_run_activity,@@ -6,9 +11,12 @@ from products.notebooks.backend.temporal.sql_v2 import (WORKFLOWS = [NotebookSQLV2RunWorkflow,+ NotebookFrameMaterializeWorkflow,]ACTIVITIES = [dispatch_sql_v2_run_activity,mark_sql_v2_run_failed_activity,+ materialize_frame_activity,+ mark_frame_materialize_failed_activity,]diff --git a/products/notebooks/backend/temporal/client.py b/products/notebooks/backend/temporal/client.pyindex dcbb89bfc349..15100d7da9fb 100644--- a/products/notebooks/backend/temporal/client.py+++ b/products/notebooks/backend/temporal/client.py@@ -1,4 +1,4 @@-"""Fire-and-forget starter for the SQLV2 run workflow, callable from sync DRF views."""+"""Fire-and-forget starters for notebook Temporal workflows, callable from sync DRF views."""from django.conf import settings@@ -7,6 +7,7 @@ from temporalio.client import Clientfrom posthog.temporal.common.client import sync_connect+from products.notebooks.backend.temporal.frame_materialize import FrameMaterializeInputsfrom products.notebooks.backend.temporal.sql_v2 import SQLV2RunInput@@ -27,3 +28,12 @@ def start_sql_v2_run_workflow(inputs: SQLV2RunInput) -> None:f"notebook-sandbox-cmd-run-{inputs.run_id}",inputs,)+++def start_frame_materialize_workflow(inputs: FrameMaterializeInputs) -> None:+ _start_workflow(+ sync_connect(),+ "notebook-frame-materialize",+ f"notebook-frame-materialize-{inputs.query_id}",+ inputs,+ )diff --git a/products/notebooks/backend/temporal/frame_materialize.py b/products/notebooks/backend/temporal/frame_materialize.pynew file mode 100644index 000000000000..e2a091013c33--- /dev/null+++ b/products/notebooks/backend/temporal/frame_materialize.py@@ -0,0 +1,686 @@+"""Temporal workflow/activity that materializes an SQLV2 frame into the object store.++The data plane dispatches this for `delivery: "object"` requests (whole-frame python-node+inputs): the activity prints the HogQL through the guarded executor (team database ++access controls), executes it over the ClickHouse HTTP interface with `FORMAT ArrowStream`,+and relays the raw response bytes into one object-store multipart upload — no pyarrow+decode in the worker, memory bounded by the part buffer. The existing async-query status+machinery carries a pointer (`{"object_key": ...}`) instead of rows; the status endpoint+turns it into a 302 to a presigned GET.++Load protection mirrors the Celery async path (`process_query_task`): a Redis Lua+concurrency limiter gates activity starts (global + per-team), slot exhaustion and+ClickHouse overload raise retryable errors, and Temporal's retry policy provides the+exponential backoff with a hard schedule-to-close deadline. ClickHouse `priority` is+deliberately not set: every other query runs at priority 0 (unprioritized), so a nonzero+value here would participate in a scheduling class of one.+"""++import time+import uuid+import hashlib+import datetime as dt+from collections.abc import Iterator+from contextlib import contextmanager, suppress+from dataclasses import dataclass+from typing import IO, cast++from django.conf import settings++import structlog+from prometheus_client import Counter, Histogram+from temporalio import activity, common, exceptions, workflow++from posthog.schema import QueryStatus++from posthog.hogql import ast+from posthog.hogql.constants import HogQLGlobalSettings, LimitContext+from posthog.hogql.errors import ExposedHogQLError+from posthog.hogql.parser import parse_select+from posthog.hogql.query import HogQLQueryExecutor++from posthog.clickhouse.client import sync_execute+from posthog.clickhouse.client.execute_async import QueryNotFoundError, QueryStatusManager, get_query_status+from posthog.clickhouse.client.limit import ConcurrencyLimitExceeded, RateLimit+from posthog.clickhouse.query_tagging import Feature, Product, tags_context+from posthog.exceptions_capture import capture_exception+from posthog.models import Team, User+from posthog.rbac.user_access_control import UserAccessControl+from posthog.storage.object_storage import ObjectStorageError+from posthog.temporal.common.base import PostHogWorkflow+from posthog.temporal.common.clickhouse import (+ ClickHouseClient,+ ClickHouseMemoryLimitExceededError,+ ClickHouseTooManyBytesError,+ ClickHouseTooManyRowsOrBytesError,+)++from products.notebooks.backend import frame_store++logger = structlog.get_logger(__name__)++# Concurrency slots for materialize jobs — the actual throttle (notebook workflows share+# the general-purpose Temporal queue, so queue slots alone don't cap us). Same Redis Lua+# mechanism that caps process_query_task at 150 global / 10 per team.+MATERIALIZE_GLOBAL_CONCURRENCY = 10+MATERIALIZE_PER_TEAM_CONCURRENCY = 2+# Safeguard expiry for a slot whose holder died without releasing; comfortably above the+# activity's schedule-to-close so a live run never loses its slot mid-stream.+_SLOT_TTL_SECONDS = 15 * 60++# Standing per-query caps, printed into the SQL's SETTINGS clause. max_execution_time is+# raised to HOGQL_INCREASED_MAX_EXECUTION_TIME by the NOTEBOOK_MATERIALIZE limit context.+_MAX_BYTES_TO_READ = 50_000_000_000 # 50GB scan budget, the logs-queries precedent+_MAX_THREADS = 16 # below interactive traffic (the API query-service cap is 60)+# Output-side cap (applied as a query setting on the HTTP request): row/scan caps don't+# bound the result — `repeat('x', 10000)` over 500k rows makes a ~5GB object from a+# near-zero scan. This bounds object size, storage/bandwidth abuse, and what the kernel+# later decodes into pandas. Overflow throws (never silently truncates).+_MAX_RESULT_BYTES = 2_000_000_000 # 2GB, tier 1++# Client-side timeouts on the ClickHouse stream. Temporal cannot interrupt a sync activity+# thread, so without a read timeout a half-open connection would pin the thread (and its+# concurrency slot) until OS-level TCP gives up — far past every deadline. The read timeout+# bounds each silent gap between socket reads, not the total transfer: a healthy stream of+# any size never trips it. A sparse-filter scan can legitimately produce no output for a+# while, so the value is generous; a false positive is retried like any transient failure.+_STREAM_CONNECT_TIMEOUT_SECONDS = 10.0+_STREAM_READ_TIMEOUT_SECONDS = 120.0++# A successful Arrow IPC stream always ends with this 8-byte end-of-stream marker, emitted+# only when the writer finalizes cleanly. ClickHouse streams `200 OK` before execution+# finishes, so a mid-stream failure can't change the status code — depending on version it+# breaks the chunked encoding (the read raises) or appends exception text and closes the+# body cleanly. The marker check catches the clean-close case (and truncation at a batch+# boundary), which would otherwise store a corrupt object and finalize as succeeded.+_ARROW_STREAM_EOS_MARKER = b"\xff\xff\xff\xff\x00\x00\x00\x00"++# system.query_log flushes every ~7.5s, so error recovery after a stream failure polls a+# few times. Only runs on the failure path.+_QUERY_LOG_LOOKUP_ATTEMPTS = 3+_QUERY_LOG_LOOKUP_INTERVAL_SECONDS = 4.0++_RESOURCE_BUDGET_MESSAGE = (+ "This query exceeds the frame materialization limits (scan or memory budget). Narrow it and re-run."+)+_TIME_BUDGET_MESSAGE = "The query hit the frame materialization time limit. Narrow it and re-run."+_RESULT_SIZE_MESSAGE = (+ "The materialized result is too large (over the frame size budget). "+ "Select fewer columns or aggregate before materializing."+)+_MID_STREAM_ERROR_MESSAGE = "The query failed while its result was streaming. Adjust it and re-run."+# ClickHouse exception codes worth a specific user-facing message when a query dies+# mid-stream: 158 TOO_MANY_ROWS, 241 MEMORY_LIMIT_EXCEEDED, 307 TOO_MANY_BYTES,+# 159 TIMEOUT_EXCEEDED, 160 TOO_SLOW, 396 TOO_MANY_ROWS_OR_BYTES (the result-bytes cap).+_MID_STREAM_MESSAGES_BY_CODE = {+ 158: _RESOURCE_BUDGET_MESSAGE,+ 241: _RESOURCE_BUDGET_MESSAGE,+ 307: _RESOURCE_BUDGET_MESSAGE,+ 159: _TIME_BUDGET_MESSAGE,+ 160: _TIME_BUDGET_MESSAGE,+ 396: _RESULT_SIZE_MESSAGE,+}+# Codes that do NOT mean the query itself is doomed: 209 SOCKET_TIMEOUT and 210+# NETWORK_ERROR are transport failures, and 394 QUERY_WAS_CANCELLED is what our own+# abandonment produces (a read timeout closes the connection and+# cancel_http_readonly_queries_on_client_close kills the query). All retry on a fresh+# connection instead of failing the cell.+_TRANSIENT_MID_STREAM_CODES = frozenset({209, 210, 394})++FRAME_MATERIALIZATIONS_STARTED_COUNTER = Counter(+ "posthog_notebooks_frame_materializations_started",+ "Number of notebook frame materialize activity attempts started.",+)+FRAME_MATERIALIZATIONS_FINISHED_COUNTER = Counter(+ "posthog_notebooks_frame_materializations_finished",+ "Number of notebook frame materialize jobs reaching a terminal state.",+ labelnames=["outcome"],+)+FRAME_MATERIALIZATION_DEDUP_COUNTER = Counter(+ "posthog_notebooks_frame_materializations_deduplicated",+ "Number of materialize requests that joined an identical in-flight job.",+)+FRAME_OBJECT_BYTES_HISTOGRAM = Histogram(+ "posthog_notebooks_frame_object_bytes",+ "Size of stored frame objects in bytes.",+ buckets=[1e5, 1e6, 1e7, 5e7, 1e8, 5e8, 1e9, 5e9],+)+FRAME_MATERIALIZE_SECONDS_HISTOGRAM = Histogram(+ "posthog_notebooks_frame_materialize_seconds",+ "End-to-end wall-clock duration of a successful materialize (print + ClickHouse + upload).",+ buckets=[1, 5, 15, 30, 60, 120, 300, 600],+)+# The relay is a single-pass pipeline, so these two are complementary slices of its wall+# clock: which side the thread was blocked on tells us whether ClickHouse production or+# object-store ingestion is the bottleneck.+FRAME_CLICKHOUSE_SECONDS_HISTOGRAM = Histogram(+ "posthog_notebooks_frame_clickhouse_seconds",+ "Time a successful materialize spent blocked on ClickHouse (response headers plus body reads).",+ buckets=[0.5, 1, 5, 15, 30, 60, 120, 300, 600],+)+FRAME_UPLOAD_SECONDS_HISTOGRAM = Histogram(+ "posthog_notebooks_frame_upload_seconds",+ "Time a successful materialize spent blocked on the object-store side of the relay (part handoff and S3 backpressure).",+ buckets=[0.5, 1, 5, 15, 30, 60, 120, 300, 600],+)+++@dataclass+class FrameMaterializeInputs:+ query_id: str+ team_id: int+ notebook_short_id: str+ user_id: int | None+ # The wrapped HogQL (outer LIMIT/OFFSET applied by the data plane). Only ever executed+ # after printing through the guarded HogQL executor — never handed to ClickHouse raw.+ query: str+ query_hash: str+ cache_key: str+++__GLOBAL_LIMITER: RateLimit | None = None+__PER_TEAM_LIMITER: RateLimit | None = None+++def _get_global_limiter() -> RateLimit:+ global __GLOBAL_LIMITER+ if __GLOBAL_LIMITER is None:+ __GLOBAL_LIMITER = RateLimit(+ max_concurrency=MATERIALIZE_GLOBAL_CONCURRENCY,+ limit_name="notebooks_materialize_global",+ get_task_name=lambda *args, **kwargs: "notebooks:materialize:global",+ get_task_id=lambda *args, **kwargs: kwargs["task_id"],+ ttl=_SLOT_TTL_SECONDS,+ )+ return __GLOBAL_LIMITER+++def _get_per_team_limiter() -> RateLimit:+ global __PER_TEAM_LIMITER+ if __PER_TEAM_LIMITER is None:+ __PER_TEAM_LIMITER = RateLimit(+ max_concurrency=MATERIALIZE_PER_TEAM_CONCURRENCY,+ limit_name="notebooks_materialize_per_team",+ get_task_name=lambda *args, **kwargs: f"notebooks:materialize:per-team:{kwargs['team_id']}",+ get_task_id=lambda *args, **kwargs: kwargs["task_id"],+ ttl=_SLOT_TTL_SECONDS,+ )+ return __PER_TEAM_LIMITER+++@contextmanager+def _materialize_slots(team_id: int, task_id: str) -> Iterator[None]:+ """Hold one global and one per-team concurrency slot; raise ConcurrencyLimitExceeded when full.++ The raise is retryable on purpose — Temporal's retry policy is the backoff loop.+ """+ global_limiter = _get_global_limiter()+ team_limiter = _get_per_team_limiter()+ global_key, global_task = global_limiter.use(task_id=f"{task_id}:global", team_id=team_id)+ team_key = team_task = None+ try:+ team_key, team_task = team_limiter.use(task_id=f"{task_id}:team", team_id=team_id)+ yield+ finally:+ # Release each slot independently: a Redis blip releasing the team slot must not+ # skip the global release and leak a global slot until its 15-minute TTL.+ if team_key and team_task:+ with suppress(Exception):+ team_limiter.release(team_key, team_task)+ if global_key and global_task:+ with suppress(Exception):+ global_limiter.release(global_key, global_task)+++def _generate_sql(+ team: Team,+ user: User | None,+ query: "str | ast.SelectQuery | ast.SelectSetQuery",+ *,+ output_format: str | None,+) -> tuple[str, dict[str, object]]:+ """Print HogQL to guarded ClickHouse SQL with the standing caps applied."""+ executor = HogQLQueryExecutor(+ query=query,+ team=team,+ user=user,+ user_access_control=UserAccessControl(user=user, team=team) if user else None,+ limit_context=LimitContext.NOTEBOOK_MATERIALIZE,+ settings=HogQLGlobalSettings(max_bytes_to_read=_MAX_BYTES_TO_READ, max_threads=_MAX_THREADS),+ pretty=False,+ )+ if output_format:+ executor.context.output_format = output_format+ sql, context = executor.generate_clickhouse_sql()+ return sql, context.values+++def _describe_columns(+ client: ClickHouseClient, printed_sql: str, values: dict[str, object], ch_query_id: str+) -> list[tuple[str, str]]:+ """Return the printed query's output columns as (name, ClickHouse type) pairs."""+ describe_sql = f"DESCRIBE TABLE ({printed_sql}) FORMAT TabSeparatedRaw"+ with client.post_query(+ describe_sql,+ query_parameters=values,+ query_id=f"{ch_query_id}_describe",+ timeout=(_STREAM_CONNECT_TIMEOUT_SECONDS, 30.0),+ ) as response:+ text = response.text+ columns: list[tuple[str, str]] = []+ for line in text.splitlines():+ parts = line.split("\t")+ if len(parts) >= 2 and parts[0]:+ columns.append((parts[0], parts[1]))+ return columns+++def _stringify_function_for(ch_type: str) -> str | None:+ """The conversion a column needs so ClickHouse's Arrow output stays kernel-friendly.++ CH emits UUID/FixedString/Enum/IP columns as Arrow (fixed-size) binary — pandas then+ holds raw bytes, which break JSON previews and read as bytes in user code (the inline+ path always delivered them as strings). Mirrors the data-modeling materializer's+ conversion table; containers are left native (a stringified array changes its shape).+ """+ lowered = ch_type.lower()+ if lowered.startswith(("array", "map", "tuple")):+ return None+ if "nullable(nothing)" in lowered:+ return "toNullableString"+ if (+ any(marker in lowered for marker in ("uuid", "enum", "ipv4", "ipv6", "fixedstring"))+ or lowered.startswith("json")+ or "object(" in lowered+ ):+ return "toString"+ return None+++def _print_clickhouse_sql(+ client: ClickHouseClient, team: Team, user: User | None, query: str, ch_query_id: str+) -> tuple[str, dict[str, object]]:+ """Print the HogQL to guarded ClickHouse SQL with `FORMAT ArrowStream` and the standing caps.++ Two passes when needed (the data-modeling recipe): print once, DESCRIBE the printed+ query (metadata only — no execution), and if any output column would leave ClickHouse+ as Arrow binary, wrap the query so those columns are stringified, then print the+ wrapper. Field names go through the HogQL AST/printer, never string splicing.+ """+ plain_sql, plain_values = _generate_sql(team, user, query, output_format=None)+ described = _describe_columns(client, plain_sql, plain_values, ch_query_id)+ conversions = [(name, _stringify_function_for(ch_type)) for name, ch_type in described]+ if not any(function for _name, function in conversions):+ return _generate_sql(team, user, query, output_format="ArrowStream")+ select_fields: list[ast.Expr] = [+ ast.Alias(expr=ast.Call(name=function, args=[ast.Field(chain=[name])]), alias=name)+ if function+ else ast.Field(chain=[name])+ for name, function in conversions+ ]+ stringified = ast.SelectQuery(select=select_fields, select_from=ast.JoinExpr(table=parse_select(query)))+ return _generate_sql(team, user, stringified, output_format="ArrowStream")+++def _finalize_status(+ manager: QueryStatusManager,+ inputs: FrameMaterializeInputs,+ *,+ results: dict[str, object] | None = None,+ error_message: str | None = None,+) -> None:+ """Write the terminal query status and release the dedup mapping."""+ try:+ status = manager.get_query_status()+ except QueryNotFoundError:+ status = QueryStatus(id=inputs.query_id, team_id=inputs.team_id)+ status.complete = True+ status.error = error_message is not None+ status.error_message = error_message+ status.results = results+ status.end_time = dt.datetime.now(dt.UTC)+ manager.store_query_status(status)+ manager.unregister_cache_key_mapping(inputs.cache_key)+++class MidStreamQueryError(Exception):+ """The ClickHouse response body ended without the Arrow end-of-stream marker."""+++class _ArrowTailReader:+ """File-like relay that remembers the final bytes of the stream it forwards.++ Lets the upload stay a bounded-memory passthrough while still allowing an+ end-of-stream integrity check once the body is fully drained. Also accumulates the+ time spent blocked in reads, so the ClickHouse and upload halves of the relay's wall+ clock can be reported separately.+ """++ def __init__(self, fileobj: IO[bytes]) -> None:+ self._fileobj = fileobj+ self.tail = b""+ self.read_seconds = 0.0++ def read(self, size: int = -1) -> bytes:+ read_started = time.perf_counter()+ chunk = self._fileobj.read(size)+ self.read_seconds += time.perf_counter() - read_started+ if chunk:+ self.tail = (self.tail + chunk)[-len(_ARROW_STREAM_EOS_MARKER) :]+ return chunk+++def _fetch_query_log_exception(ch_query_id: str) -> tuple[int, str] | None:+ """Best-effort lookup of a failed query's exception in system.query_log.++ Returns (exception_code, exception_message), or None when no exception entry appears+ (log not flushed within the polling window, or the query actually finished — e.g. the+ failure was storage-side or an intermediary truncated the response). Never raises:+ recovery must not mask the original stream failure.+ """+ for lookup_attempt in range(_QUERY_LOG_LOOKUP_ATTEMPTS):+ if lookup_attempt:+ time.sleep(_QUERY_LOG_LOOKUP_INTERVAL_SECONDS)+ try:+ rows = sync_execute(+ """+ SELECT exception_code, exception+ FROM clusterAllReplicas(%(cluster)s, system.query_log)+ WHERE query_id = %(query_id)s+ AND exception_code != 0+ AND event_date >= yesterday() AND event_time >= now() - INTERVAL 1 HOUR+ ORDER BY event_time DESC+ LIMIT 1+ """,+ {"cluster": settings.CLICKHOUSE_CLUSTER, "query_id": ch_query_id},+ )+ except Exception:+ return None+ if rows:+ return int(rows[0][0]), str(rows[0][1])+ return None+++def materialize_frame(inputs: FrameMaterializeInputs) -> str:+ """Stream the frame's ClickHouse result into the object store; return the object key.++ Raises on failure so Temporal retries per policy; user-safe HogQL errors are written+ to the query status here (terminal — retrying can't fix a bad query) before raising.+ """+ FRAME_MATERIALIZATIONS_STARTED_COUNTER.inc()+ manager = QueryStatusManager(inputs.query_id, inputs.team_id)+ team = Team.objects.get(id=inputs.team_id)+ user = User.objects.filter(id=inputs.user_id).first() if inputs.user_id else None+ key = frame_store.build_frame_key(inputs.team_id, inputs.notebook_short_id, inputs.query_hash)++ attempt = activity.info().attempt if activity.in_activity() else 1+ started_at = dt.datetime.now(dt.UTC)++ try:+ status = manager.get_query_status()+ if status.complete:+ if status.error:+ raise exceptions.ApplicationError("Materialization already failed", non_retryable=True)+ return key # a previous attempt already finished (e.g. retry after a lost ack)+ status.pickup_time = started_at+ manager.store_query_status(status)+ except QueryNotFoundError:+ pass # status expired mid-flight; still produce the object so the run can be retried++ with tags_context(+ product=Product.NOTEBOOKS,+ feature=Feature.QUERY,+ team_id=inputs.team_id,+ user_id=inputs.user_id,+ client_query_id=inputs.query_id,+ ):+ # Per-attempt CH query id: a retried attempt must not collide with a predecessor+ # ClickHouse may still be draining, and the failure path looks the id up in+ # system.query_log to recover the real error.+ ch_query_id = f"{inputs.query_id}_{attempt}"+ client = ClickHouseClient(+ url=settings.CLICKHOUSE_HTTP_URL,+ user=settings.CLICKHOUSE_USER,+ password=settings.CLICKHOUSE_PASSWORD,+ database=settings.CLICKHOUSE_DATABASE,+ output_format_arrow_string_as_string="true",+ cancel_http_readonly_queries_on_client_close=1,+ max_result_bytes=_MAX_RESULT_BYTES,+ result_overflow_mode="throw",+ )+ try:+ with _materialize_slots(inputs.team_id, inputs.query_id):+ # Everything that touches ClickHouse or Postgres lives inside the slots —+ # including printing, whose DESCRIBE round-trip would otherwise run ungated+ # on every retry attempt of a slot-blocked job, i.e. exactly when the+ # limiter is saturated. A blocked attempt now costs one Redis eval and+ # nothing else; the extra slot-hold (~100-300ms of print/describe) is noise+ # against the stream duration.+ printed_sql, context_values = _print_clickhouse_sql(client, team, user, inputs.query, ch_query_id)+ query_started = time.perf_counter()+ with client.post_query(+ printed_sql,+ query_parameters=context_values,+ query_id=ch_query_id,+ timeout=(_STREAM_CONNECT_TIMEOUT_SECONDS, _STREAM_READ_TIMEOUT_SECONDS),+ ) as response:+ headers_received = time.perf_counter()+ # A torn stream aborts the multipart upload (upload_fileobj), so no+ # partial object is ever left behind — nothing to clean up on failure.+ # The key is deterministic per (team, notebook, user, query), so we must+ # NOT delete it on generic error: that would destroy an object an earlier+ # successful run's still-live status/presigned URL points at.+ relay = _ArrowTailReader(response.raw)+ # boto3's upload_fileobj duck-types read(); the relay is not a full IO[bytes].+ object_bytes = frame_store.write_stream(key, cast("IO[bytes]", relay))+ relay_seconds = time.perf_counter() - headers_received+ if relay.tail != _ARROW_STREAM_EOS_MARKER:+ # ClickHouse failed mid-stream but closed the body cleanly (or an+ # intermediary truncated it at a batch boundary): the bytes we just+ # stored are corrupt and, at a deterministic key, could be served to+ # an earlier status's presigned fetch — remove them before failing.+ with suppress(ObjectStorageError):+ frame_store.delete_frame(key)+ raise MidStreamQueryError("ClickHouse stream ended without the Arrow end-of-stream marker")+ except ConcurrencyLimitExceeded:+ raise # retryable — Temporal backs off and re-attempts+ except ExposedHogQLError as exc:+ # User-safe and terminal: surface the message through the poll, don't retry —+ # a bad query cannot succeed on a second attempt.+ _finalize_status(manager, inputs, error_message=str(exc))+ FRAME_MATERIALIZATIONS_FINISHED_COUNTER.labels(outcome="failed").inc()+ raise exceptions.ApplicationError(str(exc), non_retryable=True) from exc+ except (+ ClickHouseMemoryLimitExceededError,+ ClickHouseTooManyBytesError,+ ClickHouseTooManyRowsOrBytesError,+ ) as exc:+ # Deterministic budget failures ClickHouse rejects before streaming.+ # Re-executing the same heavy query just burns ClickHouse and ends on the same+ # wall: terminal, with a user-facing message.+ message = (+ _RESULT_SIZE_MESSAGE if isinstance(exc, ClickHouseTooManyRowsOrBytesError) else _RESOURCE_BUDGET_MESSAGE+ )+ _finalize_status(manager, inputs, error_message=message)+ FRAME_MATERIALIZATIONS_FINISHED_COUNTER.labels(outcome="failed").inc()+ raise exceptions.ApplicationError(message, non_retryable=True) from exc+ except (MidStreamQueryError, ObjectStorageError) as exc:+ # The stream failed after ClickHouse already sent its 200 — either the chunked+ # read tore (multipart aborted, no object; the read error is opaque) or the body+ # closed cleanly without the EOS marker (corrupt object, deleted above). Recover+ # the real error from the query log: a query-side exception is deterministic for+ # an identical retry, so surface it and stop instead of re-running the scan.+ logged = _fetch_query_log_exception(ch_query_id)+ if logged is None:+ raise # no query-side exception found — plausibly transient, retry per policy+ exception_code, exception_message = logged+ if exception_code in _TRANSIENT_MID_STREAM_CODES:+ raise # transport failure or our own read-timeout cancellation — retry per policy+ # The raw ClickHouse message may embed query fragments — log it, don't expose it.+ logger.warning(+ "notebook_frame_materialize_mid_stream_error",+ team_id=inputs.team_id,+ query_id=inputs.query_id,+ exception_code=exception_code,+ error=exception_message,+ )+ message = _MID_STREAM_MESSAGES_BY_CODE.get(exception_code, _MID_STREAM_ERROR_MESSAGE)+ _finalize_status(manager, inputs, error_message=message)+ FRAME_MATERIALIZATIONS_FINISHED_COUNTER.labels(outcome="failed").inc()+ raise exceptions.ApplicationError(message, non_retryable=True) from exc++ _finalize_status(manager, inputs, results={"object_key": key})+ # ClickHouse time = waiting for response headers plus every blocking body read; upload+ # time = the rest of the relay's wall clock (part handoff and S3 backpressure).+ clickhouse_seconds = (headers_received - query_started) + relay.read_seconds+ upload_seconds = max(0.0, relay_seconds - relay.read_seconds)+ FRAME_MATERIALIZATIONS_FINISHED_COUNTER.labels(outcome="succeeded").inc()+ FRAME_OBJECT_BYTES_HISTOGRAM.observe(object_bytes)+ FRAME_MATERIALIZE_SECONDS_HISTOGRAM.observe((dt.datetime.now(dt.UTC) - started_at).total_seconds())+ FRAME_CLICKHOUSE_SECONDS_HISTOGRAM.observe(clickhouse_seconds)+ FRAME_UPLOAD_SECONDS_HISTOGRAM.observe(upload_seconds)+ logger.info(+ "notebook_frame_materialized",+ team_id=inputs.team_id,+ notebook_short_id=inputs.notebook_short_id,+ query_id=inputs.query_id,+ object_bytes=object_bytes,+ clickhouse_seconds=round(clickhouse_seconds, 3),+ upload_seconds=round(upload_seconds, 3),+ )+ return key+++def mark_frame_materialize_failed(inputs: FrameMaterializeInputs) -> None:+ """Terminal-state safety net once the materialize activity exhausts its retries."""+ manager = QueryStatusManager(inputs.query_id, inputs.team_id)+ try:+ if manager.get_query_status().complete:+ manager.unregister_cache_key_mapping(inputs.cache_key)+ return # the activity already wrote a terminal state (e.g. a user-safe error)+ except QueryNotFoundError:+ pass+ _finalize_status(manager, inputs, error_message="The frame could not be materialized. Try re-running the cell.")+ FRAME_MATERIALIZATIONS_FINISHED_COUNTER.labels(outcome="failed").inc()++[email protected](name="notebook-frame-materialize")+def materialize_frame_activity(inputs: FrameMaterializeInputs) -> str:+ return materialize_frame(inputs)++[email protected](name="notebook-frame-materialize-mark-failed")+def mark_frame_materialize_failed_activity(inputs: FrameMaterializeInputs) -> None:+ mark_frame_materialize_failed(inputs)++[email protected](name="notebook-frame-materialize")+class NotebookFrameMaterializeWorkflow(PostHogWorkflow):+ inputs_cls = FrameMaterializeInputs++ @workflow.run+ async def run(self, input: FrameMaterializeInputs) -> None:+ try:+ await workflow.execute_activity(+ materialize_frame_activity,+ input,+ start_to_close_timeout=dt.timedelta(minutes=10),+ # The analog of the Celery path's expires=600: under sustained saturation+ # the job fails with a clear error instead of piling onto ClickHouse.+ schedule_to_close_timeout=dt.timedelta(minutes=10),+ retry_policy=common.RetryPolicy(+ initial_interval=dt.timedelta(seconds=1),+ backoff_coefficient=2.0,+ maximum_interval=dt.timedelta(seconds=10),+ # Bound the storm: a deterministically-failing heavy query (e.g. a+ # mid-stream resource overrun that can't be caught up front) must not+ # re-execute for the full schedule_to_close window. Matches the Celery+ # async path's max_retries=10.+ maximum_attempts=10,+ ),+ )+ except Exception:+ await workflow.execute_activity(+ mark_frame_materialize_failed_activity,+ input,+ start_to_close_timeout=dt.timedelta(seconds=30),+ retry_policy=common.RetryPolicy(maximum_attempts=3),+ )+ raise+++def enqueue_frame_materialization(+ *,+ team: Team,+ user_id: int | None,+ notebook_short_id: str,+ query: str,+ _test_only_inline: bool = False,+) -> QueryStatus:+ """Register a materialize job for `query` and dispatch the workflow; returns its status.++ Dedup happens here: identical concurrent materializations (same team + user + query)+ join the in-flight job through the async manager's running-query mapping instead of+ stacking ClickHouse load.++ The hash folds in `user_id`: the printed SQL applies the enqueuing user's access+ controls, so two differently-permissioned users in one team must NOT share a job or an+ object — otherwise a restricted user could join a privileged user's in-flight job and+ read rows their own access controls would deny (and their objects would collide on the+ same key). Scoping the hash by user keeps both the dedup mapping and the object key+ per-user within the team.+ """+ query_hash = hashlib.sha256(f"{user_id}:{query}".encode()).hexdigest()+ cache_key = f"notebook-frame:{team.id}:{query_hash}"+ query_id = uuid.uuid4().hex+ manager = QueryStatusManager(query_id, team.id)++ try:+ existing_query_id = manager.get_running_query_by_cache_key(cache_key)+ if existing_query_id:+ existing_status = get_query_status(team.id, existing_query_id)+ if not existing_status.complete:+ FRAME_MATERIALIZATION_DEDUP_COUNTER.inc()+ return existing_status+ # The mapped job finished — clean up the stale mapping and enqueue a new one.+ manager.unregister_cache_key_mapping(cache_key)+ except QueryNotFoundError:+ manager.unregister_cache_key_mapping(cache_key)+ except Exception as exc:+ capture_exception(exc, {"cache_key": cache_key})++ query_status = QueryStatus(id=query_id, team_id=team.id, start_time=dt.datetime.now(dt.UTC))+ manager.store_query_status(query_status)+ manager.register_cache_key_mapping(cache_key)++ inputs = FrameMaterializeInputs(+ query_id=query_id,+ team_id=team.id,+ notebook_short_id=notebook_short_id,+ user_id=user_id,+ query=query,+ query_hash=query_hash,+ cache_key=cache_key,+ )+ if _test_only_inline:+ # Tests have no Temporal worker; mirror the workflow's failure handling inline.+ try:+ materialize_frame(inputs)+ except Exception:+ mark_frame_materialize_failed(inputs)+ else:+ # Deferred: client.py imports FrameMaterializeInputs from this module, so a+ # module-level import back at it would be circular.+ from products.notebooks.backend.temporal.client import start_frame_materialize_workflow # noqa: PLC0415++ try:+ start_frame_materialize_workflow(inputs)+ except Exception:+ # Dispatch failed (e.g. Temporal briefly unreachable). Roll back the status and+ # dedup mapping so identical re-runs don't dedup onto a job that will never run+ # — otherwise every retry polls a dead query_id until the 20-minute TTL.+ manager.delete_query_status()+ manager.unregister_cache_key_mapping(cache_key)+ raise++ return manager.get_query_status()diff --git a/products/notebooks/backend/test/test_frame_materialize.py b/products/notebooks/backend/test/test_frame_materialize.pynew file mode 100644index 000000000000..175ac42dba96--- /dev/null+++ b/products/notebooks/backend/test/test_frame_materialize.py@@ -0,0 +1,175 @@+import io+import uuid+from types import SimpleNamespace++from posthog.test.base import APIBaseTest+from unittest.mock import patch++from parameterized import parameterized+from temporalio import exceptions++from posthog.schema import QueryStatus++from posthog.clickhouse.client.execute_async import QueryStatusManager+from posthog.storage import object_storage+from posthog.storage.object_storage import ObjectStorageError+from posthog.temporal.common.clickhouse import ClickHouseMemoryLimitExceededError, ClickHouseTooManyRowsOrBytesError++from products.notebooks.backend import frame_store+from products.notebooks.backend.models import Notebook+from products.notebooks.backend.temporal import frame_materialize++_DISPATCH_TARGET = "products.notebooks.backend.temporal.client.start_frame_materialize_workflow"+++class TestFrameMaterializeEnqueue(APIBaseTest):+ def setUp(self):+ super().setUp()+ self.notebook = Notebook.objects.create(team=self.team, short_id="nbfm001")++ def _enqueue(self, *, user_id, query, **kwargs):+ return frame_materialize.enqueue_frame_materialization(+ team=self.team,+ user_id=user_id,+ notebook_short_id=self.notebook.short_id,+ query=query,+ **kwargs,+ )++ def test_different_users_do_not_share_a_materialize_job(self):+ # The printed SQL applies the enqueuing user's access controls, so two+ # differently-permissioned users in one team must get separate jobs (and separate+ # object keys) — otherwise a restricted user joins a privileged user's in-flight job+ # and downloads rows their own access controls would deny.+ query = "select number from numbers(1) -- different_users"+ with patch.object(frame_materialize, "materialize_frame"): # leave jobs "running"+ first = self._enqueue(user_id=101, query=query, _test_only_inline=True)+ same_user_again = self._enqueue(user_id=101, query=query, _test_only_inline=True)+ other_user = self._enqueue(user_id=202, query=query, _test_only_inline=True)+ self.assertEqual(first.id, same_user_again.id) # same user + query → dedup join+ self.assertNotEqual(first.id, other_user.id) # different user → separate job++ def test_failed_dispatch_lets_the_retry_enqueue_a_fresh_job(self):+ # A Temporal dispatch failure must roll back the status + dedup mapping. Otherwise a+ # re-run dedups onto a job that will never run and polls a dead query_id until the+ # 20-minute TTL. The retry proves rollback happened: it must actually execute rather+ # than short-circuit on a stale dedup hit.+ query = "select number from numbers(1) -- failed_dispatch"+ with patch(_DISPATCH_TARGET, side_effect=Exception("temporal unreachable")):+ with self.assertRaises(Exception):+ self._enqueue(user_id=self.user.id, query=query)+ with patch.object(frame_materialize, "materialize_frame") as run:+ self._enqueue(user_id=self.user.id, query=query, _test_only_inline=True)+ run.assert_called_once()++ def _registered_inputs(self) -> tuple["frame_materialize.FrameMaterializeInputs", QueryStatusManager]:+ query_id = uuid.uuid4().hex+ inputs = frame_materialize.FrameMaterializeInputs(+ query_id=query_id,+ team_id=self.team.id,+ notebook_short_id=self.notebook.short_id,+ user_id=self.user.id,+ query="select 1",+ query_hash="abc123",+ cache_key=f"notebook-frame:{self.team.id}:abc123",+ )+ manager = QueryStatusManager(query_id, self.team.id)+ manager.store_query_status(QueryStatus(id=query_id, team_id=self.team.id))+ manager.register_cache_key_mapping(inputs.cache_key)+ return inputs, manager++ @parameterized.expand(+ [+ # Scan/memory budget: MEMORY_LIMIT_EXCEEDED rejected up front.+ (+ "memory_budget",+ ClickHouseMemoryLimitExceededError("MEMORY_LIMIT_EXCEEDED", query="SELECT 1"),+ "materialization limits",+ ),+ # Output budget: max_result_bytes trips (a huge result from a tiny scan must not+ # persist a multi-GB object nor be retried).+ (+ "result_size_budget",+ ClickHouseTooManyRowsOrBytesError("TOO_MANY_ROWS_OR_BYTES", query="SELECT 1"),+ "too large",+ ),+ ]+ )+ def test_budget_error_is_terminal_with_a_clear_message(self, _name, clickhouse_error, expected_message):+ # A deterministic ClickHouse budget failure must be non-retryable and carry a+ # user-facing message — not retried to the schedule bound and finalized with the+ # generic 'try re-running' fallback.+ inputs, manager = self._registered_inputs()++ with (+ patch.object(frame_materialize, "_print_clickhouse_sql", return_value=("SELECT 1", {})),+ patch.object(frame_materialize, "_materialize_slots"),+ patch.object(frame_materialize.ClickHouseClient, "post_query", side_effect=clickhouse_error),+ ):+ with self.assertRaises(exceptions.ApplicationError) as caught:+ frame_materialize.materialize_frame(inputs)++ self.assertTrue(caught.exception.non_retryable)+ status = manager.get_query_status()+ self.assertTrue(status.complete and status.error)+ self.assertIn(expected_message, status.error_message or "")++ def test_mid_stream_failure_removes_the_corrupt_object_and_surfaces_the_real_error(self):+ # ClickHouse streams 200 before execution finishes; a mid-stream failure can close+ # the body cleanly with exception text appended instead of tearing the read. Without+ # the Arrow EOS-marker check that corrupt object would be stored, the status+ # finalized as succeeded, and the poll would 302 the kernel to garbage.+ inputs, manager = self._registered_inputs()+ body_without_eos = b"\xff\xff\xff\xff" + b"x" * 4096 + b"Code: 241. DB::Exception: Memory limit exceeded"++ with self.settings(OBJECT_STORAGE_ENABLED=True):+ with (+ patch.object(frame_materialize, "_print_clickhouse_sql", return_value=("SELECT 1", {})),+ patch.object(frame_materialize, "_materialize_slots"),+ patch.object(frame_materialize.ClickHouseClient, "post_query") as post_query,+ patch.object(+ frame_materialize,+ "_fetch_query_log_exception",+ return_value=(241, "Memory limit (for query) exceeded"),+ ),+ ):+ post_query.return_value.__enter__.return_value = SimpleNamespace(raw=io.BytesIO(body_without_eos))+ with self.assertRaises(exceptions.ApplicationError) as caught:+ frame_materialize.materialize_frame(inputs)++ self.assertTrue(caught.exception.non_retryable)+ status = manager.get_query_status()+ self.assertTrue(status.complete and status.error)+ self.assertIn("materialization limits", status.error_message or "")+ # The corrupt bytes were written to the deterministic key and must not survive.+ self.assertIsNone(object_storage.list_objects(frame_store.team_prefix(self.team.id)))++ @parameterized.expand(+ [+ # A storage-side upload failure (or a torn stream) with no ClickHouse-side+ # exception: only a confirmed query-side exception may be terminal, else a+ # transient S3 blip becomes a hard cell failure.+ ("no_query_log_entry", None),+ # Our own read-timeout abandonment cancels the query server-side+ # (cancel_http_readonly_queries_on_client_close), which the query log records as+ # QUERY_WAS_CANCELLED — that must not be classified as a doomed query.+ ("query_was_cancelled", (394, "Query was cancelled")),+ ]+ )+ def test_stream_failure_stays_retryable(self, _name, query_log_result):+ inputs, manager = self._registered_inputs()++ with (+ patch.object(frame_materialize, "_print_clickhouse_sql", return_value=("SELECT 1", {})),+ patch.object(frame_materialize, "_materialize_slots"),+ patch.object(frame_materialize.ClickHouseClient, "post_query") as post_query,+ patch.object(frame_materialize.frame_store, "write_stream", side_effect=ObjectStorageError("torn")),+ patch.object(frame_materialize, "_fetch_query_log_exception", return_value=query_log_result) as lookup,+ ):+ post_query.return_value.__enter__.return_value = SimpleNamespace(raw=io.BytesIO(b""))+ with self.assertRaises(ObjectStorageError):+ frame_materialize.materialize_frame(inputs)++ lookup.assert_called_once()+ status = manager.get_query_status()+ self.assertFalse(status.complete) # not finalized — Temporal retries per policydiff --git a/products/notebooks/backend/test/test_frame_store.py b/products/notebooks/backend/test/test_frame_store.pynew file mode 100644index 000000000000..861dbbc66fac--- /dev/null+++ b/products/notebooks/backend/test/test_frame_store.py@@ -0,0 +1,87 @@+import io+import urllib.request+from typing import IO, cast++from posthog.test.base import APIBaseTest++from django.test import SimpleTestCase++from parameterized import parameterized++from posthog.storage import object_storage+from posthog.storage.object_storage import ObjectStorageError++from products.notebooks.backend import frame_store+++class TestFrameKeys(SimpleTestCase):+ def test_key_is_namespaced_under_the_team_prefix(self):+ # The team prefix is the tenant isolation unit: presign_get's cross-tenant check+ # relies on every built key starting with it.+ key = frame_store.build_frame_key(42, "nb42abc", "deadbeef01")+ self.assertEqual(key, "notebooks/frames/team_42/nb42abc/deadbeef01.arrow")+ self.assertTrue(key.startswith(frame_store.team_prefix(42)))++ @parameterized.expand(+ [+ ("path_traversal", "../team_1", "deadbeef"),+ ("separator_in_short_id", "a/b", "deadbeef"),+ ("empty_short_id", "", "deadbeef"),+ ("separator_in_hash", "nb1", "dead/beef"),+ ("whitespace", "nb 1", "deadbeef"),+ ]+ )+ def test_rejects_unsafe_key_segments(self, _name, short_id, query_hash):+ # A segment with a path separator could place an object outside the team prefix,+ # defeating the tenant check at presign time.+ with self.assertRaises(frame_store.FrameStoreError):+ frame_store.build_frame_key(1, short_id, query_hash)++ def test_presign_refuses_keys_outside_the_team_prefix(self):+ # Last line of defense: a poisoned stored key must never presign across tenants.+ with self.assertRaises(frame_store.FrameStoreError):+ frame_store.presign_get("notebooks/frames/team_2/nb/hash.arrow", team_id=1)+++class TestFrameStoreObjects(APIBaseTest):+ KEY = "notebooks/frames/team_999999/nbtest/deadbeef.arrow"++ def tearDown(self):+ with self.settings(OBJECT_STORAGE_ENABLED=True):+ object_storage.delete(self.KEY)+ super().tearDown()++ def test_write_stream_then_presigned_fetch_needs_no_credentials(self):+ # The sandbox holds no storage identity — the presigned URL must be the whole+ # authorization. A broken presign config (wrong signature version, wrong endpoint+ # client) surfaces here.+ payload = b"arrow-ipc-bytes" * 1024+ with self.settings(OBJECT_STORAGE_ENABLED=True):+ stored_bytes = frame_store.write_stream(self.KEY, io.BytesIO(payload))+ url = frame_store.presign_get(self.KEY, team_id=999999)+ self.assertEqual(stored_bytes, len(payload))+ with urllib.request.urlopen(url) as response: # deliberately credential-free+ self.assertEqual(response.read(), payload)++ def test_failed_upload_leaves_no_object(self):+ # A torn ClickHouse stream mid-upload must abort the multipart upload — a partial+ # frame served to the kernel would silently truncate a dataframe.+ class _TornStream(io.RawIOBase):+ def __init__(self):+ self._served = False++ def readable(self):+ return True++ def readinto(self, buffer):+ if not self._served:+ self._served = True+ chunk = b"x" * min(len(buffer), 1024)+ buffer[: len(chunk)] = chunk+ return len(chunk)+ raise OSError("connection reset mid-stream")++ with self.settings(OBJECT_STORAGE_ENABLED=True):+ with self.assertRaises(ObjectStorageError):+ frame_store.write_stream(self.KEY, cast("IO[bytes]", _TornStream()))+ self.assertIsNone(object_storage.head_object(self.KEY))diff --git a/products/notebooks/backend/test/test_kernel_bootstrap.py b/products/notebooks/backend/test/test_kernel_bootstrap.pyindex d31d04b78d67..acdb44835a3d 100644--- a/products/notebooks/backend/test/test_kernel_bootstrap.py+++ b/products/notebooks/backend/test/test_kernel_bootstrap.py@@ -87,6 +87,20 @@ class TestKernelSessionRunNode(SimpleTestCase):self.assertEqual(envelope["columns"], ["id", "v"])self.assertEqual(envelope["first_page"], [[2, 20], [3, 30]])+ def test_binary_column_degrades_the_preview_instead_of_failing_the_run(self):+ # ClickHouse's native Arrow output emits UUID/FixedString columns as fixed-size+ # binary, so a materialized frame can hold raw bytes. pandas' ujson preview encoder+ # raises OverflowError on them — that must degrade the display cell, not fail a run+ # whose compute succeeded (the incident: "kernel did not return a result").+ binary_column = pa.array([b"\x01" * 16, b"\xff" * 16], type=pa.binary(16))+ self._write_frame("df1", pa.table({"uid": binary_column, "v": [1, 2]}))+ path = os.path.join(self._dir.name, "frames", "df1.arrow")+ envelope = self._run("df1", inputs=[{"name": "df1", "kind": "hogql", "path": path}])+ self.assertEqual(envelope["status"], "ok")+ self.assertEqual(envelope["row_count"], 2)+ self.assertEqual(envelope["first_page"][0][1], 1)+ self.assertIsInstance(envelope["first_page"][0][0], str) # degraded, JSON-safe cell+def test_missing_local_input_produces_a_clear_error(self):envelope = self._run("1 + 1", inputs=[{"name": "never_made", "kind": "local"}])self.assertEqual(envelope["status"], "error")diff --git a/products/notebooks/backend/test/test_sql_v2.py b/products/notebooks/backend/test/test_sql_v2.pyindex e5b30a19855a..b38f54f0f278 100644--- a/products/notebooks/backend/test/test_sql_v2.py+++ b/products/notebooks/backend/test/test_sql_v2.py@@ -1047,18 +1047,120 @@ class TestSQLV2DataPlaneEndpoint(APIBaseTest):_columns, rows, _types = decode_arrow_stream(response.content)self.assertEqual(rows, [(2,), (3,), (4,)])- def test_materialization_request_is_accepted_and_clipped_at_the_row_ceiling(self):+ def test_inline_materialization_stays_clipped_at_the_row_ceiling(self):# The kernel executor fetches whole frames with limit=_MATERIALIZE_ROW_CAP (2M, not# importable here: the executor module needs jupyter_client). The serializer must- # accept that limit (it once capped at 1000, 400-ing every materialization), and the- # async limit context then clips the frame at MAX_SELECT_RETURNED_ROWS (50k) — a- # deliberate bound until the object-storage frame store (sql_v2_frame_store.md)- # gives big frames a transport that doesn't round-trip through Redis.+ # accept that limit (it once capped at 1000, 400-ing every materialization). The+ # inline path is the frame store's degraded fallback and still rides the Redis JSON+ # transport, so the async limit context must keep clipping it at+ # MAX_SELECT_RETURNED_ROWS (50k) — whole frames go over the object path instead.response = self._run_to_completion({"query": "select number from numbers(50001)", "limit": 2_000_000})self.assertEqual(response.status_code, 200, response.content)_columns, rows, _types = decode_arrow_stream(response.content)self.assertEqual(len(rows), 50_000)+ def test_object_delivery_redirects_to_a_team_scoped_presigned_frame(self):+ # The frame-store path end to end: delivery="object" routes to the materialize job,+ # the poll answers 302 with a presigned URL under this team's prefix, the URL serves+ # the frame without credentials, and the frame is NOT clipped at the 50k async+ # ceiling (the silent-truncation regression that motivated the object path). The+ # UUID column pins the type-normalization pass: ClickHouse's native Arrow output+ # would deliver it as 16 raw bytes (which broke the kernel's pandas/JSON handling);+ # the worker must DESCRIBE and stringify it before streaming.+ from posthog.storage import object_storage++ from products.notebooks.backend import frame_store++ frame_uuid = "018e0e7a-1111-2222-3333-444444444444"+ with self.settings(NOTEBOOKS_FRAME_STORE_ENABLED=True, OBJECT_STORAGE_ENABLED=True):+ self.addCleanup(self._delete_team_frames)+ response = self._run_to_completion(+ {+ "query": f"select number, toUUID('{frame_uuid}') as uid from numbers(50001)",+ "limit": 2_000_000,+ "delivery": "object",+ }+ )+ self.assertEqual(response.status_code, 302, response.content)+ location = response["Location"]+ self.assertIn(f"/team_{self.team.id}/", location)+ self.assertIn(frame_store.FRAMES_PREFIX, location)+ keys = object_storage.list_objects(frame_store.team_prefix(self.team.id)) or []+ self.assertEqual(len(keys), 1)+ with urllib.request.urlopen(location) as download: # deliberately credential-free+ columns, rows, _types = decode_arrow_stream(download.read())+ self.assertEqual(len(rows), 50_001)+ self.assertEqual(columns, ["number", "uid"])+ self.assertEqual(rows[0][1], frame_uuid) # a string, not 16 bytes++ def test_object_delivery_falls_back_to_inline_when_frame_store_disabled(self):+ # Degraded mode: object storage off must not hard-fail the cell — the inline+ # (Redis) path still serves the frame, clamped at the async ceiling.+ with self.settings(NOTEBOOKS_FRAME_STORE_ENABLED=False):+ response = self._run_to_completion({"query": "select number from numbers(3)", "delivery": "object"})+ self.assertEqual(response.status_code, 200, response.content)+ _columns, rows, _types = decode_arrow_stream(response.content)+ self.assertEqual(len(rows), 3)++ def test_object_delivery_failure_surfaces_error_and_stores_no_object(self):+ # An upload failure must reach the kernel as an error status, and no (partial or+ # stale) object may remain servable under the team prefix.+ from posthog.storage import object_storage++ from products.notebooks.backend import frame_store+ from products.notebooks.backend.temporal import frame_materialize++ with self.settings(NOTEBOOKS_FRAME_STORE_ENABLED=True, OBJECT_STORAGE_ENABLED=True):+ with patch.object(frame_materialize.frame_store, "write_stream", side_effect=Exception("upload torn")):+ response = self._run_to_completion({"query": "select number from numbers(3)", "delivery": "object"})+ self.assertEqual(response.status_code, 400, response.content)+ self.assertTrue(response.json()["error"])+ self.assertIsNone(object_storage.list_objects(frame_store.team_prefix(self.team.id)))++ def test_identical_inflight_materializations_share_one_job(self):+ # Enqueue-time dedup: an impatient re-run of the same frame must join the running+ # job instead of stacking a second ClickHouse execution.+ from products.notebooks.backend.temporal import frame_materialize++ with self.settings(NOTEBOOKS_FRAME_STORE_ENABLED=True, OBJECT_STORAGE_ENABLED=True):+ # Leave the job "running": the materialize body never executes, so the status+ # stays incomplete and the cache-key mapping stays registered.+ with patch.object(frame_materialize, "materialize_frame"):+ first = self._post({"query": "select 1", "delivery": "object"}, token=self._token())+ second = self._post({"query": "select 1", "delivery": "object"}, token=self._token())+ different = self._post({"query": "select 2", "delivery": "object"}, token=self._token())+ self.assertEqual(first.status_code, 202)+ self.assertEqual(second.status_code, 202)+ self.assertEqual(first.json()["query_id"], second.json()["query_id"])+ self.assertNotEqual(first.json()["query_id"], different.json()["query_id"])++ def test_notebook_materialize_context_prints_the_tier_ceiling(self):+ # The object path's row ceiling is the NOTEBOOK_MATERIALIZE tier: a 2M request must+ # clamp to 500k — not fall back to the 50k async ceiling (silent truncation, the+ # regression that got the first version of this context reverted) and not pass 2M+ # through to a transport tier we haven't validated yet.+ from posthog.hogql.constants import LimitContext+ from posthog.hogql.query import HogQLQueryExecutor++ executor = HogQLQueryExecutor(+ query="select number from numbers(10) limit 2000000",+ team=self.team,+ limit_context=LimitContext.NOTEBOOK_MATERIALIZE,+ pretty=False,+ )+ sql, _context = executor.generate_clickhouse_sql()+ self.assertIn("LIMIT 500000", sql)++ def _delete_team_frames(self):+ from posthog.storage import object_storage++ from products.notebooks.backend import frame_store++ with self.settings(OBJECT_STORAGE_ENABLED=True):+ keys = object_storage.list_objects(frame_store.team_prefix(self.team.id)) or []+ if keys:+ object_storage.delete_objects(keys)+def test_execution_error_surfaces_through_status(self):# Valid syntax but fails at execution — the error must reach the sandbox via the poll.response = self._run_to_completion({"query": "select nonexistent_column from events"})@@ -1544,12 +1646,71 @@ class TestSQLV2KernelPackage(SimpleTestCase):with (patch.object(kernel_data_plane.urllib.request, "urlopen", side_effect=fake_urlopen),+ # The poll goes through the no-redirect opener (302s become presigned fetches).+ patch.object(kernel_data_plane._no_redirect_opener, "open", side_effect=fake_urlopen),patch.object(kernel_data_plane.time, "sleep"),):columns, rows, _types = kernel_data_plane.fetch_query_page("http://backend/dp", "t", "select 1", limit=5)self.assertEqual((columns, rows), (["n"], [(7,)]))self.assertEqual(polled_urls[1:], ["http://backend/dp/q1/", "http://backend/dp/q1/"])+ def test_materialize_follows_the_302_without_forwarding_credentials(self):+ # Object delivery: the poll's 302 must be fetched as a fresh, credential-free+ # request. urllib's default redirect handling re-sends every header — shipping the+ # data-plane bearer token to the object-store host (and S3 rejects a request that+ # carries both header auth and presigned query auth).+ import email.message++ from products.notebooks.backend.sandbox.kernel import data_plane as kernel_data_plane++ arrow_bytes = _rows_to_arrow_bytes(["n"], [(1,), (2,)], [["n", "Int64"]])+ presigned_url = "http://frame-store.local/frames/team_1/nb/hash.arrow?X-Amz-Signature=abc"+ download_requests: list[Any] = []++ class _FakeResponse(io.BytesIO):+ def __init__(self, content_type: str, body: bytes):+ super().__init__(body)+ self.headers = {"Content-Type": content_type}++ def __exit__(self, *args):+ return False++ def fake_urlopen(request, timeout=None):+ if request.full_url.startswith("http://frame-store.local/"):+ download_requests.append(request)+ return _FakeResponse("application/vnd.apache.arrow.stream", arrow_bytes)+ return _FakeResponse("application/json", b'{"query_id": "q1"}')++ def fake_poll_open(request, timeout=None):+ headers = email.message.Message()+ headers["Location"] = presigned_url+ raise urllib.error.HTTPError(request.full_url, 302, "Found", headers, None)++ import os+ import tempfile++ import pyarrow as pa++ with tempfile.TemporaryDirectory() as directory:+ dest = os.path.join(directory, "df.arrow")+ with (+ patch.object(kernel_data_plane.urllib.request, "urlopen", side_effect=fake_urlopen),+ patch.object(kernel_data_plane._no_redirect_opener, "open", side_effect=fake_poll_open),+ ):+ rows, fetched_from = kernel_data_plane.materialize_query_to_file(+ "http://backend/dp", "secret-token", "select 1", dest, limit=1000+ )+ self.assertEqual(rows, 2)+ self.assertEqual(pa.ipc.open_file(pa.memory_map(dest)).read_all().num_rows, 2)++ (download,) = download_requests+ self.assertEqual(download.full_url, presigned_url)+ self.assertFalse(download.has_header("Authorization"))+ # The surfaced source is a bearer secret truncated to a host-only preview: it must+ # never carry the signature query parameters.+ self.assertEqual(fetched_from, presigned_url[:30])+ self.assertNotIn("X-Amz-Signature", fetched_from or "")+def test_tarball_contains_the_package(self):package, version = kernel_package_bytes_and_hash()with tarfile.open(fileobj=io.BytesIO(package), mode="r:gz") as tar:@@ -1587,10 +1748,11 @@ class TestSQLV2PythonNodeRun(SimpleTestCase):"urlopen",side_effect=lambda request, timeout=None: _FakeResponse(arrow_bytes),):- rows = kernel_data_plane.materialize_query_to_file(+ rows, fetched_from = kernel_data_plane.materialize_query_to_file("http://backend/dp", "t", "select 1", dest, limit=1000)self.assertEqual(rows, 2)+ self.assertIsNone(fetched_from) # inline body — no presigned source to surfacetable = pa.ipc.open_file(pa.memory_map(dest)).read_all()self.assertEqual(table.num_rows, 2)self.assertEqual(table.column_names, ["id", "v"])