: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
chore(notebooks): remove sql v2 backend design docs (#112474)
Sinan Kucukkoseler3ccccd55cdef
diff --git a/posthog/hogql/constants.py b/posthog/hogql/constants.pyindex c5ce49c77d89..b1fb5e78724e 100644--- a/posthog/hogql/constants.py+++ b/posthog/hogql/constants.py@@ -48,9 +48,8 @@ MAX_SELECT_HEATMAPS_LIMIT = 1000000 # 1m datapoints# Max limit for all cohort calculationsMAX_SELECT_COHORT_CALCULATION_LIMIT = 1000000000 # 1b persons# Max limit for notebook dataframe materialization (the sandbox kernel fetching a whole frame-# over the object-storage frame store). Tier 1 of the rollout ladder in-# products/notebooks/backend/sql_v2_frame_store.md — raised toward the kernel executor's-# _MATERIALIZE_ROW_CAP (2M) on query-log evidence.+# over the object-storage frame store). Raise it toward the kernel executor's+# _MATERIALIZE_ROW_CAP (2M) only when query-log evidence supports it.MAX_SELECT_NOTEBOOK_MATERIALIZE_LIMIT = 500000 # 500k rows# Max limit for LLM tracesMAX_SELECT_TRACES_LIMIT_EXPORT = 10000 # 10k tracesdiff --git a/products/notebooks/backend/facade/notebook_run.py b/products/notebooks/backend/facade/notebook_run.pyindex 042acb949edd..8ed9b302dd7c 100644--- a/products/notebooks/backend/facade/notebook_run.py+++ b/products/notebooks/backend/facade/notebook_run.py@@ -4,7 +4,7 @@ Facade re-exports for the whole-notebook run.The HTTP surface starts, reads, and stops a run, and may only reach in-product code throughthis package. Every entry point is addressed by id and answers with a contract or plain data,so no caller holds a Django object. The workflow starter sits here too, because starting the-run is the last step of the endpoint that creates its record — see `notebook_run.md`.+run is the last step of the endpoint that creates its record."""from ..notebook_run import (diff --git a/products/notebooks/backend/frame_store.py b/products/notebooks/backend/frame_store.pyindex bbeb7365b486..c2987a23d081 100644--- a/products/notebooks/backend/frame_store.py+++ b/products/notebooks/backend/frame_store.py@@ -1,4 +1,4 @@-"""Object-store handoff for materialized SQLV2 frames (sql_v2_frame_store.md, phase 1).+"""Object-store handoff for materialized SQLV2 frames.A Temporal worker streams a frame's ClickHouse result (raw Arrow IPC stream bytes) intoone object here; the data-plane status endpoint answers the kernel's poll with a 302 to adiff --git a/products/notebooks/backend/models.py b/products/notebooks/backend/models.pyindex 2007f7179655..9121ca2e0b05 100644--- a/products/notebooks/backend/models.py+++ b/products/notebooks/backend/models.py@@ -342,7 +342,7 @@ class NotebookNodeRun(TeamScopedRootMixin, UUIDModel):# Which kernel this run was dispatched to, so the callback can file the run's frame# snapshot against the right KernelRuntime. A plain id rather than an FK: runtime rows# are transient (starting/stopped/discarded/error) and run history must not be coupled- # to their churn — see sql_v2_result_delivery.md, "Related model notes".+ # to their churn.kernel_runtime_id = models.UUIDField(null=True, blank=True)error = models.TextField(null=True, blank=True)created_at = models.DateTimeField(auto_now_add=True)diff --git a/products/notebooks/backend/notebook_run.md b/products/notebooks/backend/notebook_run.mddeleted file mode 100644index 1aede25298d6..000000000000--- a/products/notebooks/backend/notebook_run.md+++ /dev/null@@ -1,72 +0,0 @@-# Running a whole notebook--How the backend runs every SQL and Python cell of a markdown notebook in one action, for the editor and for an agent over MCP.-The design and the reasoning behind it are in `products/notebooks/plan/notebooks_run_all_plan.md`.--## Why the backend owns the loop--A client could dispatch the cells itself, the way the stale-cell chain does today.-Two things rule that out.-An MCP tool call has about a 45 second budget, and a notebook of ten cells does not fit it.-And a direct (pure HogQL) cell only reaches a terminal state when somebody polls it, so a run whose client walked away would stay `running` for good.--So one `NotebookRun` record and one Temporal workflow drive the cells.-Both clients call the same three endpoints, and both write the results into the document themselves, as they do for a single cell.-The backend never edits the document.--## The loop--```mermaid-flowchart TD- A[POST notebooks/id/runs] --> B[Save variables]- B --> C[Create NotebookRun with cell_plan]- C --> D[Start workflow notebook-run]- D --> E{Next cell?}- E -- no --> F[NotebookRun done]- E -- yes --> G[Activity: dispatch cell]- G --> H[Activity: check cell every 2 s]- H -- running --> H- H -- done --> I{NotebookRun still running?}- I -- yes --> E- I -- interrupted --> J[Stop, the endpoint wrote the outcome]- H -- failed / interrupted --> K[NotebookRun failed, failed_node_id set]-```--Rules the loop follows:--- Document order is dependency order, because a cell can only read exports of earlier cells. The plan needs no sorting.-- The plan freezes the whole cell at start — its code, its connection, and its raw-SQL flag — not just which cells run. A cell added while the run works does not join it. A cell edited or deleted while it works still executes what the plan captured, and a deleted cell's result has no cell to land in.-- Freezing the code is a security boundary, not only a consistency one. Notebook write access and query access are separate grants, so if the run re-read the document at dispatch, an editor who cannot run queries could swap a later cell and have it execute under the initiator's access. The plan is read once, in the request that already passed the query-access check.-- The run stops at the first cell that does not finish `done`.-- Before each dispatch and while awaiting a cell, the workflow reads the run's status. Deleting the notebook interrupts its run and stops the current child, even though the deleted notebook's API endpoints are no longer accessible.-- A dispatch that meets a busy notebook (409) or a full project (429) retries for two minutes. A person clicking Run on one cell is the case worth waiting out.-- Exhausting the dispatch retry budget fails the parent and stops any child submitted before an activity acknowledgement was lost.-- The whole run is bounded at one hour. On timeout the workflow writes `failed` with the `timed_out` outcome and stops the cell still in flight.--## Endpoints--All three are gated on `revamped-py-notebooks`, the same way `sql_v2/run` is, and all three need query access.--| Method and path | Scopes | Body | Response |-| ---------------------------------------------------- | ------------------------------ | --------------------- | ----------------------------------------------------------------------------------------------------------------------------------------- |-| `POST notebooks/{short_id}/runs/` | `notebook:write`, `query:read` | `{variables?: [...]}` | `{run_id, cell_count, starts_sandbox, sandbox_hourly_price}` |-| `GET notebooks/{short_id}/runs/{run_id}/` | `notebook:read`, `query:read` | | `{run_id, status, trigger, variables, cell_count, current_index, current_node_id, failed_node_id, error, cells, created_at, finished_at}` |-| `POST notebooks/{short_id}/runs/{run_id}/interrupt/` | `notebook:write` | | `{interrupted, status}` |--- `POST runs/` with `variables` saves them through the notebook's own serializer first, so a run and a plain PATCH apply the same limits and the same duplicate-name rule. The run then snapshots what the notebook holds. The save and the run record share one transaction, so a refused run leaves the variables untouched.-- A notebook with no runnable cell returns 400. A notebook that already has a run returns 409.-- `starts_sandbox` is true when the plan holds a Python cell and no kernel is live for the caller. Both clients must tell the user the hourly price.-- `GET runs/{run_id}/` is cheap: no result envelopes. A client fetches the one cell it wants from `GET sql_v2/runs/{run_id}`.--## Records--`NotebookRun` holds the trigger (`ui` or `mcp`), the status, the variable snapshot, the frozen `cell_plan`, `current_index`, and the cell that stopped it.-A partial unique constraint allows one `running` row per notebook, so the database enforces "one whole-notebook run at a time" without a lock.--Each cell's `NotebookNodeRun` points back through `notebook_run`, so the status endpoint reads the whole run with one join, and a cell run started from the editor stays distinguishable from one the orchestrator started.--## Related notes--- `sql_v2_result_delivery.md` — how a single cell's result reaches a client.-- `sql_v2_observability.md` — the metrics and logs, including this run's own.-- `sql_v2_kernel_architecture.md` — the sandbox the Python cells run in.diff --git a/products/notebooks/backend/presentation/views/notebook.py b/products/notebooks/backend/presentation/views/notebook.pyindex fa092605bee4..efd33b05635b 100644--- a/products/notebooks/backend/presentation/views/notebook.py+++ b/products/notebooks/backend/presentation/views/notebook.py@@ -2272,7 +2272,7 @@ class NotebookViewSet(TeamAndOrgViewSetMixin, AccessControlViewSetMixin, ForbidD)def sql_v2_run_result(self, request: Request, run_id: str | None = None, **kwargs):# The node short-polls this durable read to learn when its run finishes. One indexed- # query, no held connection — resilient to reloads/remounts (see sql_v2_result_delivery.md).+ # query, no held connection — resilient to reloads/remounts.user = self._current_user()if run_id is None:raise Http404()@@ -2326,7 +2326,7 @@ class NotebookViewSet(TeamAndOrgViewSetMixin, AccessControlViewSetMixin, ForbidDrequired_scopes=["notebook:read", "query:read"],)def sql_v2_run_page(self, request: Request, run_id: str | None = None, **kwargs):- # A page fetch is not a run (see sql_v2_result_delivery.md): a bounded synchronous+ # A page fetch is not a run: a bounded synchronous# re-query of the run's code with LIMIT/OFFSET, proxied through the running kernel.user = self._current_user()if not (settings.DEBUG or is_sql_v2_enabled(user)) or run_id is None:diff --git a/products/notebooks/backend/sandbox/kernel/__init__.py b/products/notebooks/backend/sandbox/kernel/__init__.pyindex 066dc4dee2a9..de431e5ad2e2 100644--- a/products/notebooks/backend/sandbox/kernel/__init__.py+++ b/products/notebooks/backend/sandbox/kernel/__init__.py@@ -10,6 +10,4 @@ fails the build rather than the next cold start.Intra-package imports must stay relative so the code works under both names(`products.notebooks.backend.kernel` in tests, `nb_kernel` in the sandbox).--See `products/notebooks/backend/sql_v2_kernel_architecture.md` for the design."""diff --git a/products/notebooks/backend/sandbox/kernel/bootstrap.py b/products/notebooks/backend/sandbox/kernel/bootstrap.pyindex d5ca80c39966..3e4cf9ef8c28 100644--- a/products/notebooks/backend/sandbox/kernel/bootstrap.py+++ b/products/notebooks/backend/sandbox/kernel/bootstrap.py@@ -5,7 +5,7 @@ this whole path replaces — nothing here smuggles RPCs over stdout. `run_node`server-fetched local Arrow files and returns a structured envelope.)Runs inside the sandbox's ipykernel — the process that owns compute and data, and holds-no backend credentials (see sql_v2_kernel_architecture.md, "division of labor"). The+no backend credentials. Thekernel-server hands it a single call, `_ph.run_node(payload)`, per run.`run_node` for a Python node:diff --git a/products/notebooks/backend/sandbox/kernel/envelope.py b/products/notebooks/backend/sandbox/kernel/envelope.pyindex 5d3838539edc..53cec47f4ae5 100644--- a/products/notebooks/backend/sandbox/kernel/envelope.py+++ b/products/notebooks/backend/sandbox/kernel/envelope.py@@ -2,7 +2,7 @@The envelope is the small JSON the sandbox POSTs to the backend callback:`{status, columns, row_count, first_page, result_id, error?}`. It carries a-bounded preview only — never the full result (see sql_v2_result_delivery.md).+bounded preview only — never the full result."""import mathdiff --git a/products/notebooks/backend/sandbox/kernel/executor.py b/products/notebooks/backend/sandbox/kernel/executor.pyindex 209ec70e01e1..5dcb7cba1185 100644--- a/products/notebooks/backend/sandbox/kernel/executor.py+++ b/products/notebooks/backend/sandbox/kernel/executor.py@@ -4,8 +4,7 @@ Sandbox-only: this is the one module that imports `jupyter_client` and drives akernel, both of which exist only in the notebook sandbox image — so it is exercised there,not in backend CI (the KernelSession.run_node compute it drives is unit-tested in-processin test_kernel_bootstrap). Everything network/credential-bearing stays in this process; the-kernel receives only local file paths and node code, never a token (division of labor in-sql_v2_kernel_architecture.md).+kernel receives only local file paths and node code, never a token.Flow for a kernel node (python or duckdb — the kernel branches on node.type):1. materialize each HogQL input — the server streams the full CH result to a local Arrowdiff --git a/products/notebooks/backend/sandbox/kernel/result_store.py b/products/notebooks/backend/sandbox/kernel/result_store.pyindex f74eb8c9f09f..5bdc29c95ffe 100644--- a/products/notebooks/backend/sandbox/kernel/result_store.py+++ b/products/notebooks/backend/sandbox/kernel/result_store.py@@ -6,7 +6,7 @@ pyarrow slice that never queues behind a running cell and never touches the data(the node's code is not a HogQL query, so there is nothing to re-query).Frames live only on the sandbox disk: after a sandbox death the file is gone and the-node has to be re-run — the documented alive-only trade-off in sql_v2_result_delivery.md.+node has to be re-run. This alive-only trade-off is deliberate."""import osdiff --git a/products/notebooks/backend/sandbox/kernel/runner.py b/products/notebooks/backend/sandbox/kernel/runner.pyindex 1117a08c66a2..b4e960bc767d 100644--- a/products/notebooks/backend/sandbox/kernel/runner.py+++ b/products/notebooks/backend/sandbox/kernel/runner.py@@ -1,15 +1,14 @@"""Per-run execution: fetch the data, build the envelope, deliver the callback.For the current Journey 1/2 scope every node is a pure-HogQL display node, so a-run is a capped fetch through the data plane — the ipykernel is not involved-(see sql_v2_kernel_architecture.md, "division of labor").+run is a capped fetch through the data plane — the ipykernel is not involved.A run fetches up to `cache_limit` rows in one ClickHouse query and keeps them inan in-memory per-run cache; `/page` requests within the cache are local slices(no ClickHouse work, no held backend workers). Only paging beyond the cache — orafter a kernel restart emptied it — re-queries the data plane with LIMIT/OFFSET.This is the capped, memory-resident precursor of the file-backed result store in-sql_v2_kernel_architecture.md.+`result_store.py`."""import json@@ -79,7 +78,7 @@ def inspect_code(payload: dict[str, Any]) -> dict[str, Any]:def execute_run(payload: dict[str, Any]) -> None:"""Entry point for a /run request, invoked on a background thread.- Routing rule (sql_v2_kernel_architecture.md): a kernel node — python or duckdb —+ Routing rule: a kernel node — python or duckdb —runs in the ipykernel (materialize inputs, run code); a pure-HogQL display nodestays a capped data-plane fetch and never touches the kernel."""diff --git a/products/notebooks/backend/sql_v2_direct.py b/products/notebooks/backend/sql_v2_direct.pyindex eecb278613da..447f50ce187c 100644--- a/products/notebooks/backend/sql_v2_direct.py+++ b/products/notebooks/backend/sql_v2_direct.py@@ -255,8 +255,7 @@ def _query_status_timings(status: Any) -> dict[str, float]:`queued_s` is enqueue -> Celery pickup (slot/queue wait); `clickhouse_s` is pickup ->completion — HogQL compile plus the ClickHouse execution, the closest server-side- proxy for "how long the query itself took". Both are the decomposition fields- sql_v2_observability.md gap 1 called for.+ proxy for "how long the query itself took"."""timings: dict[str, float] = {}start_time = getattr(status, "start_time", None)diff --git a/products/notebooks/backend/sql_v2_frame_store.md b/products/notebooks/backend/sql_v2_frame_store.mddeleted file mode 100644index 0e20d3e78721..000000000000--- a/products/notebooks/backend/sql_v2_frame_store.md+++ /dev/null@@ -1,457 +0,0 @@-# SQLV2 frame materialization via object storage--Design 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. **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--When a python node reads an upstream SQLV2 frame, the sandbox kernel fetches the whole frame through the data plane-(`sql_v2_data_plane.py`), which rides the generic async query manager:--1. A Celery worker executes the HogQL and holds the full result as Python tuples.-2. The worker JSON-renders the entire result into **one Redis string value** (`QueryStatusManager.store_query_status`).-3. On poll, a web worker reads the blob back, parses the JSON, and re-encodes it as an Arrow stream for the sandbox.--The frame is fully copied ~5 times, and the middle copy sits in Redis — the shared cache for the whole deployment.-This transport is implicitly sized by the 50k row ceiling (`MAX_SELECT_RETURNED_ROWS` under the async limit context),-so inline materialized frames are silently clipped at 50k rows.-A `LimitContext.NOTEBOOK_MATERIALIZE` context raising the ceiling to 2M (`_MATERIALIZE_ROW_CAP`) was built and then-**deliberately reverted**: without a better payload transport, wide multi-hundred-thousand-row frames stress Redis-(single-threaded, 512MB per-value hard cap, eviction pressure) and the workers that render/parse the JSON.-With phase 1 the context is back, applied **only on the object path** and at a 500k tier-1 ceiling-(`MAX_SELECT_NOTEBOOK_MATERIALIZE_LIMIT`, raised toward 2M on query-log evidence); the inline path — now the-degraded fallback — keeps the 50k clamp, pinned by `test_inline_materialization_stays_clipped_at_the_row_ceiling`.--## Decision sketch: durable object handoff, not live push--Two async candidates were compared (web-tier streaming is ruled out — no design may pin a web worker on bulk bytes):--- **A — worker/CH writes Arrow to object storage; sandbox pulls a presigned URL.**-- **B — worker pushes the Arrow stream directly into the sandbox's kernel server.**--A wins on every axis that matters here except single-transfer latency:--- **Lifetime decoupling.** Push needs producer and consumer alive simultaneously; the sandbox is the most ephemeral- component we have (Modal cold starts, idle teardown, kernel restarts wipe local disk). An object survives all of that:- any sandbox instance — including one restarted mid-run — can fetch, resume with Range requests, and retry per leg.-- **ClickHouse resource-hold.** A `SELECT` counts as running until the client drains the last block.- Draining into S3 happens at datacenter speed, so CH resources are held for ~pure execution time.- Draining into a Modal container is paced by public-internet throughput and the kernel's ingest —- backpressure propagates into CH (memory pinned, query slot held, execution-time clock ticking).-- **Reuse.** Frames are keyed by `query_hash`; an object serves download retries and kernel restarts without- re-executing CH. Cross-run reuse of an unchanged query is phase 3 — and gated on a staleness policy,- because the key has no freshness component (see the stale-read hazard there). Push has no reuse story —- every delivery is a fresh execution.-- **Attack surface.** Pull keeps the sandbox ingress-free; push requires a new streamed-upload endpoint on the- kernel server, exposed to the internet, plus a request/callback correlation protocol.--Making the sandbox "S3-shaped" is easy at the protocol level (accept a chunked PUT) but cannot provide S3's-semantics — durability, resume, producer/consumer decoupling — because the sandbox is ephemeral by design.-The hard part isn't accepting bytes; it's being a reliable place for bytes to live.--## Prior art in the repo--Every building block already runs in production. Inventory (per deep-dive, 2026-07):--### ClickHouse writes S3 directly (`INSERT INTO FUNCTION s3(...)`)--| Flow | User-facing? | What it teaches us |-| ----------------------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |-| **Batch exports internal stage** — `products/batch_exports/backend/pipeline/internal_stage.py:237`, `temporal/sql.py:8` | Yes, indirectly: users configure recurring batch exports (Data pipelines → Destinations); every run of every destination stages through this first | The core recipe: `INSERT INTO FUNCTION s3(...'ArrowStream') PARTITION BY rand() % N`, keyless IAM in cloud (CH instance role), partition sizing (~250k rows/file), 64MiB insert blocks, delete-prefix-before-write cleanup, bucket-lifecycle retention |-| File-download batch export — `destinations/file_download_batch_export.py:236` | Yes: user requests an export file, downloads when ready | STS `assume_role` scoped to a single bucket prefix, 1h expiry — the tightest credential pattern in the repo |-| Query-log exports (Dagster ×2) — `posthog/dags/export_query_logs_to_s3.py:98` | No: internal ops, daily schedule | `s3_truncate_on_insert=1` for idempotent re-runs; per-host fan-out |-| Duckling backfill — `posthog/dags/events_backfill_to_duckling.py:1420` | No: operator-run migration tooling | Dynamic fan-out sizing (target rows/file), bounded CH writer memory via Parquet row-group settings |-| Identity matching — `products/growth/dags/identity_matching.py:485` | No: internal experiment | CH staging its own intermediate datasets in S3 and reading them back via `FROM s3(...)` |-| Web analytics Native export — `posthog/models/web_preaggregated/sql.py:835` | No (write side appears dormant) | Native format preserves AggregateFunction states across the S3 round-trip |--### Python/Temporal worker streams CH results and uploads--| Flow | User-facing? | What it teaches us |-| ----------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |-| **Data-modeling materialization** — `posthog/temporal/data_modeling/activities/materialize_view.py:346-598` | Yes: user creates a saved query / materialized view (Data warehouse), runs it manually or on schedule | HogQL → `astream_query_as_arrow` in bounded ~100MB batches → Delta/Parquet on S3 via delta-rs; **CH reads the result back** through `s3()`/`s3Cluster()`/`deltaLake()` table functions — proof that CH→S3→query round-trips are production reality |-| CSV/XLSX exports — `products/exports/backend/tasks/csv_exporter.py:480,641`, `models/exported_asset.py:315` | Yes: user clicks "Export" on an insight/table, gets notified, downloads | `LimitContext.EXPORT` + 10k-row pagination, single PUT to `OBJECT_STORAGE_BUCKET`, **7-day TTL with lazy expiry**, download via **presigned URL** — the asset-lifecycle pattern to copy |-| Usage reports v2 — `posthog/temporal/usage_report/activities.py:105` | No: automated billing | Staging many small CH results as S3 objects with explicit best-effort cleanup |--### Relevant negative--There is **no generic S3-backed query-result cache** — the query cache (`posthog/query_cache/`) is Redis-only.-That cache exists to reuse identical insight queries within a TTL; the notebook flow gets its reuse from-`query_hash`-keyed frames (in-flight dedup and retry re-fetch today; cross-run reuse is phase 3), so we are-not duplicating (or blocked on) any platform facility.--## Security model for sandbox reads--Trust model today: the sandbox holds a signed, notebook+team-bound data-plane token and pulls from-`/internal/notebooks/data_plane/` over HTTPS. The frame store keeps that shape — the control plane stays-token-authed; only the bulk-bytes leg moves to object storage.--- **How the sandbox reads without AWS credentials.** The sandbox never assumes a role and never holds AWS- credentials of any kind. The backend — which does hold the role — signs a GET for one specific object with an- expiry and embeds that signature in the URL (a presigned URL); S3 verifies the signature server-side, so the- fetch is a plain HTTPS GET with no SDK. This is the same position a user's browser is in when it downloads a- CSV export (`ExportedAsset.get_content_response`) — an external reader given a narrow expiring capability, not- an identity. STS temp credentials (file-download-export pattern) were considered and rejected for the read- side: they would hand real, if scoped, AWS credentials to a container that executes arbitrary user code,- where a presign is one object, one verb, minutes. Note a presign is only valid while the credentials that- signed it are — fine for minutes-scale expiry, and the reason day-long URLs can't be minted from- instance-role session credentials.-- **Bucket posture.** Private bucket (or dedicated prefix), public access blocked, SSE at rest.- Per the repo's storage direction: SeaweedFS locally, S3 in cloud, standard S3 client, no hardcoded endpoints.-- **Tenant isolation lives at mint time, not in the URL.** Object keys are namespaced- `notebooks/frames/team_{team_id}/{notebook_short_id}/{query_hash}.arrow`.- The status endpoint verifies the data-plane token (which binds notebook + team) **before** presigning,- and only ever presigns objects under that team's prefix. A sandbox can never request another team's key- because it never names keys at all — it polls a query_id it was issued.-- **Presigned GET discipline.** Short expiry (minutes — long enough for a resume-with-Range retry loop, no more),- HTTPS-only, never logged. A presigned URL is a bearer secret of the same class as the existing command tokens;- its blast radius is one object for a few minutes.-- **Write-side auth.** Phase 1: the Temporal worker writes with the standard worker-held object-storage- credentials (`OBJECT_STORAGE_*` — no new identity). Phase 2, if CH writes directly: CH's instance role- (keyless, batch-exports pattern), write-scoped to the notebooks prefix. If tighter isolation is wanted- later: STS prefix-scoped credentials per run (file-download-export pattern).-- **Egress.** The sandbox already makes outbound HTTPS calls to the PostHog API; fetching a presigned S3 URL adds- one more allowed destination. If Modal egress policy must stay single-destination, the fallback is proxying the- object through the data-plane endpoint as a bounded stream — bytes transit Django once, but never Redis and- never as JSON. Keep this as a config switch, not the default.-- **Data at rest is a conscious change.** Query results currently live ≤20 min in Redis; parking them in object- storage for hours is a retention-policy decision. Bound it with a bucket lifecycle TTL (e.g. 24h) plus- delete-prefix-on-supersede, and document it.--## Resource governance — not hammering ClickHouse--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:--- **Per-query SETTINGS (batch-exports recipe).** The staging query carries hard caps, as `internal_stage.py`- does. Phase 1 ships `max_execution_time` 600s (via the `NOTEBOOK_MATERIALIZE` limit context — modestly- above the insight ceiling, frame pulls are legitimately heavier), `max_bytes_to_read` 50GB (refuse- oversized scans up front), `max_threads` 16, and `max_result_bytes` 2GB with `result_overflow_mode=throw`- (row/scan caps don't bound the _output_ — `repeat('x', 10000)` over 500k rows would make a ~5GB object- from a near-zero scan; the output cap bounds object size, storage abuse, and what the kernel later decodes- into pandas, and it throws rather than silently truncating); memory stays on the cluster profile default- for tier 1 (the typed `MEMORY_LIMIT_EXCEEDED` handling is the backstop). Further levers if data demands:- `max_memory_usage`, `max_bytes_before_external_sort/group_by` (spill to disk), `max_network_bandwidth`- to throttle the S3 write rate.-- **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 (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 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 Dagster-query-log exports make its CH footprint analyzable, so the knobs can be tightened with data.--## Phased plan — start basic, improve later--**Phase 0.** Materialization runs over the existing Redis transport, clipped at 50k rows.-Fine for the current flag-gated audience and frames up to low hundreds of thousands of rows.-Since phase 1 this path survives only as the degraded fallback (frame store disabled or unconfigured).--**Phase 1 — swap the payload path, minimal moving parts. (Shipped, gated by the `notebooks-frame-store` flag.)**-The kernel opts in per request with `delivery: "object"` (pages and envelope fetches stay `"inline"`).-The data plane registers a `notebook-frame:{team}:{query_hash}` dedup mapping and dispatches a Temporal-materialize workflow (`temporal/frame_materialize.py`, general-purpose queue, Redis-Lua concurrency slots-global 10 / per-team 2): the activity prints the HogQL through the guarded executor under-`LimitContext.NOTEBOOK_MATERIALIZE` (tier-1 ceiling 500k, not yet 2M), executes over the CH HTTP interface-with `FORMAT ArrowStream`, and relays the raw bytes into one multipart upload-(`frame_store.py`, key `notebooks/frames/team_{team}/{notebook}/{query_hash}.arrow`).-The **object key** lands in `QueryStatus` instead of rows, and the status endpoint answers the poll with a-**302 redirect to a presigned URL** (≤5 min, minted only after token verification, team-prefix-checked).-A frame key is a slot holding the query's current result, not an immutable blob: `query_hash` is-`sha256(user_id + wrapped query)` with no freshness component, and dedup only joins **in-flight**-materializations — a completed status is never served as a cache. Every re-run therefore re-executes against-ClickHouse and atomically overwrites the same key, 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.-Stream integrity: ClickHouse sends `200 OK` before execution finishes, so a mid-stream failure can't change-the status code — current versions deliberately break the chunked encoding (the read tears, the multipart-upload aborts), but older versions/intermediaries can close the body cleanly with exception text appended.-The worker therefore refuses to finalize unless the streamed bytes end with the Arrow end-of-stream marker-(a corrupt object at the deterministic key is deleted), and on any stream failure it recovers the real-ClickHouse error from `system.query_log` — a confirmed query-side exception is terminal (no doomed-re-scans), an unconfirmed failure stays retryable.-The Redis path stays as fallback when the frame store is disabled or unconfigured (dev parity, degraded mode).--_Gating (`sql_v2_data_plane.py`):_ the `notebooks-frame-store` feature flag carries the rollout by itself.-There is deliberately no environment switch beside it — one gate means one place to look, and a flag-retargets instantly where an env var needs a deploy. The only other condition is `OBJECT_STORAGE_ENABLED`,-which is a configuration guard rather than a rollout control: without it the storage client is a silent-no-op, so a materialization would "succeed", fail its post-write HEAD, and burn the activity's retry budget-re-running the query. Failing either condition degrades that request to the inline transport and its 50k-clamp. The flag is checked in the web process at delivery-decision time, which is the only place a-materialization is ever enqueued — nothing downstream re-checks it. `DEBUG` stands in for the flag, so local-dev takes the object path with no flag to evaluate. The `reason` label on-`posthog_notebooks_frame_store_fallback_inline` separates the two: `not_in_rollout` is the expected state-during a ramp, `not_configured` means the deployment has no object storage and should never appear in cloud.--Consequence worth knowing: a self-hosted instance evaluates this flag against PostHog's own cloud project-(`posthog/apps.py`), so it stays on the inline transport unless that flag targets it. That matches how-`revamped-py-notebooks` already gates the whole revamped-notebooks surface.--_Rollout prerequisites (per environment, before flipping the flag on):_--- Target the `notebooks-frame-store` flag only **after** both the web and general-purpose Temporal worker- fleets are on the new image. Temporal accepts a `start_workflow` for a workflow type no worker has- registered yet — so flipping the flag early produces a bounded window of hung polls that the enqueue- rollback (which only catches a dispatch _exception_) cannot recover.-- Confirm `OBJECT_STORAGE_PUBLIC_ENDPOINT` resolves and routes **from the sandbox kernel's network** — the- kernel fetches the presigned URL directly. An internal-only host (or the local SeaweedFS docker name)- makes every download fail (loud, not silent).-- Provision the `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- objects. The rule is infra-owned; app-level cleanup would duplicate it poorly.-- Known degraded-mode caveat: with the flag off (the default) or object storage down, a `delivery: "object"`- request falls back to the inline path clamped at 50k rows and the frame is silently truncated. Fine for- frames under the clamp; a user-visible truncation signal is a follow-up before GA.--Two decisions locked in for this phase:--- **Format: one plain Arrow IPC stream object per frame — not Delta, not Parquet.** Delta earns its machinery- when ClickHouse re-reads a versioned, overwritten _table_ (data modeling's case). A frame key is a slot- holding one query's current result (see above — re-runs overwrite it atomically), read once by pandas;- versioned re-read machinery buys nothing for that flow. The executor already consumes ArrowStream from the- data plane, so the sandbox-side change is just "read the same bytes from a different host". If size matters,- Arrow IPC supports LZ4/ZSTD buffer compression without a format change; multi-file partitioning waits for- phase 2, if ever.-- **An explicit concurrency limiter is the throttle.** Under worker streaming, one active task = one running- CH query = one upload — but the materialize workflow runs on the **shared** general-purpose Temporal queue,- so queue slots alone don't cap notebooks. The shipped throttle is the Redis-Lua concurrency limiter- (the `process_query_task` mechanism): slots acquired at activity start, global 10 / per-team 2, bounding CH- concurrency, worker memory, and S3 parallelism with one knob — 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 load- in time (retry backoff), never above the cap; the real amplification risk is impatient re-runs, and the- async manager's `cache_key` dedup (`get_running_query_by_cache_key`) closes it: enqueue with- `cache_key = notebook-frame:{team}:{sha256(user_id + query)}` (user-scoped, so differently-permissioned- teammates never share a job or an object) and duplicate in-flight materializations join the running query- instead of stacking new ones.--**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 applied- at print time) untouched — new code only handles the result. The CH-side write must print the guarded SQL- and 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 — 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 IAM- role 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- blocks, while Arrow encoding and S3 PUTs burn worker CPU/NIC instead of CH-node resources. The worker's- 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 no- double transfer for very large frames. With per-team concurrency ~1 and frames in the tens-to-hundreds of- 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-(`query_hash` in the key makes this a HEAD check), tighten lifecycle (delete on supersede),-and align the format with the local-DuckDB engine direction so materialized frames double as DuckDB-readable-tables without re-encoding.-**Stale-read hazard — must be solved before the HEAD check ships:** the key has no freshness dimension, so a-bare exists-check would serve a frame materialized before newer events landed. Phase 1 stays fresh only-because it always re-executes and overwrites; cross-run reuse needs an explicit staleness input first — an-age-based reuse rule (the insight cache's target-age precedent), a data watermark, or a time bucket folded-into the key.--## Open questions--- ~~Bucket choice~~ — 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/sql_v2_kernel_architecture.md b/products/notebooks/backend/sql_v2_kernel_architecture.mddeleted file mode 100644index d187afc9ca86..000000000000--- a/products/notebooks/backend/sql_v2_kernel_architecture.md+++ /dev/null@@ -1,193 +0,0 @@-# SQLV2 sandbox kernel architecture--How the in-sandbox runtime is structured so it can:--1. accept HTTP requests to run commands (as it does today),-2. make HTTP requests to the PostHog backend to fetch ClickHouse data (the data plane),-3. load SQL responses as Python dataframes from locally stored files,-4. run DuckDB locally against those files and against kernel-made dataframes.--This extends the Journey 1 slice (`sql_v2.py`, the `kernel/` package) toward the full walkthrough design: push compute to CH, stream Arrow to local files, sandbox drives execution, results return via callback.--## Two processes, one owner--The sandbox runs **two cooperating processes**, both owned by the notebook runtime:--```text-Sandbox (Modal / Docker container)-├── kernel-server ← long-lived HTTP server (today's exposed port)-│ ├── HTTP API: /health /run /page /interrupt /state-│ ├── run queue → executor (jupyter_client, one run at a time)-│ ├── data-plane client (streams Arrow from backend → local files)-│ └── result-store reader (pyarrow mmap / read-only DuckDB, serves /page)-├── ipykernel ← child process, spawned and owned by kernel-server-│ └── user namespace + `_ph` bootstrap module-│ (persistent DuckDB connection, frame registry, node runner)-└── /data- ├── frames/<query_hash>.arrow materialized CH inputs (Arrow IPC files)- ├── results/<result_id>.arrow node outputs, for paging- └── duck/ DuckDB db file + temp spill directory-```--**Why not one process (exec user code inside the server)?** Interrupt requires SIGINT semantics (`KernelManager.interrupt_kernel()`), a segfaulting C extension must not take down the HTTP endpoint, and ipykernel gives stdout/stderr/`display_data` (matplotlib PNG) capture for free. All of that is already in the image.--**Why not keep the backend driving a bare ipykernel (V1)?** That is the stdout bridge we are replacing: every execution round-trips the docker/Modal control plane with a generated script. Here the control plane is used exactly once — to launch the kernel-server — and everything after is plain authed HTTP. The kernel-server becomes the single owner of the kernel process (spawn, health, interrupt, restart); the backend never touches the kernel directly.--### Division of labor (the important rule)--- **The kernel-server does all network I/O.** It receives commands, calls the data plane, sends the result callback. Credentials (command secret, callback token, data-plane token) live only in the server process.-- **The ipykernel does all compute and holds all data.** User Python, DuckDB queries, pandas frames, the persistent DuckDB connection.-- **They share data through files** (`/data`), never through sockets: the server streams Arrow onto disk; the kernel maps those files into DuckDB/pandas. This keeps backend credentials out of the process that runs user code — user code can read anything in its own process, so the less that process holds, the better. (Everything in the sandbox is scoped to this one notebook/team regardless; this is defense in depth, not the boundary.)--## The HTTP API (capability 1)--Same server, same port, same HMAC command-token auth as today (`sql_v2.mint_command_token` / `_verify_command_token`), extended:--| Route | Sync? | Purpose |-| ---------------------- | ----- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |-| `GET /health` | sync | liveness + `{version, kernel_alive}` — version drives the redeploy handshake |-| `POST /run` | 202 | enqueue a node run; result arrives via callback |-| `POST /interrupt` | sync | run-scoped stop (Journey 9): sets the run's cancel event (aborts a queued run and its data-plane waits) and SIGINTs the kernel only when that run is the executing cell. Responds `{interrupted, known}`; `known: false` = already finished or never arrived (idempotent noop) |-| `POST /page` | sync | one result page — bounded, no callback. A hogql run re-queries the data plane with the run’s code + LIMIT/OFFSET; a kernel run (python/duckdb) sends `result_id` and slices its `/data/results/<result_id>.arrow` frame in the server process |-| `GET /state` | sync | list materialized frames, kernel variables, DuckDB tables (Journey 7) |-| `POST /kernel/restart` | sync | recycle the ipykernel child; frames on disk survive, namespace does not |--The command token grows a **scope** claim: `run:<run_id>` (authorizes `/run`, `/interrupt` for that run) or `kernel:<runtime_id>` (authorizes `/page`, `/state`, `/kernel/restart`). Same HMAC scheme, signed payload becomes `{scope}.{exp}`.--`POST /run` body (superset of today's):--```json-{- "run_id": "…",- "node": { "type": "hogql | duckdb | python", "code": "…", "output_name": "df3" },- "inputs": [- { "name": "df1", "kind": "hogql", "query": "<CTE-resolved HogQL>", "query_hash": "sha256…" },- { "name": "df2", "kind": "local" }- ],- "callback": { "url": "…", "token": "…" },- "data_plane": { "url": "…", "token": "…" }-}-```--The backend resolves upstream HogQL references into `inputs` before dispatch (it owns the notebook document); the sandbox never parses HogQL. `kind: local` asserts the frame already exists in the kernel (made by an earlier Python/DuckDB node); the server fails the run cleanly if it doesn't.--Runs execute **one at a time** in arrival order (a kernel has one namespace; concurrent mutation is meaningless). The server keeps a small FIFO queue and per-run state so `/run` returns 202 immediately, and the watchdog/callback bookkeeping has one source of truth. `/page` and `/state` are served concurrently off the server's own read-only view of `/data` — they never wait behind a long run.--## The data plane (capability 2)--New backend endpoint, the counterpart of the callback:--```text-POST /internal/notebooks/data_plane/query/ → 202 { "query_id" } (validate + enqueue)-GET /internal/notebooks/data_plane/query/<id>/ → 202 while running,-Authorization: Bearer <data-plane token> 200 Arrow IPC stream when complete-```--- **Auth**: a signed data-plane token, same `django.core.signing` pattern as the callback token, scoped `(notebook, team)`, minted per run and delivered inside the `/run` payload. TTL must exceed the run watchdog. Hardening later swaps both for RS256 JWTs (Code's `sandbox_event_ingest` pattern), unchanged wire shape.-- **Execution**: the endpoint validates the HogQL, then enqueues it on the **async query manager** — the same Celery-backed path insights and the SQL editor use — so no web worker ever waits on ClickHouse. The kernel polls the status route; the Celery query worker runs the HogQL layer (access controls apply) against ClickHouse — or DuckLake for warehouse sources (Journey 6) — and the completed result returns as Arrow on the poll. Large materializations that outgrow the manager's Redis-resident results will need a streaming variant of this endpoint (direct execution, record batches into the response) — that's a later, additive change.-- **Client side**: the kernel-server issues the request with `requests(..., stream=True)` and feeds `response.raw` into `pyarrow.ipc.open_stream`, writing batches straight into an Arrow IPC **file** under `/data/frames/<query_hash>.arrow`. Peak memory is one record batch, regardless of result size.--Two uses of the same endpoint:--1. **Display page for a pure-HogQL node** — the server requests the query with `LIMIT/OFFSET` for the capped page, builds the envelope from the small Arrow payload, and **never involves the kernel**. Paging/sorting a displayed HogQL node is a fresh CH query every time (accepted trade-off from the walkthrough).-2. **Materialization** — when a Python/DuckDB node needs a CH-resident input, the server fetches the **full** result to a frame file first, then hands the run to the kernel.--Frame files are keyed by `query_hash` (sha256 of the canonical resolved query): re-running a Python node whose inputs didn't change reuses the file; an edited upstream query changes the hash, so staleness falls out naturally (the UI's stale-flag flow, Journey 10, decides _when_ to re-run; the hash decides _whether_ a fetch is needed).--## Loading frames into Python (capability 3)--The kernel is bootstrapped once (at kernel start, by the kernel-server) with a small module, `_ph`, which holds:--- a **persistent DuckDB connection** (`duckdb.connect("/data/duck/duck.db")` with `temp_directory` set, so big operations spill to disk),-- a **frame registry**: `name → {query_hash, path, registered_view}`,-- the **node runner** the server invokes per run.--For each run, the server sends the kernel a single execute request — `_ph.run_node(<payload>)` — where the payload lists the node code and the (already fetched) input file paths. `run_node`:--1. **Registers inputs.** For each `hogql` input: `pyarrow.ipc.open_file(path)` (memory-mapped, zero-copy) and `duckdb.register(name, arrow_object)` — the frame is queryable in DuckDB without ever fully loading into RAM. For a **Python** node it additionally binds `name = <arrow>.to_pandas()` into the user namespace — this is the one step that materializes in RAM, matching the accepted trade-off ("pandas may need to materialize all in memory"); heavy reduction should happen in HogQL/DuckDB first.-2. **Runs the node** (below).-3. **Builds the envelope** — `{status, stdout, stderr, error?, result_id, columns, dtypes, row_count, first_page, media}` — and returns it as the execute result. The kernel-server, not the kernel, POSTs it to the callback URL.-4. **Writes the result frame** (if the node produced one) to `/data/results/<result_id>.arrow`, so `/page` can slice it later without touching the kernel.--Python node execution uses `get_ipython().run_cell(code)` inside a capture context: full IPython semantics (last-expression value, tracebacks), stdout/stderr capture, and matplotlib figures arrive as `display_data` PNG — straight into `envelope.media`.--### Notebook variables--A notebook's `<Variables>` block declares named values the whole document shares. They reach a run by lane, and only one of the two lanes involves the kernel:--- a **SQL** node has each `{name}` resolved at dispatch (`sql_v2_variables.py`). The ClickHouse lane substitutes through the HogQL AST; the DuckDB lane rewrites the placeholder to DuckDB's own `$name` parameter and carries the values on the node, so the driver binds them and no value is ever written into the SQL. Only placeholders in executable positions are rewritten — one inside a string, quoted identifier, dollar-quoted block, or comment is left as written;-- a **raw connection** query refuses variables outright. Escaping is engine- and setting-specific — MySQL treats a backslash as an escape unless `NO_BACKSLASH_ESCAPES` is set — so binding there needs the driver's own parameter binding, which the direct-query path does not carry yet;-- a **Python** node carries the values on `node.variables` and the kernel binds them into the user namespace before `run_cell`, ahead of input registration, so a dataframe still wins a name collision.--Variables are rebound every run: the block is the authority on what a name holds, so a value a previous cell assigned must not survive into the next one.--## Local DuckDB (capability 4)--**DuckDB nodes always execute inside the kernel process.** This is forced by DuckDB's replacement scans: `duckdb.sql("select * from my_pandas_df")` only resolves `my_pandas_df` if the frame lives in the same process. Since DuckDB nodes exist precisely to query local frames (decision 3), they run where the frames are.--A DuckDB node is then just: register any not-yet-registered file-backed inputs, `_ph.duck.sql(code)`, bind the result relation to `output_name` (as a registered DuckDB view + lazily-materializable frame), envelope with a capped preview. The result stays lazy in DuckDB until a downstream Python node calls for pandas.--The routing rule (from the walkthrough, now concrete) — applied by the **backend at dispatch**, not by the server:--- `node.type == hogql` and **all** inputs are `hogql` → the **direct lane** (`sql_v2_direct.py`): the backend enqueues the inlined query on the async query manager and the run never reaches the sandbox at all — no kernel required, results land on the run row via the result poll. This amends walkthrough decision 4 ("the sandbox drives execution"): the backend routes, and the sandbox drives only kernel-lane runs. The server's own hogql handling (capped fetch, result cache, `/page` re-query) remains only for runs dispatched before the direct lane and is slated for removal.-- anything else (Python node, DuckDB node, or a HogQL node would go here if we ever allow HogQL over local frames — we don't; that's what DuckDB syntax is for) → materialize `hogql` inputs to frame files, run in the kernel. Dispatch provisions the kernel itself when none is running (the run is the user's ask for compute; the panel is presentation, not a prerequisite).--### External connections--A SQL cell can target a direct-query data source (the SQL editor's connection selector, rendered in the notebook's database tree) instead of PostHog's ClickHouse.-The cell persists `connectionId` / `sendRawQuery`, the run request carries them, and `NotebookNodeRun` stores them — they reach the query runner as the `HogQLQuery` fields of the same name, so the engine choice is entirely the runner's concern.--Consequences the lanes have to respect:--- A connection run always takes the **direct lane**. The sandbox only reaches PostHog data, so a connection cell that reads a Python frame is rejected at dispatch rather than rerouted to DuckDB.-- `code` only means something on the engine that ran it, so a ref is inlined as a CTE only when the upstream cell's latest run used the _same_ connection and the same raw mode. Anything else is refused at dispatch with a cross-engine message instead of being silently shipped to the wrong engine.-- **Raw mode carries no references at all.** The HogQL parser can't read the engine's dialect, so there is nothing to inline and nothing to bound in place: `apply_raw_page_bounds` wraps the query in an aliased derived table (Postgres and MySQL reject an unaliased one) and the engine sees the rest verbatim.--## Result store and paging--`/page` reads `/data/results/<result_id>.arrow` in the **server** process (pyarrow mmap slice, or a read-only DuckDB connection for sorted/filtered pages). Consequences:--- paging a materialized result is sub-ms and never queues behind a running cell,-- `result_id` stays valid across a **kernel** restart (files survive; only the namespace dies) but not across a **sandbox** death — consistent with the documented alive-only trade-off in `sql_v2_result_delivery.md`,-- results above a size cap are written truncated with a `truncated: true` marker in the envelope; the UI offers re-run-with-filters rather than paging into a 10 GB frame.--## Packaging: from embedded string to a real package--`KERNEL_SERVER_SOURCE` (a stdlib-only string in Django) cannot carry this. Replace it with a real, dependency-using package that never imports Django:--```text-products/notebooks/kernel/ # or backend/kernel_src/ — sandbox-side code, no Django-├── server.py # HTTP server (stdlib ThreadingHTTPServer stays fine — 202s and bounded reads)-├── auth.py # command-token verification (mirror of sql_v2 HMAC, round-trip unit-tested)-├── executor.py # run queue, jupyter_client KernelManager ownership, watchdog, callback POST-├── data_plane.py # Arrow streaming fetch → /data/frames-├── result_store.py # /page + /state reads-├── bootstrap.py # the `_ph` module injected into the kernel (duck conn, frame registry, run_node)-└── envelope.py # envelope construction shared by executor/bootstrap-```--Dependencies (`jupyter_client`, `pyarrow`, `duckdb`, `pandas`, `requests`) are already in `Dockerfile.sandbox-notebook`; no new image deps needed. Delivery runs on two paths, both landing on the same `python -m nb_kernel.server --port … --secret-file … --version …` launch:--- **Baked (the normal path)**: `Dockerfile.sandbox-notebook` copies the package to `/opt/nb_kernel_pkg/nb_kernel/` and stamps its content hash into `/opt/nb_kernel_pkg/VERSION`. `_launch_baked_kernel_server` compares that stamp against the hash the backend expects and launches in place when they agree. No upload, no extract.-- **Tarball (the fallback)**: when the stamp disagrees, the backend uploads the package as a tarball and launches from `/tmp/nb_kernel_pkg` instead. This covers both the dev loop (edit `kernel/`, next run redeploys, no image rebuild) and the window in production between merging a kernel change and its image reaching the registry. A merged kernel fix therefore never waits on an image build.--`kernel_package.py` owns both the destination and the hash: the image build calls it for the bake path (`--baked-root`) and for the stamp, so the Dockerfile holds no second copy of either. A stale stamp is not an outage, only a lost optimization, because the deploy degrades to the tarball path it used before.--`/health` reports the running hash either way, which is what drives the redeploy decision in `ensure_sql_v2_server`. Editing `products/notebooks/backend/sandbox/kernel/**` rebuilds the image through `cd-sandbox-base-image.yml`.--Because the package is plain Python with no Django imports, it gets normal unit tests in CI (auth round-trip, envelope building, run_node against a real in-process DuckDB, data-plane client against a stub Arrow server).--## Failure handling--- **Kernel dies mid-run** (OOM, segfault): the server's executor notices (execute reply timeout / `km.is_alive()` false), POSTs a `{status: "failed", error: "kernel_died"}` envelope to the callback, and can restart the kernel on the next run. The backend-side watchdog stays as the outer net for the case where the whole _sandbox_ dies and no callback can ever arrive.-- **Data-plane fetch fails** mid-stream: partial frame files are written to a temp name and renamed only on success, so the registry never sees a torn file; the run fails with the fetch error in the envelope.-- **Sandbox dies**: everything under `/data` is gone; recovery is the walkthrough's re-provision + mark-all-stale + re-run flow. Nothing here changes that.--## Build order--1. **Package extraction (pure refactor).** Move the current fabricated-result server into the package + tarball bootstrap + version handshake. E2E slice stays green; `KERNEL_SERVER_SOURCE` is deleted.-2. **Server owns an ipykernel.** `executor.py` spawns the kernel via `KernelManager`, injects `_ph`; `/run` with `node.type: python` executes real code and returns a real envelope (stdout, tracebacks, matplotlib media). `/interrupt` works.-3. **Backend data-plane endpoint** (HogQL → Arrow stream) + server-side fetch. Pure-HogQL display nodes return real ClickHouse data — Journey 1 is real end to end, Journey 2 paging via re-query.-4. **Materialization.** `inputs` in the run payload, frame files, `_ph` registration + pandas binding — Journeys 4/5.-5. **DuckDB node type** — Journey 3-alt/5/6 local joins.-6. **Result store `/page` + `/state`** — Journey 2 (materialized paging) and Journey 7.diff --git a/products/notebooks/backend/sql_v2_metrics.py b/products/notebooks/backend/sql_v2_metrics.pyindex e868bcafcbe2..3b1e33d2dbf2 100644--- a/products/notebooks/backend/sql_v2_metrics.py+++ b/products/notebooks/backend/sql_v2_metrics.py@@ -1,4 +1,4 @@-"""Node-run observability: one recorder for every terminal run transition (sql_v2_observability.md gap 1).+"""Node-run observability: one recorder for every terminal run transition.Every path that moves a NotebookNodeRun to a terminal status reports it here exactly once:the sandbox callback, the direct lane, dispatch failures, and interrupts. The recorderdiff --git a/products/notebooks/backend/sql_v2_observability.md b/products/notebooks/backend/sql_v2_observability.mddeleted file mode 100644index b31960763698..000000000000--- a/products/notebooks/backend/sql_v2_observability.md+++ /dev/null@@ -1,249 +0,0 @@-# SQLV2 rollout observability--What you can watch today while rolling out the notebooks SQLV2 frame store, where each signal lives, and what is missing.-Companion to [`sql_v2_frame_store.md`](./sql_v2_frame_store.md) — that doc decides the mechanism, this one decides whether the rollout is going well.--Artifacts:--- [`observability/notebooks-rollout.grafana.json`](../observability/notebooks-rollout.grafana.json) — export of the live Grafana dashboard `notebooks-sqlv2-rollout` (Prometheus/VictoriaMetrics). Its "Transport A/B" row is the flag-on vs flag-off comparison. Its "Temporal queue" row shows the health of the worker queue that every notebook workflow shares with other products. Its "Notebook sandboxes" row counts kernel sandboxes and shows their lifetime from Modal's own metrics.-- [`observability/notebooks-query-log.sql`](../observability/notebooks-query-log.sql) — `query_log_archive` query pack (ClickHouse per-query cost). SQL 9 is the same comparison on the ClickHouse side.-- Notebook `Vs0Gjpqb` in project 2 ("SQLV2 transport benchmark") — the graduated workload to run under each arm.--## The split: two surfaces, and why--Nothing gives you all of this in one place, because the two halves have incompatible storage.--**Prometheus (Grafana)** holds the rollout mechanics: attempt/outcome rates, materialize latency, object size, throttling, HTTP.-It cannot hold per-query ClickHouse cost — scanned bytes per query is unbounded-cardinality data that only makes sense per row, not per series.--**ClickHouse `query_log_archive`** holds the per-query cost: `read_bytes`, `result_bytes`, `result_rows`, `query_duration_ms`, `memory_usage`, `peak_threads_usage`, exception codes.-It is not in Grafana — production ClickHouse holds customer data and there is deliberately no ClickHouse datasource there.-The sanctioned path is the internal Metabase under your own SSO session (the `querying-production-databases-via-metabase` skill).--Grafana dashboards are **not code-managed** in this repo — they are edited in the UI, reachable over Tailscale at `grafana-prod-us` / `grafana-prod-eu` (see `tools/infra-scripts/mcp/README.md`).-The JSON here is an export of the live dashboard, not a provisioned source of truth.-Edit the dashboard in the UI, then export its JSON back here in the same change, so that the copy stays current.--### Attribution is already wired--Both data-plane paths wrap their enqueue in `tags_context(product=Product.NOTEBOOKS, feature=Feature.QUERY, ...)` (`sql_v2_data_plane.py:161,185`), and the tags survive the process hop:-the inline path snapshots them into the Celery task argument (`execute_async.py:343` → `tasks.py:381-383`), and the materialize activity re-establishes them itself (`frame_materialize.py:665`).-So **`lc_product = 'notebooks'` is the single filter that scopes every ClickHouse query**, and `lc_temporal__workflow_type` / `lc_temporal__attempt` come along for free on the materialize path — retries are attributable in ClickHouse.--One caveat: this covers the **SQLV2 data plane**, which is what is being rolled out.-Queries from the classic notebook scene's embedded insights are not covered — `SCENE_TO_TAGS` deliberately maps `Notebook`/`Notebooks` to `None` (`query_tagging.py:168`), letting the inner query kind decide, so those land under `product_analytics` and similar.--### A naming trap--`prometheus_client` appends `_total` to counter sample names.-`Counter("posthog_notebooks_frame_materializations_started")` is scraped as **`posthog_notebooks_frame_materializations_started_total`**.-The dashboard uses the `_total` names; the source code does not have them.--## Coverage against what you asked for--| Want | Where | State |-| --------------------------------- | ------------------------------------------------------------------------------------------------------ | --------------------------------------------------------------- |-| Notebook request E2E latency | `posthog_notebooks_node_run_seconds{node_type,outcome,delivery}` + `notebook node run completed` event | Covered — see "Node-run instrumentation" below |-| CH latency for notebook queries | `query_log_archive.query_duration_ms` (SQL 1) | Covered |-| CH scanned bytes | `query_log_archive.read_bytes` (SQL 1, 6) | Covered |-| CH bytes returned | `result_bytes` / `WriteBufferFromS3Bytes` (SQL 4) | Covered, but mode-dependent — see below |-| CH rows returned | `result_rows` / `written_rows` (SQL 4) | Covered, mode-dependent |-| Overall CH health | Existing shared CH Grafana dashboards + SQL 8 | Covered by platform; SQL 8 gives notebooks' share of offline |-| Throttled queries | `posthog_clickhouse_query_concurrency_limit_exceeded_total{limit_name=~"notebooks_materialize_.*"}` | Covered (rejections only) |-| Parallel queries per team | Reconstructed from `query_log_archive` (SQL 5) | Covered by SQL; **no live gauge** — gap 3 |-| Parallel queries per user | Same, group by `lc_user_id` | Same |-| Per-notebook / per-node breakdown | `NotebookNodeRun` in Postgres (gap 4) | Available in Postgres — runs, node type, status, rough duration |-| E2E latency per transport | `posthog_notebooks_node_run_seconds{delivery}` + the event's `delivery` property | Covered — see "The `delivery` dimension" below |-| CH cost per transport | `query_log_archive` split on `query_kind` (SQL 9) | Covered |--"Bytes/rows returned" is mode-dependent and averaging the modes together is wrong:-the streaming path returns a result set (`result_bytes`, `result_rows`), while the CH-writes path is an `INSERT` whose result set is empty and whose delivered bytes show up as `ProfileEvents['WriteBufferFromS3Bytes']` and `written_rows`.-`query_kind` (`Select` vs `Insert`) is what separates them.-The Prometheus `posthog_notebooks_frame_object_bytes` histogram is the mode-independent view of the same thing, but only on the success path.--## Kernel sandbox usage events--Modal's own metrics count notebook sandboxes, but they carry no team, no size, and no price.-Two events from `kernel_sandbox_usage.py` carry those, so product analytics can show sandbox starts, sandbox-hours, and an estimated price per team.--| Event | Fires when | Main properties |-| --------------------------------- | ---------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------- |-| `notebook kernel sandbox started` | The provider returns a new sandbox, before the kernel starts inside it | `backend`, `cpu_cores`, `memory_gb`, `compute_preset`, `hourly_price_usd`, `ttl_seconds`, `provision_seconds` |-| `notebook kernel sandbox ended` | PostHog stops tracking the sandbox: a stop, a failure, a discard, or the status poll finding it gone | `ended_reason`, `sandbox_still_running`, `tracked_seconds`, `estimated_runtime_seconds`, `estimated_price_usd` |--`KernelRuntime` stores `ttl_expires_at`, the time the provider kills the sandbox at the latest, and `ended_at`.-Several paths can notice the same end, and a conditional update on `ended_at` lets only the first one report it.--Read the estimates with these rules:--- **The price is the rate card, not Modal's charge.** `hourly_price_usd` and `estimated_price_usd` use the rates in `compute_pricing.py`, which set the price shown to users. Docker sandboxes have no price.-- **A sandbox that nothing destroyed costs its full lifetime.** A discard, a kernel that does not answer, or a failed destroy leaves the sandbox running. The event then sets `sandbox_still_running` and runs the estimate to `ttl_expires_at`.-- **A sandbox found gone ends when PostHog finds it, but never after its TTL.** A sandbox that crashed early and was found late counts longer than it ran.-- **A sandbox that dies while nobody watches has no end event** until a later stop, reuse, or status poll notices it.-- **Rows from before these columns existed** have no `ttl_expires_at`, so they report no end event.--## Node-run instrumentation (closes gap 1)--Every terminal transition of a `NotebookNodeRun` — the sandbox callback, the direct-lane finish, dispatch failures, and interrupts — reports once through `sql_v2_metrics.record_node_run_terminal`, emitting three sinks:--- **`posthog_notebooks_node_run_seconds{node_type,outcome,delivery}`** — end-to-end duration, run-row `created_at` to the terminal transition. `outcome` is `done` / `failed` / `interrupted` / `timed_out`; the direct lane's grace-expiry watchdog reports `timed_out`, so an expired query is a bucket, not a user error.-- **`posthog_notebooks_node_run_phase_seconds{phase,node_type}`** — the decomposition, from the run envelope's `timings` dict. Sandbox-reported: `input_wait` (data-plane wait for referenced frames or the display fetch), `download` (presigned frame downloads), `exec` (ipykernel cell), `sandbox_total`. Direct lane, from `QueryStatus`: `queued` (enqueue → Celery pickup), `clickhouse` (pickup → completion).-- **`notebook node run completed`** PostHog event with `duration_seconds`, the phase seconds, `row_count`, `outcome`, `delivery`, `notebook_short_id` — the per-notebook/per-team view Prometheus label cardinality can't hold.--Both histograms also stream into the PostHog Metrics product via their OTLP twins (`posthog/otel_metrics.py`).--### The `delivery` dimension--`delivery` names the transport that actually served a run's rows, and it is what a transport A/B splits on:--| Value | Meaning |-| ------------------ | ---------------------------------------------------------------------------------- |-| `direct` | Direct lane: ClickHouse to Redis to the UI. The sandbox is never involved. |-| `inline` | Sandbox fetch over the inline (Redis) transport, clamped at the async row ceiling. |-| `object_relay` | Phase 1: a Temporal worker streams ClickHouse rows to object storage. |-| `object_ch_writes` | Phase 2: ClickHouse writes the object itself via `INSERT INTO FUNCTION s3`. |-| `none` | Kernel run that read no ClickHouse-backed frame, so no transport applied. |-| `mixed` | One run materialized several inputs and they did not agree on a transport. |--The data plane resolves the value where it picks a transport (`sql_v2_data_plane.py`) and reports it in the 202 accept body; the sandbox echoes it into the envelope without interpreting it.-That ordering matters: an object request that falls through either gate is labeled `inline`, so a silent fallback lands in the bucket it really used rather than the one the flags asked for.--The value crosses the sandbox boundary, where user code can forge an envelope, so `sql_v2_metrics.DELIVERY_LABEL_VALUES` is the allowlist bounding label cardinality.-Anything outside it collapses to `none`.-Adding a transport means adding it in both `sql_v2.DELIVERY_*` and that allowlist.--Two caveats when reading a comparison:--- `direct` and `none` runs have no transport choice, so including them dilutes the split. The dashboard's A/B panels select `delivery=~"object_relay|object_ch_writes|inline"`.-- The label describes delivery, not the ClickHouse write mode behind it. `query_log_archive.query_kind` (`Select` vs `Insert`) is the authoritative server-side split, and SQL 9 in the query pack uses it.--One deliberate hole: the callback is best-effort, so a kernel-lane run whose sandbox dies without delivering stays RUNNING and contributes **no** sample — the row remains visible in Postgres and the node can be re-run. A periodic reaper that would fail such rows (and record them as `timed_out`) was built and dropped as more complexity than the case warrants; revisit if stranded rows become common.--Still open from the original gap: lost-callback kernel runs (above), the frontend's own poll-to-render latency, and the kernel's presigned _download failure_ modes, which remain observable only as an `input_wait`-heavy failed run (see gap 5).--## Whole-notebook run instrumentation--A whole-notebook run (`notebook_run.md`) has its own terminal recorder, `sql_v2_metrics.record_notebook_run_terminal`, called once by whichever caller won the `NotebookRun`'s transition:--- **`posthog_notebooks_notebook_run_terminal_total{outcome,trigger}`** — how many runs ended each way. `trigger` is `ui` or `mcp`, so a person's click and an agent's tool call stay separable.-- **`posthog_notebooks_notebook_run_seconds{outcome,trigger}`** — end-to-end duration, run-row `created_at` to the terminal transition, with an OTLP twin.-- **`notebook run completed`** PostHog event with `trigger`, `outcome`, `cell_count`, `python_cell_count`, `completed_count`, `duration_ms`, and `notebook_short_id`.--The workflow logs each step with `notebook_run_id`, the cell index, and the `node_id`. It never logs cell code.--Read these four things from them: adoption by `trigger`; the share of runs that end `done`; where runs stop, from `failed_node_id`'s position and the cell's type; and the duration spread by `cell_count`, which says whether the MCP tool's 45 second budget covers a typical notebook or whether the status tool is the common path.--Each cell of a whole-notebook run also reports its own `notebook node run completed` event, so the per-cell view above still applies inside a run.--## Temporal queue health--Every notebook workflow runs on `general-purpose-task-queue`: `notebook-sandbox-cmd-run`, `notebook-frame-materialize`, and `notebook-widget-generate` (`temporal/client.py`).-Other products share that queue and its workers, so their load can delay notebook runs while the notebooks code is healthy.-The dashboard's "Temporal queue" row, under "Node runs", shows that shared health.--| Panel | Metric | Scope |-| -------------------------------------------- | ------------------------------------------------------------------------------------------------- | ----------- |-| Queue backlog by task type | `temporal_cloud_v1_approximate_backlog_count` | Whole queue |-| Tasks that wait over 1s and 10s for a worker | `temporal_activity_schedule_to_start_latency`, `temporal_workflow_task_schedule_to_start_latency` | Whole queue |-| Sync match ratio | `temporal_cloud_v1_poll_success_sync_count` / `temporal_cloud_v1_poll_success_count` | Whole queue |-| Worker slot usage | `temporal_worker_task_slots_used`, `temporal_worker_task_slots_available` | Whole queue |-| Notebook activity attempt failures | `temporal_activity_execution_failed{activity_type=~"notebook-.*"}` | Notebooks |-| Notebook workflow outcomes | `temporal_workflow_completed`, `temporal_workflow_failed` | Notebooks |-| Workflow task failures on the queue | `temporal_workflow_task_execution_failed` | Whole queue |--The queue wait matters most for materializations.-`notebook-frame-materialize` has a 10-minute `schedule_to_close_timeout` that includes the wait (`temporal/frame_materialize.py`), so a backlog uses up the materialize deadline.-The worker fleet has a fixed pod count, so a backlog does not add workers.--Three traps when you read or extend the row:--- **Temporal Cloud series are not counters.** Temporal Cloud samples each `temporal_cloud_v1_*` series once a minute as a per-second rate or a gauge. Sum or divide the series directly. `rate()` over them returns wrong values.-- **SDK histograms use milliseconds and coarse buckets.** The worker sets `durations_as_seconds=False` (`posthog/temporal/common/worker.py`). The schedule-to-start buckets are 100, 500, 1000, 5000, 10000, and 100000 ms, so a percentile over them is a guess. The panel shows the share of tasks over a bucket edge instead.-- **No metric measures the queue wait for notebooks only.** The schedule-to-start and workflow task failure series carry `task_queue` but no workflow or activity label. Temporal Cloud has series labeled `temporal_workflow_type`, but it emits them only in minutes with events and has no activity latency per type. Its workflow latency for `notebook-sandbox-cmd-run` also includes the result grace sleep.--## Notebook sandboxes from Modal--Modal exports metrics for each sandbox it runs, and notebook kernels appear there as `app_name="posthog-sandbox-notebook"`, one `container_id` per sandbox.-The dashboard's "Notebook sandboxes" row, under "Temporal queue", reads those series.-They include every notebook sandbox, whatever code path started it, because Modal reports them and not the notebooks code.--| Panel | Query | Shows |-| --------------------------- | ---------------------------------------------------------------------- | ----------------------------------- |-| Notebook sandboxes alive | `count(modal_container_running_ratio{...})` | Sandboxes that run now |-| Sandboxes in time range | `count(count_over_time(modal_container_running_ratio{...}[$__range]))` | Distinct sandboxes in the range |-| Sandbox-hours in time range | `sum(lifetime(modal_container_running_ratio{...}[$__range])) / 3600` | Total sandbox run time in the range |-| Sandbox lifetime | `quantile(0.5, lifetime(...))`, `max(lifetime(...))` | Median and longest lifetime |-| Sandbox CPU use | `modal_cpu_utilization_ratio` | Average and busiest sandbox |-| Sandbox memory use | `modal_memory_usage_bytes` | Average and busiest sandbox |--Four limits when you read or extend the row:--- **`lifetime()` is a MetricsQL function.** It returns the seconds between the first and the last sample of a series, and plain Prometheus does not have it. Modal is scraped once a minute, so each lifetime is up to a minute short.-- **A kernel has a fixed lifetime.** `NOTEBOOK_KERNEL_TTL_SECONDS`, or the notebook's `kernel_idle_timeout_seconds`, becomes the Modal sandbox `timeout`, and use of the kernel does not extend it. Lifetimes that cluster at that limit mean that idle sandboxes wait for the limit.-- **No team, size, or price.** The Modal labels name the app and the container only. The price of a sandbox is its size multiplied by the rates in `compute_pricing.py`.-- **No memory limit.** Memory use divided by `modal_memory_utilization_ratio` does not give a usable limit, so the row does not chart that series.--## Gaps — suggested follow-ups--Ordered by how much they'd hurt during a rollout.--### 1. ~~No E2E latency for a notebook query~~ — closed by the node-run instrumentation above--Shipped — see "Node-run instrumentation" above for the metric names; the lost-callback caveat there is the one remaining sliver.--### 2. Success-only histograms → add an `outcome` label--The existing `frame_materialize_seconds`, `frame_object_bytes`, and `frame_clickhouse_seconds` are observed only on the success path (`frame_materialize.py:877-883`).-A materialization that dies at the 10-minute deadline contributes **no** sample, so the histograms are survivorship-biased exactly when things are going worst.--Suggested: observe duration (and partial size) on the failure branches too, carrying the same `outcome` label as gap 1. One-line change per exit path.-Partially mitigated: the node-run histogram sees every outcome, so a dying materialization now shows up as a slow `failed`/`timed_out` _run_ — but the frame-level histograms themselves are still success-only.--### 3. No in-flight gauge for the concurrency slots--The Redis sorted set holds current occupancy (`ZCARD`), but nothing samples it.-You can see **rejections** after the fact and nothing else, so "are we near the global 10?" is unanswerable until you're already over.-SQL 5 reconstructs true concurrency from `query_log_archive`, but that's forensics, not a dashboard.--Suggested: a periodically-sampled gauge `posthog_notebooks_materialize_slots_in_use{scope}` from the limiter keys.--### 4. Node- and notebook-level breakdowns — from Postgres, not CH tags--Per-notebook and per-node breakdowns (runs per notebook, busiest notebooks, failure rate by node type, nodes per notebook) come from **`NotebookNodeRun`** (`posthog_notebooknoderun`), not from a ClickHouse tag.-Tagging queries with `notebook_short_id` was considered and rejected — it is unbounded-cardinality label data, and it would miss the `python`/`duckdb` runs that never touch ClickHouse.--The table already has everything: `notebook_id`, `node_id`, `node_type` (`hogql`/`python`/`duckdb`), `user_id`, `status` (`running`/`done`/`failed`/`interrupted`), and `created_at`/`updated_at` (so `updated_at - created_at` is a rough per-run duration).-It is indexed on `(team, notebook, node_id)`, so these are plain ORM aggregations.-This is the source for a PostHog/Metabase notebook-usage view; ClickHouse `query_log_archive` stays the source for per-query _cost_, joined on `lc_client_query_id` when a row-level correlation is needed.--### 5. `frame_store.py` is entirely uninstrumented--No counter or timer on any object-store operation. Suggested instrumentation, each failure counter split by a `reason` label because the causes map to different infra problems:--- **`write_stream`** — upload-duration histogram + failure counter (`ObjectStorageError`). The phase-1 worker→S3 leg; today only inferred indirectly from the relay split, and a failed upload has no signal.-- **`stat_frame`** — failure counter split `reason="not_stored"` (HEAD is None — a silent no-op write by an `UnavailableStorage` client, i.e. object storage misconfigured) vs `reason="predates_write"` (the CH-writes freshness guard firing — endpoint/bucket skew, CH wrote where the app can't read). "Storage down" vs "storage misrouted" — worth telling apart at a glance.-- **`presign_get`** — mint counter + failure counter split `reason="prefix_mismatch"` (a key outside the team prefix — the tenant-isolation backstop firing, so any nonzero is security-relevant) vs `reason="presign_failed"` (empty URL — storage/config).-- **`delete_frame`** — a counter. A rising delete rate is a leading indicator that corrupt objects are being produced upstream (mid-stream tears, or oversize objects failing the post-write cap).--What this **cannot** see, and it's the riskiest leg: the kernel's actual _download_ of the presigned URL.-The server mints the URL and never learns whether the fetch succeeded — and that fetch is the documented rollout hazard (`OBJECT_STORAGE_PUBLIC_ENDPOINT` must resolve _from the sandbox's network_).-Observing it needs a kernel-side signal reported back, or the proxy-through-Django fallback (which would put the bytes on a meterable path) — track that as its own follow-up rather than pretending server-side metrics close it.--### 6. HogQL timings are computed and thrown away--`kernel_runtime.py:566-567` deletes the `timings` key from the HogQL response before returning it to the sandbox.-Per-stage HogQL timings exist and are discarded — cheap to log or record.-Partially closed: the direct lane now records `queued`/`clickhouse` phases from `QueryStatus` (see the node-run instrumentation); the HogQL executor's own per-stage breakdown is still discarded.--### 7. No tracing--No OpenTelemetry/Sentry spans anywhere in the product.-Nothing links API request → Temporal workflow → ClickHouse → object store → kernel poll → callback.-`client_query_id` is the only correlation id and it does not reach the frontend or the callback.-Not a rollout blocker, but it is why gap 1 is awkward to close cleanly.--## Before you trust the dashboard--- **Verify the `view` label values** on the two HTTP panels with `list_prometheus_label_values`. The data-plane paths have no `name=` in `urls.py`, so Django derives the view name and the regex in the panel is a guess.-- **Confirm the notebooks metrics are being scraped at all.** They are defined in the Temporal worker process (`frame_materialize.py`); the general-purpose worker fleet's `/metrics` endpoint must be scraped by vmagent for any of the frame panels to have data.-- The dashboard is import-only. Grafana here is not provisioned from git, so re-importing overwrites UI edits. Export the live dashboard and compare it with the JSON here before you import.diff --git a/products/notebooks/backend/sql_v2_result_delivery.md b/products/notebooks/backend/sql_v2_result_delivery.mddeleted file mode 100644index c1bd5d89aeca..000000000000--- a/products/notebooks/backend/sql_v2_result_delivery.md+++ /dev/null@@ -1,210 +0,0 @@-# SQLV2 result delivery--How a SQLV2 node learns that its run finished and gets the result envelope.--## Current approach: FE short-poll (implemented)--The run result is written durably to `NotebookNodeRun` (Postgres). How it gets-there depends on the lane:--- **Kernel-lane runs (python/duckdb)**: the sandbox callback writes the envelope,- as before.-- **Direct-lane runs (hogql, no sandbox — `sql_v2_direct.py`)**: the run rides the- async query manager (the same engine the data plane uses), which has no- completion callback, so the result poll itself advances the row: it reads the- query status by `query_id = run_id` and applies a **guarded** transition- (`filter(status=RUNNING).update(...)`) — idempotent under concurrent pollers,- and a completed query can never overwrite an interrupt. A RUNNING run whose- query status is gone (20-min TTL) fails after a grace window — the watchdog the- kernel lane never had. While the manager's result is alive, the poll response- also carries `rows` (the full capped set, ≤300) for client-side paging.--The frontend node polls a cheap read endpoint until the run reaches a terminal-state.--- **Backend:** `GET .../sql_v2/runs/<run_id>` returns `{status, result, error}`- (+ transient `rows` for direct runs) by reading the `NotebookNodeRun` row (one- indexed query, plus one Redis status read for direct runs). No held connection,- no busy-loop.-- **Frontend:** the node polls that endpoint (~1s) while it has a `runId` and the- run is `running`; stops on `done`/`failed`/`interrupted`. In-progress state is- derived from the run status, so it survives remounts and reloads. The poll timer- lives in `cache.disposables` (auto-cleanup + pause on hidden tab).-- **Interrupt (Journey 9):** for kernel-lane runs,- `POST .../sql_v2/runs/<run_id>/interrupt` proxies a run-scoped stop to the- kernel-server; the terminal state (`interrupted`) still arrives via the- callback → run row → poll, keeping one source of truth. The interrupted- envelope carries the stdout/stderr captured before the stop, and the result- endpoint surfaces it like a `done` envelope. When no kernel is reachable the- endpoint marks the run `interrupted` itself, so a user can always break out of- a RUNNING-forever row (the kernel lane has no backend watchdog). For- **direct (hogql) runs** there is no kernel to signal, so the endpoint marks the- row abandoned itself (the guarded poll transition can't overwrite the interrupt)- and then stops the query at the async manager: `cancel_query` revokes a- still-queued Celery task, otherwise it KILLs the query on ClickHouse under the- run's derived query id. That cancellation is best effort, because the row is- already terminal: a cluster that refuses the KILL just leaves the query running- to its bounded completion with its result discarded. Stop is offered for both- lanes.--Chosen because the result is a **single terminal value**, not a live event stream.-Polling a durable row is simpler than SSE and inherently resilient to connection-death, reloads, and node remounts (the failure modes we hit). Cost is a handful of-1-query reads per run.--## Future approach: Redis pub/sub push (implement when we want lower latency)--Keep the durable Postgres write as the source of truth; add a Redis pub/sub-channel so the result is pushed the instant the callback lands, instead of waiting-for the next poll tick. This is worth doing if/when poll latency (~1s) becomes-noticeable, or when many concurrent runs make polling wasteful. It is **pub/sub,-not a Redis Stream** — we deliver one terminal result, so we don't need replay.--### Backend--1. **Callback handler** (`sql_v2_callback.py`)- - Keep the DB write (envelope → `NotebookNodeRun`) as the authoritative source.- - After the write, best-effort `PUBLISH notebook:sql_v2:run:<run_id>` with a- tiny signal (e.g. `{"status": "done"}`). Payload stays small — the SSE handler- re-reads the authoritative envelope from Postgres. A failed publish never loses- data; the connect-time read (below) covers it.--2. **SSE stream handler** — replace the busy-poll with **subscribe-then-check**:- 1. **Subscribe first** to `notebook:sql_v2:run:<run_id>` (before the DB read —- this closes the race where the callback fires between read and subscribe).- 2. **Read the run once.** If already `done`/`failed` → emit result/error,- unsubscribe, return. (Covers "finished before I connected.")- 3. Else **block on the subscription** with a bounded timeout + periodic SSE- heartbeat. On message → re-read the run → emit → return. On timeout → error.- - No polling loop, no `time.sleep`.--3. **Redis + async**- - Use the existing async Redis client; the handler must be **async** so a held- SSE connection is an idle coroutine, not a worker thread.--### Frontend--4. Node logic keeps its durable-run recovery (fetch/poll by persisted `runId` on- mount when `result` is missing) as the fallback path — the SSE push is the- fast path, the DB read on connect is the safety net.--### Edge cases--- **Subscribe-before-read ordering** — the one race that matters.-- **Postgres is authoritative**, pub/sub is only a wake-up; a missed message falls- back to the connect-time read, never data loss.-- **Timeout + heartbeat** so connections don't hang and proxies don't kill idle- streams.-- **Unsubscribe/cleanup** on every exit path (result, error, timeout, disconnect).--### Why not a Redis Stream (like PostHog Desktop)--PostHog Desktop streams many incremental agent events and needs replay on reconnect-(`Last-Event-ID` cursor over a trimmed stream). SQLV2 delivers one terminal-result, so pub/sub + a durable row is sufficient and much simpler. Revisit the-Stream approach only if SQLV2 starts streaming incremental output (stdout,-rows-as-they-arrive, progress).-------# Result storage & paging (design, not yet implemented)--## Three layers — don't conflate them--| Layer | Where it lives | Size |-| --------------------------- | ---------------------------------------------------- | ------------------------------------------------ |-| `NotebookNodeRun.envelope` | Postgres JSONField on the run | small — metadata + `first_page` **preview** only |-| Full result (all pages) | a **result store** the sandbox populates at run time | can be large |-| `NotebookNodeRun.result_id` | Postgres (UUID column, from the envelope) | tiny — a **handle** into the store |--The envelope carries `{columns, row_count, first_page, result_id}` — a bounded-preview plus a pointer. **It never holds more than the first page.** The full-dataset lives in the result store, referenced by `result_id`. This is the-"pass large data by reference, not by value" rule (same reason Temporal payloads-are capped) — a multi-MB dataframe must never land in the JSONField or the-callback body.--## One run = one row (not one row per page)--`NotebookNodeRun` is one row per **execution** (per Run click). It produces one-`result_id` and one stored result set. **A page fetch is not a run** — it's a-read of an already-materialized result, so it creates **no new `NotebookNodeRun`,-no Temporal workflow, no DB write**. Runs stay the audit/history record; page-reads stay stateless.--```text-1 Run click → 1 NotebookNodeRun → 1 result_id → 1 stored result set- ↑- page 1, 2, 3, "download all" ──read-only────┘ (0 new runs)-```--## Where the full result lives--**Now: client-side for hogql runs.** A direct run fetches up to-`RESULT_CACHE_ROWS` (300) rows in one ClickHouse query; the full capped set rides-the result poll (`rows`) while the manager's Redis result is alive (~20 min), and-the browser pages it locally — the server page endpoint refuses hogql runs.-After expiry or reload only the envelope's `first_page` remains, with a re-run-affordance — the same model the legacy SQL editor uses (one clamped fetch,-client-side pages). The kernel-server's per-run hogql cache and `/page` re-query-still exist but serve only pre-direct-lane runs; both are slated for removal.--**Kernel runs (python/duckdb) page from the on-sandbox result store.** The kernel-writes each produced frame to `/data/results/<result_id>.arrow`; `/page` requests-carrying a `result_id` slice that file in the server process (`kernel/result_store.py`,-pyarrow mmap). There is no data-plane fallback — the run's code is not a HogQL query —-so a lost frame (sandbox death) means re-run, per the alive-only trade-off below.--**Later: durable store** (object storage / Parquet / a results table). The-sandbox materializes the full result at run time; `result_id` is the storage key.-Removes the alive-only limitation below. Switch to this when results must survive-kernel teardown/reloads.--## Page fetch with a kernel-resident store--The data is _in_ the sandbox, so a page fetch **must round-trip to the sandbox** —-but it must **not** use the run's async callback. The callback exists because a-run has unbounded latency; slicing rows out of an in-memory frame is fast and-bounded, so paging is a plain **synchronous request/response**:--```text-Run (unbounded): FE → POST /sql_v2/run → Temporal → kernel-server POST /run → 202- (later) → POST /callback → DB → FE polls-Page (bounded): FE → GET /sql_v2/results/<result_id>?page=2&page_size=100- → backend finds the running kernel- → HTTP POST kernel-server /page {result_id, page, page_size}- → kernel-server slices resident frame, returns rows in the 200 response- → backend returns rows to FE-```--- **No docker control plane needed.** The run goes through Temporal partly because- `ensure_sql_v2_server` bootstraps the server via `write_file`/`execute` (docker- socket). By page-fetch time the kernel-server is already up, so paging is just a- **network HTTP call** to it — allowed even under the dev Seatbelt sandbox (only- the docker _socket_ is denied, not network egress). Hence a synchronous- web→kernel-server call is fine and low-latency.-- **To build:** add a synchronous `/page` route to the kernel-server- (`kernel/server.py`) + a thin backend read endpoint that proxies to it.--## Kernel-resident tradeoff: alive-only--The `result_id` slice exists only while that kernel is up. If the kernel-idle-times-out, is restarted, or the notebook reloads onto a fresh kernel,-`result_id` is stale → `/page` returns not-found → the UI must **re-run** to get a-fresh `result_id`. Durable storage is what removes this later.--## Related model notes--- **`KernelRuntime.server_url` / `server_connect_token`** are stored **plaintext**- (`TextField`). This matches PostHog Desktop, which keeps `sandbox_url` /- `sandbox_connect_token` plaintext in `TaskRun.state` (a plain JSONField). The- connect token is an ephemeral Modal tunnel token, not a durable account secret- (those, e.g. env vars, tasks _does_ encrypt via `EncryptedJSONStringField`). If- we ever want defense-in-depth, an encrypted field is the established pattern.-- **`NotebookNodeRun` has no FK to `KernelRuntime`** and doesn't need one: dispatch- targets the currently-running kernel and the result returns by `run_id`; a later- run just creates a new row against whatever kernel is up then. If we want- run→sandbox traceability for debugging, prefer storing the **`sandbox_id` string**- on the run over a hard FK — `KernelRuntime` rows are transient- (starting/stopped/discarded/error), so a FK would couple run history to a churny- row.diff --git a/products/notebooks/backend/temporal/frame_materialize.py b/products/notebooks/backend/temporal/frame_materialize.pyindex 8205c5bd2d78..de9fd2e6d60b 100644--- a/products/notebooks/backend/temporal/frame_materialize.py+++ b/products/notebooks/backend/temporal/frame_materialize.py@@ -24,7 +24,7 @@ pool as the default user, which is what has always served these frames. ClickHou`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+That same flag also hands the object write to ClickHouse: itissues `INSERT INTO FUNCTION s3(...)` through the pooled native clients (sync_execute), sozero result bytes transit the worker, errors arrive in-band and typed, and the streamingpath's EOS-marker check and query_log recovery are unnecessary. One flag carries both@@ -612,7 +612,7 @@ def _frame_s3_url(key: str) -> str: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).+ """Wrap the printed SELECT in the CH-side object write.The s3() endpoint/bucket/key and any credentials are bound as query parameters, notspliced as literals: sync_execute runs one `%`-substitution pass over the wholediff --git a/products/notebooks/backend/test/test_frame_materialize.py b/products/notebooks/backend/test/test_frame_materialize.pyindex 7bf09de36a73..9e7b338ffbb2 100644--- a/products/notebooks/backend/test/test_frame_materialize.py+++ b/products/notebooks/backend/test/test_frame_materialize.py@@ -284,7 +284,7 @@ class TestFrameMaterializeCHWrites(APIBaseTest):# 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.+ # regression back to literal splicing is an 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",diff --git a/products/notebooks/observability/notebooks-query-log.sql b/products/notebooks/observability/notebooks-query-log.sqlindex e705884cd4e5..010bb5404bc7 100644--- a/products/notebooks/observability/notebooks-query-log.sql+++ b/products/notebooks/observability/notebooks-query-log.sql@@ -53,7 +53,7 @@ ORDER BY hour;-- ----------------------------------------------------------------------------- 2. Rollout verification: which path, pool, and ClickHouse identity is actually--- serving notebook queries. The design doc's phase-1/phase-2 prerequisites+-- serving notebook queries. The frame-store prerequisites-- (dedicated `notebooks` CH user, offline pool) fail *open* and silently — this-- is the ClickHouse-side confirmation that they engaged.-- user — 'notebooks' once the dedicated CH user is provisioned, else the default@@ -129,11 +129,11 @@ GROUP BY query_kind;-- 5. Parallel notebook queries per team — exact concurrency, not a rejection count.-- Prometheus only counts limiter *rejections*; this reconstructs actual occupancy-- by replaying each query as a +1 at its start and a -1 at its end and taking a--- running sum. Compare the peak against the design doc's per-team ceiling of 2+-- running sum. Compare the peak against the per-team ceiling of 2-- (MATERIALIZE_PER_TEAM_CONCURRENCY) and global 10.-- Swap `team_id` for `lc_user_id` to get the per-user view.-- Note: there is no notebook_short_id in the query tags today, so a per-notebook--- breakdown is not possible — see the gaps list in sql_v2_observability.md.+-- breakdown is not possible.-- ---------------------------------------------------------------------------WITH notebook_queries AS (SELECT@@ -223,7 +223,7 @@ LIMIT 25;-- ----------------------------------------------------------------------------- 8. Notebooks' share of the offline pool — the "am I hurting batch exports?"--- question the design doc's pool-isolation decision rests on.+-- question the pool-isolation decision rests on.-- ---------------------------------------------------------------------------SELECTtoStartOfHour(event_time) AS hour,diff --git a/products/notebooks/observability/notebooks-rollout.grafana.json b/products/notebooks/observability/notebooks-rollout.grafana.jsonindex 02139a01ec92..2c8a0cef5499 100644--- a/products/notebooks/observability/notebooks-rollout.grafana.json+++ b/products/notebooks/observability/notebooks-rollout.grafana.json@@ -15,7 +15,7 @@}]},- "description": "Notebook errors and SQLV2 frame-store rollout. The first two rows answer 'what is breaking for users, in the app and via MCP'. The rows below them answer 'is the frame-store rollout going well'. Prometheus/VictoriaMetrics only: ClickHouse per-query cost lives in query_log_archive, see observability/notebooks-query-log.sql, and per-run error text lives in Postgres. Panel details and known blind spots: products/notebooks/backend/sql_v2_observability.md",+ "description": "Notebook errors and SQLV2 frame-store rollout. The first two rows answer 'what is breaking for users, in the app and via MCP'. The rows below them answer 'is the frame-store rollout going well'. Prometheus/VictoriaMetrics only: ClickHouse per-query cost lives in query_log_archive, see observability/notebooks-query-log.sql, and per-run error text lives in Postgres.","editable": true,"fiscalYearStartMonth": 0,"graphTooltip": 0,@@ -2567,7 +2567,7 @@"type": "prometheus","uid": "${datasource}"},- "description": "Mean seconds per successful materialize spent on each side of the worker relay. If the upload half starts dominating p95, that is the design doc's stated trigger for flipping NOTEBOOKS_FRAME_STORE_CH_WRITES on. No upload series is emitted on the ch_writes path \u2014 ClickHouse does the upload there.",+ "description": "Mean seconds per successful materialize spent on each side of the worker relay. If the upload half starts dominating p95, that is the trigger for flipping NOTEBOOKS_FRAME_STORE_CH_WRITES on. No upload series is emitted on the ch_writes path \u2014 ClickHouse does the upload there.","fieldConfig": {"defaults": {"color": {