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): block sandbox execution for pending deletions (#104444)

Alessandro Pogliaghi3e3eab89fa88
diff --git a/products/tasks/backend/exceptions.py b/products/tasks/backend/exceptions.py
index b4a8df8ccfba..ba5234103326 100644
--- a/products/tasks/backend/exceptions.py
+++ b/products/tasks/backend/exceptions.py
@@ -103,6 +103,11 @@ class TaskInvalidStateError(ProcessTaskFatalError):
pass
+class OrganizationExecutionError(ProcessTaskError):
+ def __init__(self, message: str, team_id: int, reason: str) -> None:
+ super().__init__(message, {"team_id": team_id, "reason": reason}, None, capture=False, non_retryable=True)
+
+
class SandboxProvisionError(ProcessTaskTransientError):
"""Failed to provision sandbox environment."""
diff --git a/products/tasks/backend/facade/api.py b/products/tasks/backend/facade/api.py
index 21d1f859734f..4706f6ae503a 100644
--- a/products/tasks/backend/facade/api.py
+++ b/products/tasks/backend/facade/api.py
@@ -6604,6 +6604,10 @@ def create_task(
)
warm_run = None
if warm_run is not None:
+ if Team.objects.filter(id=team_id, organization__is_pending_deletion=True).exists():
+ raise PermissionDenied(
+ "This organization is scheduled for deletion. Select another organization to run tasks."
+ )
_warm_retry_message_id(warm_retry_token, warm_run)
warm_task = warm_run.task
should_set_client_provenance = warm_task.client_provenance is None and client_provenance is not None
diff --git a/products/tasks/backend/temporal/execute_sandbox/activities/reap_orphaned_sandbox.py b/products/tasks/backend/temporal/execute_sandbox/activities/reap_orphaned_sandbox.py
index 4a472779c4ad..08b4c336b2a3 100644
--- a/products/tasks/backend/temporal/execute_sandbox/activities/reap_orphaned_sandbox.py
+++ b/products/tasks/backend/temporal/execute_sandbox/activities/reap_orphaned_sandbox.py
@@ -92,5 +92,5 @@ def reap_orphaned_sandbox(input: ReapOrphanedSandboxInput) -> ReapOrphanedSandbo
cpu_usage_measured_at=cpu_usage_measured_at,
)
- TaskRun.update_state_atomic(input.run_id, remove_keys=[SANDBOX_ID_STATE_KEY])
+ TaskRun.clear_sandbox_connection_state_atomic(input.run_id, sandbox_id)
return ReapOrphanedSandboxResult(reaped_sandbox_id=sandbox_id, destroy_succeeded=destroy_succeeded)
diff --git a/products/tasks/backend/temporal/execute_sandbox/activities/sandbox_state.py b/products/tasks/backend/temporal/execute_sandbox/activities/sandbox_state.py
index ad176d0b7d50..703c5adfd381 100644
--- a/products/tasks/backend/temporal/execute_sandbox/activities/sandbox_state.py
+++ b/products/tasks/backend/temporal/execute_sandbox/activities/sandbox_state.py
@@ -16,6 +16,7 @@ from dataclasses import dataclass
from temporalio import activity
+from posthog.dataclasses import frozen
from posthog.temporal.common.utils import asyncify
from products.tasks.backend.models import TaskRun
@@ -30,9 +31,10 @@ class PersistSandboxIdInput:
sandbox_id: str
-@dataclass
+@frozen
class ClearPersistedSandboxIdInput:
run_id: str
+ sandbox_id: str | None = None
@activity.defn
@@ -65,4 +67,7 @@ def clear_persisted_sandbox_id(input: ClearPersistedSandboxIdInput) -> None:
"clear_persisted_sandbox_id",
run_id=input.run_id,
):
- TaskRun.update_state_atomic(input.run_id, remove_keys=[SANDBOX_ID_STATE_KEY])
+ if input.sandbox_id is not None:
+ TaskRun.clear_sandbox_connection_state_atomic(input.run_id, input.sandbox_id)
+ else:
+ TaskRun.update_state_atomic(input.run_id, remove_keys=[SANDBOX_ID_STATE_KEY])
diff --git a/products/tasks/backend/temporal/execute_sandbox/activities/tests/test_reap_orphaned_sandbox.py b/products/tasks/backend/temporal/execute_sandbox/activities/tests/test_reap_orphaned_sandbox.py
index 1d92544d2aa1..e7914abb6ddd 100644
--- a/products/tasks/backend/temporal/execute_sandbox/activities/tests/test_reap_orphaned_sandbox.py
+++ b/products/tasks/backend/temporal/execute_sandbox/activities/tests/test_reap_orphaned_sandbox.py
@@ -5,6 +5,7 @@ from unittest.mock import ANY, Mock, patch
from asgiref.sync import async_to_sync
+from products.tasks.backend.models import TaskRun
from products.tasks.backend.temporal.execute_sandbox.activities.reap_orphaned_sandbox import (
ReapOrphanedSandboxInput,
reap_orphaned_sandbox,
@@ -60,12 +61,23 @@ class TestReapOrphanedSandbox:
assert result.reaped_sandbox_id is None
sandbox_cls.return_value.get_by_id.assert_not_called()
- def test_destroys_and_clears_when_persisted_id_present(self, activity_environment, test_task_run):
- test_task_run.state = {SANDBOX_ID_STATE_KEY: "sb-orphan", "mode": "background"}
+ @pytest.mark.parametrize("replacement", [False, True])
+ def test_destroys_and_clears_when_persisted_id_present(self, activity_environment, test_task_run, replacement):
+ connection = {
+ SANDBOX_ID_STATE_KEY: "sb-orphan",
+ "sandbox_url": "https://sandbox.example.com/rpc",
+ "sandbox_connect_token": "fake-token",
+ "sandbox_jwt_kid": "fake-kid",
+ "sandbox_backend": "modal",
+ }
+ test_task_run.state = {**connection, "mode": "background"}
test_task_run.save(update_fields=["state"])
with patch(SANDBOX_IMPORT_PATH) as sandbox_cls:
destroy_mock = Mock()
+ if replacement:
+ connection[SANDBOX_ID_STATE_KEY] = "sb-replacement"
+ destroy_mock.side_effect = lambda: TaskRun.update_state_atomic(test_task_run.id, updates=connection)
sandbox_cls.return_value.get_by_id.return_value = Mock(destroy=destroy_mock)
result = async_to_sync(activity_environment.run)(
@@ -80,8 +92,7 @@ class TestReapOrphanedSandbox:
test_task_run.refresh_from_db()
# State key is cleared; other keys preserved.
- assert SANDBOX_ID_STATE_KEY not in test_task_run.state
- assert test_task_run.state == {"mode": "background"}
+ assert test_task_run.state == ({**connection, "mode": "background"} if replacement else {"mode": "background"})
def test_records_cpu_usage_before_destroy(self, activity_environment, test_task_run):
test_task_run.state = {SANDBOX_ID_STATE_KEY: "sb-orphan"}
diff --git a/products/tasks/backend/temporal/execute_sandbox/activities/tests/test_sandbox_state.py b/products/tasks/backend/temporal/execute_sandbox/activities/tests/test_sandbox_state.py
index 7b1905f497bc..97a95f849acd 100644
--- a/products/tasks/backend/temporal/execute_sandbox/activities/tests/test_sandbox_state.py
+++ b/products/tasks/backend/temporal/execute_sandbox/activities/tests/test_sandbox_state.py
@@ -55,18 +55,29 @@ class TestPersistSandboxId:
@pytest.mark.requires_secrets
@pytest.mark.django_db(transaction=True)
class TestClearPersistedSandboxId:
- def test_removes_sandbox_id_key(self, activity_environment, test_task_run):
- test_task_run.state = {SANDBOX_ID_STATE_KEY: "sb-123", "mode": "background"}
+ @pytest.mark.parametrize("sandbox_id", [None, "sb-123", "sb-replaced"])
+ def test_removes_sandbox_id_key(self, activity_environment, test_task_run, sandbox_id):
+ connection = {
+ "sandbox_url": "https://sandbox.example.com/rpc",
+ "sandbox_connect_token": "fake-token",
+ "sandbox_jwt_kid": "fake-kid",
+ "sandbox_backend": "modal",
+ }
+ test_task_run.state = {**connection, SANDBOX_ID_STATE_KEY: "sb-123", "mode": "background"}
test_task_run.save(update_fields=["state"])
async_to_sync(activity_environment.run)(
clear_persisted_sandbox_id,
- ClearPersistedSandboxIdInput(run_id=str(test_task_run.id)),
+ ClearPersistedSandboxIdInput(run_id=str(test_task_run.id), sandbox_id=sandbox_id),
)
test_task_run.refresh_from_db()
- assert SANDBOX_ID_STATE_KEY not in test_task_run.state
- assert test_task_run.state == {"mode": "background"}
+ expected_state = {"mode": "background"}
+ if sandbox_id != "sb-123":
+ expected_state.update(connection)
+ if sandbox_id == "sb-replaced":
+ expected_state[SANDBOX_ID_STATE_KEY] = "sb-123"
+ assert test_task_run.state == expected_state
def test_noop_when_key_absent(self, activity_environment, test_task_run):
test_task_run.state = {"mode": "background"}
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 c4c28d0ad3ec..bc5e7f01d7b7 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
@@ -12,6 +12,10 @@ from products.tasks.backend.temporal.execute_sandbox.activities.reap_orphaned_sa
ReapOrphanedSandboxResult,
reap_orphaned_sandbox,
)
+from products.tasks.backend.temporal.execute_sandbox.activities.sandbox_state import (
+ ClearPersistedSandboxIdInput,
+ clear_persisted_sandbox_id,
+)
from products.tasks.backend.temporal.execute_sandbox.workflow import (
PARENT_ACK_SIGNAL,
PARENT_ATTACHED_SIGNAL,
@@ -25,6 +29,7 @@ from products.tasks.backend.temporal.execute_sandbox.workflow import (
PendingFollowup,
SandboxEvent,
)
+from products.tasks.backend.temporal.process_task.activities.cleanup_sandbox import CleanupSandboxInput, cleanup_sandbox
from products.tasks.backend.temporal.process_task.activities.get_sandbox_for_repository import (
GetSandboxForRepositoryOutput,
)
@@ -817,7 +822,7 @@ class TestRun:
use_modal_resume_snapshots=use_modal_resume_snapshots,
)
update_status_mock = AsyncMock()
- cleanup_sandbox_mock = AsyncMock()
+ execute_activity_mock = AsyncMock()
create_resume_snapshot_mock = AsyncMock()
monkeypatch.setattr(workflow, "_reap_orphaned_sandbox", AsyncMock())
@@ -827,9 +832,8 @@ class TestRun:
monkeypatch.setattr(workflow, "_track_workflow_event", AsyncMock())
monkeypatch.setattr(workflow, "_persist_sandbox_id", AsyncMock())
monkeypatch.setattr(workflow, "_read_sandbox_logs", AsyncMock())
- monkeypatch.setattr(workflow, "_cleanup_sandbox", cleanup_sandbox_mock)
+ monkeypatch.setattr(execute_sandbox_workflow_module.workflow, "execute_activity", execute_activity_mock)
monkeypatch.setattr(workflow, "_create_resume_snapshot", create_resume_snapshot_mock)
- monkeypatch.setattr(workflow, "_clear_persisted_sandbox_id", AsyncMock())
monkeypatch.setattr(workflow, "_flush_all_pending_outbound", AsyncMock())
monkeypatch.setattr(workflow, "_relay_sandbox_events", AsyncMock())
monkeypatch.setattr(workflow, "_run_credential_refresh_until_sandbox_gone", AsyncMock())
@@ -866,7 +870,11 @@ class TestRun:
call for call in update_status_mock.await_args_list if call.args[:1] in (("failed",), ("cancelled",))
]
assert terminal_status_writes == []
- cleanup_sandbox_mock.assert_awaited_once_with("sandbox-123")
+ activity_inputs = {call.args[0]: call.args[1] for call in execute_activity_mock.await_args_list}
+ assert activity_inputs[cleanup_sandbox] == CleanupSandboxInput(sandbox_id="sandbox-123", run_id="run-id")
+ assert activity_inputs[clear_persisted_sandbox_id] == ClearPersistedSandboxIdInput(
+ run_id="run-id", sandbox_id="sandbox-123"
+ )
completed_signals = [
outbound for outbound in workflow._pending_outbound if outbound.target_signal == PARENT_COMPLETED_SIGNAL
]
@@ -1275,11 +1283,33 @@ class TestCompletionStatusOnExceptionPaths:
assert isinstance(payload, ChildCompletionPayload)
assert payload.success is False
- async def test_exception_run_signals_success_false_with_failed_marker(self, monkeypatch, silent_workflow_logger):
+ @pytest.mark.parametrize("organization_denied", [False, True])
+ async def test_exception_run_signals_success_false_with_failed_marker(
+ self, monkeypatch, silent_workflow_logger, organization_denied
+ ):
workflow = ExecuteSandboxWorkflow()
- get_context_mock = AsyncMock(side_effect=RuntimeError("db down"))
+ message = (
+ "This organization is scheduled for deletion. Select another organization to run tasks."
+ if organization_denied
+ else "db down"
+ )
+ error_type = "OrganizationExecutionError" if organization_denied else "RuntimeError"
+ error: Exception = RuntimeError(message)
+ if organization_denied:
+ error = ActivityError(
+ "Activity task failed",
+ scheduled_event_id=1,
+ started_event_id=2,
+ identity="worker-1",
+ activity_type="start_agent_server",
+ activity_id="activity-1",
+ retry_state=RetryState.NON_RETRYABLE_FAILURE,
+ )
+ error.__cause__ = ApplicationError(message, type=error_type, non_retryable=True)
+ get_context_mock = AsyncMock(side_effect=error)
+ update_status_mock = AsyncMock()
monkeypatch.setattr(workflow, "_get_task_processing_context", get_context_mock)
- monkeypatch.setattr(workflow, "_update_task_run_status", AsyncMock())
+ monkeypatch.setattr(workflow, "_update_task_run_status", update_status_mock)
monkeypatch.setattr(workflow, "_track_workflow_event", AsyncMock())
monkeypatch.setattr(workflow, "_reap_orphaned_sandbox", AsyncMock())
monkeypatch.setattr(workflow, "_flush_all_pending_outbound", AsyncMock())
@@ -1288,7 +1318,9 @@ class TestCompletionStatusOnExceptionPaths:
assert result.success is False
assert workflow._completion_status == "failed"
- assert workflow._completion_error == "db down"
+ assert result.error == message
+ assert workflow._completion_error == message
+ update_status_mock.assert_awaited_with("failed", error_message=message, run_id="run-id", error_type=error_type)
completed_signals = [
outbound for outbound in workflow._pending_outbound if outbound.target_signal == PARENT_COMPLETED_SIGNAL
]
@@ -1296,4 +1328,4 @@ class TestCompletionStatusOnExceptionPaths:
payload = completed_signals[0].args[0]
assert isinstance(payload, ChildCompletionPayload)
assert payload.success is False
- assert payload.error == "db down"
+ assert payload.error == message
diff --git a/products/tasks/backend/temporal/execute_sandbox/workflow.py b/products/tasks/backend/temporal/execute_sandbox/workflow.py
index c9d28e5d5a5b..14e223d13a43 100644
--- a/products/tasks/backend/temporal/execute_sandbox/workflow.py
+++ b/products/tasks/backend/temporal/execute_sandbox/workflow.py
@@ -602,9 +602,16 @@ class ExecuteSandboxWorkflow(PostHogWorkflow):
# setting it here the orchestrator would see `success=True` for
# a run that died on an unhandled exception.
self._completion_status = "failed"
- self._completion_error = truncate_error_message(str(e))
+ cause = e.cause if isinstance(e, temporalio.exceptions.ActivityError) else e
+ cause_message = getattr(cause, "message", None) or (str(cause) if cause is not None else str(e))
+ error_type = (
+ cause.type
+ if isinstance(cause, temporalio.exceptions.ApplicationError) and cause.type
+ else type(e).__name__
+ )
+ error_message = truncate_error_message(cause_message)
+ self._completion_error = error_message
current_sandbox_id = sandbox_id or self._sandbox_id_for_cleanup
- error_message = truncate_error_message(str(e))
if self._context:
if self._current_progress_step is not None:
failed_step, failed_label, failed_group = self._current_progress_step
@@ -627,7 +634,7 @@ class ExecuteSandboxWorkflow(PostHogWorkflow):
"provider": self.context.provider,
"model": self.context.model,
"reasoning_effort": self.context.reasoning_effort,
- "error_type": type(e).__name__,
+ "error_type": error_type,
"error_message": error_message,
"sandbox_id": current_sandbox_id,
**self._activity_error_properties(e),
@@ -635,7 +642,7 @@ class ExecuteSandboxWorkflow(PostHogWorkflow):
capture_analytics=False,
)
await self._update_task_run_status(
- "failed", error_message=error_message, run_id=run_id, error_type=type(e).__name__
+ "failed", error_message=error_message, run_id=run_id, error_type=error_type
)
return ExecuteSandboxOutput(
@@ -669,7 +676,7 @@ class ExecuteSandboxWorkflow(PostHogWorkflow):
# Clear the persisted sandbox id only after cleanup actually
# ran — otherwise the next workflow start has no record of an
# orphan to reap.
- await self._clear_persisted_sandbox_id(run_id)
+ await self._clear_persisted_sandbox_id(run_id, cleanup_sandbox_id)
self._sandbox_id_for_cleanup = None
# Emit the terminal "I'm done" signal to the orchestrator before
@@ -1224,7 +1231,7 @@ class ExecuteSandboxWorkflow(PostHogWorkflow):
async def _cleanup_sandbox(self, sandbox_id: str) -> None:
await workflow.execute_activity(
cleanup_sandbox,
- CleanupSandboxInput(sandbox_id=sandbox_id),
+ CleanupSandboxInput(sandbox_id=sandbox_id, run_id=self.context.run_id),
start_to_close_timeout=timedelta(minutes=5),
retry_policy=RetryPolicy(maximum_attempts=3),
)
@@ -1270,10 +1277,10 @@ class ExecuteSandboxWorkflow(PostHogWorkflow):
# Stale state will be reaped (idempotent) on the next start, so a
# failure here doesn't compromise correctness.
@log_on_fail("execute_sandbox_clear_sandbox_id_failed", level="warning", suppress=True)
- async def _clear_persisted_sandbox_id(self, run_id: str) -> None:
+ async def _clear_persisted_sandbox_id(self, run_id: str, sandbox_id: str) -> None:
await workflow.execute_activity(
clear_persisted_sandbox_id,
- ClearPersistedSandboxIdInput(run_id=run_id),
+ ClearPersistedSandboxIdInput(run_id=run_id, sandbox_id=sandbox_id),
start_to_close_timeout=timedelta(seconds=30),
retry_policy=RetryPolicy(maximum_attempts=3),
)
diff --git a/products/tasks/backend/temporal/process_task/activities/cleanup_sandbox.py b/products/tasks/backend/temporal/process_task/activities/cleanup_sandbox.py
index 6f92c40fd5d5..e97e3772a734 100644
--- a/products/tasks/backend/temporal/process_task/activities/cleanup_sandbox.py
+++ b/products/tasks/backend/temporal/process_task/activities/cleanup_sandbox.py
@@ -102,6 +102,12 @@ def cleanup_sandbox_now(input: CleanupSandboxInput) -> None:
cpu_usage_measured_at=cpu_usage_measured_at,
)
+ if input.run_id and stream_completion_safe:
+ try:
+ TaskRun.clear_sandbox_connection_state_atomic(input.run_id, input.sandbox_id)
+ except TaskRun.DoesNotExist:
+ pass
+
if input.complete_stream_on_cleanup and input.run_id and stream_completion_safe:
try:
publish_run_stream_completion(input.run_id)
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 1d41c220d6e1..c62a0b48058f 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
@@ -10,6 +10,7 @@ from posthog.temporal.common.utils import close_db_connections
from products.tasks.backend.temporal.observability import log_activity_execution
from products.tasks.backend.temporal.process_task.activities.feature_flags import AGENT_DESIGN_STATE_KEY
+from products.tasks.backend.temporal.process_task.organization import check_organization_execution
from products.tasks.backend.temporal.process_task.utils import (
get_actor_distinct_id,
get_task_run_credential_user,
@@ -98,6 +99,8 @@ def forward_pending_user_message(run_id: str) -> None:
if not pending_message and not pending_user_artifact_ids:
return
+ check_organization_execution(task_run.team_id)
+
if state.get("await_user_message"):
from products.tasks.backend.exceptions import ComputeBillingLimitError
from products.tasks.backend.logic.services.compute_quota import get_compute_quota_denial_reason
diff --git a/products/tasks/backend/temporal/process_task/activities/provision_sandbox.py b/products/tasks/backend/temporal/process_task/activities/provision_sandbox.py
index 4bdefc104622..4df0fb25b80d 100644
--- a/products/tasks/backend/temporal/process_task/activities/provision_sandbox.py
+++ b/products/tasks/backend/temporal/process_task/activities/provision_sandbox.py
@@ -76,6 +76,7 @@ from products.tasks.backend.temporal.observability import (
log_activity_execution,
log_with_activity_context,
)
+from products.tasks.backend.temporal.process_task.organization import check_organization_execution
from products.tasks.backend.temporal.process_task.sandbox_connection import persist_sandbox_connection
from products.tasks.backend.temporal.process_task.sandbox_credentials import (
replace_sandbox_credentials,
@@ -773,6 +774,7 @@ def _create_sandbox_for_repository(input: CreateSandboxForRepositoryInput) -> Cr
image_source=prepared.image_source,
**ctx.to_log_context(),
):
+ check_organization_execution(ctx.team_id)
if not (ctx.state or {}).get("await_user_message"):
task = _load_task(ctx)
if reason := get_compute_quota_denial_reason(task):
diff --git a/products/tasks/backend/temporal/process_task/activities/start_agent_server.py b/products/tasks/backend/temporal/process_task/activities/start_agent_server.py
index f02fee1a1f4a..33378b15e9a1 100644
--- a/products/tasks/backend/temporal/process_task/activities/start_agent_server.py
+++ b/products/tasks/backend/temporal/process_task/activities/start_agent_server.py
@@ -52,6 +52,7 @@ from products.tasks.backend.temporal.metrics import (
)
from products.tasks.backend.temporal.oauth import create_oauth_access_token_for_run
from products.tasks.backend.temporal.observability import emit_agent_log, log_activity_execution
+from products.tasks.backend.temporal.process_task.organization import guard_organization_execution
from products.tasks.backend.temporal.process_task.utils import (
McpServerConfig,
format_allowed_domains_for_log,
@@ -733,6 +734,7 @@ def start_agent_server(input: StartAgentServerInput) -> StartAgentServerOutput:
origin_product=ctx.origin_product,
used_snapshot=input.used_snapshot,
),
+ guard_organization_execution(ctx.team_id),
):
emit_agent_log(ctx.run_id, "debug", "Starting agent server")
@@ -877,6 +879,7 @@ def launch_agent_server(input: StartAgentServerInput) -> StartAgentServerOutput:
origin_product=ctx.origin_product,
used_snapshot=input.used_snapshot,
),
+ guard_organization_execution(ctx.team_id),
):
emit_agent_log(ctx.run_id, "debug", "Launching agent server (deferred readiness)")
@@ -944,6 +947,7 @@ def await_agent_server_ready(input: StartAgentServerInput) -> StartAgentServerOu
origin_product=ctx.origin_product,
used_snapshot=input.used_snapshot,
),
+ guard_organization_execution(ctx.team_id),
):
sandbox = get_sandbox_class_for_sandbox_id(input.sandbox_id).get_by_id(input.sandbox_id)
agentsh_domains = _agentsh_domains_for(ctx)
diff --git a/products/tasks/backend/temporal/process_task/activities/tests/test_cleanup_sandbox.py b/products/tasks/backend/temporal/process_task/activities/tests/test_cleanup_sandbox.py
index 8215d9cb30f3..3399ef8dd23c 100644
--- a/products/tasks/backend/temporal/process_task/activities/tests/test_cleanup_sandbox.py
+++ b/products/tasks/backend/temporal/process_task/activities/tests/test_cleanup_sandbox.py
@@ -10,7 +10,11 @@ from asgiref.sync import async_to_sync
from products.tasks.backend.exceptions import SandboxNotFoundError
from products.tasks.backend.logic.services.sandbox import Sandbox, SandboxConfig, SandboxTemplate
from products.tasks.backend.logic.stream.redis_stream import TaskRunRedisStream, get_task_run_stream_key
-from products.tasks.backend.temporal.process_task.activities.cleanup_sandbox import CleanupSandboxInput, cleanup_sandbox
+from products.tasks.backend.temporal.process_task.activities.cleanup_sandbox import (
+ CleanupSandboxInput,
+ cleanup_sandbox,
+ cleanup_sandbox_now,
+)
@pytest.mark.django_db
@@ -114,16 +118,25 @@ def test_cleanup_sandbox_retries_when_final_destroy_fails(activity_environment,
@pytest.mark.django_db
-def test_cleanup_sandbox_completes_stream_when_requested(activity_environment, mocker):
- run_id = str(uuid.uuid4())
[email protected]("current_sandbox", ["sandbox-123", "sandbox-replacement"])
+def test_cleanup_sandbox_completes_stream_when_requested(mocker, test_task_run, current_sandbox):
+ run_id = str(test_task_run.id)
+ connection = {
+ "sandbox_id": current_sandbox,
+ "sandbox_url": "https://sandbox.example.com",
+ "sandbox_connect_token": "fake-token",
+ "sandbox_jwt_kid": "fake-key",
+ "sandbox_backend": "modal",
+ }
+ test_task_run.state = {"other": "preserved", **connection}
+ test_task_run.save(update_fields=["state"])
sandbox = mocker.Mock(id="sandbox-123")
mocker.patch.object(Sandbox, "get_by_id", return_value=sandbox)
publish_complete = mocker.patch(
"products.tasks.backend.temporal.process_task.activities.cleanup_sandbox.publish_task_run_stream_complete"
)
- async_to_sync(activity_environment.run)(
- cleanup_sandbox,
+ cleanup_sandbox_now(
CleanupSandboxInput(
sandbox_id="sandbox-123",
run_id=run_id,
@@ -134,6 +147,10 @@ def test_cleanup_sandbox_completes_stream_when_requested(activity_environment, m
sandbox.execute.assert_not_called()
sandbox.destroy.assert_called_once_with()
publish_complete.assert_called_once_with(run_id, False)
+ test_task_run.refresh_from_db()
+ assert test_task_run.state == (
+ {"other": "preserved"} if current_sandbox == "sandbox-123" else {"other": "preserved", **connection}
+ )
@pytest.mark.django_db
diff --git a/products/tasks/backend/temporal/process_task/activities/tests/test_provision_sandbox.py b/products/tasks/backend/temporal/process_task/activities/tests/test_provision_sandbox.py
index fd8ee5d8ac88..0e887fb50b12 100644
--- a/products/tasks/backend/temporal/process_task/activities/tests/test_provision_sandbox.py
+++ b/products/tasks/backend/temporal/process_task/activities/tests/test_provision_sandbox.py
@@ -10,7 +10,13 @@ from django.test import override_settings
from asgiref.sync import async_to_sync
from products.tasks.backend.constants import SNAPSHOT_KIND_DIRECTORY, SNAPSHOT_KIND_FILESYSTEM
-from products.tasks.backend.exceptions import RepositoryCloneError, SandboxCleanupError, SandboxRateLimitedError
+from products.tasks.backend.exceptions import (
+ ComputeBillingLimitError,
+ OrganizationExecutionError,
+ RepositoryCloneError,
+ SandboxCleanupError,
+ SandboxRateLimitedError,
+)
from products.tasks.backend.logic.services.docker_sandbox import DockerSandbox
from products.tasks.backend.logic.services.sandbox import ExecutionResult
from products.tasks.backend.models import Task
@@ -30,6 +36,14 @@ from products.tasks.backend.temporal.process_task.activities.provision_sandbox i
)
[email protected](autouse=True)
+def organization_state(mocker):
+ teams = mocker.patch("products.tasks.backend.temporal.process_task.organization.Team.objects.filter")
+ state = teams.return_value.values_list.return_value.first
+ state.return_value = (False, True)
+ return state
+
+
def _context_for_desktop_bootstrap(
*, image_name: str | None = "posthog-dev-stack", warm_enabled: bool = True
) -> TaskProcessingContext:
@@ -517,6 +531,37 @@ def _prepared_for_create() -> PrepareSandboxForRepositoryOutput:
)
[email protected]("warm", [False, True])
+ "state, reason",
+ [
+ ((True, True), "organization_pending_deletion"),
+ ((True, False), "organization_pending_deletion"),
+ ((False, False), "organization_deactivated"),
+ (None, "organization_not_found"),
+ ],
+)
+def test_blocked_organization_creates_no_sandbox(
+ mocker, activity_environment, organization_state, warm, state, reason
+) -> None:
+ organization_state.return_value = state
+ context = _context_for_desktop_bootstrap()
+ context.state = {"await_user_message": warm}
+ sandbox_class = mocker.patch.object(provision_sandbox_module, "get_sandbox_class_for_run_backend")
+
+ error_type = ComputeBillingLimitError if reason == "organization_deactivated" else OrganizationExecutionError
+ with pytest.raises(error_type) as error:
+ async_to_sync(activity_environment.run)(
+ create_sandbox_for_repository,
+ CreateSandboxForRepositoryInput(context=context, prepared=_prepared_for_create()),
+ )
+
+ assert error.value.non_retryable is True
+ assert error.value.type == error_type.__name__
+ assert error.value.context["reason"] == reason
+ sandbox_class.return_value.create.assert_not_called()
+
+
@pytest.mark.parametrize(
"failing_step,destroy_fails",
[
diff --git a/products/tasks/backend/temporal/process_task/activities/tests/test_start_agent_server.py b/products/tasks/backend/temporal/process_task/activities/tests/test_start_agent_server.py
index a48417bcebf7..216c04be3fe9 100644
--- a/products/tasks/backend/temporal/process_task/activities/tests/test_start_agent_server.py
+++ b/products/tasks/backend/temporal/process_task/activities/tests/test_start_agent_server.py
@@ -8,6 +8,7 @@ from django.db import OperationalError
from products.tasks.backend.exceptions import (
OAuthTokenError,
+ OrganizationExecutionError,
ProcessTaskFatalError,
SandboxExecutionError,
SandboxMissingRepositoryError,
@@ -40,6 +41,14 @@ from products.tasks.backend.temporal.process_task.activities.start_agent_server
)
[email protected](autouse=True)
+def organization_state(mocker):
+ teams = mocker.patch("products.tasks.backend.temporal.process_task.organization.Team.objects.filter")
+ state = teams.return_value.values_list.return_value.first
+ state.return_value = (False, True)
+ return state
+
+
@time_machine.travel("2026-08-06T12:01:30Z", tick=False)
def test_record_boot_total_excludes_wizard_time_and_labels_runtime(mocker) -> None:
record_metric = mocker.patch(
@@ -143,7 +152,28 @@ def test_network_enforcement_observation_matches_completed_checks(
assert _agentsh_domains_for(context) == expected_agentsh_domains
-async def test_start_failure_does_not_report_network_enforcement_observation(mocker) -> None:
[email protected]("activity_fn", [start_agent_server, launch_agent_server, await_agent_server_ready])
+async def test_pending_deletion_blocks_agent_start(mocker, organization_state, activity_fn) -> None:
+ organization_state.return_value = (True, True)
+ sandbox_class = mocker.patch(
+ "products.tasks.backend.temporal.process_task.activities.start_agent_server.get_sandbox_class_for_sandbox_id"
+ )
+
+ with pytest.raises(OrganizationExecutionError) as error:
+ await activity_fn(
+ StartAgentServerInput(context=_context(), sandbox_id="sandbox-id", sandbox_url="https://sandbox.example")
+ )
+
+ assert error.value.non_retryable is True
+ assert error.value.context["reason"] == "organization_pending_deletion"
+ sandbox_class.return_value.get_by_id.assert_not_called()
+
+
[email protected]("pending_deletion", [False, True])
+async def test_start_failure_does_not_report_network_enforcement_observation(
+ mocker, organization_state, pending_deletion: bool
+) -> None:
+ organization_state.side_effect = [(False, True), (pending_deletion, True)]
context = _context(
allowed_domains=["example.com"],
agentsh_domain_allowlist=["example.com", "api.posthog.com"],
@@ -171,7 +201,7 @@ async def test_start_failure_does_not_report_network_enforcement_observation(moc
"products.tasks.backend.temporal.process_task.activities.start_agent_server._record_network_enforcement_observation"
)
- with pytest.raises(RuntimeError, match="health check failed"):
+ with pytest.raises(OrganizationExecutionError if pending_deletion else RuntimeError) as error:
await start_agent_server(
StartAgentServerInput(
context=context,
@@ -180,6 +210,12 @@ async def test_start_failure_does_not_report_network_enforcement_observation(moc
)
)
+ if pending_deletion:
+ assert isinstance(error.value, OrganizationExecutionError)
+ assert error.value.non_retryable is True
+ assert error.value.context["reason"] == "organization_pending_deletion"
+ else:
+ assert str(error.value) == "health check failed"
record_observation.assert_not_called()
sandbox.wait_for_agent_server_ready.assert_called_once()
preparation_meter.return_value.with_additional_attributes.assert_called_once_with(
@@ -479,7 +515,11 @@ async def test_await_agent_server_ready_relaunches_on_activity_retries(mocker, a
record_retry.assert_not_called()
-async def test_await_agent_server_ready_records_failed_relaunch(mocker) -> None:
[email protected]("pending_deletion", [False, True])
+async def test_await_agent_server_ready_records_failed_relaunch(
+ mocker, organization_state, pending_deletion: bool
+) -> None:
+ organization_state.side_effect = [(False, True), (pending_deletion, True)]
context = _context()
sandbox = mocker.Mock(id="sandbox-id")
sandbox.start_agent_server.side_effect = RuntimeError("session did not initialize")
@@ -514,7 +554,7 @@ async def test_await_agent_server_ready_records_failed_relaunch(mocker) -> None:
"products.tasks.backend.temporal.process_task.activities.start_agent_server.increment_agent_server_readiness_retry"
)
- with pytest.raises(SandboxExecutionError, match="Failed to start agent server in sandbox"):
+ with pytest.raises(OrganizationExecutionError if pending_deletion else SandboxExecutionError) as error:
await await_agent_server_ready(
StartAgentServerInput(
context=context,
@@ -524,6 +564,10 @@ async def test_await_agent_server_ready_records_failed_relaunch(mocker) -> None:
)
)
+ assert error.value.non_retryable is pending_deletion
+ if pending_deletion:
+ assert error.value.context["reason"] == "organization_pending_deletion"
+
record_retry.assert_called_once_with(
2,
"failed",
diff --git a/products/tasks/backend/temporal/process_task/organization.py b/products/tasks/backend/temporal/process_task/organization.py
new file mode 100644
index 000000000000..680f25c35275
--- /dev/null
+++ b/products/tasks/backend/temporal/process_task/organization.py
@@ -0,0 +1,39 @@
+from collections.abc import Iterator
+from contextlib import contextmanager
+
+from posthog.models import Team
+
+from products.tasks.backend.exceptions import ComputeBillingLimitError, OrganizationExecutionError
+
+
+def check_organization_execution(team_id: int) -> None:
+ state = (
+ Team.objects.filter(id=team_id)
+ .values_list("organization__is_pending_deletion", "organization__is_active")
+ .first()
+ )
+ if state is None:
+ raise OrganizationExecutionError(
+ "This organization no longer exists. Select another organization to run tasks.",
+ team_id,
+ "organization_not_found",
+ )
+ pending_deletion, active = state
+ if pending_deletion:
+ raise OrganizationExecutionError(
+ "This organization is scheduled for deletion. Select another organization to run tasks.",
+ team_id,
+ "organization_pending_deletion",
+ )
+ if not active:
+ raise ComputeBillingLimitError({"team_id": team_id}, "organization_deactivated")
+
+
+@contextmanager
+def guard_organization_execution(team_id: int) -> Iterator[None]:
+ check_organization_execution(team_id)
+ try:
+ yield
+ except Exception:
+ check_organization_execution(team_id)
+ raise
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 c833e9db5343..41c88f4c369f 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
@@ -3,7 +3,7 @@ from datetime import timedelta
from types import SimpleNamespace
from typing import ClassVar
-from unittest.mock import patch
+from unittest.mock import Mock, patch
from django.apps import apps
from django.test import TestCase
@@ -18,6 +18,7 @@ from posthog.models.organization import Organization
from posthog.models.team.team import Team
from posthog.models.user import User
+from products.tasks.backend.exceptions import OrganizationExecutionError
from products.tasks.backend.logic.services.sandbox_usage import SandboxCpuAttribution
from products.tasks.backend.models import SandboxSession, Task, TaskRun
@@ -97,6 +98,28 @@ class TestForwardPendingUserMessage(TestCase):
forward_pending_user_message("550e8400-e29b-41d4-a716-446655440000")
assert ctx.exception.non_retryable is True
+ @parameterized.expand([(False,), (True,)])
+ @patch("products.tasks.backend.logic.services.agent_command.send_user_message")
+ def test_pending_deletion_blocks_delivery(self, warm: bool, mock_send: Mock) -> None:
+ run = self._make_run(
+ state={
+ "await_user_message": warm,
+ "pending_user_message": "fix the tests",
+ "sandbox_url": "https://sandbox.example.com/rpc",
+ }
+ )
+ self.org.is_pending_deletion = True
+ self.org.save(update_fields=["is_pending_deletion"])
+
+ with self.assertRaises(OrganizationExecutionError) as error_context:
+ forward_pending_user_message(str(run.id))
+
+ assert error_context.exception.non_retryable is True
+ assert error_context.exception.context["reason"] == "organization_pending_deletion"
+ mock_send.assert_not_called()
+ run.refresh_from_db()
+ assert run.state["pending_user_message"] == "fix the tests"
+
@patch("products.tasks.backend.logic.services.store_skills.refresh_store_skills_state")
@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")
diff --git a/products/tasks/backend/temporal/process_task/tests/test_organization.py b/products/tasks/backend/temporal/process_task/tests/test_organization.py
new file mode 100644
index 000000000000..5ab02cf42c2f
--- /dev/null
+++ b/products/tasks/backend/temporal/process_task/tests/test_organization.py
@@ -0,0 +1,31 @@
+import pytest
+
+from products.tasks.backend.exceptions import ComputeBillingLimitError, OrganizationExecutionError
+from products.tasks.backend.temporal.process_task.organization import check_organization_execution
+
+
+ "pending_deletion, active, reason",
+ [
+ (False, True, None),
+ (True, True, "organization_pending_deletion"),
+ (True, False, "organization_pending_deletion"),
+ (False, False, "organization_deactivated"),
+ ],
+)
+def test_organization_execution_uses_current_state(team, pending_deletion, active, reason) -> None:
+ check_organization_execution(team.id)
+ organization = team.organization
+ organization.is_pending_deletion = pending_deletion
+ organization.is_active = active
+ organization.save(update_fields=["is_pending_deletion", "is_active"])
+
+ if reason is None:
+ check_organization_execution(team.id)
+ else:
+ error_type = ComputeBillingLimitError if reason == "organization_deactivated" else OrganizationExecutionError
+ with pytest.raises(error_type) as error:
+ check_organization_execution(team.id)
+ assert error.value.context["reason"] == reason
+ assert error.value.non_retryable is True
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 4698056a7a0b..3a820e929aea 100644
--- a/products/tasks/backend/temporal/process_task/tests/test_workflow.py
+++ b/products/tasks/backend/temporal/process_task/tests/test_workflow.py
@@ -1846,7 +1846,10 @@ class TestProcessTaskWorkflowUnit:
extra={"run_id": "run-id", "sandbox_id": "sandbox-123"},
)
- async def test_run_cleans_up_sandbox_when_provisioning_fails_after_creation(self, monkeypatch):
+ @pytest.mark.parametrize("organization_blocked", [False, True])
+ async def test_run_cleans_up_sandbox_when_provisioning_fails_after_creation(
+ self, monkeypatch, organization_blocked
+ ):
workflow = ProcessTaskWorkflow()
get_task_processing_context_mock = AsyncMock(return_value=_build_context(github_integration_id=123))
update_task_run_status_mock = AsyncMock()
@@ -1867,6 +1870,20 @@ class TestProcessTaskWorkflowUnit:
async def fail_after_sandbox_creation() -> GetSandboxForRepositoryOutput:
workflow._sandbox_id_for_cleanup = "sandbox-123"
+ if organization_blocked:
+ raise ActivityError(
+ "Activity task failed",
+ scheduled_event_id=10,
+ started_event_id=11,
+ identity="worker",
+ activity_type="start_agent_server",
+ activity_id="activity",
+ retry_state=RetryState.NON_RETRYABLE_FAILURE,
+ ) from ApplicationError(
+ "This organization is scheduled for deletion.",
+ type="OrganizationExecutionError",
+ non_retryable=True,
+ )
raise RuntimeError("clone failed")
monkeypatch.setattr(workflow, "_get_sandbox_for_repository", fail_after_sandbox_creation)
@@ -1874,7 +1891,15 @@ class TestProcessTaskWorkflowUnit:
result = await workflow.run(ProcessTaskInput(run_id="run-id"))
assert result.success is False
- assert result.error == "clone failed"
+ assert result.error == (
+ "This organization is scheduled for deletion." if organization_blocked else "clone failed"
+ )
+ update_task_run_status_mock.assert_awaited_with(
+ "failed",
+ error_message=result.error,
+ run_id="run-id",
+ error_type="OrganizationExecutionError" if organization_blocked else "RuntimeError",
+ )
assert result.sandbox_id == "sandbox-123"
read_sandbox_logs_mock.assert_awaited_once_with("sandbox-123")
cleanup_sandbox_mock.assert_awaited_once_with("sandbox-123", complete_stream=True)
diff --git a/products/tasks/backend/tests/test_warm_facade.py b/products/tasks/backend/tests/test_warm_facade.py
index f1ea9421b72d..33a6168d152b 100644
--- a/products/tasks/backend/tests/test_warm_facade.py
+++ b/products/tasks/backend/tests/test_warm_facade.py
@@ -1271,8 +1271,11 @@ class TestCreateTaskWarmReuse(APIBaseTest):
assert "await_user_message" not in run.state
assert run.state["pr_base_branch"] is None
- def test_create_endpoint_returns_structured_compute_quota_denial_before_warm_activation(self):
+ @parameterized.expand([(False, 429, "posthog_code_billing_limit_exceeded"), (True, 403, "permission_denied")])
+ def test_create_endpoint_denies_before_warm_activation(self, pending_deletion, expected_status, expected_code):
warm_task, run = self._warm_run()
+ self.organization.is_pending_deletion = pending_deletion
+ self.organization.save(update_fields=["is_pending_deletion"])
with patch(
"products.tasks.backend.logic.services.compute_quota.get_compute_quota_denial_reason",
@@ -1284,8 +1287,8 @@ class TestCreateTaskWarmReuse(APIBaseTest):
format="json",
)
- assert response.status_code == status.HTTP_429_TOO_MANY_REQUESTS
- assert response.json()["code"] == "posthog_code_billing_limit_exceeded"
+ assert response.status_code == expected_status
+ assert response.json()["code"] == expected_code
warm_task.refresh_from_db()
run.refresh_from_db()
assert warm_task.description == ""