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): continue startup after repository clone failure (#81689)

Alessandro Pogliaghi09c68d72c02c
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 142562e4b1c1..78b6339def20 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
@@ -158,6 +158,10 @@ class StartAgentServerInput:
class MarkRepoReadyInput:
sandbox_id: str
run_id: str
+ # Clone failures are non-fatal. Materialize their expected working directories before
+ # releasing the server so it can still open a session and let the agent retry the clone.
+ failed_repositories: list[str] | None = None
+ release_barrier: bool = True
@dataclass
@@ -525,8 +529,22 @@ def launch_agent_server(input: StartAgentServerInput) -> StartAgentServerOutput:
@asyncify
def mark_repo_ready(input: MarkRepoReadyInput) -> None:
sandbox = Sandbox.get_by_id(input.sandbox_id)
- sandbox.mark_repo_ready(REPO_READY_FILE)
- emit_agent_log(input.run_id, "debug", "Repo ready; released agent-server session barrier")
+ for repository in input.failed_repositories or []:
+ repo_path = sandbox_repo_path(repository)
+ result = sandbox.execute(f"mkdir -p {shlex.quote(repo_path)}", timeout_seconds=10)
+ if result.exit_code != 0:
+ raise RuntimeError(f"Failed to create fallback workspace for {repository}: {result.stderr}")
+ if input.release_barrier:
+ sandbox.mark_repo_ready(REPO_READY_FILE)
+ if input.failed_repositories:
+ action = "released agent with" if input.release_barrier else "created"
+ emit_agent_log(
+ input.run_id,
+ "warn",
+ f"Repository clone failed; {action} empty workspace for: {', '.join(input.failed_repositories)}",
+ )
+ elif input.release_barrier:
+ emit_agent_log(input.run_id, "debug", "Repo ready; released agent-server session barrier")
@activity.defn
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 db0d310c2e5c..612ea41fa2ae 100644
--- a/products/tasks/backend/temporal/process_task/tests/test_workflow.py
+++ b/products/tasks/backend/temporal/process_task/tests/test_workflow.py
@@ -1739,7 +1739,7 @@ class TestProcessTaskWorkflowUnit:
assert cloned == ["posthog/posthog", "posthog/code"]
assert result.clone_ms is None
- async def test_overlap_releases_agent_after_primary_repository_clones(self, monkeypatch):
+ async def test_overlap_releases_agent_after_primary_clone_and_materializes_failed_secondary(self, monkeypatch):
workflow = ProcessTaskWorkflow()
workflow._context = _build_context(
github_integration_id=123,
@@ -1767,6 +1767,7 @@ class TestProcessTaskWorkflowUnit:
)
secondary_clone_started = asyncio.Event()
release_secondary_clone = asyncio.Event()
+ ready_inputs: list[Any] = []
async def fake_execute_activity(activity_fn: Any, *args: Any, **kwargs: Any) -> Any:
if activity_fn is prepare_sandbox_for_repository:
@@ -1779,13 +1780,18 @@ class TestProcessTaskWorkflowUnit:
if args[0].repository == "posthog/code":
secondary_clone_started.set()
await release_secondary_clone.wait()
+ raise RuntimeError("secondary clone failed")
else:
await secondary_clone_started.wait()
return None
if activity_fn is mark_repo_ready:
- assert secondary_clone_started.is_set()
- assert not release_secondary_clone.is_set()
- release_secondary_clone.set()
+ ready_inputs.append(args[0])
+ if args[0].release_barrier:
+ assert secondary_clone_started.is_set()
+ assert not release_secondary_clone.is_set()
+ release_secondary_clone.set()
+ else:
+ assert release_secondary_clone.is_set()
return None
if activity_fn is emit_progress_activity:
return None
@@ -1793,11 +1799,127 @@ class TestProcessTaskWorkflowUnit:
monkeypatch.setattr(process_task_workflow_module.workflow, "execute_activity", fake_execute_activity)
monkeypatch.setattr(process_task_workflow_module.workflow, "patched", lambda _: True)
+ monkeypatch.setattr(process_task_workflow_module.workflow, "logger", Mock())
result = await workflow._get_sandbox_for_repository()
assert result.agent_server_launched is True
assert release_secondary_clone.is_set()
+ assert len(ready_inputs) == 2
+ assert ready_inputs[0].failed_repositories is None
+ assert ready_inputs[0].release_barrier is True
+ assert ready_inputs[1].failed_repositories == ["posthog/code"]
+ assert ready_inputs[1].release_barrier is False
+
+ async def test_overlap_releases_agent_and_continues_when_primary_clone_fails(self, monkeypatch):
+ workflow = ProcessTaskWorkflow()
+ workflow._context = _build_context(
+ github_integration_id=123,
+ state={"repositories": ["posthog/posthog"]},
+ )
+ workflow._context.overlap_clone_boot_enabled = True
+ prepared = PrepareSandboxForRepositoryOutput(
+ sandbox_name="sandbox-name",
+ repository="posthog/posthog",
+ github_token="ghs_token",
+ branch="feature-branch",
+ environment_variables={},
+ snapshot_id=None,
+ snapshot_external_id=None,
+ used_snapshot=False,
+ should_create_snapshot=True,
+ shallow_clone=True,
+ image_source="base_image",
+ image_source_label="published sandbox base image",
+ )
+ created = CreateSandboxForRepositoryOutput(
+ sandbox_id="sandbox-123",
+ sandbox_url="https://sandbox.example",
+ connect_token="connect-token",
+ )
+ calls: list[object] = []
+ progress: list[Any] = []
+ ready_inputs: list[Any] = []
+
+ async def fake_execute_activity(activity_fn: Any, *args: Any, **kwargs: Any) -> Any:
+ calls.append(activity_fn)
+ if activity_fn is prepare_sandbox_for_repository:
+ return prepared
+ if activity_fn is create_sandbox_for_repository:
+ return created
+ if activity_fn is launch_agent_server:
+ return StartAgentServerOutput(sandbox_url=created.sandbox_url)
+ if activity_fn is clone_repository_in_sandbox:
+ raise RuntimeError("clone timed out")
+ if activity_fn is mark_repo_ready:
+ ready_inputs.append(args[0])
+ return None
+ if activity_fn is emit_progress_activity:
+ progress.append(args[0])
+ return None
+ raise AssertionError(f"Unexpected activity call: {activity_fn}")
+
+ monkeypatch.setattr(process_task_workflow_module.workflow, "execute_activity", fake_execute_activity)
+ monkeypatch.setattr(process_task_workflow_module.workflow, "patched", lambda _: True)
+ monkeypatch.setattr(process_task_workflow_module.workflow, "logger", Mock())
+
+ result = await workflow._get_sandbox_for_repository()
+
+ assert result.agent_server_launched is True
+ assert mark_repo_ready in calls
+ assert checkout_branch_in_sandbox not in calls
+ assert len(ready_inputs) == 1
+ assert ready_inputs[0].failed_repositories == ["posthog/posthog"]
+ assert ready_inputs[0].release_barrier is True
+ assert progress[-1].label == "Repository clone failed; continuing without it"
+ assert progress[-1].detail == "Could not clone: posthog/posthog"
+
+ async def test_clone_failure_does_not_hide_dead_sandbox_failure(self, monkeypatch):
+ workflow = ProcessTaskWorkflow()
+ workflow._context = _build_context(github_integration_id=123)
+ workflow._context.overlap_clone_boot_enabled = True
+ prepared = PrepareSandboxForRepositoryOutput(
+ sandbox_name="sandbox-name",
+ repository="posthog/posthog",
+ github_token="ghs_token",
+ branch=None,
+ environment_variables={},
+ snapshot_id=None,
+ snapshot_external_id=None,
+ used_snapshot=False,
+ should_create_snapshot=True,
+ shallow_clone=True,
+ image_source="base_image",
+ image_source_label="published sandbox base image",
+ )
+ created = CreateSandboxForRepositoryOutput(
+ sandbox_id="sandbox-123",
+ sandbox_url="https://sandbox.example",
+ connect_token="connect-token",
+ )
+ calls: list[object] = []
+
+ async def fake_execute_activity(activity_fn: Any, *args: Any, **kwargs: Any) -> Any:
+ calls.append(activity_fn)
+ if activity_fn is prepare_sandbox_for_repository:
+ return prepared
+ if activity_fn is create_sandbox_for_repository:
+ return created
+ if activity_fn is launch_agent_server:
+ return StartAgentServerOutput(sandbox_url=created.sandbox_url)
+ if activity_fn is clone_repository_in_sandbox:
+ raise ApplicationError("sandbox disappeared", type="SandboxNotFoundError")
+ if activity_fn is emit_progress_activity:
+ return None
+ raise AssertionError(f"Unexpected activity call: {activity_fn}")
+
+ monkeypatch.setattr(process_task_workflow_module.workflow, "execute_activity", fake_execute_activity)
+ monkeypatch.setattr(process_task_workflow_module.workflow, "patched", lambda _: True)
+
+ with pytest.raises(ApplicationError, match="sandbox disappeared"):
+ await workflow._get_sandbox_for_repository()
+
+ assert mark_repo_ready not in calls
async def test_overlap_preserves_legacy_repo_ready_order_on_replay(self, monkeypatch):
workflow = ProcessTaskWorkflow()
@@ -1919,6 +2041,7 @@ class TestProcessTaskWorkflowUnit:
monkeypatch.setattr(process_task_workflow_module.workflow, "execute_activity", fake_execute_activity)
monkeypatch.setattr(process_task_workflow_module.workflow, "logger", Mock())
+ monkeypatch.setattr(process_task_workflow_module.workflow, "patched", lambda _: True)
result = await workflow._get_sandbox_for_repository()
diff --git a/products/tasks/backend/temporal/process_task/workflow.py b/products/tasks/backend/temporal/process_task/workflow.py
index 8a04ab5cb3dd..8d4e0848f512 100644
--- a/products/tasks/backend/temporal/process_task/workflow.py
+++ b/products/tasks/backend/temporal/process_task/workflow.py
@@ -116,6 +116,7 @@ from .slack_agent_design_relay import SlackAgentDesignRelayInput, SlackAgentDesi
DEAD_SANDBOX_ERROR_TYPES = ("SandboxNotRunningError", "SandboxNotFoundError")
MAX_ACCEPTED_MESSAGE_IDS = 500
_PATCH_ID_CANCEL_SANDBOX_CREATION_ON_COMPLETION = "tasks-cancel-sandbox-creation-on-completion"
+_PATCH_ID_CONTINUE_AFTER_REPOSITORY_CLONE_FAILURE = "tasks-continue-after-repository-clone-failure"
class _TaskCompletedDuringSandboxCreation(Exception):
@@ -1468,44 +1469,101 @@ class ProcessTaskWorkflow(PostHogWorkflow):
launch_ms = launch_output.launch_ms if launch_output else None
clone_ms: int | None = None
+ failed_repositories: set[str] = set()
+ materialized_failed_repositories: set[str] = set()
+ repo_ready_released = False
release_after_primary_clone = bool(
overlap and len(repositories_to_clone) > 1 and workflow.patched(_PATCH_ID_AGENT_READY_AFTER_PRIMARY_CLONE)
)
if will_clone:
await self._emit_progress("clone", "in_progress", "Cloning repository", "setup")
-
- async def clone_repository(repository: str) -> CloneRepositoryInSandboxOutput:
- clone_output = await workflow.execute_activity(
- clone_repository_in_sandbox,
- CloneRepositoryInSandboxInput(
- context=self.context,
- sandbox_id=created.sandbox_id,
- repository=repository,
- github_token=prepared.github_token,
- shallow_clone=prepared.shallow_clone,
- ),
- start_to_close_timeout=timedelta(minutes=5),
- retry_policy=RetryPolicy(maximum_attempts=3),
- )
- if release_after_primary_clone and repository == repositories_to_clone[0]:
- await self._mark_repo_ready(created.sandbox_id)
- return clone_output
+ continue_after_clone_failure = workflow.patched(_PATCH_ID_CONTINUE_AFTER_REPOSITORY_CLONE_FAILURE)
+
+ async def clone_repository(
+ repository: str,
+ ) -> tuple[CloneRepositoryInSandboxOutput | None, bool, bool]:
+ try:
+ clone_output = await workflow.execute_activity(
+ clone_repository_in_sandbox,
+ CloneRepositoryInSandboxInput(
+ context=self.context,
+ sandbox_id=created.sandbox_id,
+ repository=repository,
+ github_token=prepared.github_token,
+ shallow_clone=prepared.shallow_clone,
+ ),
+ start_to_close_timeout=timedelta(minutes=5),
+ retry_policy=RetryPolicy(maximum_attempts=3),
+ )
+ except Exception as error:
+ if _is_dead_sandbox_failure(error) or not continue_after_clone_failure:
+ raise
+ workflow.logger.warning(
+ "repository_clone_failed_continuing_without_repository",
+ extra={
+ "run_id": self.context.run_id,
+ "sandbox_id": created.sandbox_id,
+ "repository": repository,
+ "error": str(error),
+ },
+ )
+ clone_output = None
+ clone_failed = True
+ else:
+ clone_failed = False
+
+ is_primary_repository = repository == repositories_to_clone[0]
+ should_release_after_clone = release_after_primary_clone and is_primary_repository
+ should_materialize_failure = release_after_primary_clone and clone_failed
+ if should_release_after_clone or should_materialize_failure:
+ await self._mark_repo_ready(
+ created.sandbox_id,
+ failed_repositories=[repository] if clone_failed else None,
+ release_barrier=should_release_after_clone,
+ )
+ return clone_output, clone_failed, should_release_after_clone
clone_outputs = await asyncio.gather(
*(clone_repository(repository) for repository in repositories_to_clone)
)
clone_durations: list[int] = []
- for clone_output in clone_outputs:
+ for repository, (clone_output, clone_failed, released_after_clone) in zip(
+ repositories_to_clone, clone_outputs
+ ):
+ if clone_failed:
+ failed_repositories.add(repository)
+ if release_after_primary_clone:
+ materialized_failed_repositories.add(repository)
+ repo_ready_released = repo_ready_released or released_after_clone
if (duration := getattr(clone_output, "clone_ms", None)) is not None:
clone_durations.append(duration)
clone_ms = sum(clone_durations) if clone_durations else None
- clone_label = "Cloned repository" if len(repositories_to_clone) == 1 else "Cloned repositories"
- await self._emit_progress("clone", "completed", clone_label, "setup")
+ if failed_repositories:
+ failed_list = ", ".join(sorted(failed_repositories))
+ remaining_failed_repositories = sorted(failed_repositories - materialized_failed_repositories)
+ should_release_barrier = overlap and not repo_ready_released
+ if remaining_failed_repositories or should_release_barrier:
+ await self._mark_repo_ready(
+ created.sandbox_id,
+ failed_repositories=remaining_failed_repositories or None,
+ release_barrier=should_release_barrier,
+ )
+ repo_ready_released = repo_ready_released or should_release_barrier
+ await self._emit_progress(
+ "clone",
+ "completed",
+ "Repository clone failed; continuing without it",
+ "setup",
+ detail=f"Could not clone: {failed_list}",
+ )
+ else:
+ clone_label = "Cloned repository" if len(repositories_to_clone) == 1 else "Cloned repositories"
+ await self._emit_progress("clone", "completed", clone_label, "setup")
state = self.context.state or {}
is_resume = bool(state.get("resume_from_run_id") or state.get("handoff_resumed"))
checkout_ms: int | None = None
- if will_checkout and not is_resume:
+ if will_checkout and checkout_repository not in failed_repositories and not is_resume:
assert checkout_repository is not None
assert prepared.branch is not None
branch_label_active = f"Checking out branch {prepared.branch}"
@@ -1529,7 +1587,7 @@ class ProcessTaskWorkflow(PostHogWorkflow):
checkout_ms = getattr(checkout_output, "checkout_ms", None)
await self._emit_progress("checkout", "completed", branch_label_done, "setup")
- if overlap and not release_after_primary_clone:
+ if overlap and not repo_ready_released:
await self._mark_repo_ready(created.sandbox_id)
return GetSandboxForRepositoryOutput(
@@ -1705,10 +1763,21 @@ class ProcessTaskWorkflow(PostHogWorkflow):
retry_policy=RetryPolicy(maximum_attempts=3),
)
- async def _mark_repo_ready(self, sandbox_id: str) -> None:
+ async def _mark_repo_ready(
+ self,
+ sandbox_id: str,
+ failed_repositories: list[str] | None = None,
+ *,
+ release_barrier: bool = True,
+ ) -> None:
await workflow.execute_activity(
mark_repo_ready,
- MarkRepoReadyInput(sandbox_id=sandbox_id, run_id=self.context.run_id),
+ MarkRepoReadyInput(
+ sandbox_id=sandbox_id,
+ run_id=self.context.run_id,
+ failed_repositories=failed_repositories,
+ release_barrier=release_barrier,
+ ),
start_to_close_timeout=timedelta(seconds=30),
retry_policy=RetryPolicy(maximum_attempts=3),
)