: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): resolve the protected base branch alongside launch preparation (#104331)
Alessandro Pogliaghi9c809c4a0723
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.pyindex 23cebc5efcee..f02fee1a1f4a 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@@ -2,6 +2,7 @@ import jsonimport timeimport shleximport threading+from concurrent.futures import Future, ThreadPoolExecutorfrom dataclasses import dataclass, fieldfrom datetime import UTC, datetime@@ -70,6 +71,8 @@ logger = get_logger(__name__)AGENT_SERVER_SHADOW_FEATURE_FLAG = "agent-server-shadow-observer"+PROTECTED_BASE_BRANCH_JOIN_TIMEOUT_SECONDS = 30.0+def _emit_agentsh_log_tail(ctx: TaskProcessingContext, sandbox: SandboxBase) -> None:try:@@ -397,7 +400,46 @@ def _include_personal_mcp_for_task(task: Task) -> bool:return not task.internal+def _start_protected_base_branch_lookup(+ ctx: TaskProcessingContext,+) -> tuple[ThreadPoolExecutor, Future[str | None]] | None:+ if not ctx.branch or not ctx.repository or not ctx.has_github_credentials:+ return None++ def _resolve() -> str | None:+ try:+ return _resolve_protected_base_branch(ctx)+ finally:+ try:+ connection.close()+ except Exception:+ pass++ executor = ThreadPoolExecutor(max_workers=1, thread_name_prefix=f"protected-base-branch-{ctx.run_id}")+ return executor, executor.submit(_resolve)+++def _join_protected_base_branch_lookup(+ ctx: TaskProcessingContext, lookup: tuple[ThreadPoolExecutor, Future[str | None]] | None+) -> str | None:+ if lookup is None:+ return _resolve_protected_base_branch(ctx)++ executor, future = lookup+ try:+ return future.result(timeout=PROTECTED_BASE_BRANCH_JOIN_TIMEOUT_SECONDS)+ except TimeoutError:+ logger.warning("resolve_protected_base_branch_timed_out", task_id=ctx.task_id, run_id=ctx.run_id)+ return ctx.branch+ except Exception:+ logger.warning("resolve_protected_base_branch_failed", task_id=ctx.task_id, run_id=ctx.run_id, exc_info=True)+ return ctx.branch+ finally:+ executor.shutdown(wait=False)++def _prepare_launch(ctx: TaskProcessingContext, scopes: PosthogMcpScopes, sandbox_id: str) -> _LaunchParams:+ protected_base_branch_lookup = _start_protected_base_branch_lookup(ctx)task = retry_on_db_connection_drop(lambda: Task.objects.select_related("created_by", "team").get(id=ctx.task_id))try:actor_user = get_task_run_credential_user(task, ctx.state)@@ -517,7 +559,7 @@ def _prepare_launch(ctx: TaskProcessingContext, scopes: PosthogMcpScopes, sandbof"Sandbox environment '{environment_name}' grants full network access; starting without agentsh restrictions",)- protected_base_branch = _resolve_protected_base_branch(ctx)+ protected_base_branch = _join_protected_base_branch_lookup(ctx, protected_base_branch_lookup)return _LaunchParams(mcp_configs=mcp_configs,diff --git a/products/tasks/backend/temporal/process_task/activities/tests/test_start_agent_server.py b/products/tasks/backend/temporal/process_task/activities/tests/test_start_agent_server.pyindex 4a4a4f48f1ee..a48417bcebf7 100644--- a/products/tasks/backend/temporal/process_task/activities/tests/test_start_agent_server.py+++ b/products/tasks/backend/temporal/process_task/activities/tests/test_start_agent_server.py@@ -1,3 +1,4 @@+import threadingfrom typing import Literalimport pytest@@ -628,6 +629,60 @@ def test_resolve_protected_base_skips_lookup_without_repository(mocker) -> None:get.assert_not_called()+def _mock_prepare_launch_dependencies(mocker) -> None:+ prefix = "products.tasks.backend.temporal.process_task.activities.start_agent_server"+ task = mocker.Mock(+ internal=True,+ runtime="claude",+ origin_product=None,+ mcp_builtin_agent_key=None,+ mcp_credential_owner_id=None,+ mcp_gateway_server_allowlist=None,+ )+ mocker.patch(f"{prefix}.Task.objects.select_related").return_value.get.return_value = task+ mocker.patch(f"{prefix}.get_task_run_credential_user", return_value=None)+ mocker.patch(f"{prefix}.create_oauth_access_token_for_run", return_value="access-token")+ mocker.patch(f"{prefix}.TaskRun.objects.filter").return_value.first.return_value = mocker.Mock()+ mocker.patch(f"{prefix}.get_sandbox_ph_mcp_configs", return_value=[])+ mocker.patch(f"{prefix}.get_user_mcp_server_configs", return_value=[])+ mocker.patch(f"{prefix}.get_imported_mcp_server_configs", return_value=[])+ mocker.patch(f"{prefix}.get_relayed_mcp_server_names", return_value=[])+ mocker.patch(f"{prefix}.emit_agent_log")+++ "pr_base,lookup_error,lookup_hangs,expected",+ [+ ("master", None, False, "master"),+ (None, None, False, "posthog-code/fix"),+ (None, RuntimeError("boom"), False, "posthog-code/fix"),+ ("master", None, True, "posthog-code/fix"),+ ],+)+def test_prepare_launch_resolves_protected_base_branch_alongside_preparation(+ mocker, pr_base, lookup_error, lookup_hangs, expected+) -> None:+ prefix = "products.tasks.backend.temporal.process_task.activities.start_agent_server"+ _mock_prepare_launch_dependencies(mocker)+ if lookup_error is not None:+ mocker.patch(f"{prefix}.Integration.objects.get", side_effect=lookup_error)+ else:+ integration = _mock_github_integration(mocker, pr_base=pr_base)+ if lookup_hangs:+ release = threading.Event()+ integration.get_open_pr_base_for_head.side_effect = lambda *_: release.wait(5) and pr_base+ mocker.patch(f"{prefix}.PROTECTED_BASE_BRANCH_JOIN_TIMEOUT_SECONDS", 0.01)+ threading.Timer(1.0, release.set).start()+ context = _context(github_integration_id=42, repository="PostHog/posthog", branch="posthog-code/fix")++ params = _prepare_launch(context, "read_only", "sandbox-id")+ for thread in threading.enumerate():+ if thread.name.startswith("protected-base-branch-"):+ thread.join(5)++ assert params.protected_base_branch == expected++def test_resolve_protected_base_falls_back_to_branch_on_error(mocker) -> None:mocker.patch("products.tasks.backend.temporal.process_task.activities.start_agent_server.Integration.objects.get",