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.

fix(notebooks): cap frame materialize retries at 3 attempts (#81754)

Sinan Kucukkoselerce0cbc26f7f3
diff --git a/products/notebooks/backend/temporal/frame_materialize.py b/products/notebooks/backend/temporal/frame_materialize.py
index f24aa3905d48..ee3955027da7 100644
--- a/products/notebooks/backend/temporal/frame_materialize.py
+++ b/products/notebooks/backend/temporal/frame_materialize.py
@@ -900,7 +900,7 @@ def materialize_frame(inputs: FrameMaterializeInputs) -> str:
# Post-write verification failed: the object is missing or predates this write
# (see stat_frame). Retryable — a transient object-store blip should re-run — but
# log it, because a deterministic cause (CH wrote to a store the app can't read,
- # endpoint/bucket skew) would otherwise re-scan the whale silently up to 10 times.
+ # endpoint/bucket skew) would otherwise re-scan the whale silently on every attempt.
logger.warning(
"notebook_frame_materialize_object_unverified",
team_id=inputs.team_id,
@@ -1004,14 +1004,18 @@ class NotebookFrameMaterializeWorkflow(PostHogWorkflow):
# the job fails with a clear error instead of piling onto ClickHouse.
schedule_to_close_timeout=dt.timedelta(minutes=10),
retry_policy=common.RetryPolicy(
- initial_interval=dt.timedelta(seconds=1),
+ # Slot exhaustion raises before the activity touches ClickHouse, so this
+ # backoff is the only queue a blocked job gets. The intervals are wide
+ # enough that a job blocked behind a short frame still gets a turn inside
+ # the small attempt budget below.
+ initial_interval=dt.timedelta(seconds=5),
backoff_coefficient=2.0,
- maximum_interval=dt.timedelta(seconds=10),
- # Bound the storm: a deterministically-failing heavy query (e.g. a
- # mid-stream resource overrun that can't be caught up front) must not
- # re-execute for the full schedule_to_close window. Matches the Celery
- # async path's max_retries=10.
- maximum_attempts=10,
+ maximum_interval=dt.timedelta(seconds=30),
+ # Bound the storm. A transient failure re-runs the entire scan on either
+ # transport, and schedule_to_close only caps that for queries slow enough to
+ # fill the window, so a fast query could otherwise repeat its scan on every
+ # attempt. The deterministic failures are already non-retryable in the activity.
+ maximum_attempts=3,
),
)
except Exception:
diff --git a/products/notebooks/backend/test/test_frame_materialize.py b/products/notebooks/backend/test/test_frame_materialize.py
index d1b084960339..e5bb1c069899 100644
--- a/products/notebooks/backend/test/test_frame_materialize.py
+++ b/products/notebooks/backend/test/test_frame_materialize.py
@@ -2,13 +2,17 @@ import io
import uuid
from types import SimpleNamespace
+import pytest
from posthog.test.base import APIBaseTest
from unittest.mock import patch
from django.conf import settings
from parameterized import parameterized
-from temporalio import exceptions
+from temporalio import activity, exceptions
+from temporalio.client import WorkflowFailureError
+from temporalio.testing import WorkflowEnvironment
+from temporalio.worker import UnsandboxedWorkflowRunner, Worker
from posthog.schema import QueryStatus
@@ -311,7 +315,7 @@ class TestFrameMaterializeCHWrites(APIBaseTest):
[
# Budget failures sync_execute rewraps as APIException subclasses (NOT
# InternalCHQueryError) — the case the earlier hand-built InternalCHQueryError
- # masked. Must be terminal, else the canonical whale failures retry 10x.
+ # masked. Must be terminal, else the canonical whale failures re-scan on every retry.
("memory_wrapped", _per_query_memory_error(), True, "materialization limits"),
# "(total)" / "(for user)" memory pressure: the cluster was busy, not this query too
# big, so the same query can succeed on retry. Finalizing it would both waste the
@@ -386,3 +390,57 @@ class TestFrameMaterializeCHWrites(APIBaseTest):
status = manager.get_query_status()
self.assertTrue(status.complete and status.error)
self.assertIn("too large", status.error_message or "")
+
+
+async def test_exhausted_retries_stop_at_three_scans_and_finalize_the_status():
+ # A transient tear leaves the activity retryable, so nothing in the activity itself ends
+ # the job. Two things have to hold at the workflow level: the scan repeats a bounded
+ # number of times (each attempt re-runs the whole ClickHouse query), and the run still
+ # reaches a terminal state. Without the second one the kernel polls a never-completing
+ # status until its own deadline and reports a timeout instead of the real error.
+ attempts = 0
+ marked_failed = False
+
+ @activity.defn(name="notebook-frame-materialize")
+ async def tear_every_attempt(inputs: frame_materialize.FrameMaterializeInputs) -> str:
+ nonlocal attempts
+ attempts += 1
+ raise ObjectStorageError("stream torn mid-upload")
+
+ @activity.defn(name="notebook-frame-materialize-mark-failed")
+ async def mark_failed(inputs: frame_materialize.FrameMaterializeInputs) -> None:
+ nonlocal marked_failed
+ marked_failed = True
+
+ inputs = frame_materialize.FrameMaterializeInputs(
+ query_id="fm-retry-cap",
+ team_id=1,
+ notebook_short_id="nbfm001",
+ user_id=1,
+ query="select 1",
+ query_hash="abc123",
+ cache_key="notebook-frame:1:abc123",
+ )
+ task_queue = str(uuid.uuid4())
+
+ # Time skipping fast-forwards the retry backoff, so the policy's real intervals cost the
+ # suite nothing.
+ async with await WorkflowEnvironment.start_time_skipping() as env:
+ async with Worker(
+ env.client,
+ task_queue=task_queue,
+ workflows=[frame_materialize.NotebookFrameMaterializeWorkflow],
+ activities=[tear_every_attempt, mark_failed],
+ workflow_runner=UnsandboxedWorkflowRunner(),
+ ):
+ with pytest.raises(WorkflowFailureError):
+ await env.client.execute_workflow(
+ frame_materialize.NotebookFrameMaterializeWorkflow.run,
+ inputs,
+ id=str(uuid.uuid4()),
+ task_queue=task_queue,
+ )
+
+ assert attempts == 3
+ assert marked_failed