: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
fix(tasks): propagate credential refresh cancellation (#108351)
Alessandro Pogliaghi273c5b26839b
diff --git a/docs/internal/sandboxes-setup-guide.md b/docs/internal/sandboxes-setup-guide.mdindex d00892d39355..eacd9d3f8643 100644--- a/docs/internal/sandboxes-setup-guide.md+++ b/docs/internal/sandboxes-setup-guide.md@@ -112,6 +112,9 @@ orchestrates these activities:The activities live in`products/tasks/backend/temporal/process_task/activities/`.+Credential refresh runs in the background. For workflow histories with the `tasks-credential-refresh-propagate-cancel` patch, cancellation stops the loop even during an in-flight refresh activity.+Other refresh failures retry on the default cadence.+## Running via the UIThis is very minimal at the moment, but the tasks page can be used to see whatdiff --git a/products/tasks/backend/temporal/process_task/credential_refresh.py b/products/tasks/backend/temporal/process_task/credential_refresh.pyindex 9a4ff0c2ffa9..d22fcf2a5aff 100644--- a/products/tasks/backend/temporal/process_task/credential_refresh.py+++ b/products/tasks/backend/temporal/process_task/credential_refresh.py@@ -4,6 +4,7 @@ from enum import StrEnumfrom temporalio import workflowfrom temporalio.common import RetryPolicy+from temporalio.exceptions import is_cancelled_exceptionfrom products.tasks.backend.temporal.constants import CREDENTIAL_REFRESH_INITIAL_DELAY@@ -68,6 +69,8 @@ async def run_credential_refresh_loop(return CredentialRefreshExitReason.CREDENTIALS_UNAVAILABLEnext_refresh_seconds = result.next_refresh_secondsexcept Exception as e:+ if is_cancelled_exception(e) and workflow.patched("tasks-credential-refresh-propagate-cancel"):+ raise# Non-fatal: keep the run alive and retry on the default cadence.workflow.logger.warning(f"Sandbox credential refresh failed (non-fatal): {e}")next_refresh_seconds = CREDENTIAL_REFRESH_INITIAL_DELAY.total_seconds()diff --git a/products/tasks/backend/temporal/process_task/tests/test_credential_refresh.py b/products/tasks/backend/temporal/process_task/tests/test_credential_refresh.pyindex ee1be31a2601..d0a471782ac5 100644--- a/products/tasks/backend/temporal/process_task/tests/test_credential_refresh.py+++ b/products/tasks/backend/temporal/process_task/tests/test_credential_refresh.py@@ -1,5 +1,10 @@+import asyncio++import pytestfrom unittest.mock import AsyncMock, MagicMock+from temporalio.exceptions import ActivityError, CancelledError+from products.tasks.backend.temporal.process_task import credential_refresh as credential_refresh_modulefrom products.tasks.backend.temporal.process_task.activities.refresh_sandbox_credentials import (RefreshSandboxCredentialsOutput,@@ -16,6 +21,64 @@ class TestRunCredentialRefreshLoop:monkeypatch.setattr(credential_refresh_module.workflow, "sleep", AsyncMock())monkeypatch.setattr(credential_refresh_module.workflow, "logger", MagicMock())+ @pytest.mark.parametrize("patched", [True, False])+ async def test_cancel_during_activity_propagates_only_for_patched_histories(+ self, monkeypatch: pytest.MonkeyPatch, patched: bool+ ) -> None:+ activity_started = asyncio.Event()+ cancelled = ActivityError(+ "Activity cancelled",+ scheduled_event_id=1,+ started_event_id=2,+ identity="test-worker",+ activity_type="refresh_sandbox_credentials",+ activity_id="refresh",+ retry_state=None,+ )+ cancelled.__cause__ = CancelledError()++ async def blocked_activity(*args: object, **kwargs: object) -> RefreshSandboxCredentialsOutput:+ activity_started.set()+ try:+ await asyncio.Future()+ except asyncio.CancelledError:+ raise cancelled+ raise AssertionError("Activity must be cancelled")++ execute_activity = AsyncMock(side_effect=blocked_activity)+ self._patch_workflow(monkeypatch, execute_activity)+ patch = MagicMock(return_value=patched)+ monkeypatch.setattr(credential_refresh_module.workflow, "patched", patch)+ task = asyncio.create_task(run_credential_refresh_loop(MagicMock(), "sb-1"))+ await activity_started.wait()+ execute_activity.side_effect = None+ execute_activity.return_value = RefreshSandboxCredentialsOutput(+ next_refresh_seconds=1.0, refreshed_kinds=[], sandbox_gone=True+ )+ task.cancel()++ if patched:+ with pytest.raises(ActivityError) as error:+ await task+ assert error.value is cancelled+ assert execute_activity.await_count == 1+ else:+ assert await task == CredentialRefreshExitReason.SANDBOX_GONE+ assert execute_activity.await_count == 2+ patch.assert_called_once_with("tasks-credential-refresh-propagate-cancel")++ async def test_non_cancellation_failure_retries(self, monkeypatch: pytest.MonkeyPatch) -> None:+ execute_activity = AsyncMock(+ side_effect=[+ RuntimeError("Refresh temporarily unavailable"),+ RefreshSandboxCredentialsOutput(next_refresh_seconds=1.0, refreshed_kinds=[], sandbox_gone=True),+ ]+ )+ self._patch_workflow(monkeypatch, execute_activity)++ assert await run_credential_refresh_loop(MagicMock(), "sb-1") == CredentialRefreshExitReason.SANDBOX_GONE+ assert execute_activity.await_count == 2+async def test_orphaned_kinds_are_excluded_next_cycle_and_loop_stops(self, monkeypatch):execute_activity = AsyncMock(side_effect=[diff --git a/products/tasks/backend/temporal/process_task/tests/test_workflow.py b/products/tasks/backend/temporal/process_task/tests/test_workflow.pyindex 2ad5feefb7ea..afe6031b4953 100644--- a/products/tasks/backend/temporal/process_task/tests/test_workflow.py+++ b/products/tasks/backend/temporal/process_task/tests/test_workflow.py@@ -34,7 +34,10 @@ from products.tasks.backend.temporal.constants import (SANDBOX_TTL_SNAPSHOT_LEAD,WARM_IDLE_TIMEOUT,)-from products.tasks.backend.temporal.process_task import workflow as process_task_workflow_module+from products.tasks.backend.temporal.process_task import (+ credential_refresh as credential_refresh_module,+ workflow as process_task_workflow_module,+)from products.tasks.backend.temporal.process_task.activities import (STEER_DECLINED_OUTCOME,CleanupSandboxInput,@@ -72,6 +75,11 @@ from products.tasks.backend.temporal.process_task.activities import ()from products.tasks.backend.temporal.process_task.activities.create_resume_snapshot import CreateResumeSnapshotOutputfrom products.tasks.backend.temporal.process_task.activities.emit_progress_activity import EmitProgressInput+from products.tasks.backend.temporal.process_task.activities.refresh_sandbox_credentials import (+ RefreshSandboxCredentialsInput,+ RefreshSandboxCredentialsOutput,+ refresh_sandbox_credentials,+)from products.tasks.backend.temporal.process_task.activities.send_followup_to_sandbox import SendFollowupToSandboxInputfrom products.tasks.backend.temporal.process_task.activities.update_task_run_status import (SANDBOX_GONE_STATE_KEY,@@ -239,10 +247,19 @@ class TestProcessTaskWorkflow:signal_status: str = "completed",signal_error: str | None = None,create_pr: bool = True,+ cancel_during_refresh: bool = False,) -> ProcessTaskOutput:workflow_id = str(uuid.uuid4())workflow_input = ProcessTaskInput(run_id=str(run_id), create_pr=create_pr)ready = asyncio.Event()+ refresh_started = asyncio.Event()++ @activity.defn(name="refresh_sandbox_credentials")+ async def refresh_and_observe(input: RefreshSandboxCredentialsInput) -> RefreshSandboxCredentialsOutput:+ if cancel_during_refresh:+ refresh_started.set()+ await asyncio.Future()+ return await refresh_sandbox_credentials(input)@activity.defn(name="start_agent_server")async def start_and_observe(input: StartAgentServerInput) -> StartAgentServerOutput:@@ -278,6 +295,7 @@ class TestProcessTaskWorkflow:complete_run_stream,track_workflow_event,update_task_run_status,+ refresh_and_observe,],workflow_runner=UnsandboxedWorkflowRunner(),activity_executor=ThreadPoolExecutor(max_workers=10),@@ -301,13 +319,17 @@ class TestProcessTaskWorkflow:if result_task in done:raise AssertionError(f"Workflow finished before completion signal: {result_task.result()}")assert ready_task in done, "Agent did not become ready"+ if cancel_during_refresh:+ await asyncio.wait_for(refresh_started.wait(), timeout=30)await handle.signal(ProcessTaskWorkflow.complete_task, args=[signal_status, signal_error])- result = await result_task+ result = await asyncio.wait_for(asyncio.shield(result_task), timeout=60)finally:ready_task.cancel()await asyncio.gather(ready_task, return_exceptions=True)if not result_task.done():await handle.cancel()+ await asyncio.wait({result_task}, timeout=30)+ result_task.cancel()await asyncio.gather(result_task, return_exceptions=True)return result@@ -338,15 +360,32 @@ class TestProcessTaskWorkflow:if sandbox:sandbox.destroy()- @pytest.mark.parametrize("signal_status,signal_error", [("completed", None), ("failed", "Test error")])+ @pytest.mark.parametrize(+ "signal_status,signal_error,cancel_during_refresh",+ [("completed", None, False), ("failed", "Test error", False), ("completed", None, True)],+ )async def test_workflow_starts_agent_handles_signal_and_cleans_up(- self, test_task_run, github_integration, sandbox_task_api, assert_sandbox_shutdown, signal_status, signal_error+ self,+ test_task_run,+ github_integration,+ sandbox_task_api,+ assert_sandbox_shutdown,+ signal_status,+ signal_error,+ cancel_during_refresh,+ monkeypatch,):+ if cancel_during_refresh:+ monkeypatch.setattr(credential_refresh_module, "CREDENTIAL_REFRESH_INITIAL_DELAY", timedelta(seconds=0))snapshot = await sync_to_async(self._create_test_snapshot)(github_integration)try:result = await self._run_workflow_with_signal(- test_task_run.id, sandbox_task_api, signal_status, signal_error+ test_task_run.id,+ sandbox_task_api,+ signal_status,+ signal_error,+ cancel_during_refresh=cancel_during_refresh,)assert result.success is True