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): add run storage services (#91820)

Fernando Gomes151854fb7927
diff --git a/posthog/settings/temporal.py b/posthog/settings/temporal.py
index 8a986faf5eb5..fa8b9eb40dd2 100644
--- a/posthog/settings/temporal.py
+++ b/posthog/settings/temporal.py
@@ -245,6 +245,7 @@ EXPERIMENTS_RECALCULATION_TASK_QUEUE = _set_temporal_task_queue("experiments-rec
HEALTH_CHECK_TASK_QUEUE = _set_temporal_task_queue("health-check-task-queue")
DUCKLAKE_TASK_QUEUE = _set_temporal_task_queue("ducklake-task-queue")
TASKS_TASK_QUEUE = _set_temporal_task_queue("tasks-task-queue")
+WIZARD_RUN_ARTIFACTS_S3_BUCKET = os.getenv("WIZARD_RUN_ARTIFACTS_S3_BUCKET", "")
TASKS_DISPATCHER_BATCH_SIZE = get_from_env("TASKS_DISPATCHER_BATCH_SIZE", 50, type_cast=int)
TASKS_DISPATCHER_CONCURRENCY = get_from_env("TASKS_DISPATCHER_CONCURRENCY", 20, type_cast=int)
TASKS_DISPATCHER_LEASE_SECONDS = get_from_env("TASKS_DISPATCHER_LEASE_SECONDS", 60, type_cast=int)
diff --git a/products/warehouse_sources/backend/models/util.py b/products/warehouse_sources/backend/models/util.py
index c1489e2fb9d1..1ff2faf589ea 100644
--- a/products/warehouse_sources/backend/models/util.py
+++ b/products/warehouse_sources/backend/models/util.py
@@ -784,6 +784,7 @@ _BUCKET_SETTINGS_NOT_READABLE_BY_THE_NODE_ROLE = {
"QUERY_CACHE_S3_BUCKET": "no reader found in this codebase; defaults to OBJECT_STORAGE_BUCKET",
"REPLAY_MESSAGE_TOO_LARGE_SAMPLE_BUCKET": "no reader found in this codebase",
"VIDEO_SEGMENT_CLUSTERING_S3_BUCKET": "no reader found in this codebase; defaults to OBJECT_STORAGE_BUCKET",
+ "WIZARD_RUN_ARTIFACTS_S3_BUCKET": "read via posthog.storage.object_storage (boto3) by the Wizard Temporal worker, through products/wizard/backend/logic/artifacts/service.py",
}
diff --git a/products/wizard/backend/facade/api.py b/products/wizard/backend/facade/api.py
index 0b7d8d92d430..79d9783155dc 100644
--- a/products/wizard/backend/facade/api.py
+++ b/products/wizard/backend/facade/api.py
@@ -11,14 +11,24 @@ from __future__ import annotations
from collections.abc import AsyncIterator
from contextlib import asynccontextmanager
from typing import Any
+from uuid import UUID
from products.wizard.backend import metrics
-from products.wizard.backend.facade.contracts import UpsertWizardSessionInput, WizardProgram, WizardSessionDTO
+from products.wizard.backend.facade.contracts import (
+ CreatePullRequestArtifactInput,
+ UpsertWizardSessionInput,
+ WizardProgram,
+ WizardRunArtifactDTO,
+ WizardRunGitDiffArtifactDTO,
+ WizardRunPullRequestArtifactDTO,
+ WizardSessionDTO,
+)
from products.wizard.backend.logic import (
pubsub,
registry as registry_service,
sessions,
)
+from products.wizard.backend.logic.artifacts import service as artifacts
def upsert(params: UpsertWizardSessionInput) -> tuple[WizardSessionDTO, bool]:
@@ -71,5 +81,39 @@ def record_latest_session_poll(raw_source: str | None, result: str) -> None:
).inc()
+# Wizard Workers
+
+
def get_registry(*, distinct_id: str, organization_id: str) -> tuple[WizardProgram, ...]:
+ """
+ Returns the Wizard registry, which is a list of all available programs the Wizard might run for an user.
+ """
return registry_service.get_registry(distinct_id=distinct_id, organization_id=organization_id)
+
+
+def create_git_diff_artifact(team_id: int, run_id: UUID, content: bytes) -> WizardRunGitDiffArtifactDTO | None:
+ """
+ Uploads a git diff generated in a Wizard run.
+ """
+ return artifacts.create_git_diff_artifact(team_id, run_id, content)
+
+
+def create_pull_request_artifact(params: CreatePullRequestArtifactInput) -> WizardRunPullRequestArtifactDTO:
+ """
+ Uploads a pull request artifact generated in a Wizard run.
+ """
+ return artifacts.create_pull_request_artifact(params)
+
+
+def list_run_artifacts(team_id: int, run_id: UUID) -> list[WizardRunArtifactDTO]:
+ """
+ Lists all artifacts generated by a Wizard run.
+ """
+ return artifacts.list_run_artifacts(team_id, run_id)
+
+
+def get_git_diff_artifact_content(team_id: int, run_id: UUID, artifact_id: UUID) -> bytes:
+ """
+ Returns the content of a git diff artifact generated in a Wizard run.
+ """
+ return artifacts.get_git_diff_artifact_content(team_id, run_id, artifact_id)
diff --git a/products/wizard/backend/logic/artifacts/config.py b/products/wizard/backend/logic/artifacts/config.py
new file mode 100644
index 000000000000..4d92c425e768
--- /dev/null
+++ b/products/wizard/backend/logic/artifacts/config.py
@@ -0,0 +1,6 @@
+MAX_GIT_DIFF_BYTES = 30 * 1024 * 1024
+MAX_GIT_DIFF_DOWNLOAD_BYTES = 2 * 1024 * 1024
+
+PULL_REQUEST_TITLE = "Instrument application with PostHog"
+PULL_REQUEST_BODY = "This pull request contains changes created by Wizard, PostHog's setup agent."
+PULL_REQUEST_COMMIT_MESSAGE = "Set up PostHog"
diff --git a/products/wizard/backend/logic/artifacts/mappers.py b/products/wizard/backend/logic/artifacts/mappers.py
new file mode 100644
index 000000000000..46ef91db837b
--- /dev/null
+++ b/products/wizard/backend/logic/artifacts/mappers.py
@@ -0,0 +1,68 @@
+from products.wizard.backend.facade.contracts import (
+ WizardRunArtifactDTO,
+ WizardRunGitDiffArtifactDTO,
+ WizardRunPullRequestArtifactDTO,
+)
+from products.wizard.backend.facade.enums import WizardRunArtifactType
+from products.wizard.backend.models import WizardRunArtifact
+
+
+def record_to_artifact(artifact: WizardRunArtifact) -> WizardRunArtifactDTO:
+ if WizardRunArtifactType(artifact.type) == WizardRunArtifactType.GIT_DIFF:
+ if artifact.size_bytes is None or artifact.content_hash is None:
+ raise ValueError("Git diff artifact is missing stored content metadata.")
+
+ metadata = artifact.metadata or {}
+ additions = metadata.get("additions")
+ removals = metadata.get("removals")
+
+ return WizardRunGitDiffArtifactDTO(
+ id=artifact.id,
+ team_id=artifact.team_id,
+ run_id=artifact.run_id,
+ artifact_type=WizardRunArtifactType.GIT_DIFF,
+ size_bytes=artifact.size_bytes,
+ content_hash=artifact.content_hash,
+ additions=additions if isinstance(additions, int) else None,
+ removals=removals if isinstance(removals, int) else None,
+ created_at=artifact.created_at,
+ )
+
+ metadata = artifact.metadata or {}
+ number = metadata.get("number")
+ repository = metadata.get("repository")
+ head_branch = metadata.get("head_branch")
+ base_branch = metadata.get("base_branch")
+
+ if (
+ artifact.external_url is None
+ or not isinstance(number, int)
+ or not isinstance(repository, str)
+ or not isinstance(head_branch, str)
+ or not isinstance(base_branch, str)
+ ):
+ raise ValueError("Pull request artifact is missing repository metadata.")
+
+ return WizardRunPullRequestArtifactDTO(
+ id=artifact.id,
+ team_id=artifact.team_id,
+ run_id=artifact.run_id,
+ artifact_type=WizardRunArtifactType.PULL_REQUEST,
+ url=artifact.external_url,
+ number=number,
+ repository=repository,
+ head_branch=head_branch,
+ base_branch=base_branch,
+ created_at=artifact.created_at,
+ )
+
+
+def pull_request_metadata_to_record(
+ number: int, repository: str, head_branch: str, base_branch: str
+) -> dict[str, object]:
+ return {
+ "number": number,
+ "repository": repository,
+ "head_branch": head_branch,
+ "base_branch": base_branch,
+ }
diff --git a/products/wizard/backend/logic/artifacts/service.py b/products/wizard/backend/logic/artifacts/service.py
new file mode 100644
index 000000000000..bd0e38c9e278
--- /dev/null
+++ b/products/wizard/backend/logic/artifacts/service.py
@@ -0,0 +1,134 @@
+import logging
+from hashlib import sha256
+from uuid import UUID
+
+from django.conf import settings
+
+from posthog.dataclasses import frozen
+from posthog.storage import object_storage
+
+from products.wizard.backend.facade.config import WIZARD_GIT_DIFF_CONTENT_TYPE
+from products.wizard.backend.facade.contracts import (
+ CreatePullRequestArtifactInput,
+ WizardRunArtifactDTO,
+ WizardRunGitDiffArtifactDTO,
+ WizardRunPullRequestArtifactDTO,
+)
+from products.wizard.backend.facade.errors import WizardRunArtifactNotFoundError, WizardRunArtifactTooLargeError
+from products.wizard.backend.logic.artifacts import store
+from products.wizard.backend.logic.artifacts.config import MAX_GIT_DIFF_BYTES, MAX_GIT_DIFF_DOWNLOAD_BYTES
+from products.wizard.backend.logic.runs import store as run_store
+from products.wizard.backend.observability.service import wizard_observability as run_observability
+
+logger = logging.getLogger(__name__)
+
+
+@frozen
+class _DiffLineCounts:
+ additions: int
+ removals: int
+
+
+def create_git_diff_artifact(team_id: int, run_id: UUID, content: bytes) -> WizardRunGitDiffArtifactDTO | None:
+ if not content:
+ return None
+
+ run = run_store.get_run(team_id, run_id)
+
+ if len(content) > MAX_GIT_DIFF_BYTES:
+ run_observability.git_diff_omitted(run, len(content))
+ return None
+
+ content_hash = sha256(content).hexdigest()
+ storage_path = _git_diff_storage_path(team_id, run_id, content_hash)
+ line_counts = _diff_line_counts(content)
+
+ object_storage.write(
+ storage_path,
+ content,
+ extras={"ContentType": WIZARD_GIT_DIFF_CONTENT_TYPE},
+ bucket=settings.WIZARD_RUN_ARTIFACTS_S3_BUCKET,
+ )
+
+ artifact = store.upsert_git_diff(
+ team_id=team_id,
+ run_id=run.id,
+ storage_path=storage_path,
+ size_bytes=len(content),
+ content_hash=content_hash,
+ additions=line_counts.additions,
+ removals=line_counts.removals,
+ )
+
+ run_observability.artifact_created(run, artifact)
+ return artifact
+
+
+def create_pull_request_artifact(params: CreatePullRequestArtifactInput) -> WizardRunPullRequestArtifactDTO:
+ run = run_store.get_run(params.team_id, params.run_id)
+
+ artifact = store.upsert_pull_request(
+ team_id=params.team_id,
+ run_id=run.id,
+ url=params.url,
+ number=params.number,
+ repository=params.repository,
+ head_branch=params.head_branch,
+ base_branch=params.base_branch,
+ )
+
+ run_observability.pull_request_created(run, artifact)
+ return artifact
+
+
+def list_run_artifacts(team_id: int, run_id: UUID) -> list[WizardRunArtifactDTO]:
+ run = run_store.get_run(team_id, run_id)
+
+ return store.list_artifacts(team_id, run.id)
+
+
+def get_git_diff_artifact_content(team_id: int, run_id: UUID, artifact_id: UUID) -> bytes:
+ run = run_store.get_run(team_id, run_id)
+ stored_artifact = store.get_stored_git_diff_artifact(team_id, run.id, artifact_id)
+
+ if stored_artifact is None:
+ raise WizardRunArtifactNotFoundError
+
+ if stored_artifact.size_bytes > MAX_GIT_DIFF_DOWNLOAD_BYTES:
+ raise WizardRunArtifactTooLargeError
+
+ content = object_storage.read_bytes(
+ stored_artifact.storage_path,
+ bucket=settings.WIZARD_RUN_ARTIFACTS_S3_BUCKET,
+ missing_ok=True,
+ )
+
+ if content is None:
+ raise WizardRunArtifactNotFoundError
+
+ content_hash = sha256(content).hexdigest()
+ if content_hash != stored_artifact.content_hash:
+ logger.error(
+ "wizard_git_diff_integrity_check_failed",
+ extra={"team_id": team_id, "run_id": str(run_id), "artifact_id": str(artifact_id)},
+ )
+ raise ValueError("Stored Wizard diff failed its integrity check")
+
+ return content
+
+
+def _diff_line_counts(content: bytes) -> _DiffLineCounts:
+ additions = 0
+ removals = 0
+ for line in content.split(b"\n"):
+ if line.startswith(b"+++") or line.startswith(b"---"):
+ continue
+ if line.startswith(b"+"):
+ additions += 1
+ elif line.startswith(b"-"):
+ removals += 1
+ return _DiffLineCounts(additions=additions, removals=removals)
+
+
+def _git_diff_storage_path(team_id: int, run_id: UUID, content_hash: str) -> str:
+ return f"projects/{team_id}/wizard-runs/{run_id}/artifacts/git-diff-{content_hash}.patch"
diff --git a/products/wizard/backend/logic/artifacts/store.py b/products/wizard/backend/logic/artifacts/store.py
new file mode 100644
index 000000000000..62a3c62472a8
--- /dev/null
+++ b/products/wizard/backend/logic/artifacts/store.py
@@ -0,0 +1,111 @@
+from uuid import UUID
+
+from django.db import transaction
+
+from posthog.dataclasses import frozen
+
+from products.wizard.backend.facade.contracts import (
+ WizardRunArtifactDTO,
+ WizardRunGitDiffArtifactDTO,
+ WizardRunPullRequestArtifactDTO,
+)
+from products.wizard.backend.facade.enums import WizardRunArtifactType
+from products.wizard.backend.logic.artifacts.mappers import pull_request_metadata_to_record, record_to_artifact
+from products.wizard.backend.models import WizardRun, WizardRunArtifact
+
+
+@frozen
+class StoredGitDiffArtifact:
+ storage_path: str
+ content_hash: str
+ size_bytes: int
+
+
+def upsert_git_diff(
+ *,
+ team_id: int,
+ run_id: UUID,
+ storage_path: str,
+ size_bytes: int,
+ content_hash: str,
+ additions: int,
+ removals: int,
+) -> WizardRunGitDiffArtifactDTO:
+ with transaction.atomic():
+ WizardRun.objects.for_team(team_id).select_for_update().get(id=run_id)
+ artifact, _ = WizardRunArtifact.objects.for_team(team_id).update_or_create(
+ run_id=run_id,
+ type=WizardRunArtifactType.GIT_DIFF.value,
+ defaults={
+ "team_id": team_id,
+ "storage_path": storage_path,
+ "external_url": None,
+ "metadata": {"additions": additions, "removals": removals},
+ "size_bytes": size_bytes,
+ "content_hash": content_hash,
+ },
+ )
+
+ result = record_to_artifact(artifact)
+
+ if not isinstance(result, WizardRunGitDiffArtifactDTO):
+ raise ValueError("Expected a git diff artifact")
+
+ return result
+
+
+def upsert_pull_request(
+ *,
+ team_id: int,
+ run_id: UUID,
+ url: str,
+ number: int,
+ repository: str,
+ head_branch: str,
+ base_branch: str,
+) -> WizardRunPullRequestArtifactDTO:
+ with transaction.atomic():
+ WizardRun.objects.for_team(team_id).select_for_update().get(id=run_id)
+ artifact, _ = WizardRunArtifact.objects.for_team(team_id).update_or_create(
+ run_id=run_id,
+ type=WizardRunArtifactType.PULL_REQUEST.value,
+ defaults={
+ "team_id": team_id,
+ "storage_path": None,
+ "external_url": url,
+ "metadata": pull_request_metadata_to_record(number, repository, head_branch, base_branch),
+ "size_bytes": None,
+ "content_hash": None,
+ },
+ )
+
+ result = record_to_artifact(artifact)
+
+ if not isinstance(result, WizardRunPullRequestArtifactDTO):
+ raise ValueError("Expected a pull request artifact")
+
+ return result
+
+
+def list_artifacts(team_id: int, run_id: UUID) -> list[WizardRunArtifactDTO]:
+ artifacts = WizardRunArtifact.objects.for_team(team_id).filter(run_id=run_id).order_by("created_at", "id")
+ return [record_to_artifact(artifact) for artifact in artifacts]
+
+
+def get_stored_git_diff_artifact(team_id: int, run_id: UUID, artifact_id: UUID) -> StoredGitDiffArtifact | None:
+ stored = (
+ WizardRunArtifact.objects.for_team(team_id)
+ .filter(id=artifact_id, run_id=run_id, type=WizardRunArtifactType.GIT_DIFF.value)
+ .values_list("storage_path", "content_hash", "size_bytes")
+ .first()
+ )
+
+ if stored is None:
+ return None
+
+ storage_path, content_hash, size_bytes = stored
+
+ if not isinstance(storage_path, str) or not isinstance(content_hash, str) or not isinstance(size_bytes, int):
+ return None
+
+ return StoredGitDiffArtifact(storage_path=storage_path, content_hash=content_hash, size_bytes=size_bytes)
diff --git a/products/wizard/backend/logic/runs/config.py b/products/wizard/backend/logic/runs/config.py
new file mode 100644
index 000000000000..573cff1aee02
--- /dev/null
+++ b/products/wizard/backend/logic/runs/config.py
@@ -0,0 +1,13 @@
+from datetime import timedelta
+
+CLOUD_RUN_HOURLY_LIMIT = 10
+CLOUD_RUN_HOURLY_WINDOW = timedelta(hours=1)
+
+CLOUD_RUN_DAILY_LIMIT = 20
+CLOUD_RUN_DAILY_WINDOW = timedelta(days=1)
+
+DISPATCH_RETRY_BASE_DELAY = timedelta(minutes=1)
+DISPATCH_RETRY_MAX_DELAY = timedelta(hours=1)
+DISPATCH_RETRY_MAX_ATTEMPTS = 5
+
+WORKER_CLEANUP_MAX_ATTEMPTS = 5
diff --git a/products/wizard/backend/logic/runs/diagnostics.py b/products/wizard/backend/logic/runs/diagnostics.py
new file mode 100644
index 000000000000..db766e5d92f9
--- /dev/null
+++ b/products/wizard/backend/logic/runs/diagnostics.py
@@ -0,0 +1,25 @@
+from products.wizard.backend.facade.enums import WizardRunErrorCode
+
+
+def error_message(error_code: str | None) -> str | None:
+ match error_code:
+ case WizardRunErrorCode.TIMEOUT:
+ return "The Wizard run timed out."
+ case WizardRunErrorCode.PROVISIONING_FAILED:
+ return "The Wizard Worker could not be provisioned."
+ case WizardRunErrorCode.REPOSITORY_ACCESS_FAILED:
+ return "The Wizard Worker could not access the repository."
+ case WizardRunErrorCode.WORKSPACE_PREPARATION_FAILED:
+ return "The Wizard Worker could not prepare the workspace."
+ case WizardRunErrorCode.EXECUTION_FAILED:
+ return "The Wizard could not complete the selected program."
+ case WizardRunErrorCode.ARTIFACT_CREATION_FAILED:
+ return "The Wizard Worker could not create run artifacts."
+ case WizardRunErrorCode.DISPATCH_FAILED:
+ return "The Wizard run could not be dispatched."
+ case None:
+ return None
+ case value if value.startswith("PHW_"):
+ return "The Wizard could not complete the selected program."
+ case _:
+ return "The Wizard run failed."
diff --git a/products/wizard/backend/logic/runs/errors.py b/products/wizard/backend/logic/runs/errors.py
new file mode 100644
index 000000000000..bee1190f4a2e
--- /dev/null
+++ b/products/wizard/backend/logic/runs/errors.py
@@ -0,0 +1,8 @@
+class WizardRunDispatchError(Exception):
+ def __init__(self, *, exhausted: bool) -> None:
+ self.exhausted = exhausted
+ super().__init__()
+
+
+class WizardWorkerCleanupError(Exception):
+ pass
diff --git a/products/wizard/backend/logic/runs/fingerprints.py b/products/wizard/backend/logic/runs/fingerprints.py
new file mode 100644
index 000000000000..21e451654299
--- /dev/null
+++ b/products/wizard/backend/logic/runs/fingerprints.py
@@ -0,0 +1,22 @@
+import json
+from hashlib import sha256
+
+from products.wizard.backend.facade.contracts import CreateWizardRunInput
+from products.wizard.backend.logic.runs.mappers import workspace_to_record
+
+
+def create_run_request_fingerprint(params: CreateWizardRunInput) -> str:
+ """
+ Request fingerprint helps identify duplicate run requests even if they have different idempotency key.
+ """
+ workspace_type, workspace = workspace_to_record(params.workspace)
+
+ value = {
+ "environment": params.environment.value,
+ "program_id": params.program_id,
+ "wizard_version": params.wizard_version,
+ "workspace": workspace,
+ "workspace_type": workspace_type.value,
+ }
+
+ return sha256(json.dumps(value, separators=(",", ":"), sort_keys=True).encode()).hexdigest()
diff --git a/products/wizard/backend/logic/runs/mappers.py b/products/wizard/backend/logic/runs/mappers.py
new file mode 100644
index 000000000000..debcc73e15cd
--- /dev/null
+++ b/products/wizard/backend/logic/runs/mappers.py
@@ -0,0 +1,51 @@
+from products.wizard.backend.facade.contracts import (
+ GitRepositoryWorkspace,
+ LocalFolderWorkspace,
+ WizardRunDTO,
+ WizardWorkspace,
+)
+from products.wizard.backend.facade.enums import (
+ WizardRunEnvironment,
+ WizardRunStage,
+ WizardRunStatus,
+ WizardWorkspaceType,
+)
+from products.wizard.backend.facade.validation import validate_workspace_metadata_value
+from products.wizard.backend.logic.programs import program_from_mapping
+from products.wizard.backend.models import WizardRun
+
+
+def workspace_to_record(workspace: WizardWorkspace) -> tuple[WizardWorkspaceType, dict[str, object]]:
+ match workspace:
+ case LocalFolderWorkspace(project_name=project_name):
+ return WizardWorkspaceType.LOCAL_FOLDER, {"project_name": project_name}
+ case GitRepositoryWorkspace(repository=repository):
+ return WizardWorkspaceType.GIT_REPOSITORY, {"repository": repository}
+
+
+def record_to_workspace(workspace_type: str, metadata: object) -> WizardWorkspace:
+ match WizardWorkspaceType(workspace_type):
+ case WizardWorkspaceType.LOCAL_FOLDER:
+ return LocalFolderWorkspace(project_name=validate_workspace_metadata_value(metadata, "project_name"))
+ case WizardWorkspaceType.GIT_REPOSITORY:
+ return GitRepositoryWorkspace(repository=validate_workspace_metadata_value(metadata, "repository"))
+
+
+def record_to_run(run: WizardRun) -> WizardRunDTO:
+ return WizardRunDTO(
+ id=run.id,
+ team_id=run.team_id,
+ created_by_id=run.created_by_id,
+ environment=WizardRunEnvironment(run.environment),
+ workspace=record_to_workspace(run.workspace_type, run.workspace),
+ program=program_from_mapping(run.program, allow_latest_version=True),
+ status=WizardRunStatus(run.status),
+ error_code=run.error_code,
+ error_message=run.error_message,
+ stage=WizardRunStage(run.stage) if run.stage else None,
+ created_at=run.created_at,
+ updated_at=run.updated_at,
+ started_at=run.started_at,
+ finished_at=run.finished_at,
+ deadline_at=run.deadline_at,
+ )
diff --git a/products/wizard/backend/logic/runs/store.py b/products/wizard/backend/logic/runs/store.py
new file mode 100644
index 000000000000..027c26411786
--- /dev/null
+++ b/products/wizard/backend/logic/runs/store.py
@@ -0,0 +1,211 @@
+import logging
+from uuid import UUID
+
+from django.db import (
+ models,
+ transaction as database_transaction,
+)
+from django.utils import timezone
+
+from products.wizard.backend.facade.config import WIZARD_RUN_DEADLINE
+from products.wizard.backend.facade.contracts import (
+ ListWizardRunsInput,
+ WizardProgram,
+ WizardRunCreationResult,
+ WizardRunDTO,
+ WizardRunPage,
+ WizardWorkspace,
+)
+from products.wizard.backend.facade.enums import (
+ WizardRunDispatchStatus,
+ WizardRunEnvironment,
+ WizardRunStage,
+ WizardRunStatus,
+)
+from products.wizard.backend.facade.errors import WizardRunNotFoundError
+from products.wizard.backend.logic.programs import program_to_mapping
+from products.wizard.backend.logic.runs.config import (
+ DISPATCH_RETRY_BASE_DELAY,
+ DISPATCH_RETRY_MAX_ATTEMPTS,
+ DISPATCH_RETRY_MAX_DELAY,
+)
+from products.wizard.backend.logic.runs.diagnostics import error_message
+from products.wizard.backend.logic.runs.mappers import record_to_run, workspace_to_record
+from products.wizard.backend.models import WizardRun
+
+logger = logging.getLogger(__name__)
+
+
+def _get_run_record(team_id: int, run_id: UUID) -> WizardRun:
+ run = WizardRun.objects.for_team(team_id).filter(id=run_id).first()
+
+ if run is None:
+ raise WizardRunNotFoundError
+
+ return run
+
+
+def create_run(
+ *,
+ team_id: int,
+ created_by_id: int,
+ environment: WizardRunEnvironment,
+ workspace: WizardWorkspace,
+ program: WizardProgram,
+ status: WizardRunStatus,
+ idempotency_key: str | None = None,
+ request_fingerprint: str | None = None,
+) -> WizardRunCreationResult:
+ workspace_type, workspace_metadata = workspace_to_record(workspace)
+ now = timezone.now()
+
+ values = {
+ "created_by_id": created_by_id,
+ "environment": environment.value,
+ "workspace_type": workspace_type.value,
+ "workspace": workspace_metadata,
+ "program": program_to_mapping(program),
+ "status": status.value,
+ "request_fingerprint": request_fingerprint,
+ "dispatch_status": (
+ WizardRunDispatchStatus.PENDING.value if environment == WizardRunEnvironment.CLOUD else None
+ ),
+ "stage": WizardRunStage.DISPATCHING.value if environment == WizardRunEnvironment.CLOUD else None,
+ "stage_started_at": now if environment == WizardRunEnvironment.CLOUD else None,
+ "started_at": now if environment == WizardRunEnvironment.LOCAL else None,
+ "deadline_at": now + WIZARD_RUN_DEADLINE if environment == WizardRunEnvironment.CLOUD else None,
+ }
+
+ if idempotency_key is None:
+ run = WizardRun.objects.for_team(team_id).create(team_id=team_id, idempotency_key=None, **values)
+ return WizardRunCreationResult(run=record_to_run(run), created=True)
+
+ run, created = WizardRun.objects.for_team(team_id).get_or_create(
+ team_id=team_id,
+ idempotency_key=idempotency_key,
+ defaults=values,
+ )
+
+ return WizardRunCreationResult(run=record_to_run(run), created=created)
+
+
+def get_run_by_idempotency_key(team_id: int, idempotency_key: str) -> WizardRunDTO | None:
+ run = WizardRun.objects.for_team(team_id).filter(idempotency_key=idempotency_key).first()
+
+ return record_to_run(run) if run is not None else None
+
+
+def get_request_fingerprint(team_id: int, run_id: UUID) -> str | None:
+ return _get_run_record(team_id, run_id).request_fingerprint
+
+
+def get_workflow_id(team_id: int, run_id: UUID) -> str | None:
+ return _get_run_record(team_id, run_id).workflow_id
+
+
+def mark_cancellation_requested(team_id: int, run_id: UUID) -> None:
+ WizardRun.objects.for_team(team_id).filter(id=run_id).update(cancellation_requested_at=timezone.now())
+
+
+def mark_cancellation_dispatched(team_id: int, run_id: UUID) -> None:
+ WizardRun.objects.for_team(team_id).filter(id=run_id).update(cancellation_dispatched_at=timezone.now())
+
+
+def mark_dispatch_succeeded(team_id: int, run_id: UUID, workflow_id: str) -> None:
+ WizardRun.objects.for_team(team_id).filter(id=run_id).update(
+ dispatch_status=WizardRunDispatchStatus.DISPATCHED.value,
+ dispatch_attempts=models.F("dispatch_attempts") + 1,
+ dispatch_error=None,
+ dispatch_next_attempt_at=None,
+ workflow_id=workflow_id,
+ )
+
+
+def mark_dispatch_failed(team_id: int, run_id: UUID) -> bool:
+ with database_transaction.atomic():
+ run = WizardRun.objects.for_team(team_id).select_for_update().filter(id=run_id).first()
+ if run is None:
+ raise WizardRunNotFoundError
+
+ run.dispatch_attempts += 1
+ run.dispatch_error = "Temporal dispatch failed."
+ exhausted = run.dispatch_attempts >= DISPATCH_RETRY_MAX_ATTEMPTS
+
+ if exhausted:
+ run.dispatch_next_attempt_at = None
+ else:
+ retry_delay = min(
+ DISPATCH_RETRY_BASE_DELAY * 2 ** (run.dispatch_attempts - 1),
+ DISPATCH_RETRY_MAX_DELAY,
+ )
+ run.dispatch_next_attempt_at = timezone.now() + retry_delay
+
+ run.save(update_fields=["dispatch_attempts", "dispatch_error", "dispatch_next_attempt_at", "updated_at"])
+ return exhausted
+
+
+def set_run_stage(team_id: int, run_id: UUID, stage: WizardRunStage) -> WizardRunDTO:
+ run = _get_run_record(team_id, run_id)
+
+ run.stage = stage.value
+ run.stage_started_at = timezone.now()
+ run.save(update_fields=["stage", "stage_started_at", "updated_at"])
+
+ return record_to_run(run)
+
+
+def get_run(team_id: int, run_id: UUID) -> WizardRunDTO:
+ return record_to_run(_get_run_record(team_id, run_id))
+
+
+def get_run_for_update(team_id: int, run_id: UUID) -> WizardRunDTO:
+ run = WizardRun.objects.for_team(team_id).select_for_update().filter(id=run_id).first()
+ if run is None:
+ raise WizardRunNotFoundError
+
+ return record_to_run(run)
+
+
+def list_runs(params: ListWizardRunsInput) -> WizardRunPage:
+ runs = WizardRun.objects.for_team(params.team_id).order_by("-created_at")
+ page = runs[params.offset : params.offset + params.limit]
+ results: list[WizardRunDTO] = []
+ for run in page:
+ try:
+ results.append(record_to_run(run))
+ except ValueError:
+ logger.exception(
+ "wizard_run_deserialization_failed",
+ extra={"team_id": params.team_id, "run_id": str(run.id)},
+ )
+ return WizardRunPage(results=tuple(results), count=runs.count())
+
+
+def set_run_status(
+ team_id: int,
+ run_id: UUID,
+ status: WizardRunStatus,
+ error_code: str | None,
+) -> WizardRunDTO:
+ run = _get_run_record(team_id, run_id)
+ run.status = status.value
+ run.error_code = error_code
+ run.error_message = error_message(error_code)
+
+ update_fields = ["status", "error_code", "error_message", "updated_at"]
+
+ now = timezone.now()
+
+ if status == WizardRunStatus.RUNNING and run.started_at is None:
+ run.started_at = now
+ update_fields.append("started_at")
+
+ if status in (WizardRunStatus.COMPLETED, WizardRunStatus.FAILED, WizardRunStatus.CANCELLED):
+ run.finished_at = now
+ run.stage = None
+ run.stage_started_at = None
+ update_fields.extend(["finished_at", "stage", "stage_started_at"])
+
+ run.save(update_fields=update_fields)
+
+ return record_to_run(run)
diff --git a/products/wizard/backend/logic/runs/transitions.py b/products/wizard/backend/logic/runs/transitions.py
new file mode 100644
index 000000000000..ac8d402789c9
--- /dev/null
+++ b/products/wizard/backend/logic/runs/transitions.py
@@ -0,0 +1,33 @@
+from products.wizard.backend.facade.enums import WizardRunStatus
+from products.wizard.backend.facade.errors import IllegalStatusTransitionError, InvalidTransitionMetadataError
+
+# CREATED --> RUNNING --> COMPLETED
+# | |
+# +--> FAILED +--> FAILED
+# | |
+# +--> CANCELLED
+# |
+# +--> CANCELLED
+_ALLOWED_STATUS_TRANSITIONS = frozenset(
+ {
+ (WizardRunStatus.CREATED, WizardRunStatus.RUNNING),
+ (WizardRunStatus.CREATED, WizardRunStatus.FAILED),
+ (WizardRunStatus.CREATED, WizardRunStatus.CANCELLED),
+ (WizardRunStatus.RUNNING, WizardRunStatus.COMPLETED),
+ (WizardRunStatus.RUNNING, WizardRunStatus.FAILED),
+ (WizardRunStatus.RUNNING, WizardRunStatus.CANCELLED),
+ }
+)
+
+
+def transition(
+ current_status: WizardRunStatus,
+ next_status: WizardRunStatus,
+ *,
+ error_code: str | None = None,
+) -> WizardRunStatus:
+ if (current_status, next_status) not in _ALLOWED_STATUS_TRANSITIONS:
+ raise IllegalStatusTransitionError
+ if error_code is not None and next_status != WizardRunStatus.FAILED:
+ raise InvalidTransitionMetadataError
+ return next_status
diff --git a/products/wizard/backend/logic/runs/validation.py b/products/wizard/backend/logic/runs/validation.py
new file mode 100644
index 000000000000..ce3f9d7c662b
--- /dev/null
+++ b/products/wizard/backend/logic/runs/validation.py
@@ -0,0 +1,8 @@
+from products.wizard.backend.facade.errors import InvalidRepositoryError
+
+
+def validate_git_repository_name(repository: str) -> None:
+ owner, separator, name = repository.partition("/")
+
+ if not separator or not owner or not name or "/" in name:
+ raise InvalidRepositoryError
diff --git a/products/wizard/backend/logic/workers/config.py b/products/wizard/backend/logic/workers/config.py
new file mode 100644
index 000000000000..9aa28b270dc9
--- /dev/null
+++ b/products/wizard/backend/logic/workers/config.py
@@ -0,0 +1,41 @@
+from pathlib import Path
+
+from django.conf import settings
+
+from products.tasks.backend.facade.sandbox import SandboxTemplate
+
+WIZARD_TIMEOUT_SECONDS = 45 * 60
+WIZARD_TIMEOUT_EXIT_CODE = 124
+WIZARD_ERROR_DETAIL_LENGTH = 2000
+WIZARD_ERROR_OUTPUT_PREFIX = "phw-error:"
+MAX_HANDOFF_BODY_BYTES = 60_000
+LOCAL_WIZARD_BUILD_TIMEOUT_SECONDS = 15 * 60
+LOCAL_WIZARD_ARCHIVE_PATH = "/tmp/posthog-local-wizard.tar.gz"
+LOCAL_WIZARD_INSTALL_PATH = "/tmp/posthog-local-wizard"
+LOCAL_WIZARD_SOURCE_ENTRIES = (
+ "README.md",
+ "bin.ts",
+ "package.json",
+ "pnpm-lock.yaml",
+ "pnpm-workspace.yaml",
+ "scripts",
+ "src",
+ "tsconfig.build.json",
+ "tsconfig.json",
+ "tsdown.config.ts",
+ "types",
+)
+
+SANDBOX_EXECUTION_TIMEOUT_SECONDS = WIZARD_TIMEOUT_SECONDS + 120
+SANDBOX_TTL_SECONDS = 75 * 60
+SANDBOX_TEMPLATE_BASE = SandboxTemplate.SLIM_BASE
+SANDBOX_MEMORY_GB = 4
+SANDBOX_CPU_CORES = 2
+SANDBOX_DISK_SIZE_GB = 16
+
+
+def local_wizard_source_root() -> Path | None:
+ value = getattr(settings, "LOCAL_WIZARD_ROOT", None)
+ if not settings.DEBUG or not value:
+ return None
+ return Path(value).expanduser().resolve()
diff --git a/products/wizard/backend/logic/workers/contracts.py b/products/wizard/backend/logic/workers/contracts.py
new file mode 100644
index 000000000000..759af5c79ed5
--- /dev/null
+++ b/products/wizard/backend/logic/workers/contracts.py
@@ -0,0 +1,52 @@
+from datetime import datetime
+from typing import Literal
+
+from posthog.dataclasses import frozen
+
+
+@frozen
+class WizardWorkerResourceUsage:
+ cpu_cores: float
+ memory_gb: float
+ disk_size_gb: float
+ ttl_seconds: int
+ ttl_expires_at: datetime
+ provider_cpu_usage_usec: int | None = None
+ provider_billed_cpu_usage_usec: int | None = None
+ provider_usage_measured_at: datetime | None = None
+ version: Literal[1] = 1
+
+
+@frozen
+class WizardWorkerProvisioning:
+ sandbox_id: str
+ resource_usage: WizardWorkerResourceUsage
+
+
+@frozen
+class WizardWorkerUsageMeasurement:
+ cpu_usage_usec: int | None
+ billed_cpu_usage_usec: int | None
+ measured_at: datetime
+
+
+@frozen
+class WizardWorkerTelemetry:
+ resource_usage: WizardWorkerResourceUsage
+ lifetime_seconds: float
+
+
+@frozen
+class SignedRepositoryCommit:
+ repository: str
+ branch: str
+ commit_shas: tuple[str, ...]
+
+
+@frozen
+class RepositoryPullRequest:
+ repository: str
+ number: int
+ url: str
+ head_branch: str
+ base_branch: str
diff --git a/products/wizard/backend/logic/workers/local_package.py b/products/wizard/backend/logic/workers/local_package.py
new file mode 100644
index 000000000000..a3f2e53362b1
--- /dev/null
+++ b/products/wizard/backend/logic/workers/local_package.py
@@ -0,0 +1,43 @@
+import io
+import json
+import tarfile
+from pathlib import Path
+
+from products.wizard.backend.logic.workers.config import LOCAL_WIZARD_SOURCE_ENTRIES
+
+
+class InvalidLocalWizardSourceError(Exception):
+ pass
+
+
+def build_local_wizard_source_archive(source_root: Path) -> bytes:
+ _validate_local_wizard_source(source_root)
+
+ buffer = io.BytesIO()
+ with tarfile.open(fileobj=buffer, mode="w:gz") as archive:
+ for entry in LOCAL_WIZARD_SOURCE_ENTRIES:
+ path = source_root / entry
+ if path.exists():
+ archive.add(path, arcname=entry, recursive=True, filter=_exclude_links)
+
+ return buffer.getvalue()
+
+
+def _validate_local_wizard_source(source_root: Path) -> None:
+ if not source_root.is_dir():
+ raise InvalidLocalWizardSourceError(f"Local Wizard source directory does not exist: {source_root}")
+
+ try:
+ package = json.loads((source_root / "package.json").read_text())
+ except (OSError, json.JSONDecodeError) as error:
+ raise InvalidLocalWizardSourceError(f"Local Wizard package manifest is invalid: {source_root}") from error
+
+ if not isinstance(package, dict) or package.get("name") != "@posthog/wizard":
+ raise InvalidLocalWizardSourceError(f"Local Wizard package manifest is invalid: {source_root}")
+
+ if not (source_root / "pnpm-lock.yaml").is_file():
+ raise InvalidLocalWizardSourceError(f"Local Wizard lockfile does not exist: {source_root}")
+
+
+def _exclude_links(info: tarfile.TarInfo) -> tarfile.TarInfo | None:
+ return None if info.issym() or info.islnk() else info
diff --git a/products/wizard/backend/logic/workers/serializers.py b/products/wizard/backend/logic/workers/serializers.py
new file mode 100644
index 000000000000..8fd702a99555
--- /dev/null
+++ b/products/wizard/backend/logic/workers/serializers.py
@@ -0,0 +1,85 @@
+from datetime import datetime
+
+from products.wizard.backend.logic.workers.contracts import WizardWorkerResourceUsage
+
+
+def worker_resource_usage_to_record(resource_usage: WizardWorkerResourceUsage) -> dict[str, object]:
+ return {
+ "version": resource_usage.version,
+ "cpu_cores": resource_usage.cpu_cores,
+ "memory_gb": resource_usage.memory_gb,
+ "disk_size_gb": resource_usage.disk_size_gb,
+ "ttl_seconds": resource_usage.ttl_seconds,
+ "ttl_expires_at": resource_usage.ttl_expires_at.isoformat(),
+ "provider_cpu_usage_usec": resource_usage.provider_cpu_usage_usec,
+ "provider_billed_cpu_usage_usec": resource_usage.provider_billed_cpu_usage_usec,
+ "provider_usage_measured_at": (
+ resource_usage.provider_usage_measured_at.isoformat()
+ if resource_usage.provider_usage_measured_at is not None
+ else None
+ ),
+ }
+
+
+def record_to_worker_resource_usage(value: object) -> WizardWorkerResourceUsage:
+ if not isinstance(value, dict) or value["version"] != 1:
+ raise ValueError("Invalid Wizard Worker resource usage")
+
+ cpu_cores = _positive_number(value["cpu_cores"])
+ memory_gb = _positive_number(value["memory_gb"])
+ disk_size_gb = _positive_number(value["disk_size_gb"])
+ ttl_seconds = _positive_integer(value["ttl_seconds"])
+ ttl_expires_at = _datetime(value["ttl_expires_at"])
+
+ provider_cpu_usage_usec = _optional_nonnegative_integer(value.get("provider_cpu_usage_usec"))
+ provider_billed_cpu_usage_usec = _optional_nonnegative_integer(value.get("provider_billed_cpu_usage_usec"))
+ provider_usage_measured_at = _optional_datetime(value.get("provider_usage_measured_at"))
+
+ return WizardWorkerResourceUsage(
+ cpu_cores=cpu_cores,
+ memory_gb=memory_gb,
+ disk_size_gb=disk_size_gb,
+ ttl_seconds=ttl_seconds,
+ ttl_expires_at=ttl_expires_at,
+ provider_cpu_usage_usec=provider_cpu_usage_usec,
+ provider_billed_cpu_usage_usec=provider_billed_cpu_usage_usec,
+ provider_usage_measured_at=provider_usage_measured_at,
+ )
+
+
+def _positive_number(value: object) -> float:
+ if not isinstance(value, int | float) or isinstance(value, bool) or value <= 0:
+ raise ValueError("Invalid Wizard Worker resource usage")
+
+ return float(value)
+
+
+def _positive_integer(value: object) -> int:
+ if not isinstance(value, int) or isinstance(value, bool) or value <= 0:
+ raise ValueError("Invalid Wizard Worker resource usage")
+
+ return value
+
+
+def _optional_nonnegative_integer(value: object) -> int | None:
+ if value is None:
+ return None
+
+ if not isinstance(value, int) or isinstance(value, bool) or value < 0:
+ raise ValueError("Invalid Wizard Worker resource usage")
+
+ return value
+
+
+def _datetime(value: object) -> datetime:
+ if not isinstance(value, str):
+ raise ValueError("Invalid Wizard Worker resource usage")
+
+ try:
+ return datetime.fromisoformat(value)
+ except ValueError as error:
+ raise ValueError("Invalid Wizard Worker resource usage") from error
+
+
+def _optional_datetime(value: object) -> datetime | None:
+ return None if value is None else _datetime(value)
diff --git a/products/wizard/backend/logic/workers/store.py b/products/wizard/backend/logic/workers/store.py
new file mode 100644
index 000000000000..2aa30f65091c
--- /dev/null
+++ b/products/wizard/backend/logic/workers/store.py
@@ -0,0 +1,96 @@
+from dataclasses import replace
+from uuid import UUID
+
+from django.db.models import Case, CharField, F, Value, When
+from django.utils import timezone
+
+from products.wizard.backend.facade.enums import WizardWorkerCleanupStatus
+from products.wizard.backend.logic.runs.config import WORKER_CLEANUP_MAX_ATTEMPTS
+from products.wizard.backend.logic.workers.contracts import (
+ WizardWorkerProvisioning,
+ WizardWorkerTelemetry,
+ WizardWorkerUsageMeasurement,
+)
+from products.wizard.backend.logic.workers.serializers import (
+ record_to_worker_resource_usage,
+ worker_resource_usage_to_record,
+)
+from products.wizard.backend.models import WizardWorker
+
+
+def get_sandbox_id(team_id: int, run_id: UUID) -> str | None:
+ worker = WizardWorker.objects.for_team(team_id).filter(run_id=run_id).only("sandbox_id").first()
+ return worker.sandbox_id if worker is not None else None
+
+
+def record_provisioned_worker(team_id: int, run_id: UUID, provisioning: WizardWorkerProvisioning) -> None:
+ WizardWorker.objects.for_team(team_id).update_or_create(
+ team_id=team_id,
+ run_id=run_id,
+ defaults={
+ "sandbox_id": provisioning.sandbox_id,
+ "resource_usage": worker_resource_usage_to_record(provisioning.resource_usage),
+ "cleanup_status": WizardWorkerCleanupStatus.ACTIVE.value,
+ "cleanup_error": None,
+ },
+ )
+
+
+def record_usage(team_id: int, run_id: UUID, usage: WizardWorkerUsageMeasurement) -> None:
+ worker = WizardWorker.objects.for_team(team_id).only("resource_usage").get(run_id=run_id)
+ resource_usage = record_to_worker_resource_usage(worker.resource_usage)
+
+ updated_resource_usage = replace(
+ resource_usage,
+ provider_cpu_usage_usec=usage.cpu_usage_usec,
+ provider_billed_cpu_usage_usec=usage.billed_cpu_usage_usec,
+ provider_usage_measured_at=usage.measured_at,
+ )
+
+ WizardWorker.objects.for_team(team_id).filter(run_id=run_id).update(
+ resource_usage=worker_resource_usage_to_record(updated_resource_usage)
+ )
+
+
+def mark_cleanup_pending(team_id: int, run_id: UUID) -> None:
+ WizardWorker.objects.for_team(team_id).filter(run_id=run_id).update(
+ cleanup_status=WizardWorkerCleanupStatus.PENDING.value,
+ cleanup_attempts=F("cleanup_attempts") + 1,
+ cleanup_error=None,
+ )
+
+
+def mark_cleanup_failed(team_id: int, run_id: UUID) -> None:
+ WizardWorker.objects.for_team(team_id).filter(run_id=run_id).update(
+ cleanup_status=Case(
+ When(
+ cleanup_attempts__gte=WORKER_CLEANUP_MAX_ATTEMPTS,
+ then=Value(WizardWorkerCleanupStatus.FAILED.value),
+ ),
+ default=Value(WizardWorkerCleanupStatus.PENDING.value),
+ output_field=CharField(),
+ ),
+ cleanup_error="Wizard Worker cleanup failed.",
+ )
+
+
+def mark_cleaned(team_id: int, run_id: UUID) -> None:
+ WizardWorker.objects.for_team(team_id).filter(run_id=run_id).update(
+ cleanup_status=WizardWorkerCleanupStatus.CLEANED.value,
+ cleanup_error=None,
+ cleaned_at=timezone.now(),
+ )
+
+
+def get_worker_telemetry(team_id: int, run_id: UUID) -> WizardWorkerTelemetry:
+ worker = (
+ WizardWorker.objects.for_team(team_id).only("created_at", "cleaned_at", "resource_usage").get(run_id=run_id)
+ )
+
+ if worker.cleaned_at is None:
+ raise ValueError("Wizard Worker has not been cleaned up")
+
+ return WizardWorkerTelemetry(
+ resource_usage=record_to_worker_resource_usage(worker.resource_usage),
+ lifetime_seconds=max((worker.cleaned_at - worker.created_at).total_seconds(), 0),
+ )
diff --git a/products/wizard/backend/logic/workers/wizard_error_output.py b/products/wizard/backend/logic/workers/wizard_error_output.py
new file mode 100644
index 000000000000..af56c8c9e043
--- /dev/null
+++ b/products/wizard/backend/logic/workers/wizard_error_output.py
@@ -0,0 +1,27 @@
+import json
+
+from products.wizard.backend.facade.validation import is_wizard_error_code
+from products.wizard.backend.logic.workers.config import WIZARD_ERROR_OUTPUT_PREFIX
+
+
+def stderr_to_wizard_error_code(stderr: str) -> str | None:
+ for line in reversed(stderr.splitlines()):
+ value = line.strip()
+ if not value.startswith(WIZARD_ERROR_OUTPUT_PREFIX):
+ continue
+
+ try:
+ payload = json.loads(value.removeprefix(WIZARD_ERROR_OUTPUT_PREFIX).strip())
+ except (json.JSONDecodeError, TypeError):
+ return None
+
+ if not isinstance(payload, dict):
+ return None
+
+ code = payload.get("code")
+ if not isinstance(code, str) or not is_wizard_error_code(code):
+ return None
+
+ return code
+
+ return None
diff --git a/products/wizard/backend/metrics.py b/products/wizard/backend/metrics.py
index 7aaf70151d95..1c9763cee7da 100644
--- a/products/wizard/backend/metrics.py
+++ b/products/wizard/backend/metrics.py
@@ -1,17 +1,37 @@
from prometheus_client import Counter, Histogram
from products.wizard.backend.facade.contracts import WizardSessionDTO
-from products.wizard.backend.facade.enums import RunPhase
-
-_KNOWN_WORKFLOWS = {"posthog-integration"}
-
-_TERMINAL_PHASES = {RunPhase.COMPLETED, RunPhase.ERROR}
+from products.wizard.backend.facade.enums import WizardSessionRunPhase
+
+_KNOWN_PROGRAMS = {
+ "agent-skill",
+ "ai-observability",
+ "audit",
+ "error-tracking-upload-source-maps",
+ "events-audit",
+ "mcp-add",
+ "mcp-analytics",
+ "mcp-remove",
+ "mcp-tutorial",
+ "metrics",
+ "migration",
+ "posthog-doctor",
+ "posthog-integration",
+ "replay-vision",
+ "revenue-analytics-setup",
+ "self-driving",
+ "slack",
+ "warehouse-source",
+ "web-analytics-doctor",
+}
+
+_TERMINAL_PHASES = {WizardSessionRunPhase.COMPLETED, WizardSessionRunPhase.ERROR}
_KNOWN_POLL_SOURCES = {"detector", "transport"}
-def _workflow_label(workflow_id: str) -> str:
- return workflow_id if workflow_id in _KNOWN_WORKFLOWS else "other"
+def _program_label(program_id: str) -> str:
+ return program_id if program_id in _KNOWN_PROGRAMS else "other"
def poll_source_label(raw_source: str | None) -> str:
@@ -58,7 +78,7 @@ def report_registry_fallback(reason: str) -> None:
def report_session_upserted(previous_run_phase: str | None, dto: WizardSessionDTO) -> None:
if dto.run_phase not in _TERMINAL_PHASES or previous_run_phase in _TERMINAL_PHASES:
return
- workflow = _workflow_label(dto.workflow_id)
+ workflow = _program_label(dto.workflow_id)
outcome = dto.run_phase.value
WIZARD_SESSIONS_FINISHED_TOTAL.labels(workflow=workflow, outcome=outcome).inc()
duration = (dto.updated_at - dto.started_at).total_seconds()
diff --git a/products/wizard/backend/observability/config.py b/products/wizard/backend/observability/config.py
new file mode 100644
index 000000000000..0c6d49214557
--- /dev/null
+++ b/products/wizard/backend/observability/config.py
@@ -0,0 +1,16 @@
+WIZARD_ANALYTICS_TASK = "wizard.capture_run_event"
+
+WIZARD_RUN_CREATED_EVENT = "wizard run created"
+WIZARD_RUN_DISPATCH_FINISHED_EVENT = "wizard run dispatch finished"
+WIZARD_RUN_STAGE_ENTERED_EVENT = "wizard run stage entered"
+WIZARD_RUN_COMPLETED_EVENT = "wizard run completed"
+WIZARD_RUN_FAILED_EVENT = "wizard run failed"
+WIZARD_RUN_CANCELLED_EVENT = "wizard run cancelled"
+WIZARD_WORKER_USAGE_RECORDED_EVENT = "wizard worker usage recorded"
+WIZARD_PULL_REQUEST_CREATED_EVENT = "wizard pull request created"
+
+WIZARD_RUN_DURATION_BUCKETS = (30, 60, 120, 300, 600, 1200, 1800, 3600, 7200)
+WIZARD_WORKER_LIFETIME_BUCKETS = (30, 60, 120, 300, 600, 1200, 1800, 2700, 3600, 4500)
+WIZARD_WORKER_CPU_SECONDS_BUCKETS = (1, 5, 15, 30, 60, 120, 300, 600, 1200, 2400, 4800, 9600)
+WIZARD_WORKER_MEMORY_GB_SECONDS_BUCKETS = (60, 300, 1200, 2400, 4800, 9600, 18000, 36000)
+WIZARD_WORKER_DISK_GB_SECONDS_BUCKETS = (300, 1200, 4800, 9600, 18000, 36000, 72000, 144000)
diff --git a/products/wizard/backend/observability/contracts.py b/products/wizard/backend/observability/contracts.py
new file mode 100644
index 000000000000..e6c92a7cac4e
--- /dev/null
+++ b/products/wizard/backend/observability/contracts.py
@@ -0,0 +1,26 @@
+from enum import StrEnum
+
+from posthog.dataclasses import frozen
+
+
+class WizardRunDispatchOutcome(StrEnum):
+ SUCCEEDED = "succeeded"
+ FAILED = "failed"
+
+
+class WizardWorkerCleanupOutcome(StrEnum):
+ SUCCEEDED = "succeeded"
+ FAILED = "failed"
+
+
+@frozen
+class WizardWorkerUsageObservation:
+ lifetime_seconds: float
+ cpu_cores: float
+ memory_gb: float
+ disk_size_gb: float
+ cpu_usage_seconds: float | None
+ billed_cpu_usage_seconds: float | None
+ allocated_cpu_core_seconds: float
+ allocated_memory_gb_seconds: float
+ allocated_disk_gb_seconds: float
diff --git a/products/wizard/backend/observability/events.py b/products/wizard/backend/observability/events.py
new file mode 100644
index 000000000000..5ba58c73b42e
--- /dev/null
+++ b/products/wizard/backend/observability/events.py
@@ -0,0 +1,96 @@
+from uuid import NAMESPACE_URL, uuid5
+
+from celery import current_app as celery_app
+
+from products.wizard.backend.facade.contracts import WizardRunDTO
+from products.wizard.backend.facade.enums import WizardRunStage
+from products.wizard.backend.observability.config import (
+ WIZARD_ANALYTICS_TASK,
+ WIZARD_PULL_REQUEST_CREATED_EVENT,
+ WIZARD_RUN_CREATED_EVENT,
+ WIZARD_RUN_DISPATCH_FINISHED_EVENT,
+ WIZARD_RUN_STAGE_ENTERED_EVENT,
+ WIZARD_WORKER_USAGE_RECORDED_EVENT,
+)
+from products.wizard.backend.observability.contracts import WizardRunDispatchOutcome, WizardWorkerUsageObservation
+
+type WizardEventProperty = str | int | float | bool | None
+type WizardEventProperties = dict[str, WizardEventProperty]
+
+
+def enqueue_run_created(run: WizardRunDTO) -> None:
+ _enqueue_run_event(run, WIZARD_RUN_CREATED_EVENT, "created")
+
+
+def enqueue_dispatch_finished(run: WizardRunDTO, outcome: WizardRunDispatchOutcome) -> None:
+ _enqueue_run_event(
+ run,
+ WIZARD_RUN_DISPATCH_FINISHED_EVENT,
+ f"dispatch:{outcome.value}",
+ {"outcome": outcome.value},
+ )
+
+
+def enqueue_stage_entered(run: WizardRunDTO, stage: WizardRunStage) -> None:
+ _enqueue_run_event(
+ run,
+ WIZARD_RUN_STAGE_ENTERED_EVENT,
+ f"stage:{stage.value}",
+ {"stage": stage.value},
+ )
+
+
+def enqueue_run_finished(run: WizardRunDTO, failure_stage: WizardRunStage | None, event: str) -> None:
+ properties: WizardEventProperties = {
+ "status": run.status.value,
+ "error_code": run.error_code,
+ "failure_stage": failure_stage.value if failure_stage is not None else None,
+ }
+
+ if run.started_at is not None and run.finished_at is not None:
+ properties["duration_seconds"] = max((run.finished_at - run.started_at).total_seconds(), 0)
+
+ _enqueue_run_event(run, event, f"terminal:{run.status.value}", properties)
+
+
+def enqueue_worker_usage(run: WizardRunDTO, usage: WizardWorkerUsageObservation) -> None:
+ _enqueue_run_event(
+ run,
+ WIZARD_WORKER_USAGE_RECORDED_EVENT,
+ "worker_usage",
+ {
+ "lifetime_seconds": usage.lifetime_seconds,
+ "cpu_cores": usage.cpu_cores,
+ "memory_gb": usage.memory_gb,
+ "disk_size_gb": usage.disk_size_gb,
+ "cpu_usage_seconds": usage.cpu_usage_seconds,
+ "billed_cpu_usage_seconds": usage.billed_cpu_usage_seconds,
+ },
+ )
+
+
+def enqueue_pull_request_created(run: WizardRunDTO) -> None:
+ _enqueue_run_event(run, WIZARD_PULL_REQUEST_CREATED_EVENT, "artifact:pull_request")
+
+
+def _enqueue_run_event(
+ run: WizardRunDTO,
+ event: str,
+ event_key: str,
+ properties: WizardEventProperties | None = None,
+) -> None:
+ event_uuid = uuid5(NAMESPACE_URL, f"wizard:{run.id}:{event_key}")
+ event_properties: WizardEventProperties = {
+ "environment": run.environment.value,
+ "workspace_type": run.workspace.type,
+ "program_id": run.program.id,
+ "wizard_version": run.program.wizard_version,
+ }
+
+ if properties is not None:
+ event_properties.update(properties)
+
+ celery_app.signature(
+ WIZARD_ANALYTICS_TASK,
+ args=[run.team_id, run.created_by_id, str(run.id), event, str(event_uuid), event_properties],
+ ).apply_async()
diff --git a/products/wizard/backend/observability/metrics.py b/products/wizard/backend/observability/metrics.py
new file mode 100644
index 000000000000..965a2eb0e10b
--- /dev/null
+++ b/products/wizard/backend/observability/metrics.py
@@ -0,0 +1,217 @@
+from prometheus_client import Counter, Gauge, Histogram
+
+from products.wizard.backend.facade.contracts import WizardRunArtifactDTO, WizardRunDTO
+from products.wizard.backend.facade.enums import WizardRunEnvironment, WizardRunStage, WizardRunStatus
+from products.wizard.backend.observability.config import (
+ WIZARD_RUN_DURATION_BUCKETS,
+ WIZARD_WORKER_CPU_SECONDS_BUCKETS,
+ WIZARD_WORKER_DISK_GB_SECONDS_BUCKETS,
+ WIZARD_WORKER_LIFETIME_BUCKETS,
+ WIZARD_WORKER_MEMORY_GB_SECONDS_BUCKETS,
+)
+from products.wizard.backend.observability.contracts import (
+ WizardRunDispatchOutcome,
+ WizardWorkerCleanupOutcome,
+ WizardWorkerUsageObservation,
+)
+
+WIZARD_RUNS_CREATED_TOTAL = Counter(
+ "posthog_wizard_runs_created_total",
+ "Wizard runs created",
+ labelnames=["environment"],
+)
+
+WIZARD_RUN_DISPATCH_ATTEMPTS_TOTAL = Counter(
+ "posthog_wizard_run_dispatch_attempts_total",
+ "Wizard cloud run dispatch attempts",
+ labelnames=["outcome"],
+)
+
+WIZARD_CLOUD_RUNS_ACTIVE = Gauge(
+ "posthog_wizard_cloud_runs_active",
+ "Wizard cloud runs that have not reached a terminal status",
+ labelnames=["status", "stage"],
+)
+
+WIZARD_RUN_STAGE_ENTERED_TOTAL = Counter(
+ "posthog_wizard_run_stage_entered_total",
+ "Wizard cloud runs entering each execution stage",
+ labelnames=["stage"],
+)
+
+WIZARD_RUNS_FINISHED_TOTAL = Counter(
+ "posthog_wizard_runs_finished_total",
+ "Wizard runs that reached a terminal status",
+ labelnames=["environment", "status", "error_code"],
+)
+
+WIZARD_RUN_FAILURES_TOTAL = Counter(
+ "posthog_wizard_run_failures_total",
+ "Failed Wizard runs by execution stage and error code",
+ labelnames=["environment", "stage", "error_code"],
+)
+
+WIZARD_RUN_DURATION_SECONDS = Histogram(
+ "posthog_wizard_run_duration_seconds",
+ "Wizard run duration",
+ labelnames=["environment", "status"],
+ buckets=WIZARD_RUN_DURATION_BUCKETS,
+)
+
+WIZARD_GIT_DIFFS_OMITTED_TOTAL = Counter(
+ "posthog_wizard_git_diffs_omitted_total",
+ "Wizard git diff artifacts omitted because they exceeded the size limit",
+ labelnames=["environment"],
+)
+
+WIZARD_HANDOFF_BODY_FALLBACKS_TOTAL = Counter(
+ "posthog_wizard_handoff_body_fallbacks_total",
+ "Wizard pull requests that used the generic body because the handoff document was unavailable",
+)
+
+WIZARD_ARTIFACTS_CREATED_TOTAL = Counter(
+ "posthog_wizard_artifacts_created_total",
+ "Wizard run artifacts created",
+ labelnames=["type"],
+)
+
+WIZARD_WORKER_CLEANUPS_TOTAL = Counter(
+ "posthog_wizard_worker_cleanups_total",
+ "Wizard Worker cleanup attempts",
+ labelnames=["outcome"],
+)
+
+WIZARD_RUNS_PAST_DEADLINE_TOTAL = Counter(
+ "posthog_wizard_runs_past_deadline_total",
+ "Wizard cloud runs detected past their deadline",
+ labelnames=["environment"],
+)
+
+WIZARD_WORKER_LIFETIME_SECONDS = Histogram(
+ "posthog_wizard_worker_lifetime_seconds",
+ "Wizard Worker sandbox lifetime",
+ buckets=WIZARD_WORKER_LIFETIME_BUCKETS,
+)
+
+WIZARD_WORKER_CPU_USAGE_SECONDS = Histogram(
+ "posthog_wizard_worker_cpu_usage_seconds",
+ "Wizard Worker measured CPU usage",
+ buckets=WIZARD_WORKER_CPU_SECONDS_BUCKETS,
+)
+
+WIZARD_WORKER_BILLED_CPU_USAGE_SECONDS = Histogram(
+ "posthog_wizard_worker_billed_cpu_usage_seconds",
+ "Wizard Worker provider-billed CPU usage",
+ buckets=WIZARD_WORKER_CPU_SECONDS_BUCKETS,
+)
+
+WIZARD_WORKER_ALLOCATED_CPU_CORE_SECONDS = Histogram(
+ "posthog_wizard_worker_allocated_cpu_core_seconds",
+ "Wizard Worker allocated CPU core-seconds",
+ buckets=WIZARD_WORKER_CPU_SECONDS_BUCKETS,
+)
+
+WIZARD_WORKER_ALLOCATED_MEMORY_GB_SECONDS = Histogram(
+ "posthog_wizard_worker_allocated_memory_gb_seconds",
+ "Wizard Worker allocated memory GB-seconds",
+ buckets=WIZARD_WORKER_MEMORY_GB_SECONDS_BUCKETS,
+)
+
+WIZARD_WORKER_ALLOCATED_DISK_GB_SECONDS = Histogram(
+ "posthog_wizard_worker_allocated_disk_gb_seconds",
+ "Wizard Worker allocated disk GB-seconds",
+ buckets=WIZARD_WORKER_DISK_GB_SECONDS_BUCKETS,
+)
+
+
+def report_run_created(run: WizardRunDTO) -> None:
+ WIZARD_RUNS_CREATED_TOTAL.labels(environment=run.environment.value).inc()
+
+ if run.environment == WizardRunEnvironment.CLOUD and run.stage is not None:
+ WIZARD_CLOUD_RUNS_ACTIVE.labels(status=run.status.value, stage=run.stage.value).inc()
+
+
+def report_dispatch_finished(outcome: WizardRunDispatchOutcome) -> None:
+ WIZARD_RUN_DISPATCH_ATTEMPTS_TOTAL.labels(outcome=outcome.value).inc()
+
+
+def report_stage_entered(stage: WizardRunStage) -> None:
+ WIZARD_RUN_STAGE_ENTERED_TOTAL.labels(stage=stage.value).inc()
+
+
+def report_run_stage_changed(previous: WizardRunDTO, current: WizardRunDTO) -> None:
+ if previous.environment != WizardRunEnvironment.CLOUD or previous.stage is None or current.stage is None:
+ return
+
+ WIZARD_CLOUD_RUNS_ACTIVE.labels(status=previous.status.value, stage=previous.stage.value).dec()
+ WIZARD_CLOUD_RUNS_ACTIVE.labels(status=current.status.value, stage=current.stage.value).inc()
+
+
+def report_run_status_changed(previous: WizardRunDTO, current: WizardRunDTO) -> None:
+ if previous.environment != WizardRunEnvironment.CLOUD or previous.stage is None:
+ return
+
+ WIZARD_CLOUD_RUNS_ACTIVE.labels(status=previous.status.value, stage=previous.stage.value).dec()
+
+ if current.stage is not None:
+ WIZARD_CLOUD_RUNS_ACTIVE.labels(status=current.status.value, stage=current.stage.value).inc()
+
+
+def report_run_finished(run: WizardRunDTO, failure_stage: WizardRunStage | None) -> None:
+ error_code = run.error_code or "none"
+
+ WIZARD_RUNS_FINISHED_TOTAL.labels(
+ environment=run.environment.value,
+ status=run.status.value,
+ error_code=error_code,
+ ).inc()
+
+ if run.status == WizardRunStatus.FAILED:
+ WIZARD_RUN_FAILURES_TOTAL.labels(
+ environment=run.environment.value,
+ stage=failure_stage.value if failure_stage is not None else "none",
+ error_code=error_code,
+ ).inc()
+
+ if run.started_at is None or run.finished_at is None:
+ return
+
+ duration = (run.finished_at - run.started_at).total_seconds()
+ if duration >= 0:
+ WIZARD_RUN_DURATION_SECONDS.labels(environment=run.environment.value, status=run.status.value).observe(duration)
+
+
+def report_worker_usage(usage: WizardWorkerUsageObservation) -> None:
+ if usage.lifetime_seconds < 0:
+ return
+
+ WIZARD_WORKER_LIFETIME_SECONDS.observe(usage.lifetime_seconds)
+ WIZARD_WORKER_ALLOCATED_CPU_CORE_SECONDS.observe(usage.allocated_cpu_core_seconds)
+ WIZARD_WORKER_ALLOCATED_MEMORY_GB_SECONDS.observe(usage.allocated_memory_gb_seconds)
+ WIZARD_WORKER_ALLOCATED_DISK_GB_SECONDS.observe(usage.allocated_disk_gb_seconds)
+
+ if usage.cpu_usage_seconds is not None:
+ WIZARD_WORKER_CPU_USAGE_SECONDS.observe(usage.cpu_usage_seconds)
+
+ if usage.billed_cpu_usage_seconds is not None:
+ WIZARD_WORKER_BILLED_CPU_USAGE_SECONDS.observe(usage.billed_cpu_usage_seconds)
+
+
+def report_git_diff_omitted(run: WizardRunDTO) -> None:
+ WIZARD_GIT_DIFFS_OMITTED_TOTAL.labels(environment=run.environment.value).inc()
+
+
+def report_handoff_body_fallback() -> None:
+ WIZARD_HANDOFF_BODY_FALLBACKS_TOTAL.inc()
+
+
+def report_artifact_created(artifact: WizardRunArtifactDTO) -> None:
+ WIZARD_ARTIFACTS_CREATED_TOTAL.labels(type=artifact.artifact_type.value).inc()
+
+
+def report_worker_cleanup(outcome: WizardWorkerCleanupOutcome) -> None:
+ WIZARD_WORKER_CLEANUPS_TOTAL.labels(outcome=outcome.value).inc()
+
+
+def report_run_past_deadline(run: WizardRunDTO) -> None:
+ WIZARD_RUNS_PAST_DEADLINE_TOTAL.labels(environment=run.environment.value).inc()
diff --git a/products/wizard/backend/observability/service.py b/products/wizard/backend/observability/service.py
new file mode 100644
index 000000000000..5281af706fa9
--- /dev/null
+++ b/products/wizard/backend/observability/service.py
@@ -0,0 +1,226 @@
+import logging
+from collections.abc import Callable
+from functools import partial
+from uuid import UUID
+
+from kombu.exceptions import OperationalError
+
+from products.wizard.backend.facade.contracts import WizardRunArtifactDTO, WizardRunDTO, WizardRunPullRequestArtifactDTO
+from products.wizard.backend.facade.enums import WizardRunStatus
+from products.wizard.backend.logic.workers.contracts import WizardWorkerTelemetry
+from products.wizard.backend.observability import events, metrics
+from products.wizard.backend.observability.config import (
+ WIZARD_RUN_CANCELLED_EVENT,
+ WIZARD_RUN_COMPLETED_EVENT,
+ WIZARD_RUN_FAILED_EVENT,
+)
+from products.wizard.backend.observability.contracts import WizardRunDispatchOutcome, WizardWorkerCleanupOutcome
+from products.wizard.backend.observability.worker_usage import worker_usage_observation
+
+logger = logging.getLogger(__name__)
+
+
+class WizardObservability:
+ def _observe(
+ self,
+ *,
+ name: str,
+ context: dict[str, object],
+ metric: Callable[[], None] | None = None,
+ event: Callable[[], None] | None = None,
+ metric_error: str | None = None,
+ event_error: str | None = None,
+ level: int | None = logging.INFO,
+ ) -> None:
+ if metric is not None:
+ try:
+ metric()
+ except ValueError:
+ logger.exception(metric_error or f"{name}_metric_failed", extra=context)
+
+ if event is not None:
+ try:
+ event()
+ except OperationalError:
+ logger.exception(event_error or f"{name}_event_failed", extra=context)
+
+ if level is not None:
+ logger.log(level, name, extra=context)
+
+ def run_created(self, run: WizardRunDTO) -> None:
+ self._observe(
+ name="wizard_run_created",
+ context=self._run_context(run),
+ metric=partial(metrics.report_run_created, run),
+ event=partial(events.enqueue_run_created, run),
+ )
+
+ if run.stage is not None:
+ self.stage_entered(run)
+
+ def dispatch_finished(self, run: WizardRunDTO, outcome: WizardRunDispatchOutcome) -> None:
+ self._observe(
+ name="wizard_run_dispatch_finished",
+ context={**self._run_context(run), "outcome": outcome.value},
+ metric=partial(metrics.report_dispatch_finished, outcome),
+ event=partial(events.enqueue_dispatch_finished, run, outcome),
+ metric_error="wizard_run_dispatch_metric_failed",
+ event_error="wizard_run_dispatch_event_failed",
+ )
+
+ def stage_entered(self, run: WizardRunDTO) -> None:
+ if run.stage is None:
+ return
+
+ self._observe(
+ name="wizard_run_stage_entered",
+ context={**self._run_context(run), "stage": run.stage.value},
+ metric=partial(metrics.report_stage_entered, run.stage),
+ event=partial(events.enqueue_stage_entered, run, run.stage),
+ metric_error="wizard_run_stage_metric_failed",
+ event_error="wizard_run_stage_event_failed",
+ )
+
+ def stage_changed(self, previous: WizardRunDTO, current: WizardRunDTO) -> None:
+ self.stage_entered(current)
+
+ self._observe(
+ name="wizard_run_stage_active",
+ context=self._run_context(current),
+ metric=partial(metrics.report_run_stage_changed, previous, current),
+ level=None,
+ )
+
+ def run_transitioned(self, previous: WizardRunDTO, current: WizardRunDTO) -> None:
+ if previous.status != current.status:
+ self._observe(
+ name="wizard_run_status_active",
+ context=self._run_context(current),
+ metric=partial(metrics.report_run_status_changed, previous, current),
+ level=None,
+ )
+
+ event = self._terminal_event(current.status)
+
+ if event is None or previous.status == current.status:
+ return
+
+ self._observe(
+ name="wizard_run_finished",
+ context={
+ **self._run_context(current),
+ "status": current.status.value,
+ "error_code": current.error_code,
+ "failure_stage": previous.stage.value if previous.stage is not None else None,
+ },
+ metric=partial(metrics.report_run_finished, current, previous.stage),
+ event=partial(events.enqueue_run_finished, current, previous.stage, event),
+ )
+
+ def worker_usage_recorded(self, run: WizardRunDTO, telemetry: WizardWorkerTelemetry) -> None:
+ try:
+ usage = worker_usage_observation(telemetry)
+ except ValueError:
+ logger.exception("wizard_worker_usage_mapping_failed", extra=self._run_context(run))
+ return
+
+ self._observe(
+ name="wizard_worker_usage_recorded",
+ context={
+ **self._run_context(run),
+ "lifetime_seconds": usage.lifetime_seconds,
+ "cpu_cores": usage.cpu_cores,
+ "memory_gb": usage.memory_gb,
+ "disk_size_gb": usage.disk_size_gb,
+ "cpu_usage_seconds": usage.cpu_usage_seconds,
+ "billed_cpu_usage_seconds": usage.billed_cpu_usage_seconds,
+ },
+ metric=partial(metrics.report_worker_usage, usage),
+ event=partial(events.enqueue_worker_usage, run, usage),
+ metric_error="wizard_worker_usage_metric_failed",
+ event_error="wizard_worker_usage_event_failed",
+ )
+
+ def git_diff_omitted(self, run: WizardRunDTO, size_bytes: int) -> None:
+ self._observe(
+ name="wizard_git_diff_omitted",
+ context={**self._run_context(run), "size_bytes": size_bytes},
+ metric=partial(metrics.report_git_diff_omitted, run),
+ level=logging.WARNING,
+ )
+
+ def handoff_body_fallback(self, team_id: int, run_id: UUID) -> None:
+ self._observe(
+ name="wizard_handoff_body_fallback",
+ context={"team_id": team_id, "run_id": str(run_id)},
+ metric=metrics.report_handoff_body_fallback,
+ level=logging.WARNING,
+ )
+
+ def artifact_created(self, run: WizardRunDTO, artifact: WizardRunArtifactDTO) -> None:
+ self._observe(
+ name="wizard_artifact_created",
+ context={**self._run_context(run), "artifact_type": artifact.artifact_type.value},
+ metric=partial(metrics.report_artifact_created, artifact),
+ metric_error="wizard_artifact_metric_failed",
+ )
+
+ def pull_request_created(self, run: WizardRunDTO, artifact: WizardRunPullRequestArtifactDTO) -> None:
+ self.artifact_created(run, artifact)
+
+ self._observe(
+ name="wizard_pull_request_created",
+ context={
+ **self._run_context(run),
+ "repository": artifact.repository,
+ "pull_request_number": artifact.number,
+ },
+ event=partial(events.enqueue_pull_request_created, run),
+ )
+
+ def worker_cleanup_finished(
+ self,
+ team_id: int,
+ run_id: UUID,
+ outcome: WizardWorkerCleanupOutcome,
+ ) -> None:
+ self._observe(
+ name="wizard_worker_cleanup_finished",
+ context={"team_id": team_id, "run_id": str(run_id), "outcome": outcome.value},
+ metric=partial(metrics.report_worker_cleanup, outcome),
+ metric_error="wizard_worker_cleanup_metric_failed",
+ )
+
+ def run_past_deadline(self, run: WizardRunDTO) -> None:
+ self._observe(
+ name="wizard_run_past_deadline",
+ context=self._run_context(run),
+ metric=partial(metrics.report_run_past_deadline, run),
+ metric_error="wizard_run_deadline_metric_failed",
+ level=logging.WARNING,
+ )
+
+ @staticmethod
+ def _terminal_event(status: WizardRunStatus) -> str | None:
+ match status:
+ case WizardRunStatus.COMPLETED:
+ return WIZARD_RUN_COMPLETED_EVENT
+ case WizardRunStatus.FAILED:
+ return WIZARD_RUN_FAILED_EVENT
+ case WizardRunStatus.CANCELLED:
+ return WIZARD_RUN_CANCELLED_EVENT
+ case _:
+ return None
+
+ @staticmethod
+ def _run_context(run: WizardRunDTO) -> dict[str, object]:
+ return {
+ "team_id": run.team_id,
+ "run_id": str(run.id),
+ "environment": run.environment.value,
+ "program_id": run.program.id,
+ "wizard_version": run.program.wizard_version,
+ }
+
+
+wizard_observability = WizardObservability()
diff --git a/products/wizard/backend/observability/worker_usage.py b/products/wizard/backend/observability/worker_usage.py
new file mode 100644
index 000000000000..d302f9cc2d98
--- /dev/null
+++ b/products/wizard/backend/observability/worker_usage.py
@@ -0,0 +1,26 @@
+from products.wizard.backend.logic.workers.contracts import WizardWorkerTelemetry
+from products.wizard.backend.observability.contracts import WizardWorkerUsageObservation
+
+
+def worker_usage_observation(telemetry: WizardWorkerTelemetry) -> WizardWorkerUsageObservation:
+ resource_usage = telemetry.resource_usage
+
+ return WizardWorkerUsageObservation(
+ lifetime_seconds=telemetry.lifetime_seconds,
+ cpu_cores=resource_usage.cpu_cores,
+ memory_gb=resource_usage.memory_gb,
+ disk_size_gb=resource_usage.disk_size_gb,
+ cpu_usage_seconds=(
+ resource_usage.provider_cpu_usage_usec / 1_000_000
+ if resource_usage.provider_cpu_usage_usec is not None
+ else None
+ ),
+ billed_cpu_usage_seconds=(
+ resource_usage.provider_billed_cpu_usage_usec / 1_000_000
+ if resource_usage.provider_billed_cpu_usage_usec is not None
+ else None
+ ),
+ allocated_cpu_core_seconds=resource_usage.cpu_cores * telemetry.lifetime_seconds,
+ allocated_memory_gb_seconds=resource_usage.memory_gb * telemetry.lifetime_seconds,
+ allocated_disk_gb_seconds=resource_usage.disk_size_gb * telemetry.lifetime_seconds,
+ )
diff --git a/products/wizard/backend/tests/runs/test_artifacts.py b/products/wizard/backend/tests/runs/test_artifacts.py
new file mode 100644
index 000000000000..fd3409cd2cbd
--- /dev/null
+++ b/products/wizard/backend/tests/runs/test_artifacts.py
@@ -0,0 +1,244 @@
+from hashlib import sha256
+
+import pytest
+from unittest.mock import patch
+
+from django.conf import settings
+
+from posthog.models import Team
+
+from products.wizard.backend.facade import api as wizard_facade
+from products.wizard.backend.facade.contracts import (
+ CreatePullRequestArtifactInput,
+ LocalFolderWorkspace,
+ WizardRunDTO,
+ WizardRunGitDiffArtifactDTO,
+ WizardRunPullRequestArtifactDTO,
+)
+from products.wizard.backend.facade.enums import WizardRunArtifactType, WizardRunEnvironment, WizardRunStatus
+from products.wizard.backend.facade.errors import WizardRunArtifactTooLargeError, WizardRunNotFoundError
+from products.wizard.backend.logic.registry.config import FALLBACK_REGISTRY
+from products.wizard.backend.logic.runs import store as run_store
+from products.wizard.backend.models import WizardRunArtifact
+
+
+def _create_run(team_id: int, user_id: int) -> WizardRunDTO:
+ return run_store.create_run(
+ team_id=team_id,
+ created_by_id=user_id,
+ environment=WizardRunEnvironment.LOCAL,
+ workspace=LocalFolderWorkspace(project_name="example-project"),
+ program=FALLBACK_REGISTRY.programs[0],
+ status=WizardRunStatus.RUNNING,
+ ).run
+
+
+def test_create_git_diff_artifact_stores_content_by_reference(team, user) -> None:
+ run = _create_run(team.id, user.id)
+ diff = b"diff --git a/app.py b/app.py\n"
+
+ with patch("products.wizard.backend.logic.artifacts.service.object_storage.write") as write:
+ artifact = wizard_facade.create_git_diff_artifact(team.id, run.id, diff)
+
+ assert artifact is not None
+ assert artifact.team_id == team.id
+ assert artifact.run_id == run.id
+ assert artifact.artifact_type == WizardRunArtifactType.GIT_DIFF
+ assert artifact.size_bytes == len(diff)
+ write.assert_called_once_with(
+ f"projects/{team.id}/wizard-runs/{run.id}/artifacts/git-diff-{sha256(diff).hexdigest()}.patch",
+ diff,
+ extras={"ContentType": "text/x-diff; charset=utf-8"},
+ bucket=settings.WIZARD_RUN_ARTIFACTS_S3_BUCKET,
+ )
+ assert wizard_facade.list_run_artifacts(team.id, run.id) == [artifact]
+
+
+def test_git_diff_artifact_does_not_download_oversized_content(team, user) -> None:
+ run = _create_run(team.id, user.id)
+
+ with patch("products.wizard.backend.logic.artifacts.service.object_storage.write"):
+ artifact = wizard_facade.create_git_diff_artifact(team.id, run.id, b"expected")
+
+ assert artifact is not None
+ WizardRunArtifact.objects.for_team(team.id).filter(id=artifact.id).update(size_bytes=2 * 1024 * 1024 + 1)
+ with (
+ patch("products.wizard.backend.logic.artifacts.service.object_storage.read_bytes") as read_bytes,
+ pytest.raises(WizardRunArtifactTooLargeError),
+ ):
+ wizard_facade.get_git_diff_artifact_content(team.id, run.id, artifact.id)
+ read_bytes.assert_not_called()
+
+
+def test_git_diff_artifact_rejects_changed_stored_content(team, user) -> None:
+ run = _create_run(team.id, user.id)
+
+ with patch("products.wizard.backend.logic.artifacts.service.object_storage.write"):
+ artifact = wizard_facade.create_git_diff_artifact(team.id, run.id, b"expected")
+
+ assert artifact is not None
+ with (
+ patch("products.wizard.backend.logic.artifacts.service.object_storage.read_bytes", return_value=b"changed"),
+ pytest.raises(ValueError, match="integrity check"),
+ ):
+ wizard_facade.get_git_diff_artifact_content(team.id, run.id, artifact.id)
+
+
+def test_empty_git_diff_creates_no_artifact(team, user) -> None:
+ run = _create_run(team.id, user.id)
+
+ with patch("products.wizard.backend.logic.artifacts.service.object_storage.write") as write:
+ artifact = wizard_facade.create_git_diff_artifact(team.id, run.id, b"")
+
+ assert artifact is None
+ assert wizard_facade.list_run_artifacts(team.id, run.id) == []
+ write.assert_not_called()
+
+
+def test_git_diff_artifact_stores_line_change_counts(team, user) -> None:
+ run = _create_run(team.id, user.id)
+ diff = (
+ b"diff --git a/app.py b/app.py\n"
+ b"+++ b/app.py\n"
+ b"--- a/app.py\n"
+ b"@@ -1,2 +1,3 @@\n"
+ b"+added one\n"
+ b"+added two\n"
+ b"-removed one\n"
+ b" kept line\n"
+ )
+
+ with patch("products.wizard.backend.logic.artifacts.service.object_storage.write"):
+ artifact = wizard_facade.create_git_diff_artifact(team.id, run.id, diff)
+
+ assert artifact is not None
+ assert artifact.additions == 2
+ assert artifact.removals == 1
+
+ listed = wizard_facade.list_run_artifacts(team.id, run.id)[0]
+ assert isinstance(listed, WizardRunGitDiffArtifactDTO)
+ assert listed.additions == 2
+ assert listed.removals == 1
+
+
+def test_git_diff_artifact_without_stored_counts_maps_to_none(team, user) -> None:
+ run = _create_run(team.id, user.id)
+
+ with patch("products.wizard.backend.logic.artifacts.service.object_storage.write"):
+ artifact = wizard_facade.create_git_diff_artifact(team.id, run.id, b"diff --git a/app.py b/app.py\n")
+
+ assert artifact is not None
+ WizardRunArtifact.objects.for_team(team.id).filter(id=artifact.id).update(metadata=None)
+
+ listed = wizard_facade.list_run_artifacts(team.id, run.id)[0]
+ assert isinstance(listed, WizardRunGitDiffArtifactDTO)
+ assert listed.additions is None
+ assert listed.removals is None
+
+
+def test_oversized_git_diff_creates_no_artifact(team, user) -> None:
+ run = _create_run(team.id, user.id)
+
+ with (
+ patch("products.wizard.backend.logic.artifacts.service.MAX_GIT_DIFF_BYTES", 4),
+ patch("products.wizard.backend.logic.artifacts.service.object_storage.write") as write,
+ patch("products.wizard.backend.logic.artifacts.service.run_observability") as observability,
+ ):
+ artifact = wizard_facade.create_git_diff_artifact(team.id, run.id, b"12345")
+
+ assert artifact is None
+ write.assert_not_called()
+ observability.git_diff_omitted.assert_called_once_with(run, 5)
+
+
+def test_git_diff_artifact_is_idempotent_for_run(team, user) -> None:
+ run = _create_run(team.id, user.id)
+
+ with patch("products.wizard.backend.logic.artifacts.service.object_storage.write"):
+ first = wizard_facade.create_git_diff_artifact(team.id, run.id, b"first")
+ second = wizard_facade.create_git_diff_artifact(team.id, run.id, b"second")
+
+ assert first is not None
+ assert second is not None
+ assert second.id == first.id
+ assert second.size_bytes == len(b"second")
+ assert wizard_facade.list_run_artifacts(team.id, run.id) == [second]
+
+
+def test_create_git_diff_artifact_is_scoped_to_team(team, user) -> None:
+ other_team = Team.objects.create(organization=team.organization, project=team.project, name="Other environment")
+ run = _create_run(team.id, user.id)
+
+ with (
+ patch("products.wizard.backend.logic.artifacts.service.object_storage.write") as write,
+ pytest.raises(WizardRunNotFoundError),
+ ):
+ wizard_facade.create_git_diff_artifact(other_team.id, run.id, b"diff")
+
+ write.assert_not_called()
+
+
+def test_create_pull_request_artifact_persists_pull_request_identity(team, user) -> None:
+ run = _create_run(team.id, user.id)
+ params = CreatePullRequestArtifactInput(
+ team_id=team.id,
+ run_id=run.id,
+ url="https://github.com/posthog/posthog/pull/123",
+ number=123,
+ repository="posthog/posthog",
+ head_branch="posthog/wizard-123",
+ base_branch="master",
+ )
+
+ artifact = wizard_facade.create_pull_request_artifact(params)
+
+ assert isinstance(artifact, WizardRunPullRequestArtifactDTO)
+ assert artifact.artifact_type == WizardRunArtifactType.PULL_REQUEST
+ assert artifact.url == params.url
+ assert artifact.number == params.number
+ assert artifact.repository == params.repository
+ assert artifact.head_branch == params.head_branch
+ assert artifact.base_branch == params.base_branch
+ assert wizard_facade.list_run_artifacts(team.id, run.id) == [artifact]
+
+
+ ("artifact_type", "external_url", "metadata", "size_bytes", "content_hash"),
+ [
+ (WizardRunArtifactType.GIT_DIFF, None, None, None, None),
+ (WizardRunArtifactType.PULL_REQUEST, None, {}, None, None),
+ ],
+)
+def test_list_run_artifacts_rejects_incomplete_persisted_metadata(
+ team,
+ user,
+ artifact_type: WizardRunArtifactType,
+ external_url: str | None,
+ metadata: dict[str, object] | None,
+ size_bytes: int | None,
+ content_hash: str | None,
+) -> None:
+ run = _create_run(team.id, user.id)
+ WizardRunArtifact.objects.for_team(team.id).create(
+ team_id=team.id,
+ run_id=run.id,
+ type=artifact_type.value,
+ external_url=external_url,
+ metadata=metadata,
+ size_bytes=size_bytes,
+ content_hash=content_hash,
+ )
+
+ with pytest.raises(ValueError):
+ wizard_facade.list_run_artifacts(team.id, run.id)
diff --git a/products/wizard/backend/tests/runs/test_observability.py b/products/wizard/backend/tests/runs/test_observability.py
new file mode 100644
index 000000000000..713c240891fb
--- /dev/null
+++ b/products/wizard/backend/tests/runs/test_observability.py
@@ -0,0 +1,66 @@
+import logging
+from datetime import UTC, datetime
+from uuid import UUID
+
+from unittest import TestCase
+from unittest.mock import patch
+
+from kombu.exceptions import OperationalError
+from parameterized import parameterized
+
+from products.wizard.backend.facade.contracts import LocalFolderWorkspace, WizardRunDTO
+from products.wizard.backend.facade.enums import WizardRunEnvironment, WizardRunStatus
+from products.wizard.backend.logic.registry.config import POSTHOG_INTEGRATION_PROGRAM
+from products.wizard.backend.observability import metrics
+from products.wizard.backend.observability.contracts import WizardRunDispatchOutcome
+from products.wizard.backend.observability.service import WizardObservability
+
+
+class TestWizardObservability(TestCase):
+ @parameterized.expand(
+ [
+ (False, False),
+ (True, False),
+ (False, True),
+ (True, True),
+ ]
+ )
+ def test_dispatch_observations_survive_independent_failures(self, metric_fails: bool, event_fails: bool) -> None:
+ run = WizardRunDTO(
+ id=UUID(int=1),
+ team_id=123,
+ created_by_id=456,
+ environment=WizardRunEnvironment.LOCAL,
+ workspace=LocalFolderWorkspace(project_name="example-project"),
+ program=POSTHOG_INTEGRATION_PROGRAM,
+ status=WizardRunStatus.RUNNING,
+ error_code=None,
+ error_message=None,
+ stage=None,
+ created_at=datetime(2026, 1, 1, tzinfo=UTC),
+ updated_at=None,
+ started_at=None,
+ finished_at=None,
+ deadline_at=None,
+ )
+
+ with (
+ patch.object(metrics.WIZARD_RUN_DISPATCH_ATTEMPTS_TOTAL, "labels") as counter,
+ patch("products.wizard.backend.observability.events.celery_app.signature") as signature,
+ self.assertLogs("products.wizard.backend.observability.service", level=logging.INFO) as logs,
+ ):
+ counter.return_value.inc.side_effect = ValueError("Metric unavailable") if metric_fails else None
+ signature.return_value.apply_async.side_effect = (
+ OperationalError("Queue unavailable") if event_fails else None
+ )
+
+ WizardObservability().dispatch_finished(run, WizardRunDispatchOutcome.SUCCEEDED)
+
+ counter.return_value.inc.assert_called_once_with()
+ signature.return_value.apply_async.assert_called_once_with()
+ self.assertEqual(signature.call_args.kwargs["args"][3], "wizard run dispatch finished")
+ messages = [record.getMessage() for record in logs.records]
+ self.assertEqual("wizard_run_dispatch_metric_failed" in messages, metric_fails)
+ self.assertEqual("wizard_run_dispatch_event_failed" in messages, event_fails)
+ self.assertEqual(messages[-1], "wizard_run_dispatch_finished")
+ self.assertEqual(logs.records[-1].levelno, logging.INFO)
diff --git a/products/wizard/backend/tests/runs/test_transitions.py b/products/wizard/backend/tests/runs/test_transitions.py
new file mode 100644
index 000000000000..30b6e662d3e2
--- /dev/null
+++ b/products/wizard/backend/tests/runs/test_transitions.py
@@ -0,0 +1,51 @@
+from itertools import product
+
+import pytest
+
+from products.wizard.backend.facade.enums import WizardRunErrorCode, WizardRunStatus
+from products.wizard.backend.facade.errors import IllegalStatusTransitionError, InvalidTransitionMetadataError
+from products.wizard.backend.logic.runs import validation
+from products.wizard.backend.logic.runs.transitions import transition
+
+ALLOWED_TRANSITIONS = (
+ (WizardRunStatus.CREATED, WizardRunStatus.RUNNING),
+ (WizardRunStatus.CREATED, WizardRunStatus.FAILED),
+ (WizardRunStatus.CREATED, WizardRunStatus.CANCELLED),
+ (WizardRunStatus.RUNNING, WizardRunStatus.COMPLETED),
+ (WizardRunStatus.RUNNING, WizardRunStatus.FAILED),
+ (WizardRunStatus.RUNNING, WizardRunStatus.CANCELLED),
+)
+
+ILLEGAL_TRANSITIONS = tuple(
+ transition for transition in product(WizardRunStatus, repeat=2) if transition not in ALLOWED_TRANSITIONS
+)
+
+
[email protected]("current_status, next_status", ALLOWED_TRANSITIONS)
+def test_run_accepts_valid_status_transitions(current_status: WizardRunStatus, next_status: WizardRunStatus) -> None:
+ error_code = WizardRunErrorCode.TIMEOUT if next_status == WizardRunStatus.FAILED else None
+
+ assert transition(current_status, next_status, error_code=error_code) == next_status
+
+
[email protected]("current_status, next_status", ILLEGAL_TRANSITIONS)
+def test_run_rejects_invalid_status_transitions(current_status: WizardRunStatus, next_status: WizardRunStatus) -> None:
+ with pytest.raises(IllegalStatusTransitionError):
+ transition(current_status, next_status)
+
+
+def test_run_rejects_error_code_for_non_failed_status() -> None:
+ with pytest.raises(InvalidTransitionMetadataError):
+ transition(
+ WizardRunStatus.RUNNING,
+ WizardRunStatus.COMPLETED,
+ error_code=WizardRunErrorCode.TIMEOUT,
+ )
+
+
+def test_failed_transition_allows_missing_error_code() -> None:
+ assert transition(WizardRunStatus.RUNNING, WizardRunStatus.FAILED) == WizardRunStatus.FAILED
+
+
+def test_status_transition_invariants_are_not_validation_rules() -> None:
+ assert not hasattr(validation, "validate_status_transition")
diff --git a/products/wizard/backend/tests/runs/test_wizard_error_output.py b/products/wizard/backend/tests/runs/test_wizard_error_output.py
new file mode 100644
index 000000000000..f134a815e5b5
--- /dev/null
+++ b/products/wizard/backend/tests/runs/test_wizard_error_output.py
@@ -0,0 +1,25 @@
+import pytest
+
+from products.wizard.backend.logic.workers.wizard_error_output import stderr_to_wizard_error_code
+
+
+ ("stderr", "expected"),
+ (
+ (
+ 'Wizard output\nphw-error: {"code":"PHW_DETECT_NO_POSTHOG_SDK","message":"Missing SDK"}',
+ "PHW_DETECT_NO_POSTHOG_SDK",
+ ),
+ (
+ 'phw-error: {"code":"PHW_DETECT_NO_FRAMEWORK"}\nphw-error: {"code":"PHW_AGENT_NO_PROGRESS"}',
+ "PHW_AGENT_NO_PROGRESS",
+ ),
+ ('phw-error: {"code":"PHW_FUTURE_ERROR"}', "PHW_FUTURE_ERROR"),
+ ('phw-error: {"code":"detect_no_framework"}', None),
+ ('phw-error: {"message":"Missing code"}', None),
+ ("phw-error: not-json", None),
+ ("ordinary stderr", None),
+ ),
+)
+def test_stderr_to_wizard_error_code(stderr: str, expected: str | None) -> None:
+ assert stderr_to_wizard_error_code(stderr) == expected
diff --git a/products/wizard/backend/tests/runs/test_worker_serializers.py b/products/wizard/backend/tests/runs/test_worker_serializers.py
new file mode 100644
index 000000000000..21aca109f0ad
--- /dev/null
+++ b/products/wizard/backend/tests/runs/test_worker_serializers.py
@@ -0,0 +1,49 @@
+from datetime import UTC, datetime
+
+import pytest
+
+from products.wizard.backend.logic.workers.contracts import WizardWorkerResourceUsage
+from products.wizard.backend.logic.workers.serializers import (
+ record_to_worker_resource_usage,
+ worker_resource_usage_to_record,
+)
+
+
+def test_worker_resource_usage_round_trip() -> None:
+ resource_usage = WizardWorkerResourceUsage(
+ cpu_cores=2,
+ memory_gb=4,
+ disk_size_gb=16,
+ ttl_seconds=4500,
+ ttl_expires_at=datetime(2026, 8, 24, 15, 0, tzinfo=UTC),
+ provider_cpu_usage_usec=120,
+ provider_billed_cpu_usage_usec=240,
+ provider_usage_measured_at=datetime(2026, 8, 24, 14, 30, tzinfo=UTC),
+ )
+
+ assert record_to_worker_resource_usage(worker_resource_usage_to_record(resource_usage)) == resource_usage
+
+
+ "record",
+ (
+ None,
+ {"version": 2},
+ {
+ "version": 1,
+ "cpu_cores": 0,
+ "memory_gb": 4,
+ "disk_size_gb": 16,
+ "ttl_seconds": 4500,
+ "ttl_expires_at": "2026-08-24T15:00:00+00:00",
+ },
+ ),
+)
+def test_worker_resource_usage_rejects_invalid_records(record: object) -> None:
+ with pytest.raises(ValueError, match="Invalid Wizard Worker resource usage"):
+ record_to_worker_resource_usage(record)
+
+
+def test_worker_resource_usage_requires_persisted_fields() -> None:
+ with pytest.raises(KeyError, match="version"):
+ record_to_worker_resource_usage({})
diff --git a/tach.toml b/tach.toml
index ecee816839a2..4e59a0b91e10 100644
--- a/tach.toml
+++ b/tach.toml
@@ -1314,7 +1314,7 @@ from = [
[[modules]]
path = "products.wizard"
-depends_on = ["posthog", "products.event_definitions"]
+depends_on = ["posthog", "products.event_definitions", "products.tasks"]
layer = "modules"
[[interfaces]]