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(tasks): retry relay_sandbox_events across worker restarts (#67711)

Alessandro Pogliaghi48c3730f47f5
diff --git a/products/tasks/backend/temporal/execute_sandbox/workflow.py b/products/tasks/backend/temporal/execute_sandbox/workflow.py
index 0e62a96e7ba7..c2deac20dce8 100644
--- a/products/tasks/backend/temporal/execute_sandbox/workflow.py
+++ b/products/tasks/backend/temporal/execute_sandbox/workflow.py
@@ -1116,8 +1116,23 @@ class ExecuteSandboxWorkflow(PostHogWorkflow):
sandbox_id=sandbox_id,
),
start_to_close_timeout=RELAY_SANDBOX_EVENTS_START_TO_CLOSE_TIMEOUT,
+ schedule_to_close_timeout=RELAY_SANDBOX_EVENTS_START_TO_CLOSE_TIMEOUT,
heartbeat_timeout=timedelta(minutes=2),
- retry_policy=RetryPolicy(maximum_attempts=1),
+ # A worker restart (deploy, eviction) kills the in-flight attempt while
+ # the sandbox agent keeps working — without retries the event stream is
+ # orphaned for good and the run looks dead to the user. Retrying is safe:
+ # the agent server buffers events while no relay is attached and replays
+ # them on reconnect. Terminal conditions (sandbox gone, reconnect budget
+ # exhausted) return cleanly, and application-level failures that write an
+ # error sentinel to the stream raise non-retryable ApplicationError, so
+ # retries only cover attempt-level deaths where no sentinel was written;
+ # schedule_to_close bounds the total.
+ retry_policy=RetryPolicy(
+ initial_interval=timedelta(seconds=5),
+ maximum_interval=timedelta(minutes=1),
+ maximum_attempts=0,
+ non_retryable_error_types=["ValueError"],
+ ),
cancellation_type=workflow.ActivityCancellationType.TRY_CANCEL,
)
diff --git a/products/tasks/backend/temporal/process_task/activities/relay_sandbox_events.py b/products/tasks/backend/temporal/process_task/activities/relay_sandbox_events.py
index 8f2798a0bc58..6a589932824f 100644
--- a/products/tasks/backend/temporal/process_task/activities/relay_sandbox_events.py
+++ b/products/tasks/backend/temporal/process_task/activities/relay_sandbox_events.py
@@ -11,6 +11,7 @@ import httpx_sse
import structlog
import temporalio.client
from temporalio import activity
+from temporalio.exceptions import ApplicationError
from posthog.temporal.common.utils import close_db_connections
@@ -143,7 +144,11 @@ async def relay_sandbox_events(input: RelaySandboxEventsInput) -> None:
return
logger.exception("relay_sandbox_events_failed", run_id=input.run_id, error=str(e))
await redis_stream.mark_error(str(e)[:500])
- raise
+ # The stream now carries an error sentinel — a retried attempt would
+ # append events past it that disconnected consumers never see. Fail
+ # the activity for good; retries are reserved for attempt-level
+ # deaths (worker restart), where no sentinel was written.
+ raise ApplicationError(str(e), non_retryable=True) from e
except Exception as e:
try:
marked_complete = await _mark_error_unless_run_is_terminal(redis_stream, input.run_id, str(e))
@@ -169,7 +174,9 @@ async def relay_sandbox_events(input: RelaySandboxEventsInput) -> None:
logger.info("relay_sandbox_events_stopped_after_terminal_run", run_id=input.run_id, error=str(e))
else:
logger.exception("relay_sandbox_events_failed", run_id=input.run_id, error=str(e))
- raise
+ # A complete/error sentinel was written above (or attempted) — same
+ # reasoning as the RuntimeError path: don't retry past a sentinel.
+ raise ApplicationError(str(e), non_retryable=True) from e
async def _mark_error_unless_run_is_terminal(
diff --git a/products/tasks/backend/temporal/process_task/activities/tests/test_relay_sandbox_events.py b/products/tasks/backend/temporal/process_task/activities/tests/test_relay_sandbox_events.py
index 94aa323ee75e..0fac5751bd78 100644
--- a/products/tasks/backend/temporal/process_task/activities/tests/test_relay_sandbox_events.py
+++ b/products/tasks/backend/temporal/process_task/activities/tests/test_relay_sandbox_events.py
@@ -10,6 +10,7 @@ from unittest.mock import AsyncMock
import httpx
import httpx_sse
from parameterized import parameterized
+from temporalio.exceptions import ApplicationError
from products.tasks.backend.temporal.process_task import workflow as process_task_workflow_module
from products.tasks.backend.temporal.process_task.activities.get_task_processing_context import TaskProcessingContext
@@ -603,7 +604,7 @@ class TestRelaySandboxEventsErrorHandling:
fake_mark_error_unless_run_is_terminal,
)
- with pytest.raises(RuntimeError, match="relay error"):
+ with pytest.raises(ApplicationError, match="relay error") as exc_info:
await relay_sandbox_events(
RelaySandboxEventsInput(
run_id="run-id",
@@ -615,6 +616,10 @@ class TestRelaySandboxEventsErrorHandling:
)
)
+ # An error sentinel was written to the stream, so the failure must be
+ # non-retryable — a retried attempt would append events past the
+ # sentinel that disconnected consumers never see.
+ assert exc_info.value.non_retryable is True
redis_stream.mark_complete.assert_not_awaited()
redis_stream.mark_error.assert_awaited_once_with("relay error")
diff --git a/products/tasks/backend/temporal/process_task/workflow.py b/products/tasks/backend/temporal/process_task/workflow.py
index 615f109acee8..849c375c4bbf 100644
--- a/products/tasks/backend/temporal/process_task/workflow.py
+++ b/products/tasks/backend/temporal/process_task/workflow.py
@@ -1067,8 +1067,23 @@ class ProcessTaskWorkflow(PostHogWorkflow):
relay_sandbox_events,
relay_input,
start_to_close_timeout=RELAY_SANDBOX_EVENTS_START_TO_CLOSE_TIMEOUT,
+ schedule_to_close_timeout=RELAY_SANDBOX_EVENTS_START_TO_CLOSE_TIMEOUT,
heartbeat_timeout=timedelta(minutes=2),
- retry_policy=RetryPolicy(maximum_attempts=1),
+ # A worker restart (deploy, eviction) kills the in-flight attempt while
+ # the sandbox agent keeps working — without retries the event stream is
+ # orphaned for good and the run looks dead to the user. Retrying is safe:
+ # the agent server buffers events while no relay is attached and replays
+ # them on reconnect. Terminal conditions (sandbox gone, reconnect budget
+ # exhausted) return cleanly, and application-level failures that write an
+ # error sentinel to the stream raise non-retryable ApplicationError, so
+ # retries only cover attempt-level deaths where no sentinel was written;
+ # schedule_to_close bounds the total.
+ retry_policy=RetryPolicy(
+ initial_interval=timedelta(seconds=5),
+ maximum_interval=timedelta(minutes=1),
+ maximum_attempts=0,
+ non_retryable_error_types=["ValueError"],
+ ),
cancellation_type=workflow.ActivityCancellationType.TRY_CANCEL,
)
except asyncio.CancelledError: