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): survive mid-run github integration deletion in credential refresh (#68890)

Alessandro Pogliaghi1862f5d1b53a
diff --git a/posthog/api/integration.py b/posthog/api/integration.py
index 83ce997cc735..73739b4cb835 100644
--- a/posthog/api/integration.py
+++ b/posthog/api/integration.py
@@ -92,6 +92,7 @@ from posthog.tasks.email import send_integration_access_request
from posthog.utils import is_relative_url
from products.cdp.backend.services.integration_usage import get_enabled_hog_functions_using_integration
+from products.tasks.backend.facade.api import count_in_progress_runs_for_github_integration
from products.workflows.backend.services.integration_usage import get_active_hog_flows_using_integration
logger = structlog.get_logger(__name__)
@@ -952,6 +953,17 @@ class IntegrationViewSet(
"Update them to use a different integration before disconnecting it."
)
+ if instance.kind == "github":
+ live_run_count = count_in_progress_runs_for_github_integration(
+ team_id=instance.team_id, integration_id=instance.id
+ )
+ if live_run_count:
+ raise ValidationError(
+ f"This GitHub integration is being used by {live_run_count} in-progress background agent "
+ f"run{'s' if live_run_count != 1 else ''}. Wait for them to finish or cancel them before "
+ "disconnecting it."
+ )
+
if instance.kind == "stripe":
try:
stripe_integration = StripeIntegration(instance)
diff --git a/posthog/api/test/test_integration.py b/posthog/api/test/test_integration.py
index a333a83fdcb7..29787c5a7cb1 100644
--- a/posthog/api/test/test_integration.py
+++ b/posthog/api/test/test_integration.py
@@ -4028,6 +4028,28 @@ class TestGitHubIntegrationUninstall:
assert response.status_code == status.HTTP_204_NO_CONTENT
assert not Integration.objects.filter(id=integration.id).exists()
+ @patch("posthog.api.integration.GitHubIntegration.uninstall_app_installation")
+ @patch("posthog.api.integration.count_in_progress_runs_for_github_integration")
+ def test_destroy_github_blocked_while_background_agent_runs_in_progress(
+ self, mock_count, _mock_uninstall, client: HttpClient
+ ):
+ integration = self._create_github_integration("12345")
+ mock_count.return_value = 2
+
+ client.force_login(self.user)
+ response = client.delete(f"/api/environments/{self.team.pk}/integrations/{integration.id}/")
+
+ assert response.status_code == status.HTTP_400_BAD_REQUEST
+ assert "2 in-progress background agent runs" in response.json()["detail"]
+ assert Integration.objects.filter(id=integration.id).exists()
+ mock_count.assert_called_once_with(team_id=self.team.pk, integration_id=integration.id)
+
+ mock_count.return_value = 0
+ response = client.delete(f"/api/environments/{self.team.pk}/integrations/{integration.id}/")
+
+ assert response.status_code == status.HTTP_204_NO_CONTENT
+ assert not Integration.objects.filter(id=integration.id).exists()
+
class TestIntegrationDeletionWorkflowGuard:
@pytest.fixture(autouse=True)
diff --git a/products/tasks/backend/exceptions.py b/products/tasks/backend/exceptions.py
index f7092f8ea628..729d4b25dafb 100644
--- a/products/tasks/backend/exceptions.py
+++ b/products/tasks/backend/exceptions.py
@@ -157,6 +157,18 @@ class GitHubAuthenticationError(ProcessTaskFatalError):
pass
+class CredentialUnavailableError(ProcessTaskFatalError):
+ """A sandbox credential can never be resolved again for this run — the backing
+ integration row was deleted mid-run or the user must re-authorize.
+
+ Not retriable, and an expected customer-initiated state rather than a systemic
+ failure, so it is not captured to error tracking.
+ """
+
+ def __init__(self, message: str, context: dict[str, Any], cause: Exception | None = None):
+ ProcessTaskError.__init__(self, message, context, cause, capture=False, non_retryable=True)
+
+
class PersonalAPIKeyError(ProcessTaskTransientError):
"""Failed to create or inject personal API key."""
diff --git a/products/tasks/backend/facade/api.py b/products/tasks/backend/facade/api.py
index 957ded901b45..91df1e4e63b6 100644
--- a/products/tasks/backend/facade/api.py
+++ b/products/tasks/backend/facade/api.py
@@ -457,6 +457,20 @@ def task_exists(task_id: str | UUID, team_id: int) -> bool:
return Task.objects.filter(id=task_id, team_id=team_id).exists()
+def count_in_progress_runs_for_github_integration(team_id: int, integration_id: int) -> int:
+ """In-progress runs whose task uses this team GitHub integration.
+
+ Used by core's integration API to block disconnecting a GitHub integration while
+ live runs still depend on it for credential refresh — deleting the row SET_NULLs
+ ``Task.github_integration`` and permanently orphans every live sandbox's token.
+ """
+ return TaskRun.objects.filter(
+ team_id=team_id,
+ status=TaskRun.Status.IN_PROGRESS,
+ task__github_integration_id=integration_id,
+ ).count()
+
+
def is_task_controllable_by_user(task_id: str | UUID, user_id: int | None) -> bool:
"""Whether the user may mutate the task under the task control rules.
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 128ef5c28064..c74295fcd5fb 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
@@ -569,6 +569,24 @@ class TestRun:
sandbox_id="sandbox-123",
)
+ async def test_credential_refresh_credentials_unavailable_does_not_mark_sandbox_gone(
+ self, monkeypatch, silent_workflow_logger
+ ):
+ workflow = ExecuteSandboxWorkflow()
+ workflow._context = _build_context()
+ refresh_loop_mock = AsyncMock(return_value=CredentialRefreshExitReason.CREDENTIALS_UNAVAILABLE)
+
+ 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 False
+ silent_workflow_logger.warning.assert_called_once_with(
+ "execute_sandbox_credential_refresh_stopped_credentials_unavailable",
+ run_id="run-id",
+ sandbox_id="sandbox-123",
+ )
+
@pytest.mark.parametrize(
"use_modal_resume_snapshots, expect_resume_snapshot_call",
[
diff --git a/products/tasks/backend/temporal/execute_sandbox/workflow.py b/products/tasks/backend/temporal/execute_sandbox/workflow.py
index de5d84798ded..4ab6cb3ba4fc 100644
--- a/products/tasks/backend/temporal/execute_sandbox/workflow.py
+++ b/products/tasks/backend/temporal/execute_sandbox/workflow.py
@@ -1092,6 +1092,12 @@ class ExecuteSandboxWorkflow(PostHogWorkflow):
sandbox_id=sandbox_id,
)
self._sandbox_gone = True
+ elif exit_reason == CredentialRefreshExitReason.CREDENTIALS_UNAVAILABLE:
+ workflow.logger.warning(
+ "execute_sandbox_credential_refresh_stopped_credentials_unavailable",
+ run_id=self.context.run_id,
+ sandbox_id=sandbox_id,
+ )
def _mark_sandbox_gone(self) -> None:
self._task_completed = True
diff --git a/products/tasks/backend/temporal/metrics.py b/products/tasks/backend/temporal/metrics.py
index 2759dc473406..f7be42bfcf30 100644
--- a/products/tasks/backend/temporal/metrics.py
+++ b/products/tasks/backend/temporal/metrics.py
@@ -112,8 +112,10 @@ def increment_credential_refresh(kind: str, outcome: str) -> None:
"""Record a sandbox credential refresh outcome.
outcome is one of: refreshed (token re-injected), skipped (nothing to do or
- token could not be resolved), failed (the credential raised). Best-effort:
- a metric failure must never break the refresh loop.
+ token could not be resolved), failed (the credential raised), orphaned (the
+ credential can never be refreshed again this run — integration deleted or
+ user re-auth required). Best-effort: a metric failure must never break the
+ refresh loop.
"""
try:
meter = _metric_meter({"kind": kind, "outcome": outcome})
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 630efff02a8a..206478bfc9f7 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
@@ -1,11 +1,16 @@
-from dataclasses import dataclass
+from dataclasses import dataclass, field
from temporalio import activity
from posthog.temporal.common.logger import get_logger
from posthog.temporal.common.utils import asyncify
-from products.tasks.backend.exceptions import SandboxNotFoundError, SandboxNotRunningError, TaskNotFoundError
+from products.tasks.backend.exceptions import (
+ CredentialUnavailableError,
+ SandboxNotFoundError,
+ SandboxNotRunningError,
+ TaskNotFoundError,
+)
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
@@ -45,6 +50,7 @@ def _notify_agent_server_of_refresh(ctx: TaskProcessingContext, task: Task, refr
class RefreshSandboxCredentialsInput:
context: TaskProcessingContext
sandbox_id: str
+ exclude_kinds: list[str] = field(default_factory=list)
@dataclass
@@ -55,6 +61,8 @@ class RefreshSandboxCredentialsOutput:
refreshed_kinds: list[str]
# Sandbox is gone/stopped and won't refresh again — the loop should stop, not keep skipping.
sandbox_gone: bool = False
+ orphaned_kinds: list[str] = field(default_factory=list)
+ no_credentials_left: bool = False
@activity.defn
@@ -82,9 +90,10 @@ def refresh_sandbox_credentials(input: RefreshSandboxCredentialsInput) -> Refres
raise TaskNotFoundError(f"Task {ctx.task_id} not found", {"task_id": ctx.task_id}, cause=e)
refreshed_kinds: list[str] = []
+ orphaned_kinds: list[str] = []
next_refresh = DEFAULT_REFRESH_INTERVAL_SECONDS
intervals: list[float] = []
- credentials = build_sandbox_credentials(ctx)
+ credentials = [c for c in build_sandbox_credentials(ctx) if c.kind not in input.exclude_kinds]
try:
sandbox = Sandbox.get_by_id(input.sandbox_id)
@@ -113,6 +122,17 @@ def refresh_sandbox_credentials(input: RefreshSandboxCredentialsInput) -> Refres
next_refresh_seconds=next_refresh, refreshed_kinds=[], sandbox_gone=True
)
+ if not credentials:
+ logger.info(
+ "sandbox_credentials_refresh_nothing_left",
+ sandbox_id=input.sandbox_id,
+ run_id=ctx.run_id,
+ exclude_kinds=input.exclude_kinds,
+ )
+ return RefreshSandboxCredentialsOutput(
+ next_refresh_seconds=next_refresh, refreshed_kinds=[], no_credentials_left=True
+ )
+
sandbox_gone = False
for index, credential in enumerate(credentials):
try:
@@ -127,6 +147,17 @@ def refresh_sandbox_credentials(input: RefreshSandboxCredentialsInput) -> Refres
increment_credential_refresh(skipped.kind, "skipped")
sandbox_gone = True
break
+ except CredentialUnavailableError:
+ logger.warning(
+ "sandbox_credential_refresh_orphaned",
+ kind=credential.kind,
+ sandbox_id=input.sandbox_id,
+ run_id=ctx.run_id,
+ exc_info=True,
+ )
+ increment_credential_refresh(credential.kind, "orphaned")
+ orphaned_kinds.append(credential.kind)
+ continue
except Exception:
logger.warning(
"sandbox_credential_refresh_failed",
@@ -163,5 +194,9 @@ def refresh_sandbox_credentials(input: RefreshSandboxCredentialsInput) -> Refres
)
return RefreshSandboxCredentialsOutput(
- next_refresh_seconds=next_refresh, refreshed_kinds=refreshed_kinds, sandbox_gone=sandbox_gone
+ next_refresh_seconds=next_refresh,
+ refreshed_kinds=refreshed_kinds,
+ sandbox_gone=sandbox_gone,
+ orphaned_kinds=orphaned_kinds,
+ no_credentials_left=len(orphaned_kinds) == len(credentials),
)
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 7d270d26190f..248061c91385 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
@@ -3,6 +3,8 @@ from unittest.mock import MagicMock, patch
from asgiref.sync import async_to_sync
+from posthog.models.integration import Integration
+
from products.tasks.backend.exceptions import SandboxExecutionError, SandboxNotFoundError, SandboxNotRunningError
from products.tasks.backend.logic.services.sandbox import ExecutionResult
from products.tasks.backend.temporal.process_task.activities.refresh_sandbox_credentials import (
@@ -171,6 +173,79 @@ class TestRefreshSandboxCredentialsActivity:
assert output.sandbox_gone is True
increment.assert_called_once_with("github", "skipped")
+ def test_deleted_integration_counts_as_orphaned_and_stops_loop(
+ self, activity_environment, task_context, test_task, sandbox
+ ):
+ # Delete via a queryset so the fixture instances keep their pks and teardown
+ # (integration.delete(), task.soft_delete()) still works on them.
+ Integration.objects.filter(id=test_task.github_integration_id).delete()
+ test_task.refresh_from_db()
+ with (
+ patch(
+ "products.tasks.backend.temporal.process_task.activities.refresh_sandbox_credentials.Sandbox.get_by_id",
+ return_value=sandbox,
+ ),
+ patch("products.tasks.backend.temporal.process_task.activities.refresh_sandbox_credentials.track_event"),
+ patch(
+ "products.tasks.backend.temporal.process_task.activities.refresh_sandbox_credentials.increment_credential_refresh"
+ ) as increment,
+ ):
+ output = async_to_sync(activity_environment.run)(
+ refresh_sandbox_credentials,
+ RefreshSandboxCredentialsInput(context=task_context, sandbox_id="sandbox-abc"),
+ )
+
+ assert output.orphaned_kinds == ["github"]
+ assert output.no_credentials_left is True
+ assert output.refreshed_kinds == []
+ assert output.sandbox_gone is False
+ increment.assert_called_once_with("github", "orphaned")
+
+ def test_excluded_kinds_report_nothing_left(self, activity_environment, task_context, test_task, sandbox):
+ with (
+ patch(
+ "products.tasks.backend.temporal.process_task.activities.refresh_sandbox_credentials.Sandbox.get_by_id",
+ return_value=sandbox,
+ ),
+ patch(
+ "products.tasks.backend.temporal.process_task.activities.refresh_sandbox_credentials.track_event"
+ ) as track_event,
+ ):
+ output = async_to_sync(activity_environment.run)(
+ refresh_sandbox_credentials,
+ RefreshSandboxCredentialsInput(
+ context=task_context, sandbox_id="sandbox-abc", exclude_kinds=["github"]
+ ),
+ )
+
+ assert output.no_credentials_left is True
+ assert output.sandbox_gone is False
+ assert output.refreshed_kinds == []
+ sandbox.execute.assert_not_called()
+ track_event.assert_not_called()
+
+ def test_sandbox_gone_wins_over_excluded_kinds(self, activity_environment, task_context, test_task):
+ with (
+ patch(
+ "products.tasks.backend.temporal.process_task.activities.refresh_sandbox_credentials.Sandbox.get_by_id",
+ side_effect=SandboxNotFoundError(
+ "Sandbox sandbox-abc not found",
+ {"sandbox_id": "sandbox-abc"},
+ cause=RuntimeError("Deadline Exceeded"),
+ ),
+ ),
+ patch("products.tasks.backend.temporal.process_task.activities.refresh_sandbox_credentials.track_event"),
+ ):
+ output = async_to_sync(activity_environment.run)(
+ refresh_sandbox_credentials,
+ RefreshSandboxCredentialsInput(
+ context=task_context, sandbox_id="sandbox-abc", exclude_kinds=["github"]
+ ),
+ )
+
+ assert output.sandbox_gone is True
+ assert output.no_credentials_left is False
+
def test_genuine_execution_error_counts_as_failed(self, activity_environment, task_context, test_task, sandbox):
sandbox.execute.side_effect = SandboxExecutionError(
"Failed to execute command", {"sandbox_id": "sandbox-abc"}, cause=RuntimeError("network blip")
diff --git a/products/tasks/backend/temporal/process_task/credential_refresh.py b/products/tasks/backend/temporal/process_task/credential_refresh.py
index 4e82005949c3..dee92113925c 100644
--- a/products/tasks/backend/temporal/process_task/credential_refresh.py
+++ b/products/tasks/backend/temporal/process_task/credential_refresh.py
@@ -12,6 +12,7 @@ from .activities.refresh_sandbox_credentials import RefreshSandboxCredentialsInp
class CredentialRefreshExitReason(StrEnum):
SANDBOX_GONE = "sandbox_gone"
+ CREDENTIALS_UNAVAILABLE = "credentials_unavailable"
SANDBOX_GONE_ERROR_MESSAGE = "Sandbox stopped; resume to continue"
@@ -28,18 +29,25 @@ async def run_credential_refresh_loop(context: TaskProcessingContext, sandbox_id
``process_task`` and ``execute_sandbox`` workflows.
"""
next_refresh_seconds = CREDENTIAL_REFRESH_INITIAL_DELAY.total_seconds()
+ exclude_kinds: list[str] = []
while True:
await workflow.sleep(next_refresh_seconds)
try:
result = await workflow.execute_activity(
refresh_sandbox_credentials,
- RefreshSandboxCredentialsInput(context=context, sandbox_id=sandbox_id),
+ RefreshSandboxCredentialsInput(context=context, sandbox_id=sandbox_id, exclude_kinds=exclude_kinds),
start_to_close_timeout=timedelta(minutes=2),
retry_policy=RetryPolicy(maximum_attempts=2),
)
if result.sandbox_gone:
workflow.logger.info("Stopping credential refresh loop: sandbox is gone")
return CredentialRefreshExitReason.SANDBOX_GONE
+ for kind in result.orphaned_kinds:
+ if kind not in exclude_kinds:
+ exclude_kinds.append(kind)
+ if result.no_credentials_left:
+ workflow.logger.info("Stopping credential refresh loop: no refreshable credentials left")
+ return CredentialRefreshExitReason.CREDENTIALS_UNAVAILABLE
next_refresh_seconds = result.next_refresh_seconds
except Exception as e:
# Non-fatal: keep the run alive and retry on the default cadence.
diff --git a/products/tasks/backend/temporal/process_task/sandbox_credentials.py b/products/tasks/backend/temporal/process_task/sandbox_credentials.py
index e3343112dff3..099c34756f0b 100644
--- a/products/tasks/backend/temporal/process_task/sandbox_credentials.py
+++ b/products/tasks/backend/temporal/process_task/sandbox_credentials.py
@@ -8,13 +8,16 @@ from typing import TYPE_CHECKING, Protocol
import redis
-from posthog.models.user_integration import UserGitHubIntegration
+from posthog.models.integration import Integration
+from posthog.models.user_integration import ReauthorizationRequired, UserGitHubIntegration, UserIntegration
from posthog.redis import get_client
+from products.tasks.backend.exceptions import CredentialUnavailableError
from products.tasks.backend.logic.services.agentsh import ENV_FILE
from products.tasks.backend.models import Task, TaskRun
from products.tasks.backend.temporal.process_task.utils import (
PrAuthorshipMode,
+ get_github_token,
get_pr_authorship_mode,
get_sandbox_github_token,
is_caller_token_run,
@@ -255,16 +258,43 @@ class GitHubSandboxCredential:
integration = resolve_user_github_integration_for_task(task, repository=ctx.repository, allow_refresh=True)
if integration is not None:
- return self._refresh_shared_user_integration(sandbox, ctx, integration)
-
- token = get_sandbox_github_token(
- ctx.github_integration_id,
- run_id=ctx.run_id,
- state=ctx.state,
- task=task,
- github_user_integration_id=ctx.github_user_integration_id,
- repository=ctx.repository,
+ return self._refresh_shared_user_integration(sandbox, ctx, task, integration)
+
+ github_integration_id = task.github_integration_id
+ github_user_integration_id = (
+ str(task.github_user_integration_id) if task.github_user_integration_id else ctx.github_user_integration_id
)
+ if (
+ github_integration_id is None
+ and github_user_integration_id is None
+ and not is_caller_token_run(ctx.run_id, ctx.state)
+ ):
+ raise CredentialUnavailableError(
+ "GitHub integration for this run was disconnected mid-run",
+ {"run_id": ctx.run_id, "task_id": ctx.task_id},
+ )
+
+ try:
+ token = get_sandbox_github_token(
+ github_integration_id,
+ run_id=ctx.run_id,
+ state=ctx.state,
+ task=task,
+ github_user_integration_id=github_user_integration_id,
+ repository=ctx.repository,
+ )
+ except (Integration.DoesNotExist, UserIntegration.DoesNotExist) as e:
+ raise CredentialUnavailableError(
+ "GitHub integration for this run no longer exists",
+ {"run_id": ctx.run_id, "task_id": ctx.task_id},
+ cause=e,
+ )
+ except ReauthorizationRequired as e:
+ raise CredentialUnavailableError(
+ "GitHub user integration for this run requires reauthorization",
+ {"run_id": ctx.run_id, "task_id": ctx.task_id},
+ cause=e,
+ )
if not token:
return CredentialRefreshOutcome(
self.kind, refreshed=False, next_refresh_seconds=DEFAULT_REFRESH_INTERVAL_SECONDS
@@ -276,15 +306,42 @@ class GitHubSandboxCredential:
)
def _refresh_shared_user_integration(
- self, sandbox: "SandboxBase", ctx: "TaskProcessingContext", integration: UserGitHubIntegration
+ self, sandbox: "SandboxBase", ctx: "TaskProcessingContext", task: Task, integration: UserGitHubIntegration
) -> CredentialRefreshOutcome:
- token = resolve_coordinated_user_token(integration)
+ try:
+ token = resolve_coordinated_user_token(integration)
+ except (ReauthorizationRequired, UserIntegration.DoesNotExist) as e:
+ fallback = self._installation_token_fallback(ctx, task, cause=e)
+ if not fallback:
+ return CredentialRefreshOutcome(
+ self.kind, refreshed=False, next_refresh_seconds=DEFAULT_REFRESH_INTERVAL_SECONDS
+ )
+ apply_github_credentials_to_sandbox(sandbox, ctx.repository, fallback)
+ return CredentialRefreshOutcome(
+ self.kind, refreshed=True, next_refresh_seconds=github_refresh_interval_seconds(fallback)
+ )
if token:
apply_github_credentials_to_sandbox(sandbox, ctx.repository, token)
return CredentialRefreshOutcome(
self.kind, refreshed=bool(token), next_refresh_seconds=USER_TOKEN_REFRESH_INTERVAL_SECONDS
)
+ def _installation_token_fallback(self, ctx: "TaskProcessingContext", task: Task, cause: Exception) -> str | None:
+ if task.github_integration_id is None:
+ raise CredentialUnavailableError(
+ "GitHub user integration requires reauthorization and no team installation is available",
+ {"run_id": ctx.run_id, "task_id": ctx.task_id},
+ cause=cause,
+ )
+ try:
+ return get_github_token(task.github_integration_id)
+ except Integration.DoesNotExist as e:
+ raise CredentialUnavailableError(
+ "GitHub integration for this run no longer exists",
+ {"run_id": ctx.run_id, "task_id": ctx.task_id},
+ cause=e,
+ )
+
def build_sandbox_credentials(ctx: "TaskProcessingContext") -> list[SandboxCredential]:
credentials: list[SandboxCredential] = []
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
new file mode 100644
index 000000000000..4e687bb79e7c
--- /dev/null
+++ b/products/tasks/backend/temporal/process_task/tests/test_credential_refresh.py
@@ -0,0 +1,53 @@
+from unittest.mock import AsyncMock, MagicMock
+
+from products.tasks.backend.temporal.process_task import credential_refresh as credential_refresh_module
+from products.tasks.backend.temporal.process_task.activities.refresh_sandbox_credentials import (
+ RefreshSandboxCredentialsOutput,
+)
+from products.tasks.backend.temporal.process_task.credential_refresh import (
+ CredentialRefreshExitReason,
+ run_credential_refresh_loop,
+)
+
+
+class TestRunCredentialRefreshLoop:
+ def _patch_workflow(self, monkeypatch, execute_activity):
+ monkeypatch.setattr(credential_refresh_module.workflow, "execute_activity", execute_activity)
+ monkeypatch.setattr(credential_refresh_module.workflow, "sleep", AsyncMock())
+ monkeypatch.setattr(credential_refresh_module.workflow, "logger", MagicMock())
+
+ async def test_orphaned_kinds_are_excluded_next_cycle_and_loop_stops(self, monkeypatch):
+ execute_activity = AsyncMock(
+ side_effect=[
+ RefreshSandboxCredentialsOutput(
+ next_refresh_seconds=1.0, refreshed_kinds=[], orphaned_kinds=["github"]
+ ),
+ RefreshSandboxCredentialsOutput(next_refresh_seconds=1.0, refreshed_kinds=[], no_credentials_left=True),
+ ]
+ )
+ self._patch_workflow(monkeypatch, execute_activity)
+
+ exit_reason = await run_credential_refresh_loop(MagicMock(), "sb-1")
+
+ assert exit_reason == CredentialRefreshExitReason.CREDENTIALS_UNAVAILABLE
+ assert execute_activity.await_count == 2
+ second_input = execute_activity.await_args_list[1].args[1]
+ assert second_input.exclude_kinds == ["github"]
+
+ async def test_sandbox_gone_still_wins_over_orphaned_kinds(self, monkeypatch):
+ execute_activity = AsyncMock(
+ side_effect=[
+ RefreshSandboxCredentialsOutput(
+ next_refresh_seconds=1.0,
+ refreshed_kinds=[],
+ sandbox_gone=True,
+ orphaned_kinds=["github"],
+ no_credentials_left=True,
+ ),
+ ]
+ )
+ self._patch_workflow(monkeypatch, execute_activity)
+
+ exit_reason = await run_credential_refresh_loop(MagicMock(), "sb-1")
+
+ assert exit_reason == CredentialRefreshExitReason.SANDBOX_GONE
diff --git a/products/tasks/backend/temporal/process_task/tests/test_sandbox_credentials.py b/products/tasks/backend/temporal/process_task/tests/test_sandbox_credentials.py
index 709212421066..014fd645ff43 100644
--- a/products/tasks/backend/temporal/process_task/tests/test_sandbox_credentials.py
+++ b/products/tasks/backend/temporal/process_task/tests/test_sandbox_credentials.py
@@ -146,6 +146,56 @@ class TestGitHubSandboxCredential:
sandbox.execute.assert_not_called()
sandbox.write_file.assert_not_called()
+ def test_deleted_integration_raises_credential_unavailable(self):
+ from products.tasks.backend.exceptions import CredentialUnavailableError
+
+ task = MagicMock()
+ task.github_integration_id = None
+ task.github_user_integration_id = None
+
+ with (
+ patch(f"{MODULE}.is_caller_token_run", return_value=False),
+ patch(f"{MODULE}.get_sandbox_github_token") as resolve,
+ ):
+ with pytest.raises(CredentialUnavailableError):
+ GitHubSandboxCredential().refresh(MagicMock(), _context(), task)
+
+ resolve.assert_not_called()
+
+ def test_fresh_task_ids_take_precedence_over_ctx_snapshot(self):
+ sandbox = MagicMock()
+ sandbox.execute.return_value = _ok("")
+ sandbox.write_file.return_value = _ok()
+ task = MagicMock()
+ task.github_integration_id = 456
+ task.github_user_integration_id = None
+
+ with patch(f"{MODULE}.get_sandbox_github_token", return_value="ghs_fresh") as resolve:
+ outcome = GitHubSandboxCredential().refresh(sandbox, _context(), task)
+
+ assert outcome.refreshed is True
+ assert resolve.call_args.args[0] == 456
+ assert resolve.call_args.kwargs["github_user_integration_id"] is None
+
+ def test_caller_token_run_with_deleted_integration_is_not_orphaned(self):
+ from products.tasks.backend.temporal.process_task.utils import PrAuthorshipMode
+
+ sandbox = MagicMock()
+ sandbox.execute.return_value = _ok("")
+ sandbox.write_file.return_value = _ok()
+ task = MagicMock()
+ task.github_integration_id = None
+ task.github_user_integration_id = None
+
+ with (
+ patch(f"{MODULE}.get_pr_authorship_mode", return_value=PrAuthorshipMode.USER),
+ patch(f"{MODULE}.is_caller_token_run", return_value=True),
+ patch(f"{MODULE}.get_sandbox_github_token", return_value="ghu_caller"),
+ ):
+ outcome = GitHubSandboxCredential().refresh(sandbox, _context(), task)
+
+ assert outcome.refreshed is True
+
class TestBuildSandboxCredentials:
def test_includes_github_when_credentials_present(self):
@@ -200,6 +250,49 @@ class TestSharedUserIntegrationRefresh:
assert outcome.refreshed is False
apply.assert_not_called()
+ def test_reauthorization_falls_back_to_installation_token(self):
+ import contextlib
+
+ from posthog.models.user_integration import ReauthorizationRequired
+
+ with contextlib.ExitStack() as stack:
+ self._as_user_integration_run(stack)
+ stack.enter_context(patch(f"{MODULE}.resolve_user_github_integration_for_task", return_value=MagicMock()))
+ stack.enter_context(
+ patch(f"{MODULE}.resolve_coordinated_user_token", side_effect=ReauthorizationRequired("expired"))
+ )
+ installation_token = stack.enter_context(patch(f"{MODULE}.get_github_token", return_value="ghs_team"))
+ apply = stack.enter_context(patch(f"{MODULE}.apply_github_credentials_to_sandbox"))
+ task = MagicMock()
+ task.github_integration_id = 456
+
+ sandbox = MagicMock()
+ outcome = GitHubSandboxCredential().refresh(sandbox, _context(), task)
+
+ assert outcome.refreshed is True
+ assert outcome.next_refresh_seconds == 20 * 60
+ installation_token.assert_called_once_with(456)
+ apply.assert_called_once_with(sandbox, "explore-science/paper-wizard-frontend", "ghs_team")
+
+ def test_reauthorization_without_team_integration_raises_credential_unavailable(self):
+ import contextlib
+
+ from posthog.models.user_integration import ReauthorizationRequired
+
+ from products.tasks.backend.exceptions import CredentialUnavailableError
+
+ with contextlib.ExitStack() as stack:
+ self._as_user_integration_run(stack)
+ stack.enter_context(patch(f"{MODULE}.resolve_user_github_integration_for_task", return_value=MagicMock()))
+ stack.enter_context(
+ patch(f"{MODULE}.resolve_coordinated_user_token", side_effect=ReauthorizationRequired("expired"))
+ )
+ task = MagicMock()
+ task.github_integration_id = None
+
+ with pytest.raises(CredentialUnavailableError):
+ GitHubSandboxCredential().refresh(MagicMock(), _context(), task)
+
def test_caller_token_run_skips_coordinated_path(self):
import contextlib
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 3a9acbe7b1ed..24f36bcacf0e 100644
--- a/products/tasks/backend/temporal/process_task/tests/test_workflow.py
+++ b/products/tasks/backend/temporal/process_task/tests/test_workflow.py
@@ -381,6 +381,23 @@ class TestProcessTaskWorkflowUnit:
extra={"run_id": "run-id", "sandbox_id": "sandbox-123"},
)
+ async def test_credential_refresh_credentials_unavailable_does_not_mark_sandbox_gone(self, monkeypatch):
+ workflow = ProcessTaskWorkflow()
+ workflow._context = _build_context(github_integration_id=123)
+ logger = Mock()
+ refresh_loop_mock = AsyncMock(return_value=CredentialRefreshExitReason.CREDENTIALS_UNAVAILABLE)
+
+ monkeypatch.setattr(process_task_workflow_module.workflow, "logger", logger)
+ monkeypatch.setattr(process_task_workflow_module, "run_credential_refresh_loop", refresh_loop_mock)
+
+ await workflow._run_credential_refresh_until_sandbox_gone("sandbox-123")
+
+ assert workflow._sandbox_gone is False
+ logger.warning.assert_called_once_with(
+ "credential_refresh_stopped_credentials_unavailable",
+ extra={"run_id": "run-id", "sandbox_id": "sandbox-123"},
+ )
+
async def test_run_cleans_up_sandbox_when_provisioning_fails_after_creation(self, monkeypatch):
workflow = ProcessTaskWorkflow()
get_task_processing_context_mock = AsyncMock(return_value=_build_context(github_integration_id=123))
diff --git a/products/tasks/backend/temporal/process_task/workflow.py b/products/tasks/backend/temporal/process_task/workflow.py
index f930abc169de..0024fc38e42f 100644
--- a/products/tasks/backend/temporal/process_task/workflow.py
+++ b/products/tasks/backend/temporal/process_task/workflow.py
@@ -1167,6 +1167,11 @@ class ProcessTaskWorkflow(PostHogWorkflow):
extra={"run_id": self.context.run_id, "sandbox_id": sandbox_id},
)
self._sandbox_gone = True
+ elif exit_reason == CredentialRefreshExitReason.CREDENTIALS_UNAVAILABLE:
+ workflow.logger.warning(
+ "credential_refresh_stopped_credentials_unavailable",
+ extra={"run_id": self.context.run_id, "sandbox_id": sandbox_id},
+ )
def _mark_sandbox_gone(self) -> None:
self._completion_status = "completed"
diff --git a/products/tasks/backend/tests/test_facade.py b/products/tasks/backend/tests/test_facade.py
index 01318ca94765..c6b582fc7f78 100644
--- a/products/tasks/backend/tests/test_facade.py
+++ b/products/tasks/backend/tests/test_facade.py
@@ -115,6 +115,19 @@ class TestFacadeReadsAndMappers(TestCase):
other_user = User.objects.create(email="[email protected]", distinct_id="other")
self.assertFalse(facade.is_task_controllable_by_user(task.id, other_user.id))
+ def test_count_in_progress_runs_for_github_integration_scopes_to_live_runs_of_that_integration(self):
+ integration = Integration.objects.create(team=self.team, kind="github", config={}, sensitive_config={})
+ other_integration = Integration.objects.create(team=self.team, kind="github", config={}, sensitive_config={})
+
+ live_task = self._make_task(github_integration=integration)
+ TaskRun.objects.create(task=live_task, team=self.team, status=TaskRun.Status.IN_PROGRESS)
+ TaskRun.objects.create(task=live_task, team=self.team, status=TaskRun.Status.COMPLETED)
+ other_task = self._make_task(github_integration=other_integration)
+ TaskRun.objects.create(task=other_task, team=self.team, status=TaskRun.Status.IN_PROGRESS)
+
+ self.assertEqual(facade.count_in_progress_runs_for_github_integration(self.team.id, integration.id), 1)
+ self.assertEqual(facade.count_in_progress_runs_for_github_integration(self.team.id + 999, integration.id), 0)
+
def test_get_latest_pr_url_and_run_by_task(self):
task = self._make_task()
TaskRun.objects.create(