Skip to content

:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.

fix(wizard): restore run environment metrics and billed cpu usage (#129038)

Fernando Gomes3294601937b2
diff --git a/products/tasks/backend/logic/services/modal_sandbox.py b/products/tasks/backend/logic/services/modal_sandbox.py
index 4bed35d7304d..7a8317b0d87f 100644
--- a/products/tasks/backend/logic/services/modal_sandbox.py
+++ b/products/tasks/backend/logic/services/modal_sandbox.py
@@ -599,7 +599,7 @@ def _attach_local_package_mounts(
def _build_slim_template_image() -> modal.Image:
- """Inline image for SLIM_BASE: git + ca-certificates + node + uv, nothing else.
+ """Inline image for SLIM_BASE: git + ca-certificates + node + uv + the CPU billing sampler, nothing else.
Built and cached by Modal itself from debian_slim — no registry image, no CD publish
pipeline, no digest pin to resolve. The first sandbox create after this definition
@@ -623,6 +623,14 @@ def _build_slim_template_image() -> modal.Image:
.dockerfile_commands(
[f"COPY --from={SANDBOX_SLIM_UV_IMAGE} /uv /uvx /usr/local/bin/"],
)
+ # start_cpu_billing_sampler runs this script for every provider. Without it in the image,
+ # no billing state file exists and read_billed_cpu_usage_usec fails for each slim sandbox.
+ .add_local_file(
+ str(Path(settings.BASE_DIR) / "products/tasks/backend/sandbox/images/cpu_billing_sampler.py"),
+ CPU_BILLING_SAMPLER_PATH,
+ copy=True,
+ )
+ .run_commands(f"chmod +x {CPU_BILLING_SAMPLER_PATH} && {CPU_BILLING_SAMPLER_PATH} --check")
)
diff --git a/products/tasks/backend/sandbox/images/Dockerfile.sandbox-slim b/products/tasks/backend/sandbox/images/Dockerfile.sandbox-slim
index 9deddf40cd4a..a2c52a2f8e17 100644
--- a/products/tasks/backend/sandbox/images/Dockerfile.sandbox-slim
+++ b/products/tasks/backend/sandbox/images/Dockerfile.sandbox-slim
@@ -1,6 +1,6 @@
# Minimal sandbox image for review/exec workloads that don't run the agent server —
# e.g. stamphog's PR review sandbox. Ships only git, ca-certificates, python3 (DockerSandbox.write_file
-# shells out to it), node (Claude Code CLI runtime), and uv/uvx. No @posthog/agent, no gh CLI, no
+# shells out to it), node (Claude Code CLI runtime), uv/uvx, and the CPU billing sampler. No @posthog/agent, no gh CLI, no
# ruff/ty, no skills.
#
# Anything that needs the agent server (task execution, skills, MCP) must use
@@ -33,6 +33,11 @@ RUN curl -fsSL https://deb.nodesource.com/setup_${NODE_MAJOR}.x | bash - && \
# uv comes from its pinned, registry-verified official image, same as Dockerfile.sandbox-base.
COPY --from=ghcr.io/astral-sh/uv:0.13.4 /uv /uvx /usr/local/bin/
+# start_cpu_billing_sampler runs this script for every template, so billed CPU usage
+# stays empty unless the image ships it. Keep in sync with modal_sandbox.py's SLIM_BASE image.
+COPY products/tasks/backend/sandbox/images/cpu_billing_sampler.py /usr/local/bin/posthog-cpu-billing-sampler
+RUN chmod +x /usr/local/bin/posthog-cpu-billing-sampler && /usr/local/bin/posthog-cpu-billing-sampler --check
+
WORKDIR /tmp/workspace
RUN git --version && node --version && uv --version
diff --git a/products/tasks/backend/sandbox/images/cpu_billing_sampler.py b/products/tasks/backend/sandbox/images/cpu_billing_sampler.py
index df6aa08eba08..c4c633ab0645 100644
--- a/products/tasks/backend/sandbox/images/cpu_billing_sampler.py
+++ b/products/tasks/backend/sandbox/images/cpu_billing_sampler.py
@@ -54,4 +54,7 @@ def run(path: Path, request_cores: float) -> None:
if __name__ == "__main__":
+ # Image builds run --check, so a broken interpreter or script fails the build instead of the billing.
+ if sys.argv[1:] == ["--check"]:
+ sys.exit(0)
run(Path(sys.argv[1]), float(sys.argv[2]))
diff --git a/products/wizard/backend/observability/metrics.py b/products/wizard/backend/observability/metrics.py
index 239e32e90b3d..454bb53ff95a 100644
--- a/products/wizard/backend/observability/metrics.py
+++ b/products/wizard/backend/observability/metrics.py
@@ -20,10 +20,13 @@ from products.wizard.backend.observability.contracts import (
WizardWorkerUsageObservation,
)
+# The run's local or cloud environment uses the `run_environment` label. The scrape pipeline
+# sets its own `environment` target label, so a metric label with that name is overwritten and
+# every query that filters on it returns no series.
WIZARD_RUNS_CREATED_TOTAL = Counter(
"posthog_wizard_runs_created_total",
"Wizard runs created",
- labelnames=["environment"],
+ labelnames=["run_environment"],
)
WIZARD_RUN_DISPATCH_ATTEMPTS_TOTAL = Counter(
@@ -47,26 +50,26 @@ WIZARD_RUN_STAGE_ENTERED_TOTAL = Counter(
WIZARD_RUNS_FINISHED_TOTAL = Counter(
"posthog_wizard_runs_finished_total",
"Wizard runs that reached a terminal status",
- labelnames=["environment", "status", "error_code"],
+ labelnames=["run_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"],
+ labelnames=["run_environment", "stage", "error_code"],
)
WIZARD_RUN_DURATION_SECONDS = Histogram(
"posthog_wizard_run_duration_seconds",
"Wizard run duration",
- labelnames=["environment", "status"],
+ labelnames=["run_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"],
+ labelnames=["run_environment"],
)
WIZARD_HANDOFF_BODY_FALLBACKS_TOTAL = Counter(
@@ -89,7 +92,7 @@ WIZARD_WORKER_CLEANUPS_TOTAL = Counter(
WIZARD_RUNS_PAST_DEADLINE_TOTAL = Counter(
"posthog_wizard_runs_past_deadline_total",
"Wizard cloud runs detected past their deadline",
- labelnames=["environment"],
+ labelnames=["run_environment"],
)
WIZARD_WORKER_LIFETIME_SECONDS = Histogram(
@@ -130,7 +133,7 @@ WIZARD_WORKER_ALLOCATED_DISK_GB_SECONDS = Histogram(
def report_run_created(run: WizardRunDTO) -> None:
- WIZARD_RUNS_CREATED_TOTAL.labels(environment=run.environment.value).inc()
+ WIZARD_RUNS_CREATED_TOTAL.labels(run_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()
@@ -180,14 +183,14 @@ def report_run_finished(run: WizardRunDTO, failure_stage: WizardRunStage | None)
error_code = _bounded_error_code(run.error_code)
WIZARD_RUNS_FINISHED_TOTAL.labels(
- environment=run.environment.value,
+ run_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,
+ run_environment=run.environment.value,
stage=failure_stage.value if failure_stage is not None else "none",
error_code=error_code,
).inc()
@@ -197,7 +200,9 @@ def report_run_finished(run: WizardRunDTO, failure_stage: WizardRunStage | None)
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)
+ WIZARD_RUN_DURATION_SECONDS.labels(run_environment=run.environment.value, status=run.status.value).observe(
+ duration
+ )
def report_worker_usage(usage: WizardWorkerUsageObservation) -> None:
@@ -217,7 +222,7 @@ def report_worker_usage(usage: WizardWorkerUsageObservation) -> None:
def report_git_diff_omitted(run: WizardRunDTO) -> None:
- WIZARD_GIT_DIFFS_OMITTED_TOTAL.labels(environment=run.environment.value).inc()
+ WIZARD_GIT_DIFFS_OMITTED_TOTAL.labels(run_environment=run.environment.value).inc()
def report_handoff_body_fallback() -> None:
@@ -233,4 +238,4 @@ def report_worker_cleanup(outcome: WizardWorkerCleanupOutcome) -> None:
def report_run_past_deadline(run: WizardRunDTO) -> None:
- WIZARD_RUNS_PAST_DEADLINE_TOTAL.labels(environment=run.environment.value).inc()
+ WIZARD_RUNS_PAST_DEADLINE_TOTAL.labels(run_environment=run.environment.value).inc()
diff --git a/products/wizard/backend/tests/runs/test_observability.py b/products/wizard/backend/tests/runs/test_observability.py
index e66d4a3736a1..31319b810a5f 100644
--- a/products/wizard/backend/tests/runs/test_observability.py
+++ b/products/wizard/backend/tests/runs/test_observability.py
@@ -11,6 +11,7 @@ from django.test import override_settings
from parameterized import parameterized
from prometheus_client import REGISTRY
+from prometheus_client.metrics import MetricWrapperBase
from structlog.testing import capture_logs
from products.wizard.backend.facade.contracts import (
@@ -217,9 +218,16 @@ def test_observability_does_not_hide_programming_errors() -> None:
observability.run_created(run)
+def test_metrics_do_not_use_the_scrape_environment_label() -> None:
+ wizard_metrics = [value for value in vars(metrics).values() if isinstance(value, MetricWrapperBase)]
+
+ assert wizard_metrics
+ assert [metric for metric in wizard_metrics if "environment" in metric._labelnames] == []
+
+
def test_cloud_creation_records_created_and_initial_stage_metrics() -> None:
run = _cloud_run()
- created_labels = {"environment": "cloud"}
+ created_labels = {"run_environment": "cloud"}
stage_labels = {"stage": "dispatching"}
created_before = _sample("posthog_wizard_runs_created_total", created_labels)
stage_before = _sample("posthog_wizard_run_stage_entered_total", stage_labels)
@@ -275,16 +283,16 @@ def test_failure_metrics_record_stage_and_error_code() -> None:
finished_at=datetime(2026, 8, 25, 12, 2, tzinfo=UTC),
)
finished_labels = {
- "environment": "cloud",
+ "run_environment": "cloud",
"status": "failed",
"error_code": "execution_failed",
}
failure_labels = {
- "environment": "cloud",
+ "run_environment": "cloud",
"stage": "executing_wizard",
"error_code": "execution_failed",
}
- duration_labels = {"environment": "cloud", "status": "failed"}
+ duration_labels = {"run_environment": "cloud", "status": "failed"}
finished_before = _sample("posthog_wizard_runs_finished_total", finished_labels)
failure_before = _sample("posthog_wizard_run_failures_total", failure_labels)
duration_before = _sample("posthog_wizard_run_duration_seconds_sum", duration_labels)
@@ -305,8 +313,8 @@ def test_failure_metrics_bound_unknown_error_code() -> None:
started_at=datetime(2026, 8, 25, 12, 1, tzinfo=UTC),
finished_at=datetime(2026, 8, 25, 12, 2, tzinfo=UTC),
)
- bounded_labels = {"environment": "cloud", "status": "failed", "error_code": "other"}
- raw_labels = {"environment": "cloud", "status": "failed", "error_code": "PHW_SOME_PINNED_VERSION_CODE"}
+ bounded_labels = {"run_environment": "cloud", "status": "failed", "error_code": "other"}
+ raw_labels = {"run_environment": "cloud", "status": "failed", "error_code": "PHW_SOME_PINNED_VERSION_CODE"}
bounded_before = _sample("posthog_wizard_runs_finished_total", bounded_labels)
metrics.report_run_finished(run, WizardRunStage.EXECUTING_WIZARD)
@@ -433,7 +441,7 @@ def test_reliability_metrics_record_artifacts_cleanup_and_deadlines() -> None:
)
artifact_labels = {"type": "git_diff"}
cleanup_labels = {"outcome": "succeeded"}
- deadline_labels = {"environment": "cloud"}
+ deadline_labels = {"run_environment": "cloud"}
artifact_before = _sample("posthog_wizard_artifacts_created_total", artifact_labels)
cleanup_before = _sample("posthog_wizard_worker_cleanups_total", cleanup_labels)
deadline_before = _sample("posthog_wizard_runs_past_deadline_total", deadline_labels)