:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
feat(tasks): report desktop compute credits (#76771)
Adam Bowker71b1dc6dd629
diff --git a/posthog/tasks/test/test_usage_report.py b/posthog/tasks/test/test_usage_report.pyindex 976a56a7a76f..a060c1e6ec98 100644--- a/posthog/tasks/test/test_usage_report.py+++ b/posthog/tasks/test/test_usage_report.py@@ -4805,6 +4805,64 @@ class TestTaskSandboxUsageReport(APIBaseTest):self.assertTrue(has_non_zero_usage(UsageReportCounters(**{**zero, "task_sandbox_seconds_in_period": 5})))+class TestPostHogCodeComputeUsageReport(SimpleTestCase):+ def test_component_contract_uses_integer_historical_metric_types(self) -> None:+ from posthog.tasks.usage_report import UsageReportCounters++ component_metrics = {+ "posthog_code_token_credits_used_in_period",+ "sandbox_compute_credits_used_in_period",+ "sandbox_compute_cpu_millicore_seconds_in_period",+ "sandbox_compute_memory_mib_seconds_in_period",+ }++ assert all(UsageReportCounters.__annotations__[metric] is int for metric in component_metrics)+ assert "sandbox_compute_cpu_core_seconds_in_period" not in UsageReportCounters.__annotations__+ assert "sandbox_compute_memory_gib_seconds_in_period" not in UsageReportCounters.__annotations__++ def test_combined_credits_reconcile_with_components(self) -> None:+ from posthog.tasks.usage_report import combine_posthog_code_credits++ assert combine_posthog_code_credits(123, 45) == 168++ @patch("posthog.tasks.usage_report.capture_exception")+ @patch("posthog.tasks.usage_report.get_billable_sandbox_compute_usage_by_team")+ def test_invalid_compute_configuration_is_observed_without_breaking_report(+ self, mock_compute: MagicMock, mock_capture: MagicMock+ ) -> None:+ from posthog.tasks.usage_report import get_teams_with_billable_sandbox_compute_usage_in_period++ from products.tasks.backend.facade.billing import ComputeRateCardConfigurationError, SandboxComputeUsageByTeam++ error = ComputeRateCardConfigurationError("invalid")+ mock_compute.side_effect = error++ result = get_teams_with_billable_sandbox_compute_usage_in_period(+ datetime(2026, 1, 2, tzinfo=UTC), datetime(2026, 1, 3, tzinfo=UTC)+ )++ assert result == SandboxComputeUsageByTeam([], [], [])+ mock_capture.assert_called_once_with(error)++ @patch("retry.api.time.sleep")+ @patch("posthog.tasks.usage_report.capture_exception")+ @patch("posthog.tasks.usage_report.get_billable_sandbox_compute_usage_by_team")+ def test_transient_compute_failure_propagates_after_retries(+ self, mock_compute: MagicMock, mock_capture: MagicMock, _mock_sleep: MagicMock+ ) -> None:+ from posthog.tasks.usage_report import QUERY_RETRIES, get_teams_with_billable_sandbox_compute_usage_in_period++ mock_compute.side_effect = RuntimeError("transient database failure")++ with self.assertRaises(RuntimeError):+ get_teams_with_billable_sandbox_compute_usage_in_period(+ datetime(2026, 1, 2, tzinfo=UTC), datetime(2026, 1, 3, tzinfo=UTC)+ )++ assert mock_compute.call_count == QUERY_RETRIES+ mock_capture.assert_not_called()++class TestSendUsage(LicensedTestMixin, ClickhouseDestroyTablesMixin, APIBaseTest):def setUp(self) -> None:super().setUp()diff --git a/posthog/tasks/usage_report.py b/posthog/tasks/usage_report.pyindex 9036f25e840c..6ef6de695236 100644--- a/posthog/tasks/usage_report.py+++ b/posthog/tasks/usage_report.py@@ -65,7 +65,13 @@ from products.surveys.backend.util import (get_survey_property_string_expr,get_unique_survey_event_uuids_sql_subquery,)-from products.tasks.backend.facade.billing import SandboxUsageByTeam, get_task_sandbox_usage_by_team+from products.tasks.backend.facade.billing import (+ ComputeRateCardConfigurationError,+ SandboxComputeUsageByTeam,+ SandboxUsageByTeam,+ get_billable_sandbox_compute_usage_by_team,+ get_task_sandbox_usage_by_team,+)from products.warehouse_sources.backend.facade.models import DataWarehouseTable, ExternalDataJob, ExternalDataSchemalogger = structlog.get_logger(__name__)@@ -244,8 +250,12 @@ class UsageReportCounters:# Signals Billing Credits (flat credits per report whose implementation shipped a PR)signals_credits_used_in_period: int- # PostHog Desktop Billing Credits (PostHog Desktop product usage — same cost math as ai_credits, scoped to ai_product='posthog_code')+ # PostHog Desktop Billing Creditsposthog_code_credits_used_in_period: int+ posthog_code_token_credits_used_in_period: int+ sandbox_compute_credits_used_in_period: int+ sandbox_compute_cpu_millicore_seconds_in_period: int+ sandbox_compute_memory_mib_seconds_in_period: int# Cloud task sandbox compute, all task origins (raw user-attributed usage from the# SandboxSession ledger — unpriced until a billing model is decided; pre-warm time excluded)@@ -1746,6 +1756,27 @@ def get_teams_with_task_sandbox_usage_in_period(begin: datetime, end: datetime)return get_task_sandbox_usage_by_team(begin, end)+@timed_log()+@retry(tries=QUERY_RETRIES, delay=QUERY_RETRY_DELAY, backoff=QUERY_RETRY_BACKOFF)+def get_teams_with_billable_sandbox_compute_usage_in_period(+ begin: datetime, end: datetime+) -> SandboxComputeUsageByTeam:+ """A rate-card misconfiguration degrades to empty usage rather than aborting quota/report+ runs for every product; anything else (e.g. a transient DB failure) propagates so the+ retry/abort-and-preserve semantics of the sibling billing queries apply.+ """+ try:+ return get_billable_sandbox_compute_usage_by_team(begin, end)+ except ComputeRateCardConfigurationError as err:+ logger.exception("sandbox_compute.usage_report_failed")+ capture_exception(err)+ return SandboxComputeUsageByTeam([], [], [])+++def combine_posthog_code_credits(token_credits: int, compute_credits: int) -> int:+ return token_credits + compute_credits++dwh_pricing_free_period_start = datetime(2025, 10, 29, 0, 0, 0, tzinfo=UTC)dwh_pricing_free_period_end = datetime(2025, 11, 6, 0, 0, 0, tzinfo=UTC)@@ -2546,6 +2577,8 @@ def _get_all_usage_data(period_start: datetime, period_end: datetime) -> dict[stperiod_start, period_end)task_sandbox_usage = get_teams_with_task_sandbox_usage_in_period(period_start, period_end)+ sandbox_compute_usage = get_teams_with_billable_sandbox_compute_usage_in_period(period_start, period_end)+ token_credits = get_teams_with_posthog_code_credits_used_in_period(period_start, period_end)return {"teams_with_event_count_in_period": get_teams_with_billable_event_count_in_period(@@ -2782,9 +2815,10 @@ def _get_all_usage_data(period_start: datetime, period_end: datetime) -> dict[st"teams_with_signals_credits_used_in_period": get_teams_with_signals_credits_used_in_period(period_start, period_end),- "teams_with_posthog_code_credits_used_in_period": get_teams_with_posthog_code_credits_used_in_period(- period_start, period_end- ),+ "teams_with_posthog_code_credits_used_in_period": token_credits,+ "teams_with_sandbox_compute_credits_used_in_period": sandbox_compute_usage.credits,+ "teams_with_sandbox_compute_cpu_millicore_seconds_in_period": sandbox_compute_usage.cpu_millicore_seconds,+ "teams_with_sandbox_compute_memory_mib_seconds_in_period": sandbox_compute_usage.memory_mib_seconds,"teams_with_task_sandbox_seconds_in_period": task_sandbox_usage.seconds,"teams_with_task_sandbox_cpu_core_seconds_in_period": task_sandbox_usage.cpu_core_seconds,"teams_with_task_sandbox_memory_gib_seconds_in_period": task_sandbox_usage.memory_gib_seconds,@@ -2977,7 +3011,22 @@ def _get_team_report(all_data: dict[str, Any], team: Team) -> UsageReportCounterai_event_count_in_period=all_data["teams_with_ai_event_count_in_period"].get(team.id, 0),ai_credits_used_in_period=all_data["teams_with_ai_credits_used_in_period"].get(team.id, 0),signals_credits_used_in_period=all_data["teams_with_signals_credits_used_in_period"].get(team.id, 0),- posthog_code_credits_used_in_period=all_data["teams_with_posthog_code_credits_used_in_period"].get(team.id, 0),+ posthog_code_credits_used_in_period=combine_posthog_code_credits(+ all_data["teams_with_posthog_code_credits_used_in_period"].get(team.id, 0),+ all_data["teams_with_sandbox_compute_credits_used_in_period"].get(team.id, 0),+ ),+ posthog_code_token_credits_used_in_period=all_data["teams_with_posthog_code_credits_used_in_period"].get(+ team.id, 0+ ),+ sandbox_compute_credits_used_in_period=all_data["teams_with_sandbox_compute_credits_used_in_period"].get(+ team.id, 0+ ),+ sandbox_compute_cpu_millicore_seconds_in_period=all_data[+ "teams_with_sandbox_compute_cpu_millicore_seconds_in_period"+ ].get(team.id, 0),+ sandbox_compute_memory_mib_seconds_in_period=all_data[+ "teams_with_sandbox_compute_memory_mib_seconds_in_period"+ ].get(team.id, 0),task_sandbox_seconds_in_period=all_data["teams_with_task_sandbox_seconds_in_period"].get(team.id, 0),task_sandbox_cpu_core_seconds_in_period=all_data["teams_with_task_sandbox_cpu_core_seconds_in_period"].get(team.id, 0diff --git a/posthog/temporal/tests/usage_report/test_aggregator.py b/posthog/temporal/tests/usage_report/test_aggregator.pyindex 18ee97ab958a..78a68ae85934 100644--- a/posthog/temporal/tests/usage_report/test_aggregator.py+++ b/posthog/temporal/tests/usage_report/test_aggregator.py@@ -16,6 +16,7 @@ from unittest.mock import patchfrom posthog.tasks.usage_report import InstanceMetadata, OrgReport, UsageReportCountersfrom posthog.temporal.usage_report.aggregator import (+ add_pre_sandbox_compute_patch_defaults,batched,build_manifest,filter_org_reports,@@ -154,6 +155,23 @@ def test_load_all_data_multi_output_missing_source_key_yields_empty() -> None:assert all_data["teams_with_ruby_events_count_in_period"] == {}+def test_load_all_data_defaults_compute_for_pre_patch_workflow_history() -> None:+ all_data: dict[str, dict[int, int]] = {}+ add_pre_sandbox_compute_patch_defaults(all_data, [])++ assert all_data["teams_with_sandbox_compute_credits_used_in_period"] == {}+ assert all_data["teams_with_sandbox_compute_cpu_millicore_seconds_in_period"] == {}+ assert all_data["teams_with_sandbox_compute_memory_mib_seconds_in_period"] == {}+++def test_load_all_data_does_not_default_compute_for_patched_workflow_history() -> None:+ all_data: dict[str, dict[int, int]] = {}+ results = [RunQueryToS3Result(query_name="sandbox_compute_usage", s3_key="unused", duration_ms=1)]+ add_pre_sandbox_compute_patch_defaults(all_data, results)++ assert all_data == {}++# ---- iter_chunk_lines ----------------------------------------------------diff --git a/posthog/temporal/tests/usage_report/test_workflow.py b/posthog/temporal/tests/usage_report/test_workflow.pyindex 45f898885076..b055c515b44e 100644--- a/posthog/temporal/tests/usage_report/test_workflow.py+++ b/posthog/temporal/tests/usage_report/test_workflow.py@@ -28,7 +28,17 @@ from posthog.temporal.usage_report.types import (RunQueryToS3Result,RunUsageReportsInputs,)-from posthog.temporal.usage_report.workflow import RunUsageReportsWorkflow, build_context+from posthog.temporal.usage_report.workflow import (+ SANDBOX_COMPUTE_QUERY_NAME,+ RunUsageReportsWorkflow,+ _queries_for_sandbox_compute_patch,+ build_context,+)+++def test_sandbox_compute_query_is_versioned_for_existing_histories() -> None:+ assert SANDBOX_COMPUTE_QUERY_NAME not in [spec.name for spec in _queries_for_sandbox_compute_patch(False)]+ assert SANDBOX_COMPUTE_QUERY_NAME in [spec.name for spec in _queries_for_sandbox_compute_patch(True)]@parameterized.expand(diff --git a/posthog/temporal/usage_report/activities.py b/posthog/temporal/usage_report/activities.pyindex 2b25b9dd4619..22aa62b5b536 100644--- a/posthog/temporal/usage_report/activities.py+++ b/posthog/temporal/usage_report/activities.py@@ -22,6 +22,7 @@ from posthog.tasks.usage_report import get_instance_metadatafrom posthog.temporal.common.heartbeat import Heartbeaterfrom posthog.temporal.common.metrics import ExecutionTimeRecorderfrom posthog.temporal.usage_report.aggregator import (+ add_pre_sandbox_compute_patch_defaults,batched,build_manifest,build_org_reports,@@ -129,6 +130,7 @@ async def aggregate_and_chunk_org_reports(inputs: AggregateInputs) -> AggregateRdescription="Aggregate per-query S3 results into org-report chunks.",):all_data = await sync_to_async(load_all_data)(inputs.query_results)+ add_pre_sandbox_compute_patch_defaults(all_data, inputs.query_results)@database_sync_to_asyncdef aggregate_per_org() -> dict[str, Any]:diff --git a/posthog/temporal/usage_report/aggregator.py b/posthog/temporal/usage_report/aggregator.pyindex a9bad8a2de1c..c5b80ebed7e2 100644--- a/posthog/temporal/usage_report/aggregator.py+++ b/posthog/temporal/usage_report/aggregator.py@@ -34,6 +34,13 @@ from posthog.temporal.usage_report.queries import QUERY_INDEXfrom posthog.temporal.usage_report.storage import bucket, read_jsonfrom posthog.temporal.usage_report.types import Manifest, RunQueryToS3Result, WorkflowContext+_SANDBOX_COMPUTE_QUERY_NAME = "sandbox_compute_usage"+_SANDBOX_COMPUTE_DESTINATION_KEYS = (+ "teams_with_sandbox_compute_credits_used_in_period",+ "teams_with_sandbox_compute_cpu_millicore_seconds_in_period",+ "teams_with_sandbox_compute_memory_mib_seconds_in_period",+)+def load_all_data(query_results: list[RunQueryToS3Result]) -> dict[str, dict[int, int]]:"""Reconstruct the legacy `all_data` map from per-query S3 files.@@ -56,6 +63,14 @@ def load_all_data(query_results: list[RunQueryToS3Result]) -> dict[str, dict[intreturn all_data+def add_pre_sandbox_compute_patch_defaults(+ all_data: dict[str, dict[int, int]], query_results: list[RunQueryToS3Result]+) -> None:+ if not any(result.query_name == _SANDBOX_COMPUTE_QUERY_NAME for result in query_results):+ for key in _SANDBOX_COMPUTE_DESTINATION_KEYS:+ all_data[key] = {}++def iter_chunk_lines(org_reports: Iterable[OrgReport],instance_metadata: InstanceMetadata,diff --git a/posthog/temporal/usage_report/queries.py b/posthog/temporal/usage_report/queries.pyindex 318fcfeaf744..5b9dabfaea78 100644--- a/posthog/temporal/usage_report/queries.py+++ b/posthog/temporal/usage_report/queries.py@@ -59,6 +59,7 @@ from posthog.tasks.usage_report import (get_teams_with_apm_tracing_usage_in_period,get_teams_with_billable_enhanced_persons_event_count_in_period,get_teams_with_billable_event_count_in_period,+ get_teams_with_billable_sandbox_compute_usage_in_period,get_teams_with_cdp_billable_invocations_in_period,get_teams_with_dwh_mat_views_storage_in_s3,get_teams_with_dwh_tables_storage_in_s3,@@ -216,6 +217,15 @@ def _task_sandbox_usage(begin: datetime, end: datetime) -> dict[str, list[tuple[}+def _sandbox_compute_usage(begin: datetime, end: datetime) -> dict[str, list[tuple[int, int]]]:+ usage = get_teams_with_billable_sandbox_compute_usage_in_period(begin, end)+ return {+ "credits": usage.credits,+ "cpu_millicore_seconds": usage.cpu_millicore_seconds,+ "memory_mib_seconds": usage.memory_mib_seconds,+ }++# ---- Registry ---------------------------------------------------------------@@ -488,6 +498,16 @@ QUERIES: list[QuerySpec] = ["memory_gib_seconds": "teams_with_task_sandbox_memory_gib_seconds_in_period",},),+ QuerySpec(+ name="sandbox_compute_usage",+ fn=_sandbox_compute_usage,+ output="multi",+ multi_keys_mapping={+ "credits": "teams_with_sandbox_compute_credits_used_in_period",+ "cpu_millicore_seconds": "teams_with_sandbox_compute_cpu_millicore_seconds_in_period",+ "memory_mib_seconds": "teams_with_sandbox_compute_memory_mib_seconds_in_period",+ },+ ),# ---- ClickHouse: workflows / messaging ----------------------------------QuerySpec(name="teams_with_workflow_emails_sent_in_period",diff --git a/posthog/temporal/usage_report/workflow.py b/posthog/temporal/usage_report/workflow.pyindex a30747bf90ca..7be556e49e8c 100644--- a/posthog/temporal/usage_report/workflow.py+++ b/posthog/temporal/usage_report/workflow.py@@ -43,6 +43,14 @@ from posthog.temporal.usage_report.types import (# Cap concurrent gather queries so we don't overwhelm ClickHouse / Postgres# with ~40 simultaneous heavy queries.QUERY_CONCURRENCY = 4+SANDBOX_COMPUTE_QUERY_PATCH_ID = "usage-report-sandbox-compute-query-2026-08"+SANDBOX_COMPUTE_QUERY_NAME = "sandbox_compute_usage"+++def _queries_for_sandbox_compute_patch(patch_applied: bool) -> list[QuerySpec]:+ if patch_applied:+ return QUERIES+ return [spec for spec in QUERIES if spec.name != SANDBOX_COMPUTE_QUERY_NAME]def build_context(inputs: RunUsageReportsInputs, run_id: str, now: datetime) -> WorkflowContext:@@ -90,6 +98,7 @@ class RunUsageReportsWorkflow(PostHogWorkflow):status = "FAILED"try:ctx = build_context(inputs, run_id=workflow.info().run_id, now=started_at)+ queries = _queries_for_sandbox_compute_patch(workflow.patched(SANDBOX_COMPUTE_QUERY_PATCH_ID))workflow.logger.info("Starting usage reports workflow",extra={@@ -98,7 +107,7 @@ class RunUsageReportsWorkflow(PostHogWorkflow):"report_completeness": ctx.report_completeness,"period_start": ctx.period_start.isoformat(),"period_end": ctx.period_end.isoformat(),- "spec_count": len(QUERIES),+ "spec_count": len(queries),},)@@ -113,7 +122,7 @@ class RunUsageReportsWorkflow(PostHogWorkflow):return await self._run_query(ctx, spec)query_results: list[RunQueryToS3Result] = list(- await asyncio.gather(*(_run_with_sem(spec) for spec in QUERIES))+ await asyncio.gather(*(_run_with_sem(spec) for spec in queries)))agg = await workflow.execute_activity(diff --git a/products/tasks/backend/facade/billing.py b/products/tasks/backend/facade/billing.pyindex 2388b10c4473..0f028cdb0da8 100644--- a/products/tasks/backend/facade/billing.py+++ b/products/tasks/backend/facade/billing.py@@ -4,6 +4,18 @@ The usage reporter (posthog/tasks/usage_report.py) lives in the ``posthog`` moduwhich may only import ``products.tasks`` through the facade (see tach.toml)."""-from products.tasks.backend.logic.services.sandbox_usage import SandboxUsageByTeam, get_task_sandbox_usage_by_team+from products.tasks.backend.logic.services.sandbox_pricing import ComputeRateCardConfigurationError+from products.tasks.backend.logic.services.sandbox_usage import (+ SandboxComputeUsageByTeam,+ SandboxUsageByTeam,+ get_billable_sandbox_compute_usage_by_team,+ get_task_sandbox_usage_by_team,+)-__all__ = ["SandboxUsageByTeam", "get_task_sandbox_usage_by_team"]+__all__ = [+ "ComputeRateCardConfigurationError",+ "SandboxComputeUsageByTeam",+ "SandboxUsageByTeam",+ "get_billable_sandbox_compute_usage_by_team",+ "get_task_sandbox_usage_by_team",+]diff --git a/products/tasks/backend/logic/services/sandbox_pricing.py b/products/tasks/backend/logic/services/sandbox_pricing.pyindex 2f112be4ff12..7bf60f48005d 100644--- a/products/tasks/backend/logic/services/sandbox_pricing.py+++ b/products/tasks/backend/logic/services/sandbox_pricing.py@@ -52,6 +52,13 @@ class SandboxComputeCost:COMPUTE_RATE_CARDS: tuple[ComputeRateCard, ...] = ()+def validate_reporting_window(reporting_start: datetime, reporting_end: datetime) -> None:+ if timezone.is_naive(reporting_start) or timezone.is_naive(reporting_end):+ raise ValueError("reporting timestamps must be timezone-aware")+ if reporting_end <= reporting_start:+ raise ValueError("reporting end must follow reporting start")++def validate_compute_rate_cards(rate_cards: Sequence[ComputeRateCard]) -> tuple[ComputeRateCard, ...]:cards = tuple(rate_cards)if not cards:@@ -92,10 +99,7 @@ def calculate_sandbox_compute_cost(rate_cards: Sequence[ComputeRateCard] = COMPUTE_RATE_CARDS,) -> SandboxComputeCost:cards = validate_compute_rate_cards(rate_cards)- if timezone.is_naive(reporting_start) or timezone.is_naive(reporting_end):- raise ValueError("reporting timestamps must be timezone-aware")- if reporting_end <= reporting_start:- raise ValueError("reporting end must follow reporting start")+ validate_reporting_window(reporting_start, reporting_end)now = calculated_at or timezone.now()if timezone.is_naive(now):diff --git a/products/tasks/backend/logic/services/sandbox_usage.py b/products/tasks/backend/logic/services/sandbox_usage.pyindex cc11ce736a08..11a942ff3c8d 100644--- a/products/tasks/backend/logic/services/sandbox_usage.py+++ b/products/tasks/backend/logic/services/sandbox_usage.py@@ -11,9 +11,10 @@ The write helpers swallow and log every failure: the ledger must never breaksandbox provisioning, cleanup, or user-message delivery."""-from collections.abc import Callable+from collections.abc import Callable, Sequencefrom dataclasses import dataclassfrom datetime import datetime, timedelta+from decimal import ROUND_HALF_EVEN, Decimalfrom functools import wrapsfrom typing import ParamSpec, TypeVarfrom uuid import UUID@@ -25,7 +26,14 @@ from django.utils import timezoneimport structlogfrom products.tasks.backend.logic.services.sandbox import SandboxConfig-from products.tasks.backend.models import SandboxSession, TaskRun+from products.tasks.backend.logic.services.sandbox_pricing import (+ COMPUTE_RATE_CARDS,+ ComputeRateCard,+ calculate_sandbox_compute_cost,+ validate_compute_rate_cards,+ validate_reporting_window,+)+from products.tasks.backend.models import SandboxSession, Task, TaskClientProvenance, TaskRunlogger = structlog.get_logger(__name__)@@ -144,6 +152,64 @@ class SandboxUsageByTeam:memory_gib_seconds: list[tuple[int, int]]+@dataclass(frozen=True)+class SandboxComputeUsageByTeam:+ credits: list[tuple[int, int]]+ cpu_millicore_seconds: list[tuple[int, int]]+ memory_mib_seconds: list[tuple[int, int]]+++def get_billable_sandbox_compute_usage_by_team(+ begin: datetime,+ end: datetime,+ *,+ rate_cards: Sequence[ComputeRateCard] | None = None,+) -> SandboxComputeUsageByTeam:+ validate_reporting_window(begin, end)+ rate_cards = COMPUTE_RATE_CARDS if rate_cards is None else rate_cards+ if not rate_cards:+ return SandboxComputeUsageByTeam([], [], [])++ cards = validate_compute_rate_cards(rate_cards)+ sessions = (+ SandboxSession.objects.unscoped()+ .filter(+ client_provenance=TaskClientProvenance.POSTHOG_DESKTOP,+ user_attributed_at__isnull=False,+ user_attributed_at__lt=end,+ )+ .filter(+ Q(origin_product=Task.OriginProduct.USER_CREATED)+ | Q(+ origin_product=Task.OriginProduct.LOOP,+ task_run__task__loop__isnull=False,+ task_run__task__loop__internal=False,+ )+ )+ .filter(Q(ended_at__isnull=True, ttl_expires_at__gt=begin) | Q(ended_at__gt=begin))+ )++ usage: dict[int, list[Decimal]] = {}+ calculated_at = timezone.now()+ for session in sessions.iterator():+ cost = calculate_sandbox_compute_cost(session, begin, end, calculated_at=calculated_at, rate_cards=cards)+ totals = usage.setdefault(session.team_id, [Decimal(0) for _ in range(3)])+ totals[0] += cost.cpu_core_seconds+ totals[1] += cost.memory_gib_seconds+ totals[2] += cost.cpu_cost_usd + cost.memory_cost_usd++ credits: list[tuple[int, int]] = []+ cpu_millicore_seconds: list[tuple[int, int]] = []+ memory_mib_seconds: list[tuple[int, int]] = []+ for team_id, totals in usage.items():+ cpu_quantity, memory_quantity, total_usd = totals+ credits.append((team_id, int((total_usd * 100).to_integral_value(rounding=ROUND_HALF_EVEN))))+ cpu_millicore_seconds.append((team_id, int((cpu_quantity * 1000).to_integral_value(rounding=ROUND_HALF_EVEN))))+ memory_mib_seconds.append((team_id, int((memory_quantity * 1024).to_integral_value(rounding=ROUND_HALF_EVEN))))++ return SandboxComputeUsageByTeam(credits, cpu_millicore_seconds, memory_mib_seconds)++def get_task_sandbox_usage_by_team(begin: datetime, end: datetime) -> SandboxUsageByTeam:"""Aggregate user-attributed sandbox time per team over ``[begin, end)``.diff --git a/products/tasks/backend/logic/services/tests/test_sandbox_pricing.py b/products/tasks/backend/logic/services/tests/test_sandbox_pricing.pyindex 04324cdc1343..e53b9517d7ff 100644--- a/products/tasks/backend/logic/services/tests/test_sandbox_pricing.py+++ b/products/tasks/backend/logic/services/tests/test_sandbox_pricing.py@@ -1,4 +1,4 @@-from datetime import UTC, datetime, timedelta+from datetime import UTC, datetime, timedelta, timezonefrom decimal import Decimalfrom types import SimpleNamespace@@ -9,6 +9,7 @@ from products.tasks.backend.logic.services.sandbox_pricing import (ComputeRateCardConfigurationError,calculate_sandbox_compute_cost,validate_compute_rate_cards,+ validate_reporting_window,)EFFECTIVE_AT = datetime(2026, 8, 1, tzinfo=UTC)@@ -283,3 +284,21 @@ def test_usage_before_compute_billing_effective_date_is_not_priced():def test_invalid_missing_overlapping_or_ambiguous_rate_cards_fail_safely(cards, message):with pytest.raises(ComputeRateCardConfigurationError, match=message):validate_compute_rate_cards(cards)+++ "start,end,message",+ [+ (datetime(2026, 1, 1), EFFECTIVE_AT, "timezone-aware"),+ (EFFECTIVE_AT, datetime(2026, 1, 2), "timezone-aware"),+ (EFFECTIVE_AT, EFFECTIVE_AT, "must follow"),+ (EFFECTIVE_AT + timedelta(seconds=1), EFFECTIVE_AT, "must follow"),+ ],+)+def test_invalid_reporting_windows_are_rejected(start, end, message):+ with pytest.raises(ValueError, match=message):+ validate_reporting_window(start, end)+++def test_reporting_window_accepts_different_aware_offsets():+ validate_reporting_window(EFFECTIVE_AT, EFFECTIVE_AT.astimezone(timezone(timedelta(hours=1))) + timedelta(1))diff --git a/products/tasks/backend/logic/services/tests/test_sandbox_usage.py b/products/tasks/backend/logic/services/tests/test_sandbox_usage.pyindex b987ff9c7b0b..340e471fd2b4 100644--- a/products/tasks/backend/logic/services/tests/test_sandbox_usage.py+++ b/products/tasks/backend/logic/services/tests/test_sandbox_usage.py@@ -1,20 +1,24 @@from datetime import UTC, datetime, timedelta+from decimal import Decimalfrom freezegun import freeze_timefrom posthog.test.base import APIBaseTestfrom unittest.mock import patchfrom posthog.models.organization import Organization+from posthog.models.scoping import team_scopefrom posthog.models.team.team import Teamfrom products.tasks.backend.logic.services.sandbox import SandboxConfig+from products.tasks.backend.logic.services.sandbox_pricing import ComputeRateCard, ComputeRateCardConfigurationErrorfrom products.tasks.backend.logic.services.sandbox_usage import (close_sandbox_session,+ get_billable_sandbox_compute_usage_by_team,get_task_sandbox_usage_by_team,open_sandbox_session,record_task_run_user_activity,)-from products.tasks.backend.models import SandboxSession, Task, TaskClientProvenance, TaskRun+from products.tasks.backend.models import Loop, SandboxSession, Task, TaskClientProvenance, TaskRundef _config(**overrides) -> SandboxConfig:@@ -227,7 +231,7 @@ class TestSandboxUsageAggregation(SandboxUsageBase):END = datetime(2026, 1, 3, tzinfo=UTC)def _session(self, **overrides) -> SandboxSession:- run = self._run()+ run = overrides.pop("task_run", None) or self._run()defaults: dict = {"team": self.team,"task_run": run,@@ -244,6 +248,173 @@ class TestSandboxUsageAggregation(SandboxUsageBase):defaults.setdefault("ttl_expires_at", defaults["created_at"] + timedelta(seconds=defaults["ttl_seconds"]))return SandboxSession.objects.unscoped().create(**defaults)+ def _loop_session(+ self, *, internal: bool, client_provenance: TaskClientProvenance | None = TaskClientProvenance.POSTHOG_DESKTOP+ ) -> SandboxSession:+ with team_scope(self.team.id):+ loop = Loop.objects.create(+ team=self.team,+ name="loop",+ instructions="run",+ runtime_adapter="claude",+ internal=internal,+ client_provenance=client_provenance,+ )+ task = Task.objects.create(+ team=self.team,+ title="loop run",+ description="",+ origin_product=Task.OriginProduct.LOOP,+ internal=True,+ loop=loop,+ client_provenance=client_provenance,+ )+ run = TaskRun.objects.create(task=task, team=self.team)+ return self._session(+ task_run=run,+ origin_product=Task.OriginProduct.LOOP,+ client_provenance=client_provenance,+ )++ def _rate(+ self,+ *,+ version: str = "v1",+ effective_at: datetime | None = None,+ expires_at: datetime | None = None,+ cpu_core_second_usd: Decimal = Decimal("0.001"),+ memory_gib_second_usd: Decimal = Decimal("0.0001"),+ ) -> ComputeRateCard:+ return ComputeRateCard(+ version=version,+ effective_at=effective_at or self.BEGIN,+ expires_at=expires_at,+ cpu_core_second_usd=cpu_core_second_usd,+ memory_gib_second_usd=memory_gib_second_usd,+ )++ def test_billable_compute_requires_trusted_desktop_user_created_snapshot(self):+ self._session(client_provenance=TaskClientProvenance.POSTHOG_DESKTOP)+ for origin in (Task.OriginProduct.SLACK, Task.OriginProduct.SIGNAL_REPORT, Task.OriginProduct.LOOP, None):+ self._session(client_provenance=TaskClientProvenance.POSTHOG_DESKTOP, origin_product=origin)+ self._session(client_provenance=None)++ usage = get_billable_sandbox_compute_usage_by_team(self.BEGIN, self.END, rate_cards=(self._rate(),))++ assert usage.cpu_millicore_seconds == [(self.team.id, 14_400_000)]+ assert usage.memory_mib_seconds == [(self.team.id, 58_982_400)]+ assert usage.credits == [(self.team.id, 2016)]++ def test_billable_compute_includes_user_loops_and_excludes_internal_loops(self):+ self._loop_session(internal=False)+ self._loop_session(internal=True)+ self._loop_session(internal=False, client_provenance=None)++ usage = get_billable_sandbox_compute_usage_by_team(self.BEGIN, self.END, rate_cards=(self._rate(),))++ assert usage.cpu_millicore_seconds == [(self.team.id, 14_400_000)]+ assert usage.credits == [(self.team.id, 2016)]++ def test_billable_compute_uses_session_snapshot_after_task_changes(self):+ session = self._session(client_provenance=TaskClientProvenance.POSTHOG_DESKTOP)+ Task.objects.filter(id=session.task_run.task_id).update(+ origin_product=Task.OriginProduct.SLACK, client_provenance=None+ )++ usage = get_billable_sandbox_compute_usage_by_team(self.BEGIN, self.END, rate_cards=(self._rate(),))++ assert usage.credits == [(self.team.id, 2016)]++ def test_exact_session_costs_aggregate_before_bankers_credit_rounding(self):+ for sandbox_id in ("sb-fraction-a", "sb-fraction-b"):+ self._session(+ sandbox_id=sandbox_id,+ client_provenance=TaskClientProvenance.POSTHOG_DESKTOP,+ cpu_cores=1,+ memory_gb=1,+ ended_at=datetime(2026, 1, 2, 1, 0, 1, tzinfo=UTC),+ )+ rate = self._rate(cpu_core_second_usd=Decimal("0.0025"), memory_gib_second_usd=Decimal("0.0025"))++ usage = get_billable_sandbox_compute_usage_by_team(self.BEGIN, self.END, rate_cards=(rate,))++ assert usage.credits == [(self.team.id, 1)]++ def test_integer_resource_units_round_only_after_exact_aggregation(self):+ for sandbox_id in ("sb-units-a", "sb-units-b"):+ self._session(+ sandbox_id=sandbox_id,+ client_provenance=TaskClientProvenance.POSTHOG_DESKTOP,+ cpu_request_cores=0.125,+ memory_request_mb=384,+ ended_at=self.BEGIN + timedelta(seconds=1),+ user_attributed_at=self.BEGIN,+ )++ usage = get_billable_sandbox_compute_usage_by_team(+ self.BEGIN, self.BEGIN + timedelta(microseconds=500_000), rate_cards=(self._rate(),)+ )++ assert usage.cpu_millicore_seconds == [(self.team.id, 125)]+ assert usage.memory_mib_seconds == [(self.team.id, 384)]++ def test_integer_resource_units_support_large_values(self):+ self._session(+ client_provenance=TaskClientProvenance.POSTHOG_DESKTOP,+ cpu_request_cores=999.999,+ memory_request_mb=1_048_576,+ )++ usage = get_billable_sandbox_compute_usage_by_team(self.BEGIN, self.END, rate_cards=(self._rate(),))++ assert usage.cpu_millicore_seconds == [(self.team.id, 3_599_996_400)]+ assert usage.memory_mib_seconds == [(self.team.id, 3_774_873_600)]++ def test_pre_effective_usage_reports_explicit_integer_zeros(self):+ self._session(client_provenance=TaskClientProvenance.POSTHOG_DESKTOP)++ usage = get_billable_sandbox_compute_usage_by_team(+ self.BEGIN, self.END, rate_cards=(self._rate(effective_at=self.BEGIN + timedelta(hours=3)),)+ )++ expected = [(self.team.id, 0)]+ assert usage.credits == expected+ assert usage.cpu_millicore_seconds == expected+ assert usage.memory_mib_seconds == expected+ assert all(type(value) is int for rows in usage.__dict__.values() for _, value in rows)++ def test_compute_before_first_rate_is_free_and_rate_changes_are_applied(self):+ self._session(+ client_provenance=TaskClientProvenance.POSTHOG_DESKTOP,+ cpu_cores=1,+ memory_gb=1,+ created_at=self.BEGIN,+ user_attributed_at=self.BEGIN,+ ended_at=self.BEGIN + timedelta(seconds=3),+ )+ boundary = self.BEGIN + timedelta(seconds=2)+ rates = (+ self._rate(effective_at=self.BEGIN + timedelta(seconds=1), expires_at=boundary),+ self._rate(+ version="v2",+ effective_at=boundary,+ cpu_core_second_usd=Decimal("0.002"),+ memory_gib_second_usd=Decimal("0.0002"),+ ),+ )++ usage = get_billable_sandbox_compute_usage_by_team(self.BEGIN, self.END, rate_cards=rates)++ assert usage.cpu_millicore_seconds == [(self.team.id, 2000)]++ def test_empty_rate_card_is_not_launched_but_invalid_configuration_fails(self):+ self._session(client_provenance=TaskClientProvenance.POSTHOG_DESKTOP)++ assert get_billable_sandbox_compute_usage_by_team(self.BEGIN, self.END, rate_cards=()).credits == []+ invalid = self._rate(cpu_core_second_usd=Decimal("0"))+ with self.assertRaises(ComputeRateCardConfigurationError):+ get_billable_sandbox_compute_usage_by_team(self.BEGIN, self.END, rate_cards=(invalid,))+def test_sums_attributed_window_with_resource_multipliers(self):# Attributed an hour after creation: only [01:30, 02:30) bills, not boot/pre-warm time.self._session(