: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): create missing branch for cloud task (#72837)
Alessandro Pogliaghifa92c01def82
diff --git a/products/tasks/backend/temporal/process_task/activities/provision_sandbox.py b/products/tasks/backend/temporal/process_task/activities/provision_sandbox.pyindex c3303a71c893..710d801ad4b2 100644--- a/products/tasks/backend/temporal/process_task/activities/provision_sandbox.py+++ b/products/tasks/backend/temporal/process_task/activities/provision_sandbox.py@@ -674,15 +674,37 @@ def checkout_branch_in_sandbox(input: CheckoutBranchInSandboxInput) -> CheckoutBextra={"branch": input.branch, "stderr": update_result.stderr},)- depth_flag = f" --depth {shlex.quote('1')}" if input.shallow_clone else ""- fetch_and_checkout = (- f"cd {shlex.quote(repo_path)} && "- f"git fetch{depth_flag} origin -- {shlex.quote(input.branch)} && "- f"git checkout -B {shlex.quote(input.branch)} FETCH_HEAD"- )+ branch = shlex.quote(input.branch)+ branch_ref = shlex.quote(f"refs/heads/{input.branch}")+ remote_branch_check = f"cd {shlex.quote(repo_path)} && git ls-remote --exit-code --heads origin {branch_ref}"+ remote_branch_result = sandbox.execute(remote_branch_check, timeout_seconds=30)++ if remote_branch_result.exit_code == 0:+ depth_flag = f" --depth {shlex.quote('1')}" if input.shallow_clone else ""+ checkout_command = (+ f"cd {shlex.quote(repo_path)} && "+ f"git fetch{depth_flag} origin -- {branch} && "+ f"git checkout -B {branch} FETCH_HEAD"+ )+ elif remote_branch_result.exit_code == 2:+ if input.used_snapshot:+ depth_flag = f" --depth {shlex.quote('1')}" if input.shallow_clone else ""+ checkout_command = (+ f"cd {shlex.quote(repo_path)} && "+ f"git fetch{depth_flag} origin -- HEAD && "+ f"git checkout -B {branch} FETCH_HEAD"+ )+ else:+ checkout_command = f"cd {shlex.quote(repo_path)} && git checkout -B {branch} HEAD"+ else:+ logger.warning(+ "Failed to check whether remote branch exists",+ extra={"branch": input.branch, "stderr": remote_branch_result.stderr},+ )+ raise RuntimeError(f"Failed to check whether branch {input.branch} exists")with StepTimer("branch_checkout", used_snapshot=input.used_snapshot) as checkout_timer:- result = sandbox.execute(fetch_and_checkout, timeout_seconds=5 * 60)+ result = sandbox.execute(checkout_command, timeout_seconds=5 * 60)if result.exit_code != 0:logger.warning("Branch checkout failed", extra={"branch": input.branch, "stderr": result.stderr})diff --git a/products/tasks/backend/temporal/process_task/tests/test_provision_sandbox.py b/products/tasks/backend/temporal/process_task/tests/test_provision_sandbox.pyindex 89c164bab3f6..20eebaba58b3 100644--- a/products/tasks/backend/temporal/process_task/tests/test_provision_sandbox.py+++ b/products/tasks/backend/temporal/process_task/tests/test_provision_sandbox.py@@ -1,16 +1,21 @@-from typing import Any+from collections.abc import Callable+from typing import Any, castimport pytestfrom unittest.mock import MagicMock, patchfrom django.test import override_settings+from products.tasks.backend.logic.services.sandbox import ExecutionResultfrom products.tasks.backend.temporal.process_task.activities.get_task_processing_context import TaskProcessingContextfrom products.tasks.backend.temporal.process_task.activities.provision_sandbox import (+ CheckoutBranchInSandboxInput,+ CheckoutBranchInSandboxOutput,PrepareSandboxForRepositoryOutput,_build_environment_variables,_build_sandbox_tags,_to_modal_domain_allowlist,+ checkout_branch_in_sandbox,)_PROVISION = "products.tasks.backend.temporal.process_task.activities.provision_sandbox"@@ -129,6 +134,46 @@ def test_to_modal_domain_allowlist_resolves_exact_list(allowed_domains, expectedassert _to_modal_domain_allowlist(allowed_domains) == expected+@patch(f"{_PROVISION}.emit_agent_log")+@patch(f"{_PROVISION}.Sandbox.get_by_id")+ "used_snapshot, expected_checkout",+ [+ (False, "git checkout -B new-task-branch HEAD"),+ (True, "git fetch --depth 1 origin -- HEAD && git checkout -B new-task-branch FETCH_HEAD"),+ ],+)+def test_checkout_branch_creates_missing_branch_from_current_default_branch(+ mock_get_sandbox, _mock_emit_agent_log, used_snapshot, expected_checkout+):+ sandbox = mock_get_sandbox.return_value++ def execute(command, **_kwargs):+ exit_code = 2 if "git ls-remote" in command else 0+ return ExecutionResult(stdout="", stderr="", exit_code=exit_code)++ sandbox.execute.side_effect = execute+ activity_body = cast(+ Callable[[CheckoutBranchInSandboxInput], CheckoutBranchInSandboxOutput],+ vars(checkout_branch_in_sandbox)["__wrapped__"],+ )++ activity_body(+ CheckoutBranchInSandboxInput(+ context=_context(),+ sandbox_id="sandbox-123",+ repository="posthog/posthog",+ branch="new-task-branch",+ github_token="token",+ shallow_clone=True,+ used_snapshot=used_snapshot,+ )+ )++ checkout_command = sandbox.execute.call_args_list[-1].args[0]+ assert expected_checkout in checkout_command++@patch(f"{_PROVISION}.get_git_identity_env_vars", return_value={})@patch(f"{_PROVISION}.get_sandbox_jwt_public_key", return_value="pub")@patch(f"{_PROVISION}.get_sandbox_api_url", return_value="https://api.example")