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.

feat(wizard): trace cloud worker run lifecycle (#102978)

Fernando Gomes937cd2ade04d
diff --git a/docs/internal/wizard-runs.md b/docs/internal/wizard-runs.md
index f6dc2309c773..3645918b0052 100644
--- a/docs/internal/wizard-runs.md
+++ b/docs/internal/wizard-runs.md
@@ -125,6 +125,45 @@ Events omit repository names, paths, full shell commands, diff contents, tokens,
## Deployment configuration
+### Distributed tracing
+
+Cloud runs use the shared OpenTelemetry instrumentation described in the [distributed tracing guide](https://posthog.com/docs/distributed-tracing).
+The request's trace context passes through the Temporal client's headers into the workflow and its activities.
+The worker enables Temporal's replay-safe tracing plugin for `WIZARD_TASK_QUEUE` when `OTEL_SERVICE_NAME` is configured.
+The plugin records workflow and activity durations, including separate activity attempts.
+
+Wizard spans add the following detail to the trace waterfall:
+
+| Span prefix | Operations |
+| -------------------- | ------------------------------------------------------------------------------------------------------------------------ |
+| `wizard.run` | Creation, dispatch, cancellation |
+| `wizard.worker` | Credential creation, provisioning, CPU sampler startup, usage measurement |
+| `wizard.sandbox` | Sandbox creation and destruction |
+| `wizard.repository` | Access checks, credentials, clone, remote cleanup, staging, diff capture, handoff reading, commit, pull request creation |
+| `wizard.package` | Local source archive, upload, build |
+| `wizard.cli.execute` | The sandbox command that installs and runs the setup agent |
+| `wizard.artifacts` | Diff persistence |
+
+Find a run using the `wizard.run_id` attribute on its creation, dispatch, and activity spans, then open the full trace.
+These spans also carry `team_id`.
+Clone spans include `process.exit.code`; diff persistence spans include `wizard.diff.size_bytes`.
+Custom Wizard spans record error types and error status without recording exception messages, command output, repository contents, or credentials.
+Every Wizard activity replaces failure messages with a fixed message before Temporal records the failure.
+The replacement preserves the error type and retry settings, but drops details and exception chains so automatic Temporal spans cannot export sandbox output.
+Cancellation exceptions keep their cancellation semantics.
+
+The CLI runs in a separate sandbox process and is distributed from another repository.
+Its internal agent steps are represented by the duration of `wizard.cli.execute`; they do not emit child spans from this instrumentation.
+Recovery dispatches that start outside the original request can produce another trace, correlated by `wizard.run_id`.
+
+Configure `OTEL_SERVICE_NAME` and the existing OTLP collector endpoint on both the web service and the Wizard Worker.
+The shared Python exporter sends gRPC to the collector; configure that collector to forward traces to PostHog's HTTP `/i/v1/traces` endpoint with its project token.
+The [Python installation guide](https://posthog.com/docs/distributed-tracing/installation/python) describes the HTTP exporter configuration for direct clients.
+Check web-service sampling when validating a run: a parent trace that is not sampled also suppresses its child spans.
+For a controlled validation environment, use `OTEL_TRACES_SAMPLER=always_on`, create a cloud run, and confirm its activity spans and cleanup appear in one trace.
+
+### Worker deployment
+
The production rollout depends on the [Wizard Worker chart](https://github.com/PostHog/charts/pull/14662) and [cloud infrastructure](https://github.com/PostHog/posthog-cloud-infra/pull/10081) changes.
The chart must run a worker that polls `wizard-task-queue` before cloud run creation is enabled.
`WIZARD_RUN_ARTIFACTS_S3_BUCKET` must identify the provisioned artifact bucket.
diff --git a/posthog/management/commands/start_temporal_worker.py b/posthog/management/commands/start_temporal_worker.py
index 1f640041c1d8..5130ba4ee328 100644
--- a/posthog/management/commands/start_temporal_worker.py
+++ b/posthog/management/commands/start_temporal_worker.py
@@ -746,14 +746,14 @@ class Command(BaseCommand):
tag_queries(kind="temporal")
- # Max AI and tasks-agent traces span the Django request and the Temporal activity that runs
+ # Max AI, tasks-agent, and wizard traces span the Django request and the Temporal activity that runs
# the agent loop. Without the OTel plugin on the worker, every span emitted from an activity
# is a root span and the conversation trace splits across disconnected pieces. Force-enable
- # for both queues so investigations don't depend on an operator flipping
+ # for these queues so investigations don't depend on an operator flipping
# TEMPORAL_OTEL_PLUGIN_ENABLED.
enable_otel = (
settings.TEMPORAL_OTEL_PLUGIN_ENABLED is True
- or task_queue in (settings.MAX_AI_TASK_QUEUE, settings.TASKS_TASK_QUEUE)
+ or task_queue in (settings.MAX_AI_TASK_QUEUE, settings.TASKS_TASK_QUEUE, settings.WIZARD_TASK_QUEUE)
) and settings.OTEL_SERVICE_NAME is not None
if enable_otel is True:
# Mypy doesn't understand we have already checked settings.OTEL_SERVICE_NAME
diff --git a/products/wizard/backend/logic/runs/cancellation.py b/products/wizard/backend/logic/runs/cancellation.py
index 27059ee7594c..1843cff9515e 100644
--- a/products/wizard/backend/logic/runs/cancellation.py
+++ b/products/wizard/backend/logic/runs/cancellation.py
@@ -2,18 +2,22 @@ import logging
from uuid import UUID
from products.wizard.backend.logic.runs import store
+from products.wizard.backend.observability.tracing import annotate_run_span, wizard_span
from products.wizard.backend.temporal import client as temporal_client
from products.wizard.backend.temporal.errors import WizardTemporalError
logger = logging.getLogger(__name__)
+@wizard_span("wizard.run.cancel")
def dispatch_cancellation(team_id: int, run_id: UUID) -> bool:
+ annotate_run_span(team_id, run_id)
if store.get_workflow_id(team_id, run_id) is None:
return False
try:
- temporal_client.cancel_wizard_run_workflow(run_id)
+ with wizard_span("wizard.run.cancel_workflow"):
+ temporal_client.cancel_wizard_run_workflow(run_id)
except WizardTemporalError:
logger.exception("wizard_run_cancellation_failed", extra={"team_id": team_id, "run_id": str(run_id)})
return False
diff --git a/products/wizard/backend/logic/runs/dispatch.py b/products/wizard/backend/logic/runs/dispatch.py
index 6162e945a0e8..24546b4a0af2 100644
--- a/products/wizard/backend/logic/runs/dispatch.py
+++ b/products/wizard/backend/logic/runs/dispatch.py
@@ -9,13 +9,16 @@ from products.wizard.backend.logic.runs.errors import WizardRunDispatchError
from products.wizard.backend.logic.workers.config import local_wizard_source_root
from products.wizard.backend.observability.contracts import WizardRunDispatchOutcome
from products.wizard.backend.observability.service import wizard_observability
+from products.wizard.backend.observability.tracing import annotate_run_span, wizard_span
from products.wizard.backend.temporal import client as temporal_client
from products.wizard.backend.temporal.constants import wizard_run_workflow_id
from products.wizard.backend.temporal.contracts import WizardRunActivityInput
from products.wizard.backend.temporal.errors import WizardTemporalError
+@wizard_span("wizard.run.dispatch")
def dispatch_created_cloud_wizard_run_to_temporal_worker(team_id: int, run_id: UUID) -> None:
+ annotate_run_span(team_id, run_id)
run = store.get_run(team_id, run_id)
if run.environment != WizardRunEnvironment.CLOUD or run.status != WizardRunStatus.CREATED:
diff --git a/products/wizard/backend/logic/runs/lifecycle.py b/products/wizard/backend/logic/runs/lifecycle.py
index 467ded0c7b1a..1b45afbfff6e 100644
--- a/products/wizard/backend/logic/runs/lifecycle.py
+++ b/products/wizard/backend/logic/runs/lifecycle.py
@@ -42,6 +42,7 @@ from products.wizard.backend.logic.runs.fingerprints import create_run_request_f
from products.wizard.backend.logic.runs.repository_access import authorize_git_repository_access
from products.wizard.backend.logic.runs.transitions import transition
from products.wizard.backend.observability.service import wizard_observability as run_observability
+from products.wizard.backend.observability.tracing import annotate_run_span, wizard_span
logger = logging.getLogger(__name__)
@@ -50,6 +51,7 @@ def create_run(params: CreateWizardRunInput) -> WizardRunDTO:
return create_run_with_result(params).run
+@wizard_span("wizard.run.create")
def create_run_with_result(params: CreateWizardRunInput) -> WizardRunCreationResult:
match params.environment, params.workspace:
case WizardRunEnvironment.LOCAL, LocalFolderWorkspace():
@@ -74,6 +76,7 @@ def create_run_with_result(params: CreateWizardRunInput) -> WizardRunCreationRes
if store.get_request_fingerprint(params.team_id, existing.id) != request_fingerprint:
raise WizardRunIdempotencyConflictError
+ annotate_run_span(params.team_id, existing.id)
return WizardRunCreationResult(run=existing, created=False)
user = User.objects.only("distinct_id").get(id=params.created_by_id)
@@ -112,6 +115,7 @@ def create_run_with_result(params: CreateWizardRunInput) -> WizardRunCreationRes
idempotency_key=params.idempotency_key,
request_fingerprint=request_fingerprint,
)
+ annotate_run_span(params.team_id, result.run.id)
if not result.created and store.get_request_fingerprint(params.team_id, result.run.id) != request_fingerprint:
raise WizardRunIdempotencyConflictError
diff --git a/products/wizard/backend/logic/runs/repository_access.py b/products/wizard/backend/logic/runs/repository_access.py
index f46890b56dd1..fb71f70b972d 100644
--- a/products/wizard/backend/logic/runs/repository_access.py
+++ b/products/wizard/backend/logic/runs/repository_access.py
@@ -1,8 +1,10 @@
from products.tasks.backend.facade import repo_selection
from products.wizard.backend.facade.errors import MissingGitHubIntegrationError, RepositoryNotAccessibleError
from products.wizard.backend.logic.runs.validation import validate_git_repository_name
+from products.wizard.backend.observability.tracing import wizard_span
+@wizard_span("wizard.repository.authorize")
def authorize_git_repository_access(team_id: int, repository: str) -> int:
validate_git_repository_name(repository)
diff --git a/products/wizard/backend/logic/workers/service.py b/products/wizard/backend/logic/workers/service.py
index 0f0fbff38fb6..eadcb2ff45e9 100644
--- a/products/wizard/backend/logic/workers/service.py
+++ b/products/wizard/backend/logic/workers/service.py
@@ -57,6 +57,7 @@ from products.wizard.backend.logic.workers.contracts import (
from products.wizard.backend.logic.workers.local_package import build_local_wizard_source_archive
from products.wizard.backend.logic.workers.wizard_error_output import stderr_to_wizard_error_code
from products.wizard.backend.observability.service import wizard_observability
+from products.wizard.backend.observability.tracing import annotate_run_span, wizard_span
from .repository_publisher import (
RepositoryPublishingError,
@@ -132,12 +133,16 @@ class WizardWorkerTimeoutError(Exception):
pass
+@wizard_span("wizard.worker.provision")
def provision_wizard_worker(request: WizardWorkerProvisionRequest) -> WizardWorkerProvisioning:
+ annotate_run_span(request.team_id, request.run_id)
user = User.objects.get(id=request.created_by_id)
- wizard_token = create_wizard_oauth_access_token_for_user(user, request.team_id)
+ with wizard_span("wizard.worker.credentials"):
+ wizard_token = create_wizard_oauth_access_token_for_user(user, request.team_id)
config = _build_sandbox_config(request, wizard_token)
- sandbox = get_sandbox_class().create(config)
+ with wizard_span("wizard.sandbox.create"):
+ sandbox = get_sandbox_class().create(config)
_start_cpu_billing_sampler(sandbox)
provisioned_at = timezone.now()
@@ -153,6 +158,7 @@ def provision_wizard_worker(request: WizardWorkerProvisionRequest) -> WizardWork
)
+@wizard_span("wizard.worker.start_cpu_sampler")
def _start_cpu_billing_sampler(sandbox: SandboxBase) -> None:
try:
started = sandbox.start_cpu_billing_sampler()
@@ -166,63 +172,73 @@ def _start_cpu_billing_sampler(sandbox: SandboxBase) -> None:
logger.warning("wizard_worker_cpu_billing_sampler_start_failed", extra={"sandbox_id": sandbox.id})
+@wizard_span("wizard.repository.prepare")
def clone_repository(request: GitRepositoryCloneRequest) -> str:
sandbox = get_sandbox_class().get_by_id(request.sandbox_id)
- github_token = get_github_token(request.github_integration_id) or ""
- clone_result = sandbox.clone_repository(request.repository, github_token=github_token, shallow=True)
+ with wizard_span("wizard.repository.credentials"):
+ github_token = get_github_token(request.github_integration_id) or ""
+ with wizard_span("wizard.repository.clone") as span:
+ clone_result = sandbox.clone_repository(request.repository, github_token=github_token, shallow=True)
+ span.set_attribute("process.exit.code", clone_result.exit_code)
- _raise_for_failure(
- "repository clone",
- clone_result.exit_code,
- stdout=clone_result.stdout,
- stderr=clone_result.stderr,
- sensitive_values=(github_token,),
- )
+ _raise_for_failure(
+ "repository clone",
+ clone_result.exit_code,
+ stdout=clone_result.stdout,
+ stderr=clone_result.stderr,
+ sensitive_values=(github_token,),
+ )
workspace_path = sandbox_repo_path(request.repository)
- sanitize_result = sandbox.execute(
- build_sanitize_repository_remote_command(workspace_path, request.repository),
- timeout_seconds=60,
- )
- _raise_for_failure(
- "repository credential cleanup",
- sanitize_result.exit_code,
- stdout=sanitize_result.stdout,
- stderr=sanitize_result.stderr,
- sensitive_values=(github_token,),
- )
+ with wizard_span("wizard.repository.sanitize_remote"):
+ sanitize_result = sandbox.execute(
+ build_sanitize_repository_remote_command(workspace_path, request.repository),
+ timeout_seconds=60,
+ )
+ _raise_for_failure(
+ "repository credential cleanup",
+ sanitize_result.exit_code,
+ stdout=sanitize_result.stdout,
+ stderr=sanitize_result.stderr,
+ sensitive_values=(github_token,),
+ )
return workspace_path
+@wizard_span("wizard.package.prepare")
def prepare_local_wizard(sandbox_id: str, source_root: Path) -> None:
- archive = build_local_wizard_source_archive(source_root)
+ with wizard_span("wizard.package.archive"):
+ archive = build_local_wizard_source_archive(source_root)
try:
sandbox = get_sandbox_class().get_by_id(sandbox_id)
- upload_result = sandbox.write_file(LOCAL_WIZARD_ARCHIVE_PATH, archive)
- _raise_for_failure(
- "local Wizard source upload",
- upload_result.exit_code,
- stdout=upload_result.stdout,
- stderr=upload_result.stderr,
- )
+ with wizard_span("wizard.package.upload"):
+ upload_result = sandbox.write_file(LOCAL_WIZARD_ARCHIVE_PATH, archive)
+ _raise_for_failure(
+ "local Wizard source upload",
+ upload_result.exit_code,
+ stdout=upload_result.stdout,
+ stderr=upload_result.stderr,
+ )
- build_result = sandbox.execute(
- build_local_wizard_preparation_command(),
- timeout_seconds=LOCAL_WIZARD_BUILD_TIMEOUT_SECONDS,
- )
- _raise_for_failure(
- "local Wizard build",
- build_result.exit_code,
- stdout=build_result.stdout,
- stderr=build_result.stderr,
- )
+ with wizard_span("wizard.package.build"):
+ build_result = sandbox.execute(
+ build_local_wizard_preparation_command(),
+ timeout_seconds=LOCAL_WIZARD_BUILD_TIMEOUT_SECONDS,
+ )
+ _raise_for_failure(
+ "local Wizard build",
+ build_result.exit_code,
+ stdout=build_result.stdout,
+ stderr=build_result.stderr,
+ )
except (SandboxExecutionError, SandboxNotFoundError, SandboxTimeoutError) as error:
raise WizardWorkerExecutionError("local Wizard preparation", 1, str(error)) from error
+@wizard_span("wizard.cli.execute")
def execute_wizard(request: WizardExecutionRequest) -> None:
sandbox = get_sandbox_class().get_by_id(request.sandbox_id)
@@ -250,21 +266,25 @@ def execute_wizard(request: WizardExecutionRequest) -> None:
)
+@wizard_span("wizard.repository.handoff")
def create_git_repository_handoff(request: GitRepositoryHandoffRequest) -> WizardWorkerResult:
+ annotate_run_span(request.team_id, request.run_id)
sandbox = get_sandbox_class().get_by_id(request.sandbox_id)
- stage_publishable_changes(sandbox, request.workspace_path)
+ with wizard_span("wizard.repository.stage_changes"):
+ stage_publishable_changes(sandbox, request.workspace_path)
- diff_result = sandbox.execute(
- build_git_diff_command(request.workspace_path),
- timeout_seconds=60,
- )
+ with wizard_span("wizard.repository.capture_diff"):
+ diff_result = sandbox.execute(
+ build_git_diff_command(request.workspace_path),
+ timeout_seconds=60,
+ )
- _raise_for_failure(
- "diff capture",
- diff_result.exit_code,
- stdout=diff_result.stdout,
- stderr=diff_result.stderr,
- )
+ _raise_for_failure(
+ "diff capture",
+ diff_result.exit_code,
+ stdout=diff_result.stdout,
+ stderr=diff_result.stderr,
+ )
diff = diff_result.stdout.encode("utf-8")
@@ -279,25 +299,27 @@ def create_git_repository_handoff(request: GitRepositoryHandoffRequest) -> Wizar
handoff_body = PULL_REQUEST_BODY
try:
- create_signed_commit(
- sandbox,
- team_id=request.team_id,
- integration_id=request.github_integration_id,
- repository=request.repository,
- branch=branch,
- message=PULL_REQUEST_COMMIT_MESSAGE,
- source="wizard",
- )
+ with wizard_span("wizard.repository.commit"):
+ create_signed_commit(
+ sandbox,
+ team_id=request.team_id,
+ integration_id=request.github_integration_id,
+ repository=request.repository,
+ branch=branch,
+ message=PULL_REQUEST_COMMIT_MESSAGE,
+ source="wizard",
+ )
- pull_request = create_pull_request(
- team_id=request.team_id,
- integration_id=request.github_integration_id,
- repository=request.repository,
- head_branch=branch,
- title=PULL_REQUEST_TITLE,
- body=handoff_body,
- source="wizard",
- )
+ with wizard_span("wizard.repository.create_pull_request"):
+ pull_request = create_pull_request(
+ team_id=request.team_id,
+ integration_id=request.github_integration_id,
+ repository=request.repository,
+ head_branch=branch,
+ title=PULL_REQUEST_TITLE,
+ body=handoff_body,
+ source="wizard",
+ )
except RepositoryPublishingError as error:
raise WizardWorkerExecutionError("publishing", 1, str(error)) from error
@@ -305,6 +327,7 @@ def create_git_repository_handoff(request: GitRepositoryHandoffRequest) -> Wizar
return WizardWorkerResult(diff=diff, pull_request=pull_request)
+@wizard_span("wizard.sandbox.destroy")
def destroy_worker(sandbox_id: str) -> None:
try:
sandbox = get_sandbox_class().get_by_id(sandbox_id)
@@ -313,6 +336,7 @@ def destroy_worker(sandbox_id: str) -> None:
sandbox.destroy()
+@wizard_span("wizard.worker.measure_usage")
def measure_worker_usage(sandbox_id: str) -> WizardWorkerUsageMeasurement | None:
try:
sandbox = get_sandbox_class().get_by_id(sandbox_id)
@@ -367,6 +391,7 @@ def _failure_detail(stdout: str, stderr: str, sensitive_values: tuple[str, ...])
return output[-WIZARD_ERROR_DETAIL_LENGTH:] or None
+@wizard_span("wizard.repository.read_handoff")
def _read_handoff_body(sandbox: SandboxBase, run_id: UUID) -> str | None:
handoff_result = sandbox.execute(build_read_handoff_command(run_id), timeout_seconds=10)
if handoff_result.exit_code != 0:
diff --git a/products/wizard/backend/observability/tracing.py b/products/wizard/backend/observability/tracing.py
new file mode 100644
index 000000000000..0dedf7c58e21
--- /dev/null
+++ b/products/wizard/backend/observability/tracing.py
@@ -0,0 +1,26 @@
+from collections.abc import Iterator
+from contextlib import contextmanager
+from uuid import UUID
+
+from opentelemetry import trace
+from opentelemetry.trace import Span, StatusCode
+
+tracer = trace.get_tracer(__name__)
+
+
+def annotate_run_span(team_id: int, run_id: UUID) -> None:
+ span = trace.get_current_span()
+ span.set_attribute("team_id", team_id)
+ span.set_attribute("wizard.run_id", str(run_id))
+
+
+@contextmanager
+def wizard_span(name: str) -> Iterator[Span]:
+ # Worker exceptions can contain command output and credentials; export only the error type.
+ with tracer.start_as_current_span(name, record_exception=False, set_status_on_exception=False) as span:
+ try:
+ yield span
+ except Exception as error:
+ span.set_attribute("error.type", type(error).__name__)
+ span.set_status(StatusCode.ERROR)
+ raise
diff --git a/products/wizard/backend/temporal/activities/errors.py b/products/wizard/backend/temporal/activities/errors.py
index 2f41f89415e6..b7416677c7db 100644
--- a/products/wizard/backend/temporal/activities/errors.py
+++ b/products/wizard/backend/temporal/activities/errors.py
@@ -1,4 +1,38 @@
+from collections.abc import Callable
+from functools import wraps
+from typing import ParamSpec, TypeVar
+
+from temporalio.exceptions import ApplicationError, CancelledError
+
WIZARD_REPOSITORY_ACCESS_ERROR_TYPE = "WizardRepositoryAccessError"
WIZARD_RUN_CONFIGURATION_ERROR_TYPE = "WizardRunConfigurationError"
WIZARD_WORKER_EXECUTION_ERROR_TYPE = "WizardWorkerExecutionError"
WIZARD_WORKER_TIMEOUT_ERROR_TYPE = "WizardWorkerTimeoutError"
+
+P = ParamSpec("P")
+T = TypeVar("T")
+
+
+def sanitize_activity_errors(function: Callable[P, T]) -> Callable[P, T]:
+ @wraps(function)
+ def wrapped(*args: P.args, **kwargs: P.kwargs) -> T:
+ try:
+ return function(*args, **kwargs)
+ except CancelledError:
+ raise
+ except ApplicationError as error:
+ safe_error = ApplicationError(
+ "Wizard activity failed.",
+ type=error.type,
+ non_retryable=error.non_retryable,
+ next_retry_delay=error.next_retry_delay,
+ category=error.category,
+ )
+ except Exception as error:
+ safe_error = ApplicationError("Wizard activity failed.", type=type(error).__name__)
+
+ # Temporal exports exception messages and stacks. Raise outside the handler so neither
+ # __cause__ nor __context__ carries sandbox output into traces or workflow history.
+ raise safe_error from None
+
+ return wrapped
diff --git a/products/wizard/backend/temporal/activities/execution.py b/products/wizard/backend/temporal/activities/execution.py
index 3c7981c6a2d6..a4568d7c59ad 100644
--- a/products/wizard/backend/temporal/activities/execution.py
+++ b/products/wizard/backend/temporal/activities/execution.py
@@ -7,16 +7,20 @@ from products.wizard.backend.facade import api as wizard_facade
from products.wizard.backend.facade.enums import WizardRunStage
from products.wizard.backend.logic.workers import service as cloud_worker
from products.wizard.backend.logic.workers.service import WizardExecutionRequest
+from products.wizard.backend.observability.tracing import annotate_run_span
from products.wizard.backend.temporal.activities.errors import (
WIZARD_WORKER_EXECUTION_ERROR_TYPE,
WIZARD_WORKER_TIMEOUT_ERROR_TYPE,
+ sanitize_activity_errors,
)
from products.wizard.backend.temporal.contracts import PreparedGitRepositoryWorkspace
@activity.defn(name="wizard_execute")
@asyncify
+@sanitize_activity_errors
def execute_wizard(input: PreparedGitRepositoryWorkspace) -> None:
+ annotate_run_span(input.team_id, input.run_id)
wizard_facade.update_run_stage(input.team_id, input.run_id, WizardRunStage.EXECUTING_WIZARD)
run = wizard_facade.get_run(input.team_id, input.run_id)
try:
diff --git a/products/wizard/backend/temporal/activities/handoff.py b/products/wizard/backend/temporal/activities/handoff.py
index 43504be50e7f..a3ceab150846 100644
--- a/products/wizard/backend/temporal/activities/handoff.py
+++ b/products/wizard/backend/temporal/activities/handoff.py
@@ -11,14 +11,20 @@ from products.wizard.backend.logic.workers import (
service as cloud_worker,
)
from products.wizard.backend.logic.workers.service import GitRepositoryHandoffRequest
-from products.wizard.backend.temporal.activities.errors import WIZARD_WORKER_EXECUTION_ERROR_TYPE
+from products.wizard.backend.observability.tracing import annotate_run_span, wizard_span
+from products.wizard.backend.temporal.activities.errors import (
+ WIZARD_WORKER_EXECUTION_ERROR_TYPE,
+ sanitize_activity_errors,
+)
from products.wizard.backend.temporal.activities.lifecycle import transition_cloud_run
from products.wizard.backend.temporal.contracts import PreparedGitRepositoryWorkspace
@activity.defn(name="wizard_create_run_artifacts")
@asyncify
+@sanitize_activity_errors
def create_run_artifacts(input: PreparedGitRepositoryWorkspace) -> None:
+ annotate_run_span(input.team_id, input.run_id)
wizard_facade.update_run_stage(input.team_id, input.run_id, WizardRunStage.CREATING_ARTIFACTS)
try:
result = cloud_worker.create_git_repository_handoff(
@@ -38,7 +44,9 @@ def create_run_artifacts(input: PreparedGitRepositoryWorkspace) -> None:
non_retryable=True,
) from error
- wizard_facade.create_git_diff_artifact(input.team_id, input.run_id, result.diff)
+ with wizard_span("wizard.artifacts.persist_diff") as span:
+ span.set_attribute("wizard.diff.size_bytes", len(result.diff))
+ wizard_facade.create_git_diff_artifact(input.team_id, input.run_id, result.diff)
if result.pull_request is not None:
wizard_facade.create_pull_request_artifact(
CreatePullRequestArtifactInput(
diff --git a/products/wizard/backend/temporal/activities/lifecycle.py b/products/wizard/backend/temporal/activities/lifecycle.py
index a2e04e9c0afd..faeefb1dd268 100644
--- a/products/wizard/backend/temporal/activities/lifecycle.py
+++ b/products/wizard/backend/temporal/activities/lifecycle.py
@@ -8,12 +8,16 @@ from products.wizard.backend.facade import api as wizard_facade
from products.wizard.backend.facade.contracts import WizardRunDTO
from products.wizard.backend.facade.enums import WizardRunEnvironment, WizardRunStatus
from products.wizard.backend.facade.errors import IllegalStatusTransitionError
+from products.wizard.backend.observability.tracing import annotate_run_span
+from products.wizard.backend.temporal.activities.errors import sanitize_activity_errors
from products.wizard.backend.temporal.contracts import WizardRunFinalizationActivityInput
@activity.defn(name="wizard_finalize_run")
@asyncify
+@sanitize_activity_errors
def finalize_run(input: WizardRunFinalizationActivityInput) -> None:
+ annotate_run_span(input.team_id, input.run_id)
transition_cloud_run(
input.team_id,
input.run_id,
diff --git a/products/wizard/backend/temporal/activities/local_package.py b/products/wizard/backend/temporal/activities/local_package.py
index 4a659e442b80..85084bd81545 100644
--- a/products/wizard/backend/temporal/activities/local_package.py
+++ b/products/wizard/backend/temporal/activities/local_package.py
@@ -6,16 +6,20 @@ from posthog.temporal.common.utils import asyncify
from products.wizard.backend.logic.workers import service as cloud_worker
from products.wizard.backend.logic.workers.config import local_wizard_source_root
from products.wizard.backend.logic.workers.local_package import InvalidLocalWizardSourceError
+from products.wizard.backend.observability.tracing import annotate_run_span
from products.wizard.backend.temporal.activities.errors import (
WIZARD_RUN_CONFIGURATION_ERROR_TYPE,
WIZARD_WORKER_EXECUTION_ERROR_TYPE,
+ sanitize_activity_errors,
)
from products.wizard.backend.temporal.contracts import ProvisionedWizardWorker
@activity.defn(name="wizard_prepare_local_package")
@asyncify
+@sanitize_activity_errors
def prepare_local_wizard(input: ProvisionedWizardWorker) -> None:
+ annotate_run_span(input.team_id, input.run_id)
source_root = local_wizard_source_root()
if not input.use_local_wizard_source or source_root is None:
raise ApplicationError(
diff --git a/products/wizard/backend/temporal/activities/workspace.py b/products/wizard/backend/temporal/activities/workspace.py
index ed09c3f88300..92ff09a68a9d 100644
--- a/products/wizard/backend/temporal/activities/workspace.py
+++ b/products/wizard/backend/temporal/activities/workspace.py
@@ -23,10 +23,12 @@ from products.wizard.backend.logic.workers import (
store as worker_store,
)
from products.wizard.backend.logic.workers.service import GitRepositoryCloneRequest, WizardWorkerProvisionRequest
+from products.wizard.backend.observability.tracing import annotate_run_span
from products.wizard.backend.temporal.activities.errors import (
WIZARD_REPOSITORY_ACCESS_ERROR_TYPE,
WIZARD_RUN_CONFIGURATION_ERROR_TYPE,
WIZARD_WORKER_EXECUTION_ERROR_TYPE,
+ sanitize_activity_errors,
)
from products.wizard.backend.temporal.activities.lifecycle import transition_cloud_run
from products.wizard.backend.temporal.contracts import (
@@ -38,7 +40,9 @@ from products.wizard.backend.temporal.contracts import (
@activity.defn(name="wizard_provision_worker")
@asyncify
+@sanitize_activity_errors
def provision_worker(input: WizardRunActivityInput) -> ProvisionedWizardWorker:
+ annotate_run_span(input.team_id, input.run_id)
run = _get_cloud_run(input)
wizard_facade.update_run_stage(input.team_id, input.run_id, WizardRunStage.PROVISIONING)
if run.created_by_id is None:
@@ -84,7 +88,9 @@ def provision_worker(input: WizardRunActivityInput) -> ProvisionedWizardWorker:
@activity.defn(name="wizard_clone_repository")
@asyncify
+@sanitize_activity_errors
def clone_repository(input: ProvisionedWizardWorker) -> PreparedGitRepositoryWorkspace:
+ annotate_run_span(input.team_id, input.run_id)
run = _get_cloud_run(WizardRunActivityInput(team_id=input.team_id, run_id=input.run_id))
wizard_facade.update_run_stage(input.team_id, input.run_id, WizardRunStage.PREPARING_WORKSPACE)
if not isinstance(run.workspace, GitRepositoryWorkspace):
@@ -132,7 +138,9 @@ def clone_repository(input: ProvisionedWizardWorker) -> PreparedGitRepositoryWor
@activity.defn(name="wizard_destroy_worker")
@asyncify
+@sanitize_activity_errors
def destroy_worker(input: ProvisionedWizardWorker) -> None:
+ annotate_run_span(input.team_id, input.run_id)
worker_lifecycle.cleanup_worker(input.team_id, input.run_id, input.sandbox_id)
diff --git a/products/wizard/backend/tests/runs/test_cloud_activities.py b/products/wizard/backend/tests/runs/test_cloud_activities.py
index 681723e80517..35912dcccf6f 100644
--- a/products/wizard/backend/tests/runs/test_cloud_activities.py
+++ b/products/wizard/backend/tests/runs/test_cloud_activities.py
@@ -3,15 +3,21 @@ from pathlib import Path
from uuid import uuid4
import pytest
-from unittest.mock import MagicMock, patch
+from unittest.mock import AsyncMock, MagicMock, patch
from django.apps import apps
from django.test import override_settings
from django.utils import timezone
from asgiref.sync import async_to_sync
-from temporalio.exceptions import ApplicationError
+from opentelemetry.sdk.trace import TracerProvider
+from opentelemetry.sdk.trace.export import SimpleSpanProcessor
+from opentelemetry.sdk.trace.export.in_memory_span_exporter import InMemorySpanExporter
+from opentelemetry.trace import StatusCode
+from temporalio.contrib.opentelemetry import OpenTelemetryInterceptor
+from temporalio.exceptions import ApplicationError, ApplicationErrorCategory, CancelledError
from temporalio.testing import ActivityEnvironment
+from temporalio.worker import ActivityInboundInterceptor, ExecuteActivityInput
from products.wizard.backend.facade import api as wizard_facade
from products.wizard.backend.facade.contracts import (
@@ -134,6 +140,20 @@ async def _run_execute_wizard(input: PreparedGitRepositoryWorkspace) -> None:
await ActivityEnvironment().run(execute_wizard, input)
+async def _invoke_activity(input: ExecuteActivityInput) -> None:
+ await input.fn(*input.args)
+
+
+async def _run_traced_execute_wizard(input: PreparedGitRepositoryWorkspace) -> None:
+ downstream = MagicMock(spec=ActivityInboundInterceptor)
+ downstream.execute_activity = AsyncMock(side_effect=_invoke_activity)
+ interceptor = OpenTelemetryInterceptor(add_temporal_spans=True).intercept_activity(downstream)
+ await ActivityEnvironment().run(
+ interceptor.execute_activity,
+ ExecuteActivityInput(fn=execute_wizard, args=[input], executor=None, headers={}),
+ )
+
+
async def _run_create_run_artifacts(input: PreparedGitRepositoryWorkspace) -> None:
await ActivityEnvironment().run(create_run_artifacts, input)
@@ -265,17 +285,34 @@ def test_clone_repository_keeps_transient_clone_failure_retryable(team, user) ->
@pytest.mark.parametrize(
- "worker_error, error_type",
+ "worker_error, error_type, non_retryable",
(
- (WizardWorkerTimeoutError(), WIZARD_WORKER_TIMEOUT_ERROR_TYPE),
- (WizardWorkerExecutionError("execution", 1), WIZARD_WORKER_EXECUTION_ERROR_TYPE),
+ (WizardWorkerTimeoutError(), WIZARD_WORKER_TIMEOUT_ERROR_TYPE, True),
+ (
+ WizardWorkerExecutionError("execution", 1, detail="fake-wizard-api-key-for-test"),
+ WIZARD_WORKER_EXECUTION_ERROR_TYPE,
+ True,
+ ),
(
WizardWorkerExecutionError("execution", 1, wizard_error_code="PHW_DETECT_NO_POSTHOG_SDK"),
"PHW_DETECT_NO_POSTHOG_SDK",
+ True,
+ ),
+ (RuntimeError("fake-wizard-api-key-for-test"), "RuntimeError", False),
+ (
+ ApplicationError(
+ "fake-wizard-api-key-for-test",
+ {"credential": "fake-wizard-api-key-for-test"},
+ type="ProviderUnavailable",
+ next_retry_delay=timedelta(seconds=10),
+ category=ApplicationErrorCategory.BENIGN,
+ ),
+ "ProviderUnavailable",
+ False,
),
),
)
-def test_execute_wizard_maps_worker_error(worker_error: Exception, error_type: str) -> None:
+def test_execute_wizard_maps_worker_error(worker_error: Exception, error_type: str, non_retryable: bool) -> None:
workspace = PreparedGitRepositoryWorkspace(
team_id=7,
run_id=uuid4(),
@@ -285,7 +322,12 @@ def test_execute_wizard_maps_worker_error(worker_error: Exception, error_type: s
github_integration_id=456,
)
+ exporter = InMemorySpanExporter()
+ provider = TracerProvider()
+ provider.add_span_processor(SimpleSpanProcessor(exporter))
+
with (
+ patch("temporalio.contrib.opentelemetry._otel_interceptor.get_tracer", provider.get_tracer),
patch("products.wizard.backend.temporal.activities.execution.wizard_facade.update_run_stage"),
patch("products.wizard.backend.temporal.activities.execution.wizard_facade.get_run") as get_run,
patch(
@@ -296,7 +338,9 @@ def test_execute_wizard_maps_worker_error(worker_error: Exception, error_type: s
):
get_run.return_value.program.command = ()
get_run.return_value.program.wizard_version = "2.60.0"
- async_to_sync(_run_execute_wizard)(workspace)
+ async_to_sync(_run_traced_execute_wizard)(workspace)
+
+ provider.shutdown()
execute.assert_called_once_with(
WizardExecutionRequest(
@@ -308,6 +352,45 @@ def test_execute_wizard_maps_worker_error(worker_error: Exception, error_type: s
)
)
assert error.value.type == error_type
+ assert error.value.non_retryable is non_retryable
+ assert error.value.message == "Wizard activity failed."
+ assert error.value.__cause__ is None
+ assert error.value.__context__ is None
+ assert not error.value.details
+ if isinstance(worker_error, ApplicationError):
+ assert error.value.next_retry_delay == worker_error.next_retry_delay
+ assert error.value.category == worker_error.category
+
+ spans = exporter.get_finished_spans()
+ assert len(spans) == 1
+ span = spans[0]
+ assert span.name.startswith("RunActivity:")
+ if not isinstance(worker_error, ApplicationError) or worker_error.category != ApplicationErrorCategory.BENIGN:
+ assert span.status.status_code == StatusCode.ERROR
+ assert span.events
+ assert "fake-wizard-api-key-for-test" not in span.to_json()
+
+
+def test_execute_wizard_preserves_cancellation() -> 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,
+ )
+ cancellation = CancelledError("Activity cancelled")
+ with (
+ patch(
+ "products.wizard.backend.temporal.activities.execution.wizard_facade.update_run_stage",
+ side_effect=cancellation,
+ ),
+ pytest.raises(CancelledError) as error,
+ ):
+ async_to_sync(_run_execute_wizard)(workspace)
+
+ assert error.value is cancellation
@pytest.mark.django_db(transaction=True)
diff --git a/products/wizard/backend/tests/runs/test_cloud_worker.py b/products/wizard/backend/tests/runs/test_cloud_worker.py
index 69c53ee7e77e..4582885c7b6d 100644
--- a/products/wizard/backend/tests/runs/test_cloud_worker.py
+++ b/products/wizard/backend/tests/runs/test_cloud_worker.py
@@ -1,5 +1,6 @@
import io
import tarfile
+from collections.abc import Iterator
from pathlib import Path
from types import SimpleNamespace
from uuid import uuid4
@@ -9,9 +10,16 @@ from unittest.mock import MagicMock, patch
from django.test import override_settings
+from asgiref.sync import async_to_sync
from modal.exception import NotFoundError as ModalNotFoundError
+from opentelemetry.sdk.trace import TracerProvider
+from opentelemetry.sdk.trace.export import SimpleSpanProcessor
+from opentelemetry.sdk.trace.export.in_memory_span_exporter import InMemorySpanExporter
+from opentelemetry.trace import StatusCode
from parameterized import parameterized
+from posthog.temporal.common.utils import asyncify
+
from products.tasks.backend.facade.sandbox import SandboxNotFoundError, SandboxNotRunningError
from products.wizard.backend.logic.artifacts.config import MAX_GIT_DIFF_BYTES
from products.wizard.backend.logic.workers.commands import wizard_handoff_output_path
@@ -40,6 +48,17 @@ from products.wizard.backend.logic.workers.service import (
prepare_local_wizard,
provision_wizard_worker,
)
+from products.wizard.backend.observability.tracing import wizard_span
+
+
+def span_exporter() -> Iterator[InMemorySpanExporter]:
+ exporter = InMemorySpanExporter()
+ provider = TracerProvider()
+ provider.add_span_processor(SimpleSpanProcessor(exporter))
+ with patch("products.wizard.backend.observability.tracing.tracer", provider.get_tracer("test.wizard")):
+ yield exporter
+ provider.shutdown()
def _execution_result(*, stdout: str = "", stderr: str = "", exit_code: int = 0) -> SimpleNamespace:
@@ -59,6 +78,7 @@ def test_provision_worker_configures_wizard_environment(
get_user: MagicMock,
create_wizard_token: MagicMock,
get_sandbox_class: MagicMock,
+ span_exporter: InMemorySpanExporter,
) -> None:
request = WizardWorkerProvisionRequest(team_id=7, created_by_id=13, run_id=uuid4())
create_wizard_token.return_value = "wizard-secret"
@@ -84,6 +104,14 @@ def test_provision_worker_configures_wizard_environment(
assert config.environment_variables["POSTHOG_HANDOFF_OUTPUT_PATH"] == wizard_handoff_output_path(request.run_id)
assert config.ttl_seconds == 75 * 60
+ spans = {span.name: span for span in span_exporter.get_finished_spans()}
+ attributes = spans["wizard.worker.provision"].attributes
+ assert attributes is not None
+ assert attributes["team_id"] == request.team_id
+ assert attributes["wizard.run_id"] == str(request.run_id)
+ assert "wizard.sandbox.create" in spans
+ assert all("wizard-secret" not in span.to_json() for span in spans.values())
+
@patch("products.wizard.backend.logic.workers.service.get_sandbox_class")
@patch("products.wizard.backend.logic.workers.service.create_wizard_oauth_access_token_for_user")
@@ -163,6 +191,7 @@ def test_provision_worker_ignores_local_mcp_endpoint_outside_debug_mode(
def test_clone_repository_uses_integration_token(
get_github_token: MagicMock,
get_sandbox_class: MagicMock,
+ span_exporter: InMemorySpanExporter,
) -> None:
request = GitRepositoryCloneRequest(
sandbox_id="worker-id",
@@ -174,7 +203,8 @@ def test_clone_repository_uses_integration_token(
sandbox.clone_repository.return_value = _execution_result()
sandbox.execute.return_value = _execution_result()
- root_path = clone_repository(request)
+ with wizard_span("request") as parent:
+ root_path = async_to_sync(asyncify(clone_repository))(request)
assert root_path == "/tmp/workspace/repos/posthog/posthog"
get_sandbox_class.return_value.get_by_id.assert_called_once_with(request.sandbox_id)
@@ -183,12 +213,28 @@ def test_clone_repository_uses_integration_token(
assert "github-secret" not in sanitize_command
assert "https://github.com/PostHog/PostHog.git" in sanitize_command
+ spans = {span.name: span for span in span_exporter.get_finished_spans()}
+ preparation = spans["wizard.repository.prepare"]
+ assert preparation.context is not None
+ assert preparation.parent is not None
+ assert preparation.parent.span_id == parent.get_span_context().span_id
+ for name in ("wizard.repository.credentials", "wizard.repository.clone", "wizard.repository.sanitize_remote"):
+ child = spans[name]
+ assert child.context is not None
+ assert child.parent is not None
+ assert child.parent.span_id == preparation.context.span_id
+ assert child.context.trace_id == parent.get_span_context().trace_id
+ assert child.start_time is not None and child.end_time is not None
+ assert child.end_time >= child.start_time
+ assert all("github-secret" not in span.to_json() for span in spans.values())
+
@patch("products.wizard.backend.logic.workers.service.get_sandbox_class")
@patch("products.wizard.backend.logic.workers.service.get_github_token", return_value="github-secret")
def test_clone_repository_rejects_clone_failure(
_get_github_token: MagicMock,
get_sandbox_class: MagicMock,
+ span_exporter: InMemorySpanExporter,
) -> None:
request = GitRepositoryCloneRequest(
sandbox_id="worker-id",
@@ -207,6 +253,22 @@ def test_clone_repository_rejects_clone_failure(
assert "github-secret" not in str(error.value)
assert "[REDACTED]" in str(error.value)
+ spans = {span.name: span for span in span_exporter.get_finished_spans()}
+ for name in ("wizard.repository.clone", "wizard.repository.prepare"):
+ span = spans[name]
+ assert span.status.status_code == StatusCode.ERROR
+ assert span.status.description is None
+ assert span.attributes is not None
+ assert span.attributes["error.type"] == "WizardWorkerExecutionError"
+ assert not span.events
+ attributes = spans["wizard.repository.clone"].attributes
+ assert attributes is not None
+ assert attributes["process.exit.code"] == 128
+ assert "wizard.repository.sanitize_remote" not in spans
+ assert all(
+ "github-secret" not in span.to_json() and "PostHog/PostHog" not in span.to_json() for span in spans.values()
+ )
+
@patch("products.wizard.backend.logic.workers.service.get_sandbox_class")
def test_prepare_local_wizard_uploads_source_and_builds_it(get_sandbox_class: MagicMock, tmp_path: Path) -> None:
diff --git a/products/wizard/backend/tests/runs/test_finalization_activity.py b/products/wizard/backend/tests/runs/test_finalization_activity.py
index 098b3a38ed3a..98c11560eb57 100644
--- a/products/wizard/backend/tests/runs/test_finalization_activity.py
+++ b/products/wizard/backend/tests/runs/test_finalization_activity.py
@@ -2,6 +2,7 @@ import pytest
from unittest.mock import patch
from asgiref.sync import async_to_sync
+from temporalio.exceptions import ApplicationError
from temporalio.testing import ActivityEnvironment
from products.wizard.backend.facade import api as wizard_facade
@@ -129,5 +130,11 @@ def test_finalize_run_rejects_local_run(team, user) -> None:
status=WizardRunStatus.CANCELLED,
)
- with pytest.raises(ValueError, match="cloud Wizard Run"):
+ with pytest.raises(ApplicationError) as error:
async_to_sync(_run_activity)(input)
+
+ assert error.value.type == "ValueError"
+ assert error.value.message == "Wizard activity failed."
+ assert error.value.__cause__ is None
+ assert error.value.__context__ is None
+ assert wizard_facade.get_run(team.id, run.id).status == WizardRunStatus.RUNNING