:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
fix(tasks): start multi-repo agents after primary clone (#79443)
Alessandro Pogliaghi290e4f7e3eab
diff --git a/products/tasks/backend/temporal/process_task/tests/test_workflow.py b/products/tasks/backend/temporal/process_task/tests/test_workflow.pyindex faf7266bc687..740be49f1848 100644--- a/products/tasks/backend/temporal/process_task/tests/test_workflow.py+++ b/products/tasks/backend/temporal/process_task/tests/test_workflow.py@@ -6,6 +6,7 @@ import asyncioimport dataclassesfrom concurrent.futures import ThreadPoolExecutorfrom datetime import UTC, datetime, timedelta+from typing import Anyimport pytestfrom unittest.mock import AsyncMock, Mock@@ -47,6 +48,8 @@ from products.tasks.backend.temporal.process_task.activities import (get_task_processing_context,inject_fresh_tokens_on_resume,invalidate_resume_snapshot,+ launch_agent_server,+ mark_repo_ready,post_permission_delivery_failure_notice,prepare_sandbox_for_repository,read_sandbox_logs,@@ -1346,7 +1349,7 @@ class TestProcessTaskWorkflowUnit:activity_calls: list[object] = []inject_call_args: dict = {}- async def fake_execute_activity(activity_fn, *args, **kwargs):+ async def fake_execute_activity(activity_fn: Any, *args: Any, **kwargs: Any) -> Any:activity_calls.append(activity_fn)if activity_fn is prepare_sandbox_for_repository:return prepared@@ -1440,7 +1443,7 @@ class TestProcessTaskWorkflowUnit:)cloned: list[str] = []- async def fake_execute_activity(activity_fn, *args, **kwargs):+ async def fake_execute_activity(activity_fn: Any, *args: Any, **kwargs: Any) -> Any:if activity_fn is prepare_sandbox_for_repository:return preparedif activity_fn is create_sandbox_for_repository:@@ -1453,12 +1456,125 @@ class TestProcessTaskWorkflowUnit: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)result = await workflow._get_sandbox_for_repository()assert cloned == ["posthog/posthog", "posthog/code"]assert result.clone_ms is None+ async def test_overlap_releases_agent_after_primary_repository_clones(self, monkeypatch):+ workflow = ProcessTaskWorkflow()+ workflow._context = _build_context(+ github_integration_id=123,+ state={"repositories": ["posthog/posthog", "posthog/code"]},+ )+ 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",+ )+ secondary_clone_started = asyncio.Event()+ release_secondary_clone = asyncio.Event()++ async def fake_execute_activity(activity_fn: Any, *args: Any, **kwargs: Any) -> Any:+ 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:+ if args[0].repository == "posthog/code":+ secondary_clone_started.set()+ await release_secondary_clone.wait()+ 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()+ return None+ 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)++ result = await workflow._get_sandbox_for_repository()++ assert result.agent_server_launched is True+ assert release_secondary_clone.is_set()++ async def test_overlap_preserves_legacy_repo_ready_order_on_replay(self, monkeypatch):+ workflow = ProcessTaskWorkflow()+ workflow._context = _build_context(+ github_integration_id=123,+ state={"repositories": ["posthog/posthog", "posthog/code"]},+ )+ 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[str] = []++ async def fake_execute_activity(activity_fn: Any, *args: Any, **kwargs: Any) -> Any:+ 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:+ calls.append(f"clone:{args[0].repository}")+ return None+ if activity_fn is mark_repo_ready:+ calls.append("ready")+ return None+ 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 _: False)++ await workflow._get_sandbox_for_repository()++ assert calls == ["clone:posthog/posthog", "clone:posthog/code", "ready"]+@pytest.mark.parametrize("custom_image_name, expected_image_source, expected_image_source_label",[diff --git a/products/tasks/backend/temporal/process_task/workflow.py b/products/tasks/backend/temporal/process_task/workflow.pyindex ccdf753116b3..62fb637df7e5 100644--- a/products/tasks/backend/temporal/process_task/workflow.py+++ b/products/tasks/backend/temporal/process_task/workflow.py@@ -57,6 +57,7 @@ from .activities.post_slack_update import PostSlackUpdateInput, post_slack_updatfrom .activities.provision_sandbox import (CheckoutBranchInSandboxInput,CloneRepositoryInSandboxInput,+ CloneRepositoryInSandboxOutput,CreateSandboxForRepositoryInput,InjectFreshTokensOnResumeInput,InvalidateResumeSnapshotInput,@@ -248,6 +249,10 @@ _PATCH_ID_CONCURRENT_FOLLOWUP_STEERING = "tasks-concurrent-followup-steering"# preserve that input while new histories subtract the setup agent's elapsed time._PATCH_ID_EXCLUDE_WIZARD_FROM_BOOT_TOTAL = "tasks-exclude-wizard-from-boot-total"+# Multi-repo histories before this patch release the agent only after every clone completes.+# Preserve that command order on replay while new runs can release it after the primary clone.+_PATCH_ID_AGENT_READY_AFTER_PRIMARY_CLONE = "tasks-agent-ready-after-primary-clone"+# #60923 dropped the redundant slack post that ran immediately after sandbox# provisioning — between `_get_sandbox_for_repository` and the agent-start# progress emit. Pre-rollout histories scheduled a `post_slack_update` activity@@ -1359,24 +1364,31 @@ class ProcessTaskWorkflow(PostHogWorkflow):launch_ms = launch_output.launch_ms if launch_output else Noneclone_ms: int | None = None+ 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")- clone_outputs = await asyncio.gather(- *(- 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),- )- for repository in repositories_to_clone++ 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++ clone_outputs = await asyncio.gather(+ *(clone_repository(repository) for repository in repositories_to_clone))clone_durations: list[int] = []for clone_output in clone_outputs:@@ -1413,7 +1425,7 @@ class ProcessTaskWorkflow(PostHogWorkflow):checkout_ms = getattr(checkout_output, "checkout_ms", None)await self._emit_progress("checkout", "completed", branch_label_done, "setup")- if overlap:+ if overlap and not release_after_primary_clone:await self._mark_repo_ready(created.sandbox_id)return GetSandboxForRepositoryOutput(