: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(wizard): retry transient github failures when publishing runs (#129095)
Fernando Gomes25950e1a09c4
diff --git a/products/wizard/backend/logic/workers/repository_publisher.py b/products/wizard/backend/logic/workers/repository_publisher.pyindex 90dffc6682f1..c0e3996115de 100644--- a/products/wizard/backend/logic/workers/repository_publisher.py+++ b/products/wizard/backend/logic/workers/repository_publisher.py@@ -34,7 +34,13 @@ _BRANCH_TIP_QUERY = """query($owner: String!, $name: String!, $qualifiedName: Stclass RepositoryPublishingError(Exception):- pass+ def __init__(self, message: str, *, retryable: bool = False) -> None:+ super().__init__(message)+ self.retryable = retryable+++def _is_transient_github_status(status_code: object) -> bool:+ return isinstance(status_code, int) and (status_code == 429 or status_code >= 500)@frozen@@ -75,7 +81,10 @@ def create_signed_commit(branch_tip = head_shaelse:branch_existed = True- _fetch_branch(sandbox, repository_path, branch)+ # A retry after branch creation finds the tip at the local HEAD. Origin has no credentials+ # by then, so a fetch would fail for a private repository.+ if existing_tip != head_sha:+ _fetch_branch(sandbox, repository_path, branch)branch_tip = existing_tipchanges = _staged_changes(sandbox, repository_path, branch_tip)@@ -266,7 +275,10 @@ def _graphql_request(timeout=GITHUB_MUTATION_TIMEOUT_SECONDS,)if response.status_code != 200:- raise RepositoryPublishingError(f"GitHub {endpoint_label} failed with status code {response.status_code}.")+ raise RepositoryPublishingError(+ f"GitHub {endpoint_label} failed with status code {response.status_code}.",+ retryable=_is_transient_github_status(response.status_code),+ )try:payload: Any = response.json()except ValueError as error:@@ -357,7 +369,11 @@ def _created_pull_request(base_branch: str,) -> RepositoryPullRequest:if not isinstance(payload, dict) or payload.get("success") is not True:- raise RepositoryPublishingError("GitHub did not create the pull request.")+ status_code = payload.get("status_code") if isinstance(payload, dict) else None+ raise RepositoryPublishingError(+ f"GitHub did not create the pull request (status code {status_code}).",+ retryable=_is_transient_github_status(status_code),+ )number = payload.get("pr_number")url = payload.get("pr_url")if not isinstance(number, int) or not isinstance(url, str):diff --git a/products/wizard/backend/logic/workers/service.py b/products/wizard/backend/logic/workers/service.pyindex 98bfdf84b4f4..07304d3e7bc9 100644--- a/products/wizard/backend/logic/workers/service.py+++ b/products/wizard/backend/logic/workers/service.py@@ -119,11 +119,14 @@ class WizardWorkerExecutionError(Exception):exit_code: int,detail: str | None = None,wizard_error: WizardErrorLine | None = None,+ *,+ retryable: bool = False,) -> None:self.stage = stageself.exit_code = exit_codeself.detail = detailself.wizard_error = wizard_error+ self.retryable = retryablemessage = f"Wizard Worker {stage} failed with exit code {exit_code}."if detail:@@ -326,7 +329,7 @@ def create_git_repository_handoff(request: GitRepositoryHandoffRequest) -> Wizar)except RepositoryPublishingError as error:- raise WizardWorkerExecutionError("publishing", 1, str(error)) from error+ raise WizardWorkerExecutionError("publishing", 1, str(error), retryable=error.retryable) from errorreturn WizardWorkerResult(diff=diff, pull_request=pull_request)diff --git a/products/wizard/backend/observability/service.py b/products/wizard/backend/observability/service.pyindex bd7b8c1740be..520aabbb5424 100644--- a/products/wizard/backend/observability/service.py+++ b/products/wizard/backend/observability/service.py@@ -157,6 +157,31 @@ class WizardObservability:level=logging.WARNING,)+ def handoff_failed(+ self,+ team_id: int,+ run_id: UUID,+ *,+ error_type: str,+ retryable: bool,+ stage: str | None = None,+ exit_code: int | None = None,+ status_code: int | None = None,+ ) -> None:+ self._observe(+ name="wizard_handoff_failed",+ context={+ "team_id": team_id,+ "run_id": str(run_id),+ "error_type": error_type,+ "retryable": retryable,+ "stage": stage,+ "exit_code": exit_code,+ "status_code": status_code,+ },+ level=logging.WARNING,+ )+def git_diff_omitted(self, run: WizardRunDTO, size_bytes: int) -> None:self._observe(name="wizard_git_diff_omitted",diff --git a/products/wizard/backend/temporal/activities/handoff.py b/products/wizard/backend/temporal/activities/handoff.pyindex 0b1ac19d7f31..11a027c3f40c 100644--- a/products/wizard/backend/temporal/activities/handoff.py+++ b/products/wizard/backend/temporal/activities/handoff.py@@ -1,5 +1,5 @@from temporalio import activity-from temporalio.exceptions import ApplicationError+from temporalio.exceptions import ApplicationError, CancelledErrorfrom posthog.temporal.common.utils import asyncify@@ -11,6 +11,7 @@ from products.wizard.backend.logic.workers import (service as cloud_worker,)from products.wizard.backend.logic.workers.service import GitRepositoryHandoffRequest+from products.wizard.backend.observability.service import wizard_observabilityfrom products.wizard.backend.observability.tracing import annotate_run_span, wizard_spanfrom products.wizard.backend.temporal.activities.errors import (WIZARD_WORKER_EXECUTION_ERROR_TYPE,@@ -39,11 +40,31 @@ def create_run_artifacts(input: PreparedGitRepositoryWorkspace) -> None:))except cloud_worker.WizardWorkerExecutionError as error:+ wizard_observability.handoff_failed(+ input.team_id,+ input.run_id,+ error_type=WIZARD_WORKER_EXECUTION_ERROR_TYPE,+ retryable=error.retryable,+ stage=error.stage,+ exit_code=error.exit_code,+ )raise ApplicationError(str(error),type=WIZARD_WORKER_EXECUTION_ERROR_TYPE,- non_retryable=True,+ non_retryable=not error.retryable,) from error+ except CancelledError:+ raise+ except Exception as error:+ status_code = getattr(error, "status_code", None)+ wizard_observability.handoff_failed(+ input.team_id,+ input.run_id,+ error_type=type(error).__name__,+ retryable=True,+ status_code=status_code if isinstance(status_code, int) else None,+ )+ raisewith wizard_span("wizard.artifacts.persist_diff") as span:span.set_attribute("wizard.diff.size_bytes", len(result.diff))diff --git a/products/wizard/backend/temporal/config.py b/products/wizard/backend/temporal/config.pyindex d55cd72545ce..cd765eb45e70 100644--- a/products/wizard/backend/temporal/config.py+++ b/products/wizard/backend/temporal/config.py@@ -14,6 +14,11 @@ FINALIZATION_RETRY_POLICY = RetryPolicy(maximum_attempts=3)PROVISION_RETRY_POLICY = RetryPolicy(maximum_attempts=1)PREPARATION_RETRY_POLICY = RetryPolicy(maximum_attempts=3)EXECUTION_RETRY_POLICY = RetryPolicy(maximum_attempts=1)-HANDOFF_RETRY_POLICY = RetryPolicy(maximum_attempts=3)+HANDOFF_RETRY_POLICY = RetryPolicy(+ initial_interval=timedelta(seconds=30),+ backoff_coefficient=2.0,+ maximum_interval=timedelta(minutes=2),+ maximum_attempts=5,+)LOCAL_PACKAGE_PREPARATION_RETRY_POLICY = RetryPolicy(maximum_attempts=1)CLEANUP_RETRY_POLICY = RetryPolicy(maximum_attempts=3)diff --git a/products/wizard/backend/tests/runs/test_cloud_activities.py b/products/wizard/backend/tests/runs/test_cloud_activities.pyindex b8e65737d368..3cfd26ad4aeb 100644--- a/products/wizard/backend/tests/runs/test_cloud_activities.py+++ b/products/wizard/backend/tests/runs/test_cloud_activities.py@@ -21,6 +21,8 @@ from temporalio.exceptions import ApplicationError, ApplicationErrorCategory, Cafrom temporalio.testing import ActivityEnvironmentfrom temporalio.worker import ActivityInboundInterceptor, ExecuteActivityInput+from posthog.models.github_integration_base import GitHubIntegrationError+from products.wizard.backend.facade import api as wizard_facadefrom products.wizard.backend.facade.contracts import (CreateWizardRunInput,@@ -415,6 +417,71 @@ def test_execute_wizard_preserves_cancellation() -> None:assert error.value is cancellation+ "handoff_error, error_type, non_retryable, logged",+ (+ (+ WizardWorkerExecutionError(+ "publishing", 1, "GitHub signed commit failed with status code 502.", retryable=True+ ),+ WIZARD_WORKER_EXECUTION_ERROR_TYPE,+ False,+ {"stage": "publishing", "exit_code": 1},+ ),+ (+ WizardWorkerExecutionError("publishing", 1, "Could not read staged file 'fake-wizard-api-key-for-test'."),+ WIZARD_WORKER_EXECUTION_ERROR_TYPE,+ True,+ {"stage": "publishing", "exit_code": 1},+ ),+ (+ WizardWorkerExecutionError("diff capture", 1, detail="fake-wizard-api-key-for-test"),+ WIZARD_WORKER_EXECUTION_ERROR_TYPE,+ True,+ {"stage": "diff capture", "exit_code": 1},+ ),+ (+ GitHubIntegrationError("fake-wizard-api-key-for-test", status_code=503),+ "GitHubIntegrationError",+ False,+ {"stage": None, "status_code": 503},+ ),+ ),+)+def test_create_run_artifacts_retries_only_transient_failures_and_logs_the_step(+ handoff_error: Exception, error_type: str, non_retryable: bool, logged: dict[str, object]+) -> None:+ workspace = PreparedGitRepositoryWorkspace(+ team_id=7,+ run_id=uuid4(),+ sandbox_id="worker-id",+ repository="posthog/posthog",+ root_path="/tmp/workspace/repos/posthog/posthog",+ github_integration_id=456,+ )++ with (+ patch("products.wizard.backend.temporal.activities.handoff.wizard_facade.update_run_stage"),+ patch(+ "products.wizard.backend.temporal.activities.handoff.cloud_worker.create_git_repository_handoff",+ side_effect=handoff_error,+ ),+ pytest.raises(ApplicationError) as error,+ capture_logs() as logs,+ ):+ async_to_sync(_run_create_run_artifacts)(workspace)++ assert error.value.type == error_type+ assert error.value.non_retryable is non_retryable+ assert error.value.message == "Wizard activity failed."+ failure_logs = [log for log in logs if log["event"] == "wizard_handoff_failed"]+ assert len(failure_logs) == 1+ assert failure_logs[0]["log_level"] == "warning"+ assert failure_logs[0]["retryable"] is not non_retryable+ assert {key: failure_logs[0][key] for key in logged} == logged+ assert "fake-wizard-api-key-for-test" not in str(logs)++@pytest.mark.django_db(transaction=True)@patch("products.wizard.backend.logic.artifacts.service.object_storage.write")def test_create_run_artifacts_persists_git_diff_and_pull_request(_write: MagicMock, team, user) -> None:diff --git a/products/wizard/backend/tests/runs/test_cloud_worker.py b/products/wizard/backend/tests/runs/test_cloud_worker.pyindex c73f7d5ad45a..e767a0f4c858 100644--- a/products/wizard/backend/tests/runs/test_cloud_worker.py+++ b/products/wizard/backend/tests/runs/test_cloud_worker.py@@ -32,6 +32,7 @@ from products.wizard.backend.logic.workers.config import ()from products.wizard.backend.logic.workers.contracts import RepositoryPullRequestfrom products.wizard.backend.logic.workers.errors import InvalidWizardProgramCommandError, InvalidWizardVersionError+from products.wizard.backend.logic.workers.repository_publisher import RepositoryPublishingErrorfrom products.wizard.backend.logic.workers.service import (GitRepositoryCloneRequest,GitRepositoryHandoffRequest,@@ -559,6 +560,36 @@ def test_git_repository_handoff_uses_generic_body_when_handoff_is_unavailable(handoff_body_fallback.assert_called_once_with(request.team_id, request.run_id)[email protected]("retryable", [True, False])+@patch("products.wizard.backend.logic.workers.service.stage_publishable_changes")+@patch("products.wizard.backend.logic.workers.service.create_signed_commit")+@patch("products.wizard.backend.logic.workers.service.get_sandbox_class")+def test_git_repository_handoff_keeps_publishing_failures_retryable_only_when_transient(+ get_sandbox_class: MagicMock,+ create_signed_commit: MagicMock,+ _stage_publishable_changes: MagicMock,+ retryable: bool,+) -> None:+ request = GitRepositoryHandoffRequest(+ team_id=7,+ run_id=uuid4(),+ sandbox_id="worker-id",+ workspace_path="/tmp/workspace/repos/posthog/posthog",+ github_integration_id=17,+ repository="PostHog/PostHog",+ )+ get_sandbox_class.return_value.get_by_id.return_value.execute.return_value = _execution_result(+ stdout="diff --git a/a b/a\n"+ )+ create_signed_commit.side_effect = RepositoryPublishingError("GitHub failed.", retryable=retryable)++ with pytest.raises(WizardWorkerExecutionError) as error:+ create_git_repository_handoff(request)++ assert error.value.stage == "publishing"+ assert error.value.retryable is retryable++@patch("products.wizard.backend.logic.workers.service.stage_publishable_changes")@patch("products.wizard.backend.logic.workers.service.create_pull_request")@patch("products.wizard.backend.logic.workers.service.get_sandbox_class")diff --git a/products/wizard/backend/tests/runs/test_cloud_workflow.py b/products/wizard/backend/tests/runs/test_cloud_workflow.pyindex 11d80c3e9d3b..1155184ddf3e 100644--- a/products/wizard/backend/tests/runs/test_cloud_workflow.py+++ b/products/wizard/backend/tests/runs/test_cloud_workflow.py@@ -93,7 +93,7 @@ async def test_cloud_workflow_completes_after_worker_execution(assert execute_activity.await_args_list[4].args[1] == workerassert execute_activity.await_args_list[1].kwargs["retry_policy"].maximum_attempts == 3assert execute_activity.await_args_list[2].kwargs["retry_policy"].maximum_attempts == 1- assert execute_activity.await_args_list[3].kwargs["retry_policy"].maximum_attempts == 3+ assert execute_activity.await_args_list[3].kwargs["retry_policy"].maximum_attempts == 5assert execute_activity.await_args_list[0].kwargs["retry_policy"].maximum_attempts == 1assert execute_activity.await_args_list[4].kwargs["retry_policy"].maximum_attempts == 3diff --git a/products/wizard/backend/tests/runs/test_repository_publisher.py b/products/wizard/backend/tests/runs/test_repository_publisher.pyindex 3c5bfbfd1662..7858bd74dac5 100644--- a/products/wizard/backend/tests/runs/test_repository_publisher.py+++ b/products/wizard/backend/tests/runs/test_repository_publisher.py@@ -3,10 +3,16 @@ import subprocessfrom pathlib import Pathfrom types import SimpleNamespace+import pytestfrom unittest.mock import MagicMock, patchfrom products.wizard.backend.logic.workers.publishable_paths import select_publishable_paths-from products.wizard.backend.logic.workers.repository_publisher import create_signed_commit, stage_publishable_changes+from products.wizard.backend.logic.workers.repository_publisher import (+ RepositoryPublishingError,+ create_pull_request,+ create_signed_commit,+ stage_publishable_changes,+)def _execution_result(*, stdout: str = "", exit_code: int = 0) -> SimpleNamespace:@@ -141,17 +147,26 @@ def test_stage_publishable_changes_replaces_existing_staging(tmp_path: Path) ->assert _git(repository, "diff", "--cached", "--name-only").splitlines() == ["src/component's name.tsx"][email protected]("branch_created_by_earlier_attempt", [False, True])@patch("products.wizard.backend.logic.workers.repository_publisher.GitHubIntegration")@patch("products.wizard.backend.logic.workers.repository_publisher.IntegrationManager")def test_create_signed_commit_strips_head_sha_and_supports_binary_files(integration_manager: MagicMock,github_integration_class: MagicMock,+ branch_created_by_earlier_attempt: bool,) -> None:integration_manager.github.oauth.get_many.return_value = {13: MagicMock()}github = github_integration_class.return_value+ existing_ref = {"target": {"oid": "7a6e71985f4e0058f10517fc662813a39818f805"}}github.api_request.side_effect = [- _graphql_response({"data": {"repository": {"id": "R_1", "ref": None}}}),- _graphql_response({"data": {"createRef": {"ref": {"name": "refs/heads/posthog/wizard-123"}}}}),+ _graphql_response(+ {"data": {"repository": {"id": "R_1", "ref": existing_ref if branch_created_by_earlier_attempt else None}}}+ ),+ *(+ []+ if branch_created_by_earlier_attempt+ else [_graphql_response({"data": {"createRef": {"ref": {"name": "refs/heads/posthog/wizard-123"}}}})]+ ),_graphql_response({"data": {"createCommitOnBranch": {"commit": {"oid": "newsha456"}}}}),]@@ -173,8 +188,65 @@ def test_create_signed_commit_strips_head_sha_and_supports_binary_files(source="wizard",)- create_ref_input = github.api_request.call_args_list[1].kwargs["json_body"]["variables"]["input"]- commit_input = github.api_request.call_args_list[2].kwargs["json_body"]["variables"]["input"]- assert create_ref_input["oid"] == "7a6e71985f4e0058f10517fc662813a39818f805"+ if not branch_created_by_earlier_attempt:+ create_ref_input = github.api_request.call_args_list[1].kwargs["json_body"]["variables"]["input"]+ assert create_ref_input["oid"] == "7a6e71985f4e0058f10517fc662813a39818f805"+ commit_input = github.api_request.call_args_list[-1].kwargs["json_body"]["variables"]["input"]assert commit_input["expectedHeadOid"] == "7a6e71985f4e0058f10517fc662813a39818f805"+ assert not any("fetch" in call.args[0] for call in sandbox.execute.call_args_list)assert result.commit_shas == ("newsha456",)+++ "operation, status_code, retryable",+ [+ ("commit", 502, True),+ ("commit", 401, False),+ ("pull_request", 503, True),+ ("pull_request", 429, True),+ ("pull_request", 422, False),+ ],+)+@patch("products.wizard.backend.logic.workers.repository_publisher.GitHubIntegration")+@patch("products.wizard.backend.logic.workers.repository_publisher.IntegrationManager")+def test_github_failures_are_retryable_only_for_transient_status_codes(+ integration_manager: MagicMock,+ github_integration_class: MagicMock,+ operation: str,+ status_code: int,+ retryable: bool,+) -> None:+ integration_manager.github.oauth.get_many.return_value = {13: MagicMock()}+ github = github_integration_class.return_value+ github.organization.return_value = "posthog"+ github.list_pull_requests.return_value = {"success": True, "pull_requests": []}+ github.create_pull_request.return_value = {"success": False, "status_code": status_code}+ github.api_request.return_value = SimpleNamespace(status_code=status_code)+ sandbox = MagicMock()+ sandbox.execute.return_value = _execution_result(stdout="7a6e71985f4e0058f10517fc662813a39818f805\n")++ with pytest.raises(RepositoryPublishingError) as error:+ if operation == "commit":+ create_signed_commit(+ sandbox,+ team_id=7,+ integration_id=13,+ repository="posthog/posthog",+ branch="posthog/wizard-123",+ message="Set up PostHog",+ source="wizard",+ )+ else:+ create_pull_request(+ team_id=7,+ integration_id=13,+ repository="posthog/posthog",+ head_branch="posthog/wizard-123",+ base_branch="main",+ title="Set up PostHog",+ body="Body",+ source="wizard",+ )++ assert error.value.retryable is retryable+ assert str(status_code) in str(error.value)