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): restore branch after fresh resume fallback (#71847)

Alessandro Pogliaghi50df7a260cdd
diff --git a/products/tasks/backend/logic/services/docker_sandbox.py b/products/tasks/backend/logic/services/docker_sandbox.py
index bbae5929e740..ac8ac638d115 100644
--- a/products/tasks/backend/logic/services/docker_sandbox.py
+++ b/products/tasks/backend/logic/services/docker_sandbox.py
@@ -726,12 +726,18 @@ class DockerSandbox(SandboxBase):
return result
- def clone_repository(self, repository: str, github_token: str | None = "", shallow: bool = True) -> ExecutionResult:
+ def clone_repository(
+ self,
+ repository: str,
+ github_token: str | None = "",
+ shallow: bool = True,
+ branch: str | None = None,
+ ) -> ExecutionResult:
mount_map = parse_sandbox_repo_mount_map()
if repository.lower() in mount_map:
logger.info(f"Repository {repository} is bind-mounted from host, skipping clone")
return ExecutionResult(stdout="", stderr="", exit_code=0, error=None)
- return super().clone_repository(repository, github_token, shallow)
+ return super().clone_repository(repository, github_token, shallow, branch)
def setup_repository(self, repository: str) -> ExecutionResult:
"""No-op: Repository setup is now handled by agent-server."""
diff --git a/products/tasks/backend/logic/services/sandbox.py b/products/tasks/backend/logic/services/sandbox.py
index f55045de66c0..b55e80aaf546 100644
--- a/products/tasks/backend/logic/services/sandbox.py
+++ b/products/tasks/backend/logic/services/sandbox.py
@@ -250,7 +250,13 @@ class SandboxBase(ABC):
result = self.execute("grep -q autoPublish /scripts/node_modules/.bin/agent-server", timeout_seconds=10)
return result.exit_code == 0
- def clone_repository(self, repository: str, github_token: str | None = "", shallow: bool = True) -> ExecutionResult:
+ def clone_repository(
+ self,
+ repository: str,
+ github_token: str | None = "",
+ shallow: bool = True,
+ branch: str | None = None,
+ ) -> ExecutionResult:
if not self.is_running():
raise RuntimeError("Sandbox not in running state.")
@@ -265,6 +271,7 @@ class SandboxBase(ABC):
org_path = f"{WORKING_DIR}/repos/{org}"
depth_flag = f" --depth {shlex.quote('1')}" if shallow else ""
+ branch_flag = f" --branch {shlex.quote(branch)}" if branch else ""
# Skip blobs over 128kB during full clones — large test snapshots and auto-generated
# files get fetched on demand. Shallow clones are already small enough.
blob_filter = "" if shallow else " --filter=blob:limit=128k"
@@ -272,7 +279,8 @@ class SandboxBase(ABC):
f"rm -rf {shlex.quote(target_path)} && "
f"mkdir -p {shlex.quote(org_path)} && "
f"cd {shlex.quote(org_path)} && "
- f"git clone --single-branch{blob_filter}{depth_flag} {shlex.quote(repo_url)} {shlex.quote(repo)}"
+ f"git clone --single-branch{blob_filter}{depth_flag}{branch_flag} "
+ f"{shlex.quote(repo_url)} {shlex.quote(repo)}"
)
_logger.info(f"Cloning repository {repository} to {target_path} in sandbox {self.id} (shallow={shallow})")
return self.execute(clone_command, timeout_seconds=5 * 60)
diff --git a/products/tasks/backend/logic/services/test_docker_sandbox.py b/products/tasks/backend/logic/services/test_docker_sandbox.py
index bda25d8240de..a9c9eae4be08 100644
--- a/products/tasks/backend/logic/services/test_docker_sandbox.py
+++ b/products/tasks/backend/logic/services/test_docker_sandbox.py
@@ -1,4 +1,5 @@
import os
+import shlex
import subprocess
from typing import Any
@@ -282,8 +283,6 @@ class TestDockerSandboxUnit:
],
)
def test_clone_repository_command_escaping(self, repository):
- import shlex
-
sandbox = DockerSandbox.__new__(DockerSandbox)
sandbox._container_id = "abc123"
sandbox.id = "abc123"
@@ -324,6 +323,20 @@ class TestDockerSandboxUnit:
if not_expected_in_command:
assert not_expected_in_command not in command
+ def test_clone_repository_branch_flag(self):
+ sandbox = DockerSandbox.__new__(DockerSandbox)
+ sandbox._container_id = "abc123"
+ sandbox.id = "abc123"
+ sandbox.config = SandboxConfig(name="test")
+ branch = "feature/branch; echo hacked"
+
+ with patch.object(sandbox, "is_running", return_value=True):
+ with patch.object(sandbox, "execute") as mock_execute:
+ sandbox.clone_repository("PostHog/posthog", github_token="test-token", branch=branch)
+ command = mock_execute.call_args[0][0]
+
+ assert f"--branch {shlex.quote(branch)}" in command
+
@pytest.mark.parametrize(
"repository,task_id,run_id,mode",
[
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 bd90152676fd..e2021f16ef86 100644
--- a/products/tasks/backend/temporal/process_task/activities/provision_sandbox.py
+++ b/products/tasks/backend/temporal/process_task/activities/provision_sandbox.py
@@ -590,11 +590,15 @@ def clone_repository_in_sandbox(input: CloneRepositoryInSandboxInput) -> CloneRe
emit_agent_log(ctx.run_id, "debug", f"Cloning {input.repository} into sandbox")
sandbox = Sandbox.get_by_id(input.sandbox_id)
+ state = ctx.state or {}
+ is_resume = bool(state.get("resume_from_run_id") or state.get("handoff_resumed"))
+
with StepTimer("repository_clone", used_snapshot=False) as clone_timer:
clone_result = sandbox.clone_repository(
input.repository,
github_token=input.github_token,
shallow=input.shallow_clone,
+ branch=ctx.branch if is_resume else None,
)
if clone_result.exit_code != 0:
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
new file mode 100644
index 000000000000..54de6b15a2d8
--- /dev/null
+++ b/products/tasks/backend/temporal/process_task/activities/tests/test_provision_sandbox.py
@@ -0,0 +1,54 @@
+import pytest
+
+from asgiref.sync import async_to_sync
+
+from products.tasks.backend.logic.services.sandbox import ExecutionResult, Sandbox
+from products.tasks.backend.temporal.process_task.activities.get_task_processing_context import TaskProcessingContext
+from products.tasks.backend.temporal.process_task.activities.provision_sandbox import (
+ CloneRepositoryInSandboxInput,
+ clone_repository_in_sandbox,
+)
+
+
+ "state, expected_branch",
+ [
+ ({"resume_from_run_id": "previous-run-id"}, "feature-branch"),
+ ({"handoff_resumed": True}, "feature-branch"),
+ ({}, None),
+ ],
+)
+def test_clone_repository_uses_saved_branch_only_for_resumes(mocker, activity_environment, state, expected_branch):
+ context = TaskProcessingContext(
+ task_id="task-id",
+ run_id="run-id",
+ team_id=1,
+ team_uuid="team-uuid",
+ organization_id="organization-id",
+ github_integration_id=123,
+ repository="posthog/posthog",
+ distinct_id="distinct-id",
+ state=state,
+ _branch="feature-branch",
+ )
+ sandbox = mocker.Mock()
+ sandbox.clone_repository.return_value = ExecutionResult(stdout="", stderr="", exit_code=0)
+ mocker.patch.object(Sandbox, "get_by_id", return_value=sandbox)
+
+ async_to_sync(activity_environment.run)(
+ clone_repository_in_sandbox,
+ CloneRepositoryInSandboxInput(
+ context=context,
+ sandbox_id="sandbox-id",
+ repository="posthog/posthog",
+ github_token="github-token",
+ shallow_clone=True,
+ ),
+ )
+
+ sandbox.clone_repository.assert_called_once_with(
+ "posthog/posthog",
+ github_token="github-token",
+ shallow=True,
+ branch=expected_branch,
+ )