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): stop team deletion orphaning live task workflows (#74047)

Fernando Gomes93f2ed0fbad5
diff --git a/posthog/test/setup_receivers_baseline.txt b/posthog/test/setup_receivers_baseline.txt
index 064889f27351..60d7e2ebddf8 100644
--- a/posthog/test/setup_receivers_baseline.txt
+++ b/posthog/test/setup_receivers_baseline.txt
@@ -213,6 +213,7 @@ pre_delete:posthog.storage.team_llm_gateway_policy_signal_handlers._clear_cache_
pre_delete:products.alerts.backend.activity_logging.cleanup_alert_hog_functions
pre_delete:products.alerts.backend.activity_logging.handle_alert_subscription_delete
pre_delete:products.managed_migrations.backend.activity_logging.handle_batch_import_delete
+pre_delete:products.tasks.backend.team_deletion.cancel_task_workflows_on_team_delete
pre_save:posthog.models.event_ingestion_restriction_config.capture_old_restriction_type
pre_save:posthog.models.organization.organization_about_to_be_created
pre_save:posthog.models.organization.organization_membership_saved
diff --git a/products/tasks/backend/apps.py b/products/tasks/backend/apps.py
index 9450313294d2..a57e25eab2fd 100644
--- a/products/tasks/backend/apps.py
+++ b/products/tasks/backend/apps.py
@@ -7,7 +7,7 @@ class TasksConfig(AppConfig):
label = "tasks"
def ready(self):
- # Activity-log receivers live in their own import-light module so every
+ # Signal receivers live in their own import-light modules so every
# process type (celery, temporal, migrate) wires them without pulling
# the viewset import graph into django.setup().
- from products.tasks.backend import activity_logging # noqa: F401, PLC0415
+ from products.tasks.backend import activity_logging, team_deletion # noqa: F401, PLC0415
diff --git a/products/tasks/backend/team_deletion.py b/products/tasks/backend/team_deletion.py
new file mode 100644
index 000000000000..7e6af8a66041
--- /dev/null
+++ b/products/tasks/backend/team_deletion.py
@@ -0,0 +1,122 @@
+"""Team-deletion handling for tasks: stop live workflows before their rows cascade away.
+
+``Task.team`` and ``TaskRun.team`` are ``on_delete=CASCADE``, and Django's deletion collector
+deletes related rows directly instead of calling each instance's ``delete()``, so the model-level
+delete guards never run for a team/project/organization delete. The rows vanish while any running
+``process_task``/``execute_sandbox`` workflow keeps executing against them.
+
+Stopping is a cancel, not a terminate. A terminate ends the execution without running any workflow
+code, so the teardown that reaps the Modal sandbox and completes the run stream is skipped, and the
+``SandboxSession``/``SandboxEnvironment`` rows that would let anything else reap the sandbox are
+cascade-deleted in the same transaction. Both workflows handle ``asyncio.CancelledError`` by
+tearing the sandbox down, so cancelling is what actually frees the compute. A workflow that never
+acts on the cancel is left to its own inactivity timeout, which is the accepted cost of not leaking
+a sandbox in the normal case.
+
+Kept in a module with no temporalio or API imports so ``AppConfig.ready()`` can wire the receiver
+in every process type (celery, temporal, migrate) without dragging the Temporal SDK onto the
+``django.setup()`` import path.
+"""
+
+import logging
+from datetime import timedelta
+from typing import Any
+
+from django.db import transaction
+from django.db.models.signals import pre_delete
+from django.dispatch import receiver
+
+from posthog.models.team.team import Team
+
+from products.tasks.backend.models import TaskRun
+
+logger = logging.getLogger(__name__)
+
+_NON_TERMINAL_TASK_RUN_STATUSES = (TaskRun.Status.NOT_STARTED, TaskRun.Status.QUEUED, TaskRun.Status.IN_PROGRESS)
+
+# ``TaskRun.workflow_id`` is the orchestrator's id. ``execute_sandbox`` runs under a sibling id and
+# is started as an independent top-level execution rather than a Temporal child, so cancelling the
+# orchestrator does not reach it. ``TaskManagementWorkflow.run`` derives the same suffix.
+_SANDBOX_WORKFLOW_ID_SUFFIX = "-sandbox"
+
+# Per-call cap plus a cap on the whole sweep. The on-commit callback runs in-band with the delete,
+# which for a real team delete is `delete_team_records_activity` under a 10-minute start-to-close
+# timeout, so a hung Temporal frontend must not be able to burn that budget.
+_CANCEL_RPC_TIMEOUT = timedelta(seconds=10)
+_CANCEL_TOTAL_TIMEOUT_SECONDS = 60.0
+
+
+@receiver(pre_delete, sender=Team)
+def cancel_task_workflows_on_team_delete(sender: type[Team], instance: Team, **kwargs: Any) -> None:
+ """Request cancellation of the team's live task workflows before its rows are collected.
+
+ Django sends every ``pre_delete`` before it issues any delete, so the runs are still readable
+ here. The cancel calls are deferred to ``on_commit`` so a rolled-back delete cancels nothing
+ and the Temporal round-trips stay outside the delete transaction. Best-effort throughout: a
+ Temporal failure must never block the deletion.
+ """
+ team_id = instance.pk
+ workflows = [
+ (str(run.id), run.workflow_id)
+ for run in TaskRun.objects.filter(team_id=team_id, status__in=_NON_TERMINAL_TASK_RUN_STATUSES).only(
+ "id", "task_id", "state"
+ )
+ ]
+ if not workflows:
+ return
+
+ transaction.on_commit(lambda: cancel_task_workflows(team_id, workflows))
+
+
+def cancel_task_workflows(team_id: int, workflows: list[tuple[str, str]]) -> None:
+ """Cancel the workflows behind each ``(run_id, workflow_id)`` pair, swallowing Temporal errors."""
+ import asyncio # noqa: PLC0415 - only needed when there is something to cancel
+
+ from temporalio.service import ( # noqa: PLC0415 - keeps the Temporal SDK off the django.setup() import path
+ RPCError,
+ RPCStatusCode,
+ )
+
+ from posthog.temporal.common.client import sync_connect # noqa: PLC0415 - same
+
+ try:
+ client = sync_connect()
+ except Exception:
+ logger.exception(
+ "tasks_team_delete_temporal_connect_failed",
+ extra={"team_id": team_id, "run_count": len(workflows)},
+ )
+ return
+
+ async def cancel_all() -> None:
+ # One event loop drives the whole sweep, so the client is never used across loops.
+ for run_id, workflow_id in workflows:
+ for target_id in (workflow_id, f"{workflow_id}{_SANDBOX_WORKFLOW_ID_SUFFIX}"):
+ try:
+ await client.get_workflow_handle(target_id).cancel(rpc_timeout=_CANCEL_RPC_TIMEOUT)
+ except RPCError as error:
+ # NOT_FOUND covers "never started" and "already finished", which is also the
+ # normal outcome for the sandbox id on a run that has no sandbox workflow.
+ if error.status != RPCStatusCode.NOT_FOUND:
+ logger.exception(
+ "tasks_team_delete_workflow_cancel_failed",
+ extra={"team_id": team_id, "run_id": run_id, "workflow_id": target_id},
+ )
+ except Exception:
+ logger.exception(
+ "tasks_team_delete_workflow_cancel_failed",
+ extra={"team_id": team_id, "run_id": run_id, "workflow_id": target_id},
+ )
+
+ try:
+ asyncio.run(asyncio.wait_for(cancel_all(), _CANCEL_TOTAL_TIMEOUT_SECONDS))
+ except TimeoutError:
+ logger.warning(
+ "tasks_team_delete_workflow_cancel_timed_out",
+ extra={"team_id": team_id, "run_count": len(workflows)},
+ )
+ except Exception:
+ logger.exception(
+ "tasks_team_delete_workflow_cancel_sweep_failed",
+ extra={"team_id": team_id, "run_count": len(workflows)},
+ )
diff --git a/products/tasks/backend/temporal/execute_sandbox/tests/test_execute_sandbox_workflow.py b/products/tasks/backend/temporal/execute_sandbox/tests/test_execute_sandbox_workflow.py
index 445ef22e8ee7..6e265187b743 100644
--- a/products/tasks/backend/temporal/execute_sandbox/tests/test_execute_sandbox_workflow.py
+++ b/products/tasks/backend/temporal/execute_sandbox/tests/test_execute_sandbox_workflow.py
@@ -31,7 +31,10 @@ from products.tasks.backend.temporal.process_task.activities.get_sandbox_for_rep
from products.tasks.backend.temporal.process_task.activities.get_task_processing_context import TaskProcessingContext
from products.tasks.backend.temporal.process_task.activities.send_followup_to_sandbox import STEER_DECLINED_OUTCOME
from products.tasks.backend.temporal.process_task.activities.start_agent_server import StartAgentServerOutput
-from products.tasks.backend.temporal.process_task.credential_refresh import CredentialRefreshExitReason
+from products.tasks.backend.temporal.process_task.credential_refresh import (
+ TASK_ROWS_GONE_ERROR_MESSAGE,
+ CredentialRefreshExitReason,
+)
def _build_context(
@@ -752,6 +755,23 @@ class TestRun:
sandbox_id="sandbox-123",
)
+ async def test_credential_refresh_task_gone_marks_the_run_failed(self, monkeypatch, silent_workflow_logger):
+ # An interactive run is exempt from the terminal status write on its normal
+ # completion path, so without this the workflow would report success for a run
+ # whose rows were deleted underneath it.
+ workflow = ExecuteSandboxWorkflow()
+ workflow._context = _build_context()
+ refresh_loop_mock = AsyncMock(return_value=CredentialRefreshExitReason.TASK_GONE)
+
+ monkeypatch.setattr(execute_sandbox_workflow_module, "run_credential_refresh_loop", refresh_loop_mock)
+
+ await workflow._run_credential_refresh_until_sandbox_gone("sandbox-123")
+
+ assert workflow._sandbox_gone is True
+ assert workflow._completion_status == "failed"
+ assert workflow._completion_error == TASK_ROWS_GONE_ERROR_MESSAGE
+ assert workflow._completion_error_type == "TaskRunDeletedError"
+
async def test_credential_refresh_credentials_unavailable_does_not_mark_sandbox_gone(
self, monkeypatch, silent_workflow_logger
):
diff --git a/products/tasks/backend/temporal/execute_sandbox/workflow.py b/products/tasks/backend/temporal/execute_sandbox/workflow.py
index 8fc1ff6b5e8f..e9407467dcaf 100644
--- a/products/tasks/backend/temporal/execute_sandbox/workflow.py
+++ b/products/tasks/backend/temporal/execute_sandbox/workflow.py
@@ -102,6 +102,7 @@ from products.tasks.backend.temporal.process_task.activities.update_task_run_sta
update_task_run_status,
)
from products.tasks.backend.temporal.process_task.credential_refresh import (
+ TASK_ROWS_GONE_ERROR_MESSAGE,
CredentialRefreshExitReason,
run_credential_refresh_loop,
)
@@ -1353,6 +1354,23 @@ class ExecuteSandboxWorkflow(PostHogWorkflow):
run_id=self.context.run_id,
sandbox_id=sandbox_id,
)
+ elif exit_reason == CredentialRefreshExitReason.TASK_GONE:
+ workflow.logger.warning(
+ "execute_sandbox_task_rows_gone_detected",
+ run_id=self.context.run_id,
+ sandbox_id=sandbox_id,
+ )
+ # Ends the main loop through the sandbox-gone event so the workflow winds down
+ # instead of waiting on signals that can never arrive. Recording failure here is
+ # what makes the end visible: an interactive run is exempt from the terminal
+ # status write on its normal completion path, so without this it would report
+ # success for a run whose rows no longer exist. The write itself then fails
+ # non-retryably, since those rows are gone, which fails the workflow in both
+ # modes rather than only for background runs.
+ self._completion_status = "failed"
+ self._completion_error = TASK_ROWS_GONE_ERROR_MESSAGE
+ self._completion_error_type = "TaskRunDeletedError"
+ self._sandbox_gone = True
def _mark_sandbox_gone(self) -> None:
self._task_completed = True
diff --git a/products/tasks/backend/temporal/process_task/activities/forward_pending_message.py b/products/tasks/backend/temporal/process_task/activities/forward_pending_message.py
index b7e334e99ccb..94c06b35747a 100644
--- a/products/tasks/backend/temporal/process_task/activities/forward_pending_message.py
+++ b/products/tasks/backend/temporal/process_task/activities/forward_pending_message.py
@@ -68,8 +68,15 @@ def forward_pending_user_message(run_id: str) -> None:
try:
task_run = TaskRun.objects.select_related("task__created_by", "task__team").get(id=run_id)
except TaskRun.DoesNotExist:
+ # The run existed when this workflow started, so a missing row means it was
+ # hard-deleted mid-run (team/org deletion cascade). Fail the workflow rather
+ # than letting the agent session run on with no rows to report into.
logger.warning("forward_pending_message_run_not_found", run_id=run_id)
- return
+ raise ApplicationError(
+ f"TaskRun {run_id} no longer exists; cannot forward the pending user message",
+ non_retryable=True,
+ type="TaskRunDeletedError",
+ )
retryable_delivery_error: str | None = None
diff --git a/products/tasks/backend/temporal/process_task/activities/refresh_sandbox_credentials.py b/products/tasks/backend/temporal/process_task/activities/refresh_sandbox_credentials.py
index a15d61618158..f94e5b16c520 100644
--- a/products/tasks/backend/temporal/process_task/activities/refresh_sandbox_credentials.py
+++ b/products/tasks/backend/temporal/process_task/activities/refresh_sandbox_credentials.py
@@ -5,12 +5,7 @@ from temporalio import activity
from posthog.temporal.common.logger import get_logger
from posthog.temporal.common.utils import asyncify, retry_on_db_connection_drop
-from products.tasks.backend.exceptions import (
- CredentialUnavailableError,
- SandboxNotFoundError,
- SandboxNotRunningError,
- TaskNotFoundError,
-)
+from products.tasks.backend.exceptions import CredentialUnavailableError, SandboxNotFoundError, SandboxNotRunningError
from products.tasks.backend.logic.services.agent_command import send_refresh_session
from products.tasks.backend.logic.services.connection_token import create_sandbox_connection_token
from products.tasks.backend.logic.services.sandbox import Sandbox
@@ -72,6 +67,10 @@ class RefreshSandboxCredentialsOutput:
sandbox_gone: bool = False
orphaned_kinds: list[str] = field(default_factory=list)
no_credentials_left: bool = False
+ # Task rows were hard-deleted mid-run (team deletion cascade); the loop should stop.
+ # A flag rather than an error so old histories (which decode the missing field as
+ # False) replay unchanged, per the workflow-versioning rules.
+ task_gone: bool = False
@activity.defn
@@ -103,8 +102,16 @@ def refresh_sandbox_credentials(input: RefreshSandboxCredentialsInput) -> Refres
id=ctx.task_id
)
)
- except Task.DoesNotExist as e:
- raise TaskNotFoundError(f"Task {ctx.task_id} not found", {"task_id": ctx.task_id}, cause=e)
+ except Task.DoesNotExist:
+ logger.info(
+ "sandbox_credentials_refresh_stopped_task_gone",
+ sandbox_id=input.sandbox_id,
+ run_id=ctx.run_id,
+ task_id=ctx.task_id,
+ )
+ return RefreshSandboxCredentialsOutput(
+ next_refresh_seconds=DEFAULT_REFRESH_INTERVAL_SECONDS, refreshed_kinds=[], task_gone=True
+ )
refreshed_kinds: list[str] = []
orphaned_kinds: list[str] = []
diff --git a/products/tasks/backend/temporal/process_task/activities/tests/test_refresh_sandbox_credentials.py b/products/tasks/backend/temporal/process_task/activities/tests/test_refresh_sandbox_credentials.py
index 4448b1c44bd5..ac4d1c68024a 100644
--- a/products/tasks/backend/temporal/process_task/activities/tests/test_refresh_sandbox_credentials.py
+++ b/products/tasks/backend/temporal/process_task/activities/tests/test_refresh_sandbox_credentials.py
@@ -1,3 +1,6 @@
+import uuid
+import dataclasses
+
import pytest
from unittest.mock import MagicMock, patch
@@ -143,6 +146,23 @@ class TestRefreshSandboxCredentialsActivity:
sandbox.execute.assert_not_called()
increment.assert_called_once_with("github", "skipped")
+ def test_missing_task_returns_task_gone_flag(self, activity_environment, task_context, test_task, sandbox):
+ # Rows hard-deleted mid-run (team deletion cascade) must surface as an output
+ # flag the refresh loop stops on, not as an error the loop swallows and retries.
+ context = dataclasses.replace(task_context, task_id=str(uuid.uuid4()))
+ with patch(
+ "products.tasks.backend.temporal.process_task.activities.refresh_sandbox_credentials.Sandbox.get_by_id",
+ return_value=sandbox,
+ ):
+ output = async_to_sync(activity_environment.run)(
+ refresh_sandbox_credentials,
+ RefreshSandboxCredentialsInput(context=context, sandbox_id="sandbox-abc"),
+ )
+
+ assert output.task_gone is True
+ assert output.refreshed_kinds == []
+ sandbox.execute.assert_not_called()
+
def test_skips_refresh_when_sandbox_gone(self, activity_environment, task_context, test_task):
# A reaped/unreachable sandbox surfaces as SandboxNotFoundError from get_by_id.
# The refresh must skip gracefully rather than fail the activity (which would
diff --git a/products/tasks/backend/temporal/process_task/activities/tests/test_update_task_run_status.py b/products/tasks/backend/temporal/process_task/activities/tests/test_update_task_run_status.py
index 45b61d284a20..6557eddf4e93 100644
--- a/products/tasks/backend/temporal/process_task/activities/tests/test_update_task_run_status.py
+++ b/products/tasks/backend/temporal/process_task/activities/tests/test_update_task_run_status.py
@@ -2,6 +2,7 @@ import pytest
from unittest.mock import patch
from asgiref.sync import async_to_sync
+from temporalio.exceptions import ApplicationError
from products.tasks.backend.models import Loop, TaskRun
from products.tasks.backend.temporal.process_task.activities.update_task_run_status import (
@@ -201,13 +202,17 @@ class TestUpdateTaskRunStatusActivity:
assert loop.last_run_at is not None
@pytest.mark.django_db(transaction=True)
- def test_handles_non_existent_task_run(self, activity_environment):
+ def test_missing_task_run_raises_non_retryable(self, activity_environment):
+ # Rows hard-deleted mid-run (team deletion cascade) must fail the workflow fast,
+ # not be swallowed as a successful status write.
non_existent_run_id = "550e8400-e29b-41d4-a716-446655440000"
input_data = UpdateTaskRunStatusInput(
run_id=non_existent_run_id,
status=TaskRun.Status.IN_PROGRESS,
)
- async_to_sync(activity_environment.run)(update_task_run_status, input_data)
+ with pytest.raises(ApplicationError) as exc_info:
+ async_to_sync(activity_environment.run)(update_task_run_status, input_data)
+ assert exc_info.value.non_retryable is True
@pytest.mark.django_db(transaction=True)
@pytest.mark.parametrize(
diff --git a/products/tasks/backend/temporal/process_task/activities/update_task_run_status.py b/products/tasks/backend/temporal/process_task/activities/update_task_run_status.py
index 3e2e86eb1c20..3646f6abc184 100644
--- a/products/tasks/backend/temporal/process_task/activities/update_task_run_status.py
+++ b/products/tasks/backend/temporal/process_task/activities/update_task_run_status.py
@@ -5,6 +5,7 @@ from django.db import transaction
from django.utils import timezone
from temporalio import activity
+from temporalio.exceptions import ApplicationError
from posthog.temporal.common.utils import asyncify
@@ -85,8 +86,14 @@ def update_task_run_status(input: UpdateTaskRunStatusInput) -> None:
task_run.completed_at = timezone.now()
task_run.save(update_fields=["status", "error_message", "completed_at", "updated_at"])
except TaskRun.DoesNotExist:
- activity.logger.warning(f"TaskRun {input.run_id} not found for status update")
- return
+ # The row was hard-deleted mid-run (team/org deletion cascades bypass the model
+ # delete() guards). Nothing can ever terminalize this run again, so fail the
+ # workflow instead of letting it run on believing the status was written.
+ raise ApplicationError(
+ f"TaskRun {input.run_id} no longer exists; its rows were deleted while the workflow was running",
+ non_retryable=True,
+ type="TaskRunDeletedError",
+ )
# Side effects run after commit, outside the row lock (repo convention: no side effects in atomic).
task_run.publish_stream_state_event()
diff --git a/products/tasks/backend/temporal/process_task/credential_refresh.py b/products/tasks/backend/temporal/process_task/credential_refresh.py
index dee92113925c..fee290caa219 100644
--- a/products/tasks/backend/temporal/process_task/credential_refresh.py
+++ b/products/tasks/backend/temporal/process_task/credential_refresh.py
@@ -13,9 +13,11 @@ from .activities.refresh_sandbox_credentials import RefreshSandboxCredentialsInp
class CredentialRefreshExitReason(StrEnum):
SANDBOX_GONE = "sandbox_gone"
CREDENTIALS_UNAVAILABLE = "credentials_unavailable"
+ TASK_GONE = "task_gone"
SANDBOX_GONE_ERROR_MESSAGE = "Sandbox stopped; resume to continue"
+TASK_ROWS_GONE_ERROR_MESSAGE = "Task records were deleted while the run was in progress"
async def run_credential_refresh_loop(context: TaskProcessingContext, sandbox_id: str) -> CredentialRefreshExitReason:
@@ -39,6 +41,9 @@ async def run_credential_refresh_loop(context: TaskProcessingContext, sandbox_id
start_to_close_timeout=timedelta(minutes=2),
retry_policy=RetryPolicy(maximum_attempts=2),
)
+ if result.task_gone:
+ workflow.logger.warning("Stopping credential refresh loop: task rows are gone")
+ return CredentialRefreshExitReason.TASK_GONE
if result.sandbox_gone:
workflow.logger.info("Stopping credential refresh loop: sandbox is gone")
return CredentialRefreshExitReason.SANDBOX_GONE
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.py
index 4e687bb79e7c..b4cfd738e19c 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
@@ -34,6 +34,20 @@ class TestRunCredentialRefreshLoop:
second_input = execute_activity.await_args_list[1].args[1]
assert second_input.exclude_kinds == ["github"]
+ async def test_task_gone_stops_loop(self, monkeypatch):
+ # Without this exit the loop would spin forever against rows a team deletion removed.
+ execute_activity = AsyncMock(
+ side_effect=[
+ RefreshSandboxCredentialsOutput(next_refresh_seconds=1.0, refreshed_kinds=[], task_gone=True),
+ ]
+ )
+ self._patch_workflow(monkeypatch, execute_activity)
+
+ exit_reason = await run_credential_refresh_loop(MagicMock(), "sb-1")
+
+ assert exit_reason == CredentialRefreshExitReason.TASK_GONE
+ assert execute_activity.await_count == 1
+
async def test_sandbox_gone_still_wins_over_orphaned_kinds(self, monkeypatch):
execute_activity = AsyncMock(
side_effect=[
diff --git a/products/tasks/backend/temporal/process_task/tests/test_forward_pending_message.py b/products/tasks/backend/temporal/process_task/tests/test_forward_pending_message.py
index 75441e4e1082..2801fe007305 100644
--- a/products/tasks/backend/temporal/process_task/tests/test_forward_pending_message.py
+++ b/products/tasks/backend/temporal/process_task/tests/test_forward_pending_message.py
@@ -89,6 +89,13 @@ class TestForwardPendingUserMessage(TestCase):
run.refresh_from_db()
assert run.state == {"mode": "background"}
+ def test_missing_run_raises_non_retryable(self):
+ # A run deleted mid-run (team deletion cascade) must fail the workflow at the
+ # first forward, not leave the agent session running headless.
+ with self.assertRaises(ApplicationError) as ctx:
+ forward_pending_user_message("550e8400-e29b-41d4-a716-446655440000")
+ assert ctx.exception.non_retryable is True
+
@patch("products.tasks.backend.logic.services.connection_token.create_sandbox_connection_token", return_value="jwt")
@patch("products.tasks.backend.logic.services.agent_command.send_user_message")
def test_pending_message_delivered_successfully(self, mock_send, mock_token):
diff --git a/products/tasks/backend/temporal/process_task/tests/test_workflow.py b/products/tasks/backend/temporal/process_task/tests/test_workflow.py
index 2863f388bd95..8311562dc6b1 100644
--- a/products/tasks/backend/temporal/process_task/tests/test_workflow.py
+++ b/products/tasks/backend/temporal/process_task/tests/test_workflow.py
@@ -13,6 +13,7 @@ from django.conf import settings
from asgiref.sync import sync_to_async
from parameterized import parameterized
+from temporalio.client import WorkflowFailureError
from temporalio.common import RetryPolicy
from temporalio.exceptions import ActivityError, ApplicationError, RetryState
from temporalio.testing import WorkflowEnvironment
@@ -291,17 +292,28 @@ class TestProcessTaskWorkflow:
activity_executor=ThreadPoolExecutor(max_workers=10),
),
):
- result = await env.client.execute_workflow(
- ProcessTaskWorkflow.run,
- workflow_input,
- id=workflow_id,
- task_queue=settings.TASKS_TASK_QUEUE,
- retry_policy=RetryPolicy(maximum_attempts=1),
- execution_timeout=timedelta(minutes=60),
- )
+ # The run row does not exist, so the terminal status write raises
+ # TaskRunDeletedError and the workflow fails rather than returning a result. A
+ # workflow with no row left to update has nowhere to record an outcome, so
+ # failing is the only way its end is visible.
+ with pytest.raises(WorkflowFailureError) as failure:
+ await env.client.execute_workflow(
+ ProcessTaskWorkflow.run,
+ workflow_input,
+ id=workflow_id,
+ task_queue=settings.TASKS_TASK_QUEUE,
+ retry_policy=RetryPolicy(maximum_attempts=1),
+ execution_timeout=timedelta(minutes=60),
+ )
- assert result.success is False
- assert result.error is not None
+ # `WorkflowFailureError` carries only a generic message; the reason is in the cause
+ # chain, so assert there rather than on `str(failure.value)`.
+ causes = []
+ error: BaseException | None = failure.value
+ while error is not None:
+ causes.append(str(error))
+ error = error.__cause__
+ assert any("no longer exists" in cause or "not found" in cause for cause in causes), causes
class TestProcessTaskFollowupDispatch:
diff --git a/products/tasks/backend/temporal/process_task/workflow.py b/products/tasks/backend/temporal/process_task/workflow.py
index c2f31312be09..5568554ecb72 100644
--- a/products/tasks/backend/temporal/process_task/workflow.py
+++ b/products/tasks/backend/temporal/process_task/workflow.py
@@ -1706,6 +1706,15 @@ class ProcessTaskWorkflow(PostHogWorkflow):
"credential_refresh_stopped_credentials_unavailable",
extra={"run_id": self.context.run_id, "sandbox_id": sandbox_id},
)
+ elif exit_reason == CredentialRefreshExitReason.TASK_GONE:
+ workflow.logger.warning(
+ "task_rows_gone_detected",
+ extra={"run_id": self.context.run_id, "sandbox_id": sandbox_id},
+ )
+ # Ends the main loop through the sandbox-gone event; the status update on that
+ # path then fails non-retryably (the rows are gone), failing the workflow instead
+ # of leaving it waiting on signals that can never arrive.
+ self._sandbox_gone = True
def _mark_sandbox_gone(self) -> None:
self._completion_status = "completed"
diff --git a/products/tasks/backend/tests/test_team_deletion.py b/products/tasks/backend/tests/test_team_deletion.py
new file mode 100644
index 000000000000..4544908fb178
--- /dev/null
+++ b/products/tasks/backend/tests/test_team_deletion.py
@@ -0,0 +1,118 @@
+from unittest.mock import AsyncMock, MagicMock, patch
+
+from django.test import TestCase
+
+from temporalio.service import RPCError, RPCStatusCode
+
+from posthog.models import Organization, Team, User
+
+from products.tasks.backend.models import Task, TaskRun
+
+MODULE = "products.tasks.backend.team_deletion"
+
+
+def _cancellable_client() -> tuple[MagicMock, AsyncMock]:
+ cancel = AsyncMock()
+ handle = MagicMock()
+ handle.cancel = cancel
+ client = MagicMock()
+ client.get_workflow_handle.return_value = handle
+ return client, cancel
+
+
+class TestCancelTaskWorkflowsOnTeamDelete(TestCase):
+ def setUp(self):
+ self.organization = Organization.objects.create(name="Test Org")
+ self.team = Team.objects.create(organization=self.organization, name="Test Team")
+ self.user = User.objects.create_user(
+ email="[email protected]", first_name="Owner", password="password"
+ )
+
+ def _run(self, status: str) -> TaskRun:
+ task = Task.objects.create(
+ team=self.team,
+ created_by=self.user,
+ title="Fix the flake",
+ description="d",
+ origin_product=Task.OriginProduct.USER_CREATED,
+ )
+ return TaskRun.objects.create(task=task, team=self.team, status=status)
+
+ def test_deleting_a_team_stops_only_its_live_run_workflows(self):
+ # The rows are collected by CASCADE without ever calling TaskRun.delete(), so the
+ # workflow IDs have to be captured in pre_delete or they are unrecoverable.
+ live = self._run(TaskRun.Status.IN_PROGRESS)
+ queued = self._run(TaskRun.Status.QUEUED)
+ self._run(TaskRun.Status.COMPLETED)
+ team_id = self.team.pk
+
+ with patch(f"{MODULE}.cancel_task_workflows") as cancel_workflows:
+ with self.captureOnCommitCallbacks(execute=True):
+ self.team.delete()
+
+ cancel_workflows.assert_called_once()
+ called_team_id, workflows = cancel_workflows.call_args.args
+ self.assertEqual(called_team_id, team_id)
+ self.assertEqual(
+ dict(workflows),
+ {str(live.id): live.workflow_id, str(queued.id): queued.workflow_id},
+ )
+
+ def test_no_temporal_call_when_the_team_has_no_live_runs(self):
+ self._run(TaskRun.Status.CANCELLED)
+
+ with patch(f"{MODULE}.cancel_task_workflows") as cancel_workflows:
+ with self.captureOnCommitCallbacks(execute=True):
+ self.team.delete()
+
+ cancel_workflows.assert_not_called()
+
+ def test_both_the_orchestrator_and_its_sandbox_workflow_are_cancelled(self):
+ # execute_sandbox is started as an independent top-level execution, so cancelling the
+ # orchestrator alone would leave the workflow holding the Modal sandbox running.
+ run = self._run(TaskRun.Status.IN_PROGRESS)
+ client, cancel = _cancellable_client()
+
+ with patch("posthog.temporal.common.client.sync_connect", return_value=client):
+ with self.captureOnCommitCallbacks(execute=True):
+ self.team.delete()
+
+ self.assertEqual(
+ [call.args[0] for call in client.get_workflow_handle.call_args_list],
+ [run.workflow_id, f"{run.workflow_id}-sandbox"],
+ )
+ # Cancel rather than terminate: only the workflow's own cancellation path reaps the
+ # sandbox, and the rows that would let anything else reap it are already gone.
+ self.assertEqual(cancel.await_count, 2)
+ # Every call is bounded, so an unreachable frontend cannot burn the caller's budget.
+ self.assertTrue(all(call.kwargs.get("rpc_timeout") for call in cancel.await_args_list))
+
+ def test_a_missing_workflow_is_not_reported_as_a_failure(self):
+ # NOT_FOUND is the normal outcome for a run that never started a sandbox workflow.
+ self._run(TaskRun.Status.IN_PROGRESS)
+ client, cancel = _cancellable_client()
+ cancel.side_effect = RPCError("no such workflow", RPCStatusCode.NOT_FOUND, b"")
+
+ with patch("posthog.temporal.common.client.sync_connect", return_value=client):
+ with self.assertNoLogs(MODULE, level="ERROR"):
+ with self.captureOnCommitCallbacks(execute=True):
+ self.team.delete()
+
+ self.assertEqual(cancel.await_count, 2)
+
+ def test_temporal_failures_never_block_the_delete(self):
+ run = self._run(TaskRun.Status.IN_PROGRESS)
+ team_id = self.team.pk
+ client = MagicMock()
+ client.get_workflow_handle.side_effect = RuntimeError("temporal unreachable")
+
+ with patch("posthog.temporal.common.client.sync_connect", return_value=client):
+ with self.captureOnCommitCallbacks(execute=True):
+ self.team.delete()
+
+ self.assertEqual(
+ [call.args[0] for call in client.get_workflow_handle.call_args_list],
+ [run.workflow_id, f"{run.workflow_id}-sandbox"],
+ )
+ self.assertFalse(Team.objects.filter(pk=team_id).exists())
+ self.assertFalse(TaskRun.objects.filter(id=run.id).exists())