Skip to content

: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.

feat(notebooks): gate object-delivery frames on a per-user flag (#80333)

Sinan Kucukkoseler297270c386a8
diff --git a/products/notebooks/backend/sql_v2.py b/products/notebooks/backend/sql_v2.py
index 827620f549a0..5983df371d00 100644
--- a/products/notebooks/backend/sql_v2.py
+++ b/products/notebooks/backend/sql_v2.py
@@ -31,6 +31,7 @@ from products.tasks.backend.facade.sandbox import SandboxBase, get_sandbox_class
logger = structlog.get_logger(__name__)
REVAMPED_PY_NOTEBOOKS_FLAG = "revamped-py-notebooks"
+NOTEBOOKS_FRAME_STORE_FLAG = "notebooks-frame-store"
_CALLBACK_TOKEN_SALT = "notebooks.sql_v2.callback"
_CALLBACK_TOKEN_MAX_AGE_SECONDS = 3600
@@ -80,7 +81,7 @@ class SQLV2PageError(Exception):
"""A page fetch the kernel rejected or failed; message is user-facing."""
-def is_sql_v2_enabled(user: User | None) -> bool:
+def _flag_enabled_for(flag: str, user: User | None) -> bool:
if user is None or not user.distinct_id:
return False
kwargs: dict = {"only_evaluate_locally": False, "send_feature_flag_events": False}
@@ -89,7 +90,22 @@ def is_sql_v2_enabled(user: User | None) -> bool:
org_id = str(org.id)
kwargs["groups"] = {"organization": org_id}
kwargs["group_properties"] = {"organization": {"id": org_id}}
- return bool(posthoganalytics.feature_enabled(REVAMPED_PY_NOTEBOOKS_FLAG, user.distinct_id, **kwargs))
+ return bool(posthoganalytics.feature_enabled(flag, user.distinct_id, **kwargs))
+
+
+def is_sql_v2_enabled(user: User | None) -> bool:
+ return _flag_enabled_for(REVAMPED_PY_NOTEBOOKS_FLAG, user)
+
+
+def is_frame_store_enabled(user: User | None) -> bool:
+ """Whether this user's whole-frame materializations may use the object-storage path.
+
+ Narrower than `is_sql_v2_enabled`: it gates only the transport, so a user without it
+ still runs SQLV2 nodes, just over the inline transport and its 50k row clamp. Both this
+ and the deployment's `frame_store.is_enabled()` must hold, so the flag can widen the
+ rollout no further than the environment is provisioned for.
+ """
+ return _flag_enabled_for(NOTEBOOKS_FRAME_STORE_FLAG, user)
def mint_callback_token(run_id: str, team_id: int) -> str:
diff --git a/products/notebooks/backend/sql_v2_data_plane.py b/products/notebooks/backend/sql_v2_data_plane.py
index 885fecd7c456..0b3bf05dee60 100644
--- a/products/notebooks/backend/sql_v2_data_plane.py
+++ b/products/notebooks/backend/sql_v2_data_plane.py
@@ -36,7 +36,7 @@ from posthog.models import Team, User
from products.notebooks.backend import frame_store
from products.notebooks.backend.models import Notebook
-from products.notebooks.backend.sql_v2 import verify_data_plane_token
+from products.notebooks.backend.sql_v2 import is_frame_store_enabled, verify_data_plane_token
from products.notebooks.backend.sql_v2_direct import apply_page_bounds
from products.notebooks.backend.sql_v2_serializers import NotebookSQLV2DataPlaneRequestSerializer
@@ -47,6 +47,9 @@ ARROW_STREAM_CONTENT_TYPE = "application/vnd.apache.arrow.stream"
FRAME_STORE_FALLBACK_COUNTER = Counter(
"posthog_notebooks_frame_store_fallback_inline",
"Number of object-delivery requests that fell back to the inline (Redis) path.",
+ # `not_in_rollout` is expected while the flag ramps; `not_configured` means the
+ # deployment cannot serve objects at all and should be near zero once provisioned.
+ labelnames=["reason"],
)
@@ -142,7 +145,15 @@ def notebook_sql_v2_data_plane(request: HttpRequest) -> HttpResponse:
bounded = apply_page_bounds(data["query"], limit=data["limit"], offset=data["offset"])
if data["delivery"] == "object":
- if frame_store.is_enabled():
+ # Two independent gates. The deployment gate says the environment can serve objects
+ # at all; the per-user flag says this user is in the rollout. Failing either one
+ # falls through to the inline transport below, which is correct for any user but
+ # clamped at the async row ceiling. DEBUG stands in for the flag, the way the SQLV2
+ # endpoints already treat `revamped-py-notebooks`, so local dev reaches the object
+ # path by setting NOTEBOOKS_FRAME_STORE_ENABLED alone. Without it, local testing
+ # would need a real flag on whichever project this instance sends analytics to.
+ frame_store_configured = frame_store.is_enabled()
+ if frame_store_configured and (settings.DEBUG or is_frame_store_enabled(user)):
# Whole-frame materialization: stream the result to object storage via a
# Temporal worker; the poll answers with a 302 to a presigned URL. The
# frame_materialize module is imported lazily — it pulls temporalio and the
@@ -164,16 +175,22 @@ def notebook_sql_v2_data_plane(request: HttpRequest) -> HttpResponse:
logger.exception("notebook_frame_materialize_enqueue_failed", notebook_short_id=notebook_short_id)
return JsonResponse({"error": "Query could not be scheduled."}, status=500)
return JsonResponse({"query_id": status.id}, status=202)
- # Degraded mode: the cell still runs over the inline (Redis) transport, clamped at
- # the async row ceiling, instead of hard-failing. Loud on purpose.
- FRAME_STORE_FALLBACK_COUNTER.inc()
- logger.warning(
- "notebook_frame_store_fallback_inline",
- notebook_short_id=notebook_short_id,
- team_id=team_id,
- frame_store_enabled=settings.NOTEBOOKS_FRAME_STORE_ENABLED,
- object_storage_enabled=settings.OBJECT_STORAGE_ENABLED,
- )
+ if frame_store_configured:
+ # The environment is provisioned but this user is outside the rollout, which is
+ # the expected state for most users while the flag ramps. Counted, not logged:
+ # at warning level this would drown the misconfiguration case below.
+ FRAME_STORE_FALLBACK_COUNTER.labels(reason="not_in_rollout").inc()
+ else:
+ # Degraded mode: the cell still runs over the inline (Redis) transport, clamped
+ # at the async row ceiling, instead of hard-failing. Loud on purpose.
+ FRAME_STORE_FALLBACK_COUNTER.labels(reason="not_configured").inc()
+ logger.warning(
+ "notebook_frame_store_fallback_inline",
+ notebook_short_id=notebook_short_id,
+ team_id=team_id,
+ frame_store_enabled=settings.NOTEBOOKS_FRAME_STORE_ENABLED,
+ object_storage_enabled=settings.OBJECT_STORAGE_ENABLED,
+ )
try:
with tags_context(product=Product.NOTEBOOKS, feature=Feature.QUERY, team_id=team.id):
diff --git a/products/notebooks/backend/sql_v2_frame_store.md b/products/notebooks/backend/sql_v2_frame_store.md
index 402e9d701bef..26d7541b8a2b 100644
--- a/products/notebooks/backend/sql_v2_frame_store.md
+++ b/products/notebooks/backend/sql_v2_frame_store.md
@@ -1,7 +1,7 @@
# SQLV2 frame materialization via object storage
Design notes for moving python-node frame materialization off the Redis JSON transport and onto an object-storage handoff.
-Status: **phase 1 shipped** (env-gated by `NOTEBOOKS_FRAME_STORE_ENABLED`, default off) — object delivery at a 500k row tier-1 ceiling (`MAX_SELECT_NOTEBOOK_MATERIALIZE_LIMIT`); the inline path remains as the degraded fallback, still clamped at 50k. Phases 2+ not started.
+Status: **phase 1 shipped** (env-gated by `NOTEBOOKS_FRAME_STORE_ENABLED`, default off, **and** per-user by the `notebooks-frame-store` feature flag) — object delivery at a 500k row tier-1 ceiling (`MAX_SELECT_NOTEBOOK_MATERIALIZE_LIMIT`); the inline path remains as the degraded fallback, still clamped at 50k. Phases 2+ not started.
## Problem
@@ -196,6 +196,17 @@ ClickHouse error from `system.query_log` — a confirmed query-side exception is
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).
+_Two gates, both required (`sql_v2_data_plane.py`):_ `NOTEBOOKS_FRAME_STORE_ENABLED` says the deployment can
+serve objects at all, and the `notebooks-frame-store` feature flag says a given user is in the rollout.
+Failing either one degrades that request to the inline transport and its 50k clamp, so the environment
+setting can be enabled estate-wide while the flag stays targeted at a handful of users. 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 only needs
+`NOTEBOOKS_FRAME_STORE_ENABLED=1` on the web and worker processes to exercise the object path.
+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 cannot serve objects and should be near zero once provisioned.
+
_Rollout prerequisites (per environment, before flipping the flag on):_
- Enable `NOTEBOOKS_FRAME_STORE_ENABLED` only **after** both the web and general-purpose Temporal worker
diff --git a/products/notebooks/backend/test/test_sql_v2.py b/products/notebooks/backend/test/test_sql_v2.py
index 1eee105f1a39..22949ae76899 100644
--- a/products/notebooks/backend/test/test_sql_v2.py
+++ b/products/notebooks/backend/test/test_sql_v2.py
@@ -1603,6 +1603,12 @@ class TestSQLV2DataPlaneEndpoint(APIBaseTest):
def setUp(self):
super().setUp()
self.notebook = Notebook.objects.create(team=self.team, short_id="nbdp001")
+ # Object delivery needs the deployment setting and a per-user rollout flag. These
+ # cases exercise the transport, so put the user in the rollout; the fallback case
+ # below overrides this to cover the other side.
+ rollout = patch("products.notebooks.backend.sql_v2_data_plane.is_frame_store_enabled", return_value=True)
+ rollout.start()
+ self.addCleanup(rollout.stop)
def _post(self, body: dict, token: str | None = None):
kwargs: dict[str, Any] = {"data": json.dumps(body), "content_type": "application/json"}
@@ -1690,14 +1696,30 @@ class TestSQLV2DataPlaneEndpoint(APIBaseTest):
self.assertEqual(columns, ["number", "uid"])
self.assertEqual(rows[0][1], frame_uuid) # a string, not 16 bytes
- def test_object_delivery_falls_back_to_inline_when_frame_store_disabled(self):
- # Degraded mode: object storage off must not hard-fail the cell — the inline
- # (Redis) path still serves the frame, clamped at the async ceiling.
- with self.settings(NOTEBOOKS_FRAME_STORE_ENABLED=False):
- response = self._run_to_completion({"query": "select number from numbers(3)", "delivery": "object"})
- self.assertEqual(response.status_code, 200, response.content)
- _columns, rows, _types = decode_arrow_stream(response.content)
- self.assertEqual(len(rows), 3)
+ @parameterized.expand(
+ [
+ ("frame_store_disabled", False, True),
+ ("user_not_in_rollout", True, False),
+ ]
+ )
+ def test_object_delivery_falls_back_to_inline(self, _name, frame_store_enabled, in_rollout):
+ # Either gate failing must degrade to the inline (Redis) path rather than hard-fail
+ # the cell, and must write no object. The rollout case is the one that matters for
+ # the flag: dropping that check would put every user's frames on object storage.
+ from posthog.storage import object_storage
+
+ from products.notebooks.backend import frame_store
+
+ with self.settings(NOTEBOOKS_FRAME_STORE_ENABLED=frame_store_enabled, OBJECT_STORAGE_ENABLED=True):
+ with patch(
+ "products.notebooks.backend.sql_v2_data_plane.is_frame_store_enabled",
+ return_value=in_rollout,
+ ):
+ response = self._run_to_completion({"query": "select number from numbers(3)", "delivery": "object"})
+ self.assertEqual(response.status_code, 200, response.content)
+ _columns, rows, _types = decode_arrow_stream(response.content)
+ self.assertEqual(len(rows), 3)
+ self.assertIsNone(object_storage.list_objects(frame_store.team_prefix(self.team.id)))
def test_object_delivery_failure_surfaces_error_and_stores_no_object(self):
# An upload failure must reach the kernel as an error status, and no (partial or