: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 frames offline and via ClickHouse, behind a flag (#81258)
Sinan Kucukkoseler0c57b084aa2e
diff --git a/posthog/clickhouse/client/connection.py b/posthog/clickhouse/client/connection.pyindex 5f6276299bf5..40aa057c339f 100644--- a/posthog/clickhouse/client/connection.py+++ b/posthog/clickhouse/client/connection.py@@ -72,6 +72,8 @@ class ClickHouseUser(StrEnum):MESSAGING = "messaging" # a.k.a. behavioral cohortsMAX_AI = "max_ai" # llm/aLLM_ANALYTICS = "llm_analytics" # background AI observability workflows; interactive requests use APP+ # Notebook frame materializations (Temporal worker streaming to the object store)+ NOTEBOOKS = "notebooks"ERROR_TRACKING = "error_tracking"ENDPOINTS = "endpoints"BILLING = "billing"diff --git a/posthog/settings/object_storage.py b/posthog/settings/object_storage.pyindex 7220e61c0429..89d0d5c04eb1 100644--- a/posthog/settings/object_storage.py+++ b/posthog/settings/object_storage.py@@ -36,6 +36,30 @@ 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")+# Endpoint the ClickHouse *cluster* uses to reach the frames bucket for that INSERT — which is+# NOT always OBJECT_STORAGE_ENDPOINT. CI points OBJECT_STORAGE_ENDPOINT at localhost:19000 for+# the test process, but ClickHouse runs in docker-compose and reaches object storage by service+# name (objectstorage:19000) — using localhost there makes the cluster connect to itself and the+# s3() call hangs. So in TEST/DEBUG default to the cluster-reachable host; on prod it stays empty+# and the URL builder falls back to the virtual-hosted AWS form (IAM role, no inline keys),+# mirroring IDENTITY_MATCHING_S3_ENDPOINT (the sibling CH-side s3 writer). Frames live in+# NOTEBOOKS_FRAME_STORE_S3_BUCKET (below), which the app presigns and the kernel fetches from.+if TEST or DEBUG:+ NOTEBOOKS_FRAME_STORE_S3_ENDPOINT = os.getenv("NOTEBOOKS_FRAME_STORE_S3_ENDPOINT", "http://objectstorage:19000")+else:+ NOTEBOOKS_FRAME_STORE_S3_ENDPOINT = os.getenv("NOTEBOOKS_FRAME_STORE_S3_ENDPOINT", "")++# Frames get a dedicated bucket in cloud (its own 1-day TTL, and a least-privilege grant so the+# ClickHouse writer identity can PutObject there without access to the general object store).+# Falls back to OBJECT_STORAGE_BUCKET so dev / CI / self-hosted work with no extra config.+#+# There is deliberately no region knob beside it. ClickHouse writes the object and the app+# presigns it, and the app's presigning client is built once from OBJECT_STORAGE_REGION — so a+# frames-only region would put the write in one region and the SigV4 credential scope in+# another, and AWS would reject every presigned fetch. The bucket is per product; the region is+# per deployment.+NOTEBOOKS_FRAME_STORE_S3_BUCKET = os.getenv("NOTEBOOKS_FRAME_STORE_S3_BUCKET") or OBJECT_STORAGE_BUCKET+# 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/storage/object_storage.py b/posthog/storage/object_storage.pyindex 1f2ebd5adfb0..671634c04a50 100644--- a/posthog/storage/object_storage.py+++ b/posthog/storage/object_storage.py@@ -531,8 +531,8 @@ def read_object(return object_storage_client().read_object(bucket, file_name, missing_ok=missing_ok)-def list_objects(prefix: str) -> Optional[list[str]]:- return object_storage_client().list_objects(bucket=settings.OBJECT_STORAGE_BUCKET, prefix=prefix)+def list_objects(prefix: str, bucket: str | None = None) -> Optional[list[str]]:+ return object_storage_client().list_objects(bucket=bucket or settings.OBJECT_STORAGE_BUCKET, prefix=prefix)def copy_objects(source_prefix: str, target_prefix: str) -> int:@@ -559,9 +559,10 @@ def get_presigned_url(expiration: int = 3600,content_type: Optional[str] = None,content_disposition: Optional[str] = None,+ bucket: str | None = None,) -> Optional[str]:return object_storage_client().get_presigned_url(- bucket=settings.OBJECT_STORAGE_BUCKET,+ bucket=bucket or settings.OBJECT_STORAGE_BUCKET,file_key=file_key,expiration=expiration,content_type=content_type,diff --git a/products/notebooks/backend/frame_store.py b/products/notebooks/backend/frame_store.pyindex 1bb5480fa7c9..bbeb7365b486 100644--- a/products/notebooks/backend/frame_store.py+++ b/products/notebooks/backend/frame_store.py@@ -8,6 +8,7 @@ refuses any key outside the requesting team's prefix."""import re+import datetime as dtfrom typing import IOfrom django.conf import settings@@ -50,7 +51,10 @@ def build_frame_key(team_id: int, notebook_short_id: str, query_hash: str) -> sthash, 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):+ # fullmatch, not match: `$` in `.match` also matches before a trailing newline, so a+ # segment like "nb\n" would pass — and this key is spliced into a SQL statement on the+ # CH-writes path, where the doc's threat model makes exact charset validation load-bearing.+ if not _KEY_SEGMENT_RE.fullmatch(segment):raise FrameStoreError(f"Invalid frame key segment: {segment!r}")return f"{team_prefix(team_id)}{notebook_short_id}/{query_hash}.arrow"@@ -63,23 +67,52 @@ def write_stream(key: str, fileobj: IO[bytes]) -> int:post-write HEAD both confirms the object exists (an UnavailableStorage client no-opswrites 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)+ object_storage.write_stream(+ key, fileobj, extras={"ContentType": ARROW_STREAM_CONTENT_TYPE}, bucket=settings.NOTEBOOKS_FRAME_STORE_S3_BUCKET+ )+ return stat_frame(key)+++def stat_frame(key: str, *, written_after: "dt.datetime | None" = None) -> int:+ """Confirm the frame object at `key` exists and return its size.++ The post-write existence check for both write paths: the worker upload (an+ UnavailableStorage client no-ops writes silently) and the CH-side INSERT (whose+ success response says the query finished, not that the bytes are servable).++ `written_after` guards the CH-side path against a silent no-op: ClickHouse writes from+ its own network, so if it "succeeds" against a store/bucket the app can't read, a stale+ object from an earlier run at this deterministic key would otherwise pass existence and be+ served as fresh. Requiring LastModified at/after the write start turns that into a loud+ failure. The margin for clock skew is the caller's to bake into `written_after`.+ """+ head = object_storage.head_object(key, bucket=settings.NOTEBOOKS_FRAME_STORE_S3_BUCKET)if head is None:raise FrameStoreError("Frame object was not stored")+ if written_after is not None:+ last_modified = head.get("LastModified")+ if isinstance(last_modified, dt.datetime) and last_modified < written_after:+ raise FrameStoreError("Frame object predates this write — object store endpoint/bucket skew?")return int(head.get("ContentLength") or 0)-def presign_get(key: str, team_id: int) -> str:+def presign_get(key: str, team_id: int, bucket: str | None = None) -> 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 isthe last line keeping a poisoned stored key from ever crossing tenant boundaries.++ `bucket` is the one the writer recorded on the run. Signing against the current setting+ instead would break every frame written before a bucket change for as long as its status+ lives, since the key alone does not say where the object went."""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+ key,+ expiration=PRESIGN_EXPIRY_SECONDS,+ content_type=ARROW_STREAM_CONTENT_TYPE,+ bucket=bucket or settings.NOTEBOOKS_FRAME_STORE_S3_BUCKET,)if not url:raise FrameStoreError("Could not presign the frame object")@@ -93,4 +126,4 @@ def delete_frame(key: str) -> None:must never delete — it could destroy an object an earlier successful run's still-livestatus points at. The only legitimate caller is the writer discarding its own bytes."""- object_storage.delete(key)+ object_storage.delete(key, bucket=settings.NOTEBOOKS_FRAME_STORE_S3_BUCKET)diff --git a/products/notebooks/backend/sql_v2.py b/products/notebooks/backend/sql_v2.pyindex d066e6696bef..c9100c7ed574 100644--- a/products/notebooks/backend/sql_v2.py+++ b/products/notebooks/backend/sql_v2.py@@ -32,6 +32,7 @@ logger = structlog.get_logger(__name__)REVAMPED_PY_NOTEBOOKS_FLAG = "revamped-py-notebooks"NOTEBOOKS_FRAME_STORE_FLAG = "notebooks-frame-store"+NOTEBOOKS_FRAME_STORE_CH_WRITES_FLAG = "notebooks-frame-store-ch-writes"# How a run's result rows reached whoever consumes them. The data plane resolves this at# the moment it picks a transport and reports it in the 202 accept body; the sandbox echoes@@ -121,6 +122,19 @@ def is_frame_store_enabled(user: User | None) -> bool:return _flag_enabled_for(NOTEBOOKS_FRAME_STORE_FLAG, user)+def is_frame_store_ch_writes_enabled(user: User | None) -> bool:+ """Whether this user's materializations take the ClickHouse-side write path.++ One switch for the whole new flow: it moves the query onto the offline pool as the+ dedicated `notebooks` user, and hands the object write to ClickHouse. Sits inside+ `is_frame_store_enabled`, which has to be on before any of this is reached.++ Resolved in the web process and carried on the job, because the Temporal activity that+ acts on it has no request user to evaluate a flag against.+ """+ return _flag_enabled_for(NOTEBOOKS_FRAME_STORE_CH_WRITES_FLAG, user)++def mint_callback_token(run_id: str, team_id: int) -> str:return signing.dumps({"run_id": run_id, "team_id": team_id}, salt=_CALLBACK_TOKEN_SALT)diff --git a/products/notebooks/backend/sql_v2_data_plane.py b/products/notebooks/backend/sql_v2_data_plane.pyindex ad1243bffe77..4a49397d0b35 100644--- a/products/notebooks/backend/sql_v2_data_plane.py+++ b/products/notebooks/backend/sql_v2_data_plane.py@@ -39,6 +39,7 @@ from products.notebooks.backend.models import Notebookfrom products.notebooks.backend.sql_v2 import (DELIVERY_INLINE,DELIVERY_OBJECT_RELAY,+ is_frame_store_ch_writes_enabled,is_frame_store_enabled,verify_data_plane_token,)@@ -173,6 +174,7 @@ def notebook_sql_v2_data_plane(request: HttpRequest) -> HttpResponse:user_id=user.id if user else None,notebook_short_id=notebook_short_id,query=bounded,+ ch_writes=is_frame_store_ch_writes_enabled(user),_test_only_inline=settings.TEST,)except Exception:@@ -260,7 +262,13 @@ def notebook_sql_v2_data_plane_status(request: HttpRequest, query_id: str) -> Ht# 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)+ # Sign against the bucket the writer recorded. A status written before a bucket+ # change still points at the old bucket, and signing it against the new one+ # would 404 every frame materialized in the window before that deploy.+ recorded_bucket = results.get("bucket")+ presigned_url = frame_store.presign_get(+ str(object_key), team_id, bucket=str(recorded_bucket) if recorded_bucket else None+ )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)diff --git a/products/notebooks/backend/sql_v2_frame_store.md b/products/notebooks/backend/sql_v2_frame_store.mdindex 2ea068af4221..0e20d3e78721 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: **phase 1 shipped**, gated per user by the `notebooks-frame-store` feature flag (off by default) — 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.+Status: **phase 1 shipped**, gated per user by the `notebooks-frame-store` feature flag (off by default) — 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. **Phase 2 implemented dark**, gated per user by the `notebooks-frame-store-ch-writes` feature flag (off by default) — CH writes the object itself; see the phase-2 prerequisites before flipping. Phase 3 not started.## Problem@@ -119,14 +119,19 @@ token-authed; only the bulk-bytes leg moves to object storage.## Resource governance — not hammering ClickHouse-Materialization is **user-facing** — someone is waiting on their cell — so it belongs on the ONLINE pool with-interactive queries (OFFLINE is where batch exports, usage reports, and cohort calculations run, with-explicitly accepted latency variance and failure rates; a user-waiting query must not queue behind those).-The risk is different: a single materialization can be far more expensive than an insight query, an-**uncapped whale in a pool tuned for bounded queries**. The governance goal is therefore not relocation but-making the whale impossible. Note the cap that matters is not the row count — an insight query with-`LIMIT 50000` can still scan billions of rows; cost is bounded by execution time, bytes read, memory,-and threads.+Materialization runs on the **OFFLINE pool** (batch exports' home), as a **dedicated `notebooks` ClickHouse+user**, for any run whose user has the `notebooks-frame-store-ch-writes` flag. One flag carries the whole new+flow: the pool, the CH user, and (phase 2) handing the object write to ClickHouse. Without it a run keeps the+interactive pool and the default user, so the rollout is per user rather than per deployment.+An earlier draft argued for ONLINE — someone is waiting on their cell — but the query itself is+batch-shaped: a 500k-row streaming pull with minutes-scale deadlines (the kernel's object-delivery poll+already tolerates 11 minutes), far closer to a batch export than to an insight query. The decisive risk runs+the other way: a single materialization can be far more expensive than an insight query, an **uncapped whale+in a pool tuned for bounded queries** — so it contends with batch work, whose latency variance the async flow+absorbs, instead of degrading interactive latency. Where no offline cluster exists (EU, self-hosted, dev/test)+the offline URL falls back to the online one, and the remaining levers below still bound the whale. Note the+cap that matters is not the row count — an insight query with `LIMIT 50000` can still scan billions of rows;+cost is bounded by execution time, bytes read, memory, and threads.Layered levers:@@ -140,24 +145,25 @@ Layered levers: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.+- **No scheduler priority.** CH's `priority` setting could make materialization yield CPU to other offline+ work 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;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 gets- profile limits, QUOTAs, and `max_concurrent_queries_for_user` — a hard server-enforced ceiling no- application bug can exceed.+- **Dedicated ClickHouse user as the backstop (shipped).** The repo already splits traffic across CH users+ (`ClickHouseUser.APP` / `API`), each governed by a server-side settings profile. Materializations run as+ `ClickHouseUser.NOTEBOOKS` (credentials from `CLICKHOUSE_NOTEBOOKS_USER`/`CLICKHOUSE_NOTEBOOKS_PASSWORD`,+ falling back to the default user where not provisioned), so the user gets profile limits, QUOTAs, and+ `max_concurrent_queries_for_user` — a hard server-enforced ceiling no application bug can exceed.- **Demand elimination.** Phase 3's `query_hash` reuse means an unchanged upstream query never re-executes;long-term this is the strongest lever.-- **Escalation path.** If notebooks' share of online capacity becomes meaningful, the router already supports- product-specific pools (`Workload.ENDPOINTS` is precedent) — a dedicated notebooks pool with online-grade- latency is the growth answer, decided with data rather than up front.+- **Escalation path.** If notebooks' share of offline capacity becomes meaningful (or batch-export contention+ starts hurting frame latency), the router already supports product-specific pools (`Workload.ENDPOINTS` is+ precedent) — a dedicated notebooks pool is the growth answer, decided with data rather than up front.The flow is already measurable: the data plane tags queries with `Product.NOTEBOOKS`, and the Dagsterquery-log exports make its CH footprint analyzable, so the knobs can be tightened with data.@@ -181,9 +187,11 @@ The **object key** lands in `QueryStatus` instead of rows, and the status endpoiA 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).+ClickHouse and atomically overwrites the same key, so a re-run after new events lands returns fresh rows+modulo offline replica lag — materialization reads the OFFLINE pool, which can trail ingestion further than+the online nodes the inline path reads, so a frame can briefly miss rows an inline preview of the same query+just showed (batch exports accept the same window). 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.@@ -221,6 +229,26 @@ _Rollout prerequisites (per environment, before flipping the flag on):_- Confirm `OBJECT_STORAGE_PUBLIC_ENDPOINT` resolves and routes **from the sandbox kernel's network** — thekernel fetches the presigned URL directly. An internal-only host (or the local SeaweedFS docker name)makes every download fail (loud, not silent).+- Provision the `notebooks` ClickHouse user, **in this order**: create and verify the user server-side first+ (a `SELECT 1` as the user), then set `CLICKHOUSE_NOTEBOOKS_USER`/`CLICKHOUSE_NOTEBOOKS_PASSWORD` on the+ general-purpose Temporal worker fleet — env vars pointing at a not-yet-created user (or a rotated password;+ creds are cached per worker process, rotation needs a fleet restart) fail every materialization with a+ generic retried auth error, a hard outage rather than a fallback. The user spec, since HogQL fans out to+ distributed tables (remote legs authenticate as the initiating user via the interserver secret): exists on+ **every** node of the `posthog` cluster, SELECT grants mirroring the app user (including data-warehouse+ table functions), a profile with `readonly = 2` — `readonly = 1` rejects the per-query SETTINGS/HTTP params+ this path sends, and if the phase-2 CH-writes flag is enabled the phase-2 writer-identity spec (`readonly+= 0`, zero table-write grants) supersedes this — and no setting constraints below the app-side caps; prefer+ per-query `max_memory_usage`+ over `..._for_user` so a `MEMORY_LIMIT_EXCEEDED` stays attributable to the offending query, and leave QUOTA+ headroom since a shared-user quota breach reads as a (wrong) "narrow your query" message to whichever+ tenant trips it. Deliberately fail-open: until provisioned, the flow runs as the default CH user+ (dev/self-hosted parity) — the `ch_user` label on `posthog_notebooks_frame_materializations_started` is the+ signal that the dedicated user actually engaged.+- Confirm `CLICKHOUSE_OFFLINE_CLUSTER_HOST` is set on the **general-purpose** Temporal worker fleet (US) —+ batch exports prove offline routing on _their_ deployment, not this one, and an unset host silently+ falls back to the online URL, no-opping the pool isolation. The `pool` label on the started counter+ verifies routing from metrics.- 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@@ -242,25 +270,82 @@ Two decisions locked in for this phase: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+ concurrency, worker memory, and S3 parallelism with one knob — the dedicated `notebooks` CH user is the+ server-side backstop behind it, and a dedicated notebooks task queue stays a later infra option. Throttling moves loadin time (retry backoff), never above the cap; the real amplification risk is impatient re-runs, and theasync 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-permissionedteammates 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).**-Replace the worker-streamed upload with `INSERT INTO FUNCTION s3(...'ArrowStream')` (batch-exports recipe):-the worker's job shrinks to issuing one statement; zero result bytes transit PostHog Python.-Add partitioned files + a manifest for very large frames, and Range-based resume in the executor.--Why phase 1 streams from the worker instead of starting here:+**Phase 2 — let ClickHouse do the writing (implemented, behind the `notebooks-frame-store-ch-writes`+feature flag, off by default).**+The flag is resolved per user in the web process and travels with the job as a field on+`FrameMaterializeInputs`, because the Temporal activity that acts on it has no request user of its own.+The field is defaulted, so a history recorded before it existed replays on the streaming path.+The worker-streamed upload is replaced with `INSERT INTO FUNCTION s3(...'ArrowStream')` (batch-exports+recipe), issued through the pooled native clients (`sync_execute`, offline workload, `notebooks` user) with a+bounded socket timeout (the pooled clients' prod default is effectively infinite; a sync activity can't be+interrupted, so a half-open connection would pin the worker thread — the timeout mirrors the streaming path's+read-timeout defense). The worker's job shrinks to issuing one statement; zero result bytes transit PostHog+Python, and errors arrive in-band and typed — so the EOS-marker check and `system.query_log` recovery have no+role, but note the budget codes come back as `sync_execute`'s wrapped exception types (`ClickHouse*` for+241/159/160, `CHQueryError*`/`InternalCHQueryError` for 158/307/396), all mapped to terminal here. The s3()+endpoint/bucket/key/credentials are **bound as query parameters**, not spliced as literals: `sync_execute`'s+one `%`-substitution pass escapes them, so a `%` or quote in operator config can't corrupt the statement or+reach the credential zone (this is the real binding channel — client-side `escape_param`, the same all HogQL+`sync_execute` uses — not server-side binding). One object per frame, deliberately no `PARTITION BY`: the+poll/presign contract is a single object, and partitioned files + a manifest + Range-based resume stay future+work if frames outgrow it.++The output cap is enforced **post-write** (`max_result_bytes` bounds a result set returned to a client, not+an INSERT's sink). This is a real cost delta worth eyes-on: the in-flight bound is gone, so a pathological+wide-row query (`repeat('x', N)` over 500k rows) can have CH write tens of GB to the store — bounded only by+the 50GB scan budget, 600s time budget, and CH→S3 throughput — before the size check deletes it and fails the+run terminal (no retry). A post-write freshness check (LastModified vs the write start, 5-min skew margin)+also guards against a silent no-op write serving a stale prior-run object under endpoint skew.++The s3() target URL is built from a **dedicated** `NOTEBOOKS_FRAME_STORE_S3_ENDPOINT`, not the app's shared+`OBJECT_STORAGE_ENDPOINT` — mirroring `IDENTITY_MATCHING_S3_ENDPOINT`, the sibling CH-side s3 writer, for two+reasons that bit that product first. (1) The endpoint must be reachable from the **ClickHouse cluster's**+network, which isn't always the app's: CI points `OBJECT_STORAGE_ENDPOINT` at `localhost:19000`, but CH runs+in compose and reaches the store as `objectstorage:19000` — `localhost` there makes CH connect to itself and+the s3() call hangs. (2) On prod `OBJECT_STORAGE_ENDPOINT` is empty (the app's boto3 uses the AWS default+endpoint), so concatenating it would yield a scheme-less URL CH rejects. So the endpoint defaults to the+cluster-reachable host in TEST/DEBUG and is empty on prod, where the URL builder falls back to the+virtual-hosted AWS form (`https://{bucket}.s3.{region}.amazonaws.com/{key}`) and the cluster authenticates via+its IAM role.++_Prerequisites for flipping the flag (per environment, on top of the phase-1 list):_++- Set `NOTEBOOKS_FRAME_STORE_S3_ENDPOINT` to a host the **ClickHouse cluster** can reach (or leave empty on+ cloud AWS to use the virtual-hosted URL + instance role). Frames live in `NOTEBOOKS_FRAME_STORE_S3_BUCKET`+ (cloud: a dedicated bucket with its own 1-day TTL and a least-privilege CH-node grant; defaults to+ `OBJECT_STORAGE_BUCKET` for dev/CI/self-hosted). Writer and reader agree on the bucket — the app presigns+ and the kernel fetches from the same one — so only the CH-reachable endpoint differs.+- Credentials: keyless in cloud (the CH instance role, write-scoped to the frames bucket);+ where `OBJECT_STORAGE_ACCESS_KEY_ID`/`SECRET` are set they ride inline in the statement and land in+ `system.query_log` — acceptable for dev/self-hosted, not for cloud. Verify the deployed CH version masks+ `s3(url, key, secret, ...)` credential arguments as `[HIDDEN]` in `query_log` (masking is signature-based).+- The writer identity per the security notes above: `readonly = 0` with **zero** table-write grants,+ `GRANT S3` + `CREATE TEMPORARY TABLE`, `remote_url_allow_hosts` pinned to our storage endpoints. This+ supersedes the phase-1 `readonly = 2` spec for the `notebooks` user once the flag is on. Fail-safe: the code+ refuses to run the write-capable statement as the default user in a real deployment — if the flag is flipped+ before this identity is provisioned (creds still resolving to default), materialization degrades to the+ read-only streaming path with a warning rather than handing S3-egress to the broad account.+- Resource note (not a blocker, but size the profile for it): Arrow encoding and S3 upload buffering now burn+ CH initiator-node CPU/memory (the default S3 write buffers are ~hundreds of MiB per INSERT, counted against+ the query's `max_memory_usage`), the trade for freeing worker CPU/NIC. The `mode` label on the started /+ finished counters and the `clickhouse_seconds` histogram separates this path's footprint from the streaming+ path's for the flip decision.++Why the worker relay stays the default until then:- **Security path.** Phase 1 keeps the whole HogQL runner path (team scoping, property access controls appliedat print time) untouched — new code only handles the result. The CH-side write must print the guarded SQLand splice it into a raw `INSERT ... SELECT` executed outside the runner; batch exports does this safely,- but over its own known tables, not arbitrary user HogQL. That seam deserves its own review, not a ride-along.+ but over its own known tables, not arbitrary user HogQL. That seam deserves its own review, not a+ ride-along — the phase-2 security notes below break down what it entails.- **Credentials.** Workers already hold object-storage credentials; the CH-side write needs the cluster's IAMrole extended to the notebooks prefix (see open questions) and local CH → SeaweedFS config.- **Load placement.** Worker streaming actually puts _less_ work on ClickHouse — CH only executes and streams@@ -268,7 +353,78 @@ Why phase 1 streams from the worker instead of starting here:drain pace is set by an in-region worker→S3 leg, so CH's result-hold time is near-identical either way.- **What A buys.** Worker economics at scale (a slot held seconds instead of the stream duration) and nodouble transfer for very large frames. With per-team concurrency ~1 and frames in the tens-to-hundreds of- MB, neither matters yet — escalate on query-log evidence, and phase 2 may never be needed.+ MB, neither matters yet — flip on query-log evidence (upload-half p95 dominating the split metrics, worker+ contention, or a byte-cap raise); the flag can stay off indefinitely if the data never asks.++_Phase-2 security notes (splice analysis, 2026-07) — read before building the CH-side write:_++This section is the pre-implementation analysis. As built (see the phase-2 block above), the s3() arguments+are **bound as query parameters** rather than literal-spliced — which resolves the injection and escaping+issue classes below by construction — and the interim-write bound became a post-write size check. The+privilege amplification analysis stands unchanged and is the load-bearing part.++The statement is `INSERT INTO FUNCTION s3('<url>/<key>', '<creds?>', 'ArrowStream') PARTITION BY rand() % N+<printed SELECT ... SETTINGS ...>` — three trust zones: the prefix (our code, our metadata), the printed+SELECT (user HogQL via the guarded printer), and the query parameters (client-side `escape_param` inlining —+the same channel all HogQL `sync_execute` uses; not literally server-side binding). Two facts+cap the risk: the printed SELECT is already the trusted-executable artifact (executed verbatim today, and+already spliced once into `DESCRIBE TABLE (...)`), and ClickHouse refuses multi-statement execution over both+HTTP and native protocols — realistic injection is clause-level corruption of the prefix, not stacked+statements. Issue classes, by zone:++- **The new injection surface is our own s3() arguments, not the user's query.** Today the object key is an+ inert boto3 API argument; in phase 2 it sits inside a SQL string literal in the most privileged statement+ we run. Key segments are safe today (int team id, hex digest, `[A-Za-z0-9_-]+`-validated short id), but+ that makes charset validation load-bearing forever — someone relaxing the short-id charset later turns a+ cosmetic change into SQL injection. Manual escaping is subtler than it looks: the batch-exports builder+ (`get_s3_function_call`) quote-doubles credentials but not the URL/folder, and quote-doubling alone+ mishandles a value ending in `\` — both fine there only because the inputs have known charsets.+- **Assembly-context grammar bugs.** The printer must run without `output_format` (a trailing+ `FORMAT ArrowStream` is invalid inside `INSERT ... SELECT`; the object format comes from the s3() arg);+ the printer's trailing `SETTINGS` must merge with INSERT-level settings (`s3_truncate_on_insert`) since two+ SETTINGS clauses are a syntax error; WITH-leading and UNION-set shapes interact with `PARTITION BY`+ placement, and the tempting `SELECT * FROM (<printed>)` wrap breaks the settings clause (invalid in a+ subquery), forcing settings-hoisting string surgery. Most failures are fail-safe syntax errors — but every+ workaround is string surgery on printer output, which is where the risk concentrates.+- **The parameter channel must survive.** The `%(hogql_val_N)s` placeholders resolve through `sync_execute`'s+ single `escape_param` substitution pass (client-side, the same as all HogQL) — and the s3() arguments now+ ride the same channel. An implementation that hand-inlines any of these values instead reintroduces classic+ injection for every user literal.+- **Privilege amplification is the deepest issue and is not about splicing — but it is narrower than it+ first looks, because `readonly` and GRANTs are independent layers.** An INSERT is a write statement even+ into a table function, so `readonly = 2` is off the table: the writer identity needs `readonly = 0`.+ That does NOT mean it can write ClickHouse: `INSERT` privileges are per-table and `s3()` is gated by its+ own source grant, so the right shape is `readonly = 0` with a grant set of SELECT on the HogQL-reachable+ tables, `GRANT S3 ON *.*`, `CREATE TEMPORARY TABLE`, and **zero** INSERT/ALTER/CREATE/DROP/TRUNCATE on+ any database or table — a user that physically cannot mutate CH state yet can run+ `INSERT INTO FUNCTION s3`. The `readonly` downgrade then costs only defense-in-depth redundancy, not+ authorization. What grants cannot close: `GRANT S3` is source-level, not resource-level — no per-user+ "only this bucket" exists, and a holder can call `s3('https://anywhere/...', key, secret)` with **inline+ attacker credentials**, bypassing our IAM entirely. That residual exfiltration channel is fenced+ server-side, not per-user: `remote_url_allow_hosts` pinned to our storage endpoints (verify it covers+ `s3()` on our CH version), plus confining the write-capable identity to the one materialize code path+ while everything else notebook-shaped stays on a read-only user. With allowlist + minimal grants, the+ blast radius of a hypothetical printer bug shrinks from "exfiltrate anywhere" to "write malformed objects+ into our own lifecycle-TTL'd frames prefix" — integrity, not confidentiality. One tempting dead end,+ preempted: an admin-created `ENGINE = S3` table (plain table-scoped INSERT grant, no S3 source grant, no+ URL in SQL at all) fails on schema — engine tables are fixed-schema and every frame carries its own+ arbitrary column set, which is exactly why `INSERT INTO FUNCTION s3` (per-statement schema inference) is+ the only shape that fits.++The playbook, if/when built: keep the URL out of the statement via a named collection pinned to bucket ++`notebooks/frames/` prefix (only a charset-validated **and** escaped `filename` override in SQL — validation+as policy, escaping as defense in depth; also keeps credentials out of `system.query_log` and error text);+build the INSERT wrapper as a printer-level construct rather than post-hoc string surgery, with a shape-matrix+test (plain / WITH / UNION / settings-suffix) asserting the output parses as exactly one INSERT; keep every+s3() value in the `sync_execute` parameter map, with no interpolation ahead of its single client-side+escaping pass (there is no server-side binding on this path to fall back on); give the writer identity the+minimal-grant shape above (`readonly = 0`, no+table-write grants, S3 source grant) confined to the materialize path; pin `remote_url_allow_hosts` to our+storage endpoints; scope the CH-side credentials write-only to the notebooks prefix. Verdict: the splice is a+contained engineering problem with a known playbook and its own security review, and the table-mutation half+of the amplification is fully closable through grants; what is permanent is the S3-egress capability itself —+containable to our-own-bucket blast radius via the host allowlist, never eliminable — and that residual is+what must be consciously accepted.**Phase 3 — reuse and convergence.**Serve repeat materializations of an unchanged upstream query straight from the existing object@@ -283,11 +439,19 @@ into the key.## Open questions-- ~~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)?+- ~~Bucket choice~~ — resolved in phase 1 as `OBJECT_STORAGE_BUCKET` under the `notebooks/frames/` prefix,+ then superseded for cloud: `NOTEBOOKS_FRAME_STORE_S3_BUCKET` points at a dedicated frames bucket+ (1-day lifecycle TTL, least-privilege CH-node grant), falling back to `OBJECT_STORAGE_BUCKET` for+ dev/CI/self-hosted. The lifecycle TTL is a bucket rule owned by infra, not app code.+ **Both write paths target that one bucket**, which is easy to misread from the CH-node grant alone:+ ClickHouse writes it on the phase-2 path, and the worker writes it on the phase-1 streaming path —+ still the default, and the fallback whenever the CH writer identity is missing. So the worker's IAM+ role needs `PutObject` plus the multipart actions there, not just the read/delete it needs to size-check+ and clean up. One bucket also means one TTL covers frames from either path. Drop the worker's write+ grant only if the streaming path itself is removed.+- ~~Does cloud CH's instance role already permit writes to the chosen bucket?~~ — infra work, in flight for+ dev: the dedicated bucket grants the CH node role Put/Get/List/Abort (no Delete), mirrored in the CH+ identity policy's allowed-bucket list; prod-us/prod-eu follow after dev verification.- Presign from SeaweedFS in local dev: verify the presigned host is reachable from the locally-run kernel.- Whether phase 1 should also carry SQLV2 (hogql-node) first pages, or stay materialization-only(recommendation: materialization-only — envelopes are small and the current path serves them well).diff --git a/products/notebooks/backend/temporal/frame_materialize.py b/products/notebooks/backend/temporal/frame_materialize.pyindex e2a091013c33..f24aa3905d48 100644--- a/products/notebooks/backend/temporal/frame_materialize.py+++ b/products/notebooks/backend/temporal/frame_materialize.py@@ -11,17 +11,30 @@ turns it into a 302 to a presigned GET.Load protection mirrors the Celery async path (`process_query_task`): a Redis Luaconcurrency limiter gates activity starts (global + per-team), slot exhaustion andClickHouse 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.+exponential backoff with a hard schedule-to-close deadline. For a run whose user has the+`notebooks-frame-store-ch-writes` flag, the query goes to the OFFLINE pool (batch exports'+home) as the dedicated `notebooks` ClickHouse user, so a whale materialization contends+with batch work rather than interactive queries, and the user's server-side profile/quota+is a ceiling no application bug can exceed. Without the flag it stays on the interactive+pool as the default user, which is what has always served these frames. 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.++That same flag also hands the object write to ClickHouse (phase 2 of the design doc): it+issues `INSERT INTO FUNCTION s3(...)` through the pooled native clients (sync_execute), so+zero result bytes transit the worker, errors arrive in-band and typed, and the streaming+path's EOS-marker check and query_log recovery are unnecessary. One flag carries both+halves, so a run is either entirely the old path or entirely the new one. The worker-relay+path below still runs whenever the flag is off, and as the fail-closed fallback when the+confined writer identity is missing."""import timeimport uuidimport hashlibimport datetime as dt-from collections.abc import Iterator-from contextlib import contextmanager, suppress+from collections.abc import Callable, Iterator+from contextlib import AbstractContextManager, contextmanager, suppressfrom dataclasses import dataclassfrom typing import IO, cast@@ -40,9 +53,25 @@ from posthog.hogql.parser import parse_selectfrom posthog.hogql.query import HogQLQueryExecutorfrom posthog.clickhouse.client import sync_execute+from posthog.clickhouse.client.connection import (+ ClickHouseCredentials,+ ClickHouseUser,+ get_clickhouse_creds,+ get_kwargs_for_client,+ make_ch_pool,+)from posthog.clickhouse.client.execute_async import QueryNotFoundError, QueryStatusManager, get_query_statusfrom posthog.clickhouse.client.limit import ConcurrencyLimitExceeded, RateLimitfrom posthog.clickhouse.query_tagging import Feature, Product, tags_context+from posthog.clickhouse.workload import Workload+from posthog.dataclasses import frozen+from posthog.errors import ExposedCHQueryError, InternalCHQueryError+from posthog.exceptions import (+ ClickHouseEstimatedQueryExecutionTimeTooLong,+ ClickHouseQueryMemoryLimitExceeded,+ ClickHouseQuerySizeExceeded,+ ClickHouseQueryTimeOut,+)from posthog.exceptions_capture import capture_exceptionfrom posthog.models import Team, Userfrom posthog.rbac.user_access_control import UserAccessControl@@ -87,6 +116,15 @@ _MAX_RESULT_BYTES = 2_000_000_000 # 2GB, tier 1_STREAM_CONNECT_TIMEOUT_SECONDS = 10.0_STREAM_READ_TIMEOUT_SECONDS = 120.0+# Socket timeout for the CH-writes INSERT's native client. The pooled clients default to an+# effectively infinite send_receive_timeout in prod, but Temporal cannot interrupt a sync+# activity thread — so a half-open connection during the (minutes-long) INSERT would pin the+# thread and its Redis slot until OS-level TCP gives up, exactly as the streaming path's read+# timeout prevents. Set just above the 600s max_execution_time so the server-side timeout wins+# (returning its error in-band) on a healthy query, while an abandoned connection still unblocks+# shortly after the activity deadline. Clamped in TEST so a misrouted test INSERT fails fast.+_INSERT_SEND_RECEIVE_TIMEOUT_SECONDS = 30 if settings.TEST else 630+# 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@@ -104,6 +142,7 @@ _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."+_QUERY_SIZE_MESSAGE = "The query is too large to materialize. Simplify it (e.g. smaller IN lists) and re-run."_RESULT_SIZE_MESSAGE = ("The materialized result is too large (over the frame size budget). ""Select fewer columns or aggregate before materializing."@@ -130,11 +169,16 @@ _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.",+ # Both fallbacks (default creds, online URL) are deliberate and silent, so the labels+ # are the only signal distinguishing "dedicated user on the offline pool engaged"+ # from "provisioning gap, still running as default against interactive nodes". `mode`+ # separates the worker-relay path from the CH-writes path so a flag rollout is legible.+ labelnames=["ch_user", "pool", "mode"],)FRAME_MATERIALIZATIONS_FINISHED_COUNTER = Counter("posthog_notebooks_frame_materializations_finished","Number of notebook frame materialize jobs reaching a terminal state.",- labelnames=["outcome"],+ labelnames=["outcome", "mode"],)FRAME_MATERIALIZATION_DEDUP_COUNTER = Counter("posthog_notebooks_frame_materializations_deduplicated",@@ -150,13 +194,17 @@ FRAME_MATERIALIZE_SECONDS_HISTOGRAM = Histogram("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.+# On the streaming path these two are complementary slices of the relay's wall clock: which+# side the thread was blocked on tells us whether ClickHouse production or object-store+# ingestion is the bottleneck. On the CH-writes path there is no relay — `clickhouse_seconds`+# is the whole INSERT (execution + CH-side S3 upload) and no upload half is emitted — so the+# `mode` label keeps the two distributions from being averaged together.FRAME_CLICKHOUSE_SECONDS_HISTOGRAM = Histogram("posthog_notebooks_frame_clickhouse_seconds",- "Time a successful materialize spent blocked on ClickHouse (response headers plus body reads).",+ "Time a successful materialize spent on ClickHouse. mode=streaming: response headers plus body reads. "+ "mode=ch_writes: the whole INSERT INTO s3 wall clock (execution plus CH-side upload).",buckets=[0.5, 1, 5, 15, 30, 60, 120, 300, 600],+ labelnames=["mode"],)FRAME_UPLOAD_SECONDS_HISTOGRAM = Histogram("posthog_notebooks_frame_upload_seconds",@@ -176,6 +224,42 @@ class FrameMaterializeInputs:query: strquery_hash: strcache_key: str+ # Resolved from the per-user flag in the web process, because the worker has no request+ # user to evaluate it against. Defaulted so a history recorded before this field existed+ # decodes to the streaming path on the interactive pool, which keeps in-flight runs+ # replayable across the deploy.+ ch_writes: bool = False+++@frozen+class _ResolvedWriter:+ """Which write path a run really takes, once the writer identity is known."""++ # The path actually taken, which is not always the one the flag asked for.+ ch_writes: bool+ # The confined `notebooks` writer identity is not provisioned here.+ is_default_user: bool+ # None on the streaming path, which runs as the default user by design.+ creds: ClickHouseCredentials | None+++def _resolve_writer(inputs: FrameMaterializeInputs) -> _ResolvedWriter:+ """Resolve the requested transport against the writer identity this deployment has.++ Shared with the terminal safety net so a run that degraded is not counted under the+ transport it asked for — the metric that separates the two transports is the whole point+ of the rollout, and a failure filed under the wrong one is worse than no sample.+ """+ creds = get_clickhouse_creds(ClickHouseUser.NOTEBOOKS) if inputs.ch_writes else None+ is_default_user = creds is None or creds.user == settings.CLICKHOUSE_USER+ # Fail closed in a real deployment: the CH-writes statement is write-capable (readonly=0+ # + S3 egress), so running it as the broad default user — when the flag was flipped before+ # the confined `notebooks` writer identity was provisioned — defeats the whole containment+ # model. Degrade to the read-only streaming path (correct as any user) rather than hand a+ # write+egress statement to the default account. Dev/test keep CH-writes on the default+ # user so the path stays exercisable.+ degraded = is_default_user and not settings.DEBUG and not settings.TEST+ return _ResolvedWriter(ch_writes=inputs.ch_writes and not degraded, is_default_user=is_default_user, creds=creds)__GLOBAL_LIMITER: RateLimit | None = None@@ -255,6 +339,9 @@ def _generate_sql(return sql, context.values+_DescribeFn = Callable[[str, dict[str, object]], list[tuple[str, str]]]++def _describe_columns(client: ClickHouseClient, printed_sql: str, values: dict[str, object], ch_query_id: str) -> list[tuple[str, str]]:@@ -275,6 +362,25 @@ def _describe_columns(return columns+def _describe_columns_pooled(printed_sql: str, values: dict[str, object], team_id: int) -> list[tuple[str, str]]:+ """`_describe_columns` for the CH-writes path — pooled native client, same routing as the INSERT.++ Bounded socket timeout for the same reason the INSERT is (a half-open connection must not+ pin the uninterruptible activity thread), though a DESCRIBE is metadata-only and fast.+ """+ with _bounded_offline_client(team_id) as client:+ # nosemgrep: clickhouse-fstring-param-audit - printed_sql is HogQL-compiled by the guarded printer, not user input+ rows = sync_execute(+ f"DESCRIBE TABLE ({printed_sql})",+ values,+ workload=Workload.OFFLINE,+ ch_user=ClickHouseUser.NOTEBOOKS,+ team_id=team_id,+ sync_client=client,+ )+ return [(str(row[0]), str(row[1])) for row in rows]++def _stringify_function_for(ch_type: str) -> str | None:"""The conversion a column needs so ClickHouse's Arrow output stays kernel-friendly.@@ -298,20 +404,25 @@ def _stringify_function_for(ch_type: str) -> str | None:def _print_clickhouse_sql(- client: ClickHouseClient, team: Team, user: User | None, query: str, ch_query_id: str+ describe: _DescribeFn, team: Team, user: User | None, query: str, *, output_format: str | None) -> tuple[str, dict[str, object]]:- """Print the HogQL to guarded ClickHouse SQL with `FORMAT ArrowStream` and the standing caps.+ """Print the HogQL to guarded ClickHouse SQL with the standing caps.Two passes when needed (the data-modeling recipe): print once, DESCRIBE the printedquery (metadata only — no execution), and if any output column would leave ClickHouseas Arrow binary, wrap the query so those columns are stringified, then print thewrapper. Field names go through the HogQL AST/printer, never string splicing.+ `output_format` is "ArrowStream" for the streaming path; None for the CH-writes path,+ where the s3() function argument defines the object format and a FORMAT clause would+ be invalid inside the INSERT."""plain_sql, plain_values = _generate_sql(team, user, query, output_format=None)- described = _describe_columns(client, plain_sql, plain_values, ch_query_id)+ described = describe(plain_sql, plain_values)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")+ if output_format is None:+ return plain_sql, plain_values+ return _generate_sql(team, user, query, output_format=output_format)select_fields: list[ast.Expr] = [ast.Alias(expr=ast.Call(name=function, args=[ast.Field(chain=[name])]), alias=name)if function@@ -319,7 +430,126 @@ def _print_clickhouse_sql(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")+ return _generate_sql(team, user, stringified, output_format=output_format)+++class FrameTooLargeError(Exception):+ """The CH-written object exceeds the frame size budget (enforced post-write)."""+++def _frame_s3_url(key: str) -> str:+ """The s3() target URL for the frames bucket, reachable from the ClickHouse cluster.++ Mirrors the identity_matching CH-side writer: when a cluster-reachable endpoint is set+ (dev/test/self-hosted S3-compatible storage) use a path-style URL including the bucket;+ on prod the endpoint is empty and the cluster reaches AWS S3 over its IAM role, so emit a+ virtual-hosted HTTPS URL. Reusing OBJECT_STORAGE_ENDPOINT directly would break prod (it is+ empty there → a scheme-less URL CH rejects) and mis-route dev (it may be an app-only host+ CH can't reach), which is why this has its own NOTEBOOKS_FRAME_STORE_S3_ENDPOINT knob.++ The region is OBJECT_STORAGE_REGION, not a frames-specific one: whatever region this write+ lands in is the region the app's presigning client signs the read with.+ """+ bucket = settings.NOTEBOOKS_FRAME_STORE_S3_BUCKET+ endpoint = settings.NOTEBOOKS_FRAME_STORE_S3_ENDPOINT+ if endpoint:+ return f"{endpoint}/{bucket}/{key}"+ return f"https://{bucket}.s3.{settings.OBJECT_STORAGE_REGION}.amazonaws.com/{key}"+++def _insert_into_s3_sql(printed_sql: str, key: str) -> tuple[str, dict[str, object]]:+ """Wrap the printed SELECT in the CH-side object write (design doc phase 2).++ The s3() endpoint/bucket/key and any credentials are bound as query parameters, not+ spliced as literals: sync_execute runs one `%`-substitution pass over the whole+ statement (clickhouse-driver's `escape_param`), so binding gives correct CH-literal+ escaping for free and — unlike hand-rolled quoting — a `%` or quote in an+ operator-configured endpoint/bucket/credential can neither corrupt that format pass nor+ reach the credential zone. The key is already charset-validated by build_frame_key. The+ SELECT is the same guarded-printer artifact the streaming path executes verbatim,+ printed without a FORMAT clause (the s3() argument defines the object format).+ Credentials are emitted only for the path-style (endpoint-set) case; on prod the empty+ endpoint yields a virtual-hosted URL and the cluster authenticates via its IAM role, so+ no secret is ever interpolated into a statement that lands in system.query_log.+ """+ endpoint = settings.NOTEBOOKS_FRAME_STORE_S3_ENDPOINT+ params: dict[str, object] = {"_nb_s3_url": _frame_s3_url(key)}+ target = ["%(_nb_s3_url)s"]+ if endpoint and settings.OBJECT_STORAGE_ACCESS_KEY_ID and settings.OBJECT_STORAGE_SECRET_ACCESS_KEY:+ params["_nb_s3_key"] = settings.OBJECT_STORAGE_ACCESS_KEY_ID+ params["_nb_s3_secret"] = settings.OBJECT_STORAGE_SECRET_ACCESS_KEY+ target.append("%(_nb_s3_key)s")+ target.append("%(_nb_s3_secret)s")+ target.append("'ArrowStream'")+ return f"INSERT INTO FUNCTION s3({', '.join(target)})\n{printed_sql}", params+++def _bounded_offline_client(team_id: int) -> AbstractContextManager:+ """A native client for the CH-writes path with a finite socket timeout.++ `sync_execute`'s default pooled client has an effectively infinite send/receive timeout+ in prod, which would let a half-open connection pin the (uninterruptible) activity+ thread. Route through a dedicated pool that shares the offline-host + notebooks-user+ routing but caps the socket timeout just above max_execution_time. `make_ch_pool` is+ cached, so this is one extra pool per (offline, notebooks) combination, not per call.+ (Note: sync_execute enters the client as its own context manager and disconnects it on+ exit, so connections aren't kept warm across calls — the pool's value here is the bounded+ timeout, not connection reuse. Negligible at this path's volume: one reconnect per+ materialization, dwarfed by the INSERT itself.)+ """+ kwargs = get_kwargs_for_client(workload=Workload.OFFLINE, team_id=team_id, ch_user=ClickHouseUser.NOTEBOOKS)+ pool = make_ch_pool(send_receive_timeout=_INSERT_SEND_RECEIVE_TIMEOUT_SECONDS, **kwargs)+ return pool.get_client()+++def _execute_insert_to_s3(team: Team, user: User | None, query: str, key: str) -> tuple[int, float]:+ """Materialize by having ClickHouse write the object itself; return (bytes, CH seconds).++ Runs through the pooled native clients (sync_execute) with a bounded socket timeout:+ offline workload and hedging hygiene come from the workload routing, errors arrive+ in-band and typed, and no result bytes transit the worker — so the streaming path's+ EOS-marker check and query_log recovery have no equivalent here.+ """+ printed_sql, values = _print_clickhouse_sql(+ lambda sql, sql_values: _describe_columns_pooled(sql, sql_values, team.pk),+ team,+ user,+ query,+ output_format=None,+ )+ insert_sql, s3_params = _insert_into_s3_sql(printed_sql, key)+ insert_values = {**values, **s3_params}+ ch_settings = {+ # Idempotent retries: a re-attempt overwrites the object, never appends.+ "s3_truncate_on_insert": 1,+ # The client param the streaming path sets on its HTTP client; without it the+ # Arrow file CH writes carries strings as binary and pandas sees bytes.+ "output_format_arrow_string_as_string": 1,+ }+ write_started_at = dt.datetime.now(dt.UTC)+ query_started = time.perf_counter()+ with _bounded_offline_client(team.pk) as client:+ sync_execute(+ insert_sql,+ insert_values,+ settings=ch_settings,+ workload=Workload.OFFLINE,+ ch_user=ClickHouseUser.NOTEBOOKS,+ team_id=team.pk,+ sync_client=client,+ )+ clickhouse_seconds = time.perf_counter() - query_started+ # Freshness margin covers worker↔object-store clock skew without admitting a+ # hours-stale prior-run object (see stat_frame).+ object_bytes = frame_store.stat_frame(key, written_after=write_started_at - dt.timedelta(minutes=5))+ if object_bytes > _MAX_RESULT_BYTES:+ # max_result_bytes bounds result sets returned to a client, not an INSERT's sink —+ # the output cap has to be enforced after the fact on this path. The bytes are+ # ours (this attempt just wrote them), so deleting is safe.+ with suppress(ObjectStorageError):+ frame_store.delete_frame(key)+ raise FrameTooLargeError(f"Frame object is {object_bytes} bytes, over the {_MAX_RESULT_BYTES} budget")+ return object_bytes, clickhouse_secondsdef _finalize_status(@@ -332,6 +562,12 @@ def _finalize_status("""Write the terminal query status and release the dedup mapping."""try:status = manager.get_query_status()+ if status.complete:+ # First terminal write wins. A slow zombie attempt (one that outlived its Temporal+ # deadline while a retry — or mark-failed — already finalized) must not overwrite+ # what the user has seen: not a success flipping a recorded failure, and not a late+ # error clobbering a genuinely-materialized frame that still exists at the key.+ returnexcept QueryNotFoundError:status = QueryStatus(id=inputs.query_id, team_id=inputs.team_id)status.complete = True@@ -382,6 +618,13 @@ def _fetch_query_log_exception(ch_query_id: str) -> tuple[int, str] | None:if lookup_attempt:time.sleep(_QUERY_LOG_LOOKUP_INTERVAL_SECONDS)try:+ # Deliberately the default CH principal, not the notebooks user: recovery must+ # not share fate with the failing subject (a quota/grant condition that killed+ # the query would reject its own diagnosis too, silently turning terminal+ # failures into whale re-executions). Batch exports run this exact lookup as+ # the default user against offline-executed queries, so both the grants and+ # the clusterAllReplicas topology are production-proven. It's three LIMIT 1+ # metadata reads on the failure path — pool placement is irrelevant.rows = sync_execute("""SELECT exception_code, exception@@ -394,7 +637,10 @@ def _fetch_query_log_exception(ch_query_id: str) -> tuple[int, str] | None:""",{"cluster": settings.CLICKHOUSE_CLUSTER, "query_id": ch_query_id},)- except Exception:+ except Exception as exc:+ # A broken lookup silently downgrades error classification (deterministic+ # failures become retries), so it must be visible even though it can't raise.+ logger.warning("notebook_frame_query_log_lookup_failed", ch_query_id=ch_query_id, error=str(exc))return Noneif rows:return int(rows[0][0]), str(rows[0][1])@@ -407,7 +653,36 @@ def materialize_frame(inputs: FrameMaterializeInputs) -> str:Raises on failure so Temporal retries per policy; user-safe HogQL errors are writtento the query status here (terminal — retrying can't fix a bad query) before raising."""- FRAME_MATERIALIZATIONS_STARTED_COUNTER.inc()+ # The new flow rides one flag, resolved per user in the web process and carried on the+ # job. Off, this run is the path that has been serving frames all along: interactive+ # pool, default credentials, hedging left alone.+ offline = inputs.ch_writes+ # Dedicated `notebooks` CH user (server-side profile/quota backstop no application+ # bug can exceed); falls back to the default credentials where not provisioned.+ # sync_execute on the CH-writes path resolves the same creds via the same enum.+ resolved = _resolve_writer(inputs)+ creds = resolved.creds+ resolved_default_user = resolved.is_default_user+ ch_writes = resolved.ch_writes+ if inputs.ch_writes and not ch_writes:+ logger.warning(+ "notebook_frame_ch_writes_missing_writer_identity",+ team_id=inputs.team_id,+ query_id=inputs.query_id,+ )+ mode = "ch_writes" if ch_writes else "streaming"+ ch_url = settings.CLICKHOUSE_OFFLINE_HTTP_URL if offline else settings.CLICKHOUSE_HTTP_URL+ # Reports where the query actually went, not what the flag asked for, and the two paths+ # answer that differently: sync_execute keys on the offline host being set at all, while+ # the HTTP client's URL collapses to the online one under TEST/DEBUG as well.+ pool_offline = (+ settings.CLICKHOUSE_OFFLINE_CLUSTER_HOST is not None if ch_writes else ch_url != settings.CLICKHOUSE_HTTP_URL+ )+ FRAME_MATERIALIZATIONS_STARTED_COUNTER.labels(+ ch_user="notebooks" if not resolved_default_user else "default",+ pool="offline" if pool_offline else "online",+ mode=mode,+ ).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@@ -438,16 +713,6 @@ def materialize_frame(inputs: FrameMaterializeInputs) -> str:# 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 —@@ -456,40 +721,91 @@ def materialize_frame(inputs: FrameMaterializeInputs) -> str:# 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")+ if ch_writes:+ object_bytes, clickhouse_seconds = _execute_insert_to_s3(team, user, inputs.query, key)+ upload_seconds = None # CH performs the upload; the relay split doesn't exist+ else:+ client = ClickHouseClient(+ # With the flag on this is the offline pool (batch exports' home), so a+ # whale materialization does not contend with interactive queries. It+ # falls back to the online URL where no offline cluster exists (EU,+ # self-hosted, dev/test), and stays online entirely without the flag.+ url=ch_url,+ user=creds.user if creds is not None else settings.CLICKHOUSE_USER,+ password=creds.password if creds is not None else 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",+ )+ if offline:+ # sync_execute's offline hygiene, and only meaningful off the+ # interactive pool: without it, distributed subqueries of a saturated+ # offline query hedge onto online replicas, bleeding the whale back+ # into the pool this move protects. Set after construction rather than+ # as a kwarg so the online path sends no such setting at all, exactly+ # as it did before this flag existed.+ client.params["use_hedged_requests"] = "0"+ printed_sql, context_values = _print_clickhouse_sql(+ lambda sql, sql_values: _describe_columns(client, sql, sql_values, ch_query_id),+ team,+ user,+ inputs.query,+ output_format="ArrowStream",+ )+ 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")+ # 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)except ConcurrencyLimitExceeded:raise # retryable — Temporal backs off and re-attemptsexcept 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()+ FRAME_MATERIALIZATIONS_FINISHED_COUNTER.labels(outcome="failed", mode=mode).inc()raise exceptions.ApplicationError(str(exc), non_retryable=True) from exc+ except FrameTooLargeError as exc:+ # The CH-writes analog of the result-bytes cap: deterministic, so terminal. The+ # user-facing message is deliberately vague about the limit, so log the actual+ # size: it is the only record of how far over the cap ClickHouse ran before the+ # post-write check caught it, which is what tells us whether the cap is set right.+ logger.warning(+ "notebook_frame_materialize_object_too_large",+ team_id=inputs.team_id,+ query_id=inputs.query_id,+ error=str(exc),+ )+ _finalize_status(manager, inputs, error_message=_RESULT_SIZE_MESSAGE)+ FRAME_MATERIALIZATIONS_FINISHED_COUNTER.labels(outcome="failed", mode=mode).inc()+ raise exceptions.ApplicationError(_RESULT_SIZE_MESSAGE, non_retryable=True) from excexcept (ClickHouseMemoryLimitExceededError,ClickHouseTooManyBytesError,@@ -502,9 +818,103 @@ def materialize_frame(inputs: FrameMaterializeInputs) -> str:_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()+ FRAME_MATERIALIZATIONS_FINISHED_COUNTER.labels(outcome="failed", mode=mode).inc()raise exceptions.ApplicationError(message, non_retryable=True) from exc+ except (+ ClickHouseQueryMemoryLimitExceeded,+ ClickHouseQueryTimeOut,+ ClickHouseEstimatedQueryExecutionTimeTooLong,+ ClickHouseQuerySizeExceeded,+ ) as exc:+ # CH-writes path: sync_execute rewraps some codes (241 MEMORY, 159 TIMEOUT, 160+ # TOO_SLOW, and the query-size overflow) as APIException subclasses — NOT+ # InternalCHQueryError — so they must be caught here or they'd fall through to a+ # retry. All deterministic, so terminal with an actionable message.+ if isinstance(exc, ClickHouseQuerySizeExceeded):+ message = _QUERY_SIZE_MESSAGE+ elif isinstance(exc, ClickHouseQueryMemoryLimitExceeded):+ if not exc.is_per_query_limit:+ # "(total)" or "(for user)": the cluster was under pressure, this query was+ # not too big. classify_failure() draws the same line. Retrying is what+ # fixes it, and telling the user to narrow a fine query would be wrong.+ logger.warning(+ "notebook_frame_materialize_insert_cluster_memory_pressure",+ team_id=inputs.team_id,+ query_id=inputs.query_id,+ )+ raise+ message = _RESOURCE_BUDGET_MESSAGE+ else:+ message = _TIME_BUDGET_MESSAGE+ logger.warning(+ "notebook_frame_materialize_insert_budget_error",+ team_id=inputs.team_id,+ query_id=inputs.query_id,+ error_type=type(exc).__name__,+ )+ _finalize_status(manager, inputs, error_message=message)+ FRAME_MATERIALIZATIONS_FINISHED_COUNTER.labels(outcome="failed", mode=mode).inc()+ raise exceptions.ApplicationError(message, non_retryable=True) from exc+ except ExposedCHQueryError as exc:+ # A user-safe ClickHouse query error surfaced at DESCRIBE/execution (e.g.+ # TYPE_MISMATCH, UNKNOWN_FUNCTION) that HogQL didn't catch at print time —+ # deterministic, so terminal with the sanitized message (ExposedCHQueryError.__str__+ # strips the stack trace) rather than 10 pointless re-analyses ending generic.+ # Budget overruns arrive here too (TOO_MANY_BYTES for the scan cap is an+ # ExposedCHQueryError), so consult the shared code table first: the same failure+ # must read the same way whichever transport produced it.+ message = _MID_STREAM_MESSAGES_BY_CODE.get(exc.code, "") or str(exc)+ _finalize_status(manager, inputs, error_message=message)+ FRAME_MATERIALIZATIONS_FINISHED_COUNTER.labels(outcome="failed", mode=mode).inc()+ raise exceptions.ApplicationError(message, non_retryable=True) from exc+ except InternalCHQueryError as exc:+ # CH-writes path: sync_execute surfaces the query's real error in-band and+ # typed, with its ClickHouse code — no 200-before-failure ambiguity, so the+ # streaming path's query_log recovery has no role here. Known budget codes are+ # deterministic and terminal; anything else retries per policy. (Codes 241/159/160+ # arrive as the APIException subclasses handled just above, not here — this catches+ # 158/307/396 and the like.)+ mapped = _MID_STREAM_MESSAGES_BY_CODE.get(exc.code or 0)+ if mapped is None:+ # Unrecognized code — plausibly transient (network, S3 blip), or a deterministic+ # misconfig (e.g. 164 READONLY if the writer identity wasn't re-provisioned).+ # Retry per policy, but log the code so a retry storm is attributable.+ logger.warning(+ "notebook_frame_materialize_insert_unmapped_error",+ team_id=inputs.team_id,+ query_id=inputs.query_id,+ exception_code=exc.code,+ )+ raise+ message = mapped+ logger.warning(+ "notebook_frame_materialize_insert_error",+ team_id=inputs.team_id,+ query_id=inputs.query_id,+ exception_code=exc.code,+ )+ _finalize_status(manager, inputs, error_message=message)+ FRAME_MATERIALIZATIONS_FINISHED_COUNTER.labels(outcome="failed", mode=mode).inc()+ raise exceptions.ApplicationError(message, non_retryable=True) from exc+ except frame_store.FrameStoreError as exc:+ # Post-write verification failed: the object is missing or predates this write+ # (see stat_frame). Retryable — a transient object-store blip should re-run — but+ # log it, because a deterministic cause (CH wrote to a store the app can't read,+ # endpoint/bucket skew) would otherwise re-scan the whale silently up to 10 times.+ logger.warning(+ "notebook_frame_materialize_object_unverified",+ team_id=inputs.team_id,+ query_id=inputs.query_id,+ error=str(exc),+ )+ raiseexcept (MidStreamQueryError, ObjectStorageError) as exc:+ if ch_writes:+ # The query_log recovery below is streaming-only: it looks up ch_query_id,+ # which the CH-writes path never attaches (sync_execute mints its own id). Any+ # ObjectStorageError that reaches here on the CH-writes path is transient —+ # retry rather than chase a nonexistent log entry.+ raise# 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@@ -526,27 +936,29 @@ def materialize_frame(inputs: FrameMaterializeInputs) -> str:)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()+ FRAME_MATERIALIZATIONS_FINISHED_COUNTER.labels(outcome="failed", mode=mode).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()+ # The bucket travels with the key: a status outlives the deploy that changes+ # NOTEBOOKS_FRAME_STORE_S3_BUCKET, and the key alone does not say where the object went.+ _finalize_status(manager, inputs, results={"object_key": key, "bucket": settings.NOTEBOOKS_FRAME_STORE_S3_BUCKET})+ FRAME_MATERIALIZATIONS_FINISHED_COUNTER.labels(outcome="succeeded", mode=mode).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)+ FRAME_CLICKHOUSE_SECONDS_HISTOGRAM.labels(mode=mode).observe(clickhouse_seconds)+ if upload_seconds is not None:+ # Only the worker-relay path has an observable upload half; a stream of zeros from+ # the CH-writes path would poison the histogram this split exists to interpret.+ 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,+ ch_writes=ch_writes,clickhouse_seconds=round(clickhouse_seconds, 3),- upload_seconds=round(upload_seconds, 3),+ upload_seconds=round(upload_seconds, 3) if upload_seconds is not None else None,)return key@@ -561,7 +973,10 @@ def mark_frame_materialize_failed(inputs: FrameMaterializeInputs) -> None: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()+ # The effective transport, not the requested one: a run that fell back to streaming must+ # not land in the ch_writes bucket, or the rollout comparison counts its failures twice over.+ mode = "ch_writes" if _resolve_writer(inputs).ch_writes else "streaming"+ FRAME_MATERIALIZATIONS_FINISHED_COUNTER.labels(outcome="failed", mode=mode).inc()@activity.defn(name="notebook-frame-materialize")@@ -615,6 +1030,7 @@ def enqueue_frame_materialization(user_id: int | None,notebook_short_id: str,query: str,+ ch_writes: bool = False,_test_only_inline: bool = False,) -> QueryStatus:"""Register a materialize job for `query` and dispatch the workflow; returns its status.@@ -661,6 +1077,7 @@ def enqueue_frame_materialization(query=query,query_hash=query_hash,cache_key=cache_key,+ ch_writes=ch_writes,)if _test_only_inline:# Tests have no Temporal worker; mirror the workflow's failure handling inline.diff --git a/products/notebooks/backend/test/test_frame_materialize.py b/products/notebooks/backend/test/test_frame_materialize.pyindex 175ac42dba96..d1b084960339 100644--- a/products/notebooks/backend/test/test_frame_materialize.py+++ b/products/notebooks/backend/test/test_frame_materialize.py@@ -5,12 +5,16 @@ from types import SimpleNamespacefrom posthog.test.base import APIBaseTestfrom unittest.mock import patch+from django.conf import settings+from parameterized import parameterizedfrom temporalio import exceptionsfrom posthog.schema import QueryStatusfrom posthog.clickhouse.client.execute_async import QueryStatusManager+from posthog.errors import ExposedCHQueryError, InternalCHQueryError+from posthog.exceptions import ClickHouseQueryMemoryLimitExceeded, ClickHouseQuerySizeExceeded, ClickHouseQueryTimeOutfrom posthog.storage import object_storagefrom posthog.storage.object_storage import ObjectStorageErrorfrom posthog.temporal.common.clickhouse import ClickHouseMemoryLimitExceededError, ClickHouseTooManyRowsOrBytesError@@ -22,6 +26,34 @@ from products.notebooks.backend.temporal import frame_materialize_DISPATCH_TARGET = "products.notebooks.backend.temporal.client.start_frame_materialize_workflow"+def _per_query_memory_error() -> ClickHouseQueryMemoryLimitExceeded:+ # wrap_clickhouse_query_error sets this out of band, and it defaults to False — the+ # cluster-pressure reading. Only the query's own budget overrun is terminal.+ error = ClickHouseQueryMemoryLimitExceeded()+ error.is_per_query_limit = True+ return error+++def _registered_inputs(+ team_id: int, notebook_short_id: str, user_id: int, query: str = "select 1", ch_writes: bool = False+) -> tuple["frame_materialize.FrameMaterializeInputs", QueryStatusManager]:+ query_id = uuid.uuid4().hex+ inputs = frame_materialize.FrameMaterializeInputs(+ query_id=query_id,+ team_id=team_id,+ notebook_short_id=notebook_short_id,+ user_id=user_id,+ query=query,+ query_hash="abc123",+ cache_key=f"notebook-frame:{team_id}:abc123",+ ch_writes=ch_writes,+ )+ manager = QueryStatusManager(query_id, team_id)+ manager.store_query_status(QueryStatus(id=query_id, team_id=team_id))+ manager.register_cache_key_mapping(inputs.cache_key)+ return inputs, manager++class TestFrameMaterializeEnqueue(APIBaseTest):def setUp(self):super().setUp()@@ -63,20 +95,7 @@ class TestFrameMaterializeEnqueue(APIBaseTest):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+ return _registered_inputs(self.team.id, self.notebook.short_id, self.user.id)@parameterized.expand([@@ -173,3 +192,197 @@ class TestFrameMaterializeEnqueue(APIBaseTest):lookup.assert_called_once()status = manager.get_query_status()self.assertFalse(status.complete) # not finalized — Temporal retries per policy+++class TestFrameMaterializeCHWrites(APIBaseTest):+ def setUp(self):+ super().setUp()+ self.notebook = Notebook.objects.create(team=self.team, short_id="nbfmch1")++ def test_ch_writes_materializes_a_readable_arrow_object(self):+ # End-to-end through the real path: pooled DESCRIBE, the stringify second pass,+ # the INSERT assembly around real printed HogQL (trailing SETTINGS clause,+ # %(hogql_val)s placeholders), and CH writing the object itself. Catches any+ # assembly change that produces invalid SQL, and the loss of+ # output_format_arrow_string_as_string / the UUID stringification, which would+ # hand pandas raw bytes.+ frame_uuid = "018e0e7a-1111-2222-3333-444444444444"+ inputs, manager = _registered_inputs(+ self.team.id,+ self.notebook.short_id,+ self.user.id,+ query=f"select number as n, toUUID('{frame_uuid}') as u from numbers(3)",+ ch_writes=True,+ )+ key = frame_store.build_frame_key(inputs.team_id, inputs.notebook_short_id, inputs.query_hash)+ self.addCleanup(object_storage.delete, key)++ with self.settings(OBJECT_STORAGE_ENABLED=True):+ returned_key = frame_materialize.materialize_frame(inputs)++ self.assertEqual(returned_key, key)+ status = manager.get_query_status()+ self.assertTrue(status.complete and not status.error)+ # The bucket is recorded next to the key so the status survives a bucket change:+ # the poll signs against what the writer used, not whatever the setting says later.+ self.assertEqual(status.results, {"object_key": key, "bucket": settings.NOTEBOOKS_FRAME_STORE_S3_BUCKET})++ import pyarrow as pa # noqa: PLC0415 — keeps the heavy dep off the module import path++ data = object_storage.read_bytes(key)+ assert data is not None+ table = pa.ipc.open_stream(data).read_all()+ self.assertEqual(table.num_rows, 3)+ self.assertTrue(pa.types.is_string(table.schema.field("u").type))+ self.assertEqual(table.column("u").to_pylist(), [frame_uuid] * 3)++ def test_ch_writes_zero_row_result_writes_a_valid_empty_object(self):+ # Empty results are common in notebooks (a filter matching nothing). CH must still+ # write a valid (header-only) Arrow object for a zero-row INSERT INTO s3, or stat_frame+ # would see no object → retry → generic failure. Guards against a CH version/setting+ # change (or a switch away from ArrowStream) that stops emitting the empty object.+ inputs, manager = _registered_inputs(+ self.team.id,+ self.notebook.short_id,+ self.user.id,+ query="select number as n from numbers(0)",+ ch_writes=True,+ )+ key = frame_store.build_frame_key(inputs.team_id, inputs.notebook_short_id, inputs.query_hash)+ self.addCleanup(object_storage.delete, key)++ with self.settings(OBJECT_STORAGE_ENABLED=True):+ frame_materialize.materialize_frame(inputs)++ status = manager.get_query_status()+ self.assertTrue(status.complete and not status.error)++ import pyarrow as pa # noqa: PLC0415 — keeps the heavy dep off the module import path++ data = object_storage.read_bytes(key)+ assert data is not None+ self.assertEqual(pa.ipc.open_stream(data).read_all().num_rows, 0)++ def test_insert_sql_binds_s3_args_as_parameters(self):+ # The s3() endpoint/bucket/key/credentials are bound as query params, not spliced as+ # literals: sync_execute's single %-substitution pass escapes them (so a % or quote in+ # a config value can't corrupt the format pass or reach the credential zone). A+ # regression back to literal splicing is the design doc's named injection risk.+ # Path-style URL uses the CH-reachable endpoint, NOT OBJECT_STORAGE_ENDPOINT.+ with self.settings(+ NOTEBOOKS_FRAME_STORE_S3_ENDPOINT="http://store:19000",+ NOTEBOOKS_FRAME_STORE_S3_BUCKET="bucket",+ OBJECT_STORAGE_ACCESS_KEY_ID="ke'y%s",+ OBJECT_STORAGE_SECRET_ACCESS_KEY="s'ec\\ret",+ ):+ sql, params = frame_materialize._insert_into_s3_sql("SELECT 1", "notebooks/frames/team_1/nb/abc.arrow")+ self.assertEqual(+ sql,+ "INSERT INTO FUNCTION s3(%(_nb_s3_url)s, %(_nb_s3_key)s, %(_nb_s3_secret)s, 'ArrowStream')\nSELECT 1",+ )+ # Raw values, unescaped, under reserved keys — escaping happens in the substitution+ # pass, and nothing hostile is ever concatenated into the statement text.+ self.assertEqual(params["_nb_s3_url"], "http://store:19000/bucket/notebooks/frames/team_1/nb/abc.arrow")+ self.assertEqual(params["_nb_s3_key"], "ke'y%s")+ self.assertEqual(params["_nb_s3_secret"], "s'ec\\ret")++ def test_insert_sql_prod_endpoint_is_virtual_hosted_and_keyless(self):+ # The prod branch that dev/CI never exercises: an empty CH endpoint (cluster reaches AWS+ # via IAM role) must yield a virtual-hosted HTTPS URL and NO inline credentials — not a+ # scheme-less `/bucket/key` from concatenating an empty endpoint (which CH rejects).+ # The region is OBJECT_STORAGE_REGION on purpose: the app presigns the read with that+ # same region, and a frames-only region would sign the URL under a scope AWS rejects.+ with self.settings(+ NOTEBOOKS_FRAME_STORE_S3_ENDPOINT="",+ NOTEBOOKS_FRAME_STORE_S3_BUCKET="ph-frames",+ OBJECT_STORAGE_REGION="eu-west-1",+ OBJECT_STORAGE_ACCESS_KEY_ID="should-be-ignored",+ OBJECT_STORAGE_SECRET_ACCESS_KEY="should-be-ignored",+ ):+ sql, params = frame_materialize._insert_into_s3_sql("SELECT 1", "notebooks/frames/team_1/nb/abc.arrow")+ self.assertEqual(sql, "INSERT INTO FUNCTION s3(%(_nb_s3_url)s, 'ArrowStream')\nSELECT 1")+ self.assertEqual(+ params["_nb_s3_url"],+ "https://ph-frames.s3.eu-west-1.amazonaws.com/notebooks/frames/team_1/nb/abc.arrow",+ )+ self.assertNotIn("_nb_s3_key", params)++ @parameterized.expand(+ [+ # Budget failures sync_execute rewraps as APIException subclasses (NOT+ # InternalCHQueryError) — the case the earlier hand-built InternalCHQueryError+ # masked. Must be terminal, else the canonical whale failures retry 10x.+ ("memory_wrapped", _per_query_memory_error(), True, "materialization limits"),+ # "(total)" / "(for user)" memory pressure: the cluster was busy, not this query too+ # big, so the same query can succeed on retry. Finalizing it would both waste the+ # retry budget and tell the user to narrow a query that is fine.+ ("cluster_memory_pressure", ClickHouseQueryMemoryLimitExceeded(), False, None),+ ("timeout_wrapped", ClickHouseQueryTimeOut(), True, "time limit"),+ # A big-but-valid query (printer-expanded IN lists) that overflows max_query_size:+ # deterministic, terminal with an actionable message, not a retry.+ ("query_size_wrapped", ClickHouseQuerySizeExceeded(), True, "too large to materialize"),+ # A user-safe CH query error surfaced at execution (e.g. type mismatch): terminal+ # with the real, sanitized message — not retried into a generic failure.+ (+ "exposed_user_error",+ ExposedCHQueryError("Code: 53. DB::Exception: There is no supertype for types", code=53),+ True,+ "no supertype for types",+ ),+ # The scan-budget overrun. wrap_clickhouse_query_error maps 307 to+ # CHQueryErrorTooManyBytes, which is an ExposedCHQueryError, so it lands in the+ # sanitized-message branch rather than the code-table one. It must still read as+ # the budget message: the same overrun says the same thing on either transport.+ (+ "too_many_bytes",+ ExposedCHQueryError("Code: 307. DB::Exception: Limit for bytes to read exceeded", code=307),+ True,+ "materialization limits",+ ),+ # Unrecognized code (e.g. an S3-side blip): plausibly transient, retry per policy.+ ("unrecognized_code", InternalCHQueryError("DB::Exception", code=499), False, None),+ ]+ )+ def test_insert_error_maps_to_terminal_or_retryable(self, _name, error, terminal, expected_message):+ inputs, manager = _registered_inputs(self.team.id, self.notebook.short_id, self.user.id, ch_writes=True)++ with (+ patch.object(frame_materialize, "_print_clickhouse_sql", return_value=("SELECT 1", {})),+ patch.object(frame_materialize, "_materialize_slots"),+ patch.object(frame_materialize, "sync_execute", side_effect=error),+ ):+ with self.assertRaises(exceptions.ApplicationError if terminal else type(error)) as caught:+ frame_materialize.materialize_frame(inputs)++ status = manager.get_query_status()+ if terminal:+ self.assertTrue(caught.exception.non_retryable)+ self.assertTrue(status.complete and status.error)+ self.assertIn(expected_message, status.error_message or "")+ else:+ self.assertFalse(status.complete) # not finalized — Temporal retries per policy++ def test_oversize_object_is_deleted_and_terminal(self):+ # max_result_bytes bounds results returned to a client, not an INSERT's sink — the+ # post-write size check is the only output cap on this path. Removing it as+ # "redundant" would let a huge-per-row query persist an unbounded object.+ inputs, manager = _registered_inputs(self.team.id, self.notebook.short_id, self.user.id, ch_writes=True)+ key = frame_store.build_frame_key(inputs.team_id, inputs.notebook_short_id, inputs.query_hash)++ with (+ patch.object(frame_materialize, "_print_clickhouse_sql", return_value=("SELECT 1", {})),+ patch.object(frame_materialize, "_materialize_slots"),+ patch.object(frame_materialize, "sync_execute", return_value=None),+ patch.object(+ frame_materialize.frame_store, "stat_frame", return_value=frame_materialize._MAX_RESULT_BYTES + 1+ ),+ patch.object(frame_materialize.frame_store, "delete_frame") as delete_frame,+ ):+ with self.assertRaises(exceptions.ApplicationError) as caught:+ frame_materialize.materialize_frame(inputs)++ delete_frame.assert_called_once_with(key)+ self.assertTrue(caught.exception.non_retryable)+ status = manager.get_query_status()+ self.assertTrue(status.complete and status.error)+ self.assertIn("too large", status.error_message or "")diff --git a/products/notebooks/backend/test/test_frame_store.py b/products/notebooks/backend/test/test_frame_store.pyindex 861dbbc66fac..28d45a85b52e 100644--- a/products/notebooks/backend/test/test_frame_store.py+++ b/products/notebooks/backend/test/test_frame_store.py@@ -3,13 +3,15 @@ import urllib.requestfrom typing import IO, castfrom posthog.test.base import APIBaseTest+from unittest.mock import patch+from django.conf import settingsfrom django.test import SimpleTestCasefrom parameterized import parameterizedfrom posthog.storage import object_storage-from posthog.storage.object_storage import ObjectStorageError+from posthog.storage.object_storage import ObjectStorageError, UnavailableStoragefrom products.notebooks.backend import frame_store@@ -53,16 +55,39 @@ class TestFrameStoreObjects(APIBaseTest):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.+ # authorization, and must carry a signature. The local store serves anonymous reads, so+ # the round trip alone would also pass for a bare object URL that 403s in cloud; the+ # signature assertion is what rejects that. Mapping the URL onto a public host is a+ # deployment concern covered in posthog/storage/test/test_object_storage.py.payload = b"arrow-ipc-bytes" * 1024- with self.settings(OBJECT_STORAGE_ENABLED=True):+ # Presign against the endpoint this process writes through, so the fetch below does not+ # depend on OBJECT_STORAGE_PUBLIC_ENDPOINT resolving from here — the frame-store runbook+ # tells devs to point that at the sandbox's network, which on macOS is+ # host.docker.internal and resolves only inside Docker. Dropping the cached client is+ # what makes the override bite: the storage client keeps its presigning endpoint in a+ # module global and rebuilds only after a call made while storage is disabled.+ with (+ self.settings(OBJECT_STORAGE_ENABLED=True, OBJECT_STORAGE_PUBLIC_ENDPOINT=settings.OBJECT_STORAGE_ENDPOINT),+ patch.object(object_storage, "_client", UnavailableStorage()),+ ):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))+ self.assertIn("X-Amz-Signature=", url)with urllib.request.urlopen(url) as response: # deliberately credential-freeself.assertEqual(response.read(), payload)+ def test_presign_signs_against_the_dedicated_frame_bucket(self):+ # Frames get their own bucket in cloud, and the app-side presign must sign against it —+ # not the general OBJECT_STORAGE_BUCKET. If presign_get drops the bucket override, the+ # kernel is 302'd to a URL signed for a bucket ClickHouse never wrote to → 404. The+ # write→presign→fetch round-trip can't catch this (there both buckets are the default and+ # coincide), so drive a distinct frame bucket and assert it lands in the signed URL.+ # (presign is a client-side signing op, so the bucket need not exist.)+ with self.settings(OBJECT_STORAGE_ENABLED=True, NOTEBOOKS_FRAME_STORE_S3_BUCKET="ph-notebook-frames"):+ url = frame_store.presign_get(self.KEY, team_id=999999)+ self.assertIn("ph-notebook-frames", url)+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.diff --git a/products/notebooks/backend/test/test_sql_v2.py b/products/notebooks/backend/test/test_sql_v2.pyindex 8dc7347e60a3..0d53d2be8e37 100644--- a/products/notebooks/backend/test/test_sql_v2.py+++ b/products/notebooks/backend/test/test_sql_v2.py@@ -17,6 +17,7 @@ from freezegun import freeze_timefrom posthog.test.base import APIBaseTestfrom unittest.mock import patch+from django.conf import settingsfrom django.core import signingfrom django.core.cache import cachefrom django.test import SimpleTestCase, override_settings@@ -1697,7 +1698,12 @@ class TestSQLV2DataPlaneEndpoint(APIBaseTest):from products.notebooks.backend import frame_storeframe_uuid = "018e0e7a-1111-2222-3333-444444444444"- with self.settings(OBJECT_STORAGE_ENABLED=True):+ # Presign against the endpoint this process writes through, dropping the cached storage+ # client so the override applies — see test_frame_store.py for why both halves matter.+ with (+ self.settings(OBJECT_STORAGE_ENABLED=True, OBJECT_STORAGE_PUBLIC_ENDPOINT=settings.OBJECT_STORAGE_ENDPOINT),+ patch.object(object_storage, "_client", object_storage.UnavailableStorage()),+ ):self.addCleanup(self._delete_team_frames)response = self._run_to_completion({