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(tasks): raw usage ledger for cloud sandbox compute (#72325)

Adam Bowker1059a399875b
diff --git a/.semgrep/rules/security/idor-team-scoped-models.yaml b/.semgrep/rules/security/idor-team-scoped-models.yaml
index 93dee461f7db..7ccb1b10a171 100644
--- a/.semgrep/rules/security/idor-team-scoped-models.yaml
+++ b/.semgrep/rules/security/idor-team-scoped-models.yaml
@@ -241,6 +241,7 @@ rules:
|ReviewUserSettings
|SandboxCustomImage
|SandboxEnvironment
+ |SandboxSession
|ResourceLink
|ScoreDefinition
|SavedHeatmap
@@ -549,6 +550,7 @@ rules:
|ReviewUserSettings
|SandboxCustomImage
|SandboxEnvironment
+ |SandboxSession
|ResourceLink
|ScoreDefinition
|SavedHeatmap
diff --git a/posthog/tasks/test/test_usage_report.py b/posthog/tasks/test/test_usage_report.py
index f8b8cd81d98d..10506645e7ad 100644
--- a/posthog/tasks/test/test_usage_report.py
+++ b/posthog/tasks/test/test_usage_report.py
@@ -2,7 +2,7 @@ import gzip
import json
import base64
import dataclasses
-from datetime import datetime, timedelta
+from datetime import UTC, datetime, timedelta
from typing import Any
from uuid import uuid4
@@ -4649,6 +4649,64 @@ class TestAIEventsUsageReport(ClickhouseDestroyTablesMixin, TestCase, Clickhouse
self.assertTrue(has_non_zero_usage(UsageReportCounters(**{**zero, "posthog_code_credits_used_in_period": 5})))
+class TestTaskSandboxUsageReport(APIBaseTest):
+ PERIOD_START = datetime(2026, 1, 2, tzinfo=UTC)
+ PERIOD_END = datetime(2026, 1, 3, tzinfo=UTC)
+
+ def _session(self, **overrides: Any) -> None:
+ # String-based model access (like ErrorTrackingIssue above): the tasks product
+ # only exposes its facade to static imports from the posthog module.
+ Task = apps.get_model("tasks", "Task")
+ TaskRun = apps.get_model("tasks", "TaskRun")
+ SandboxSession = apps.get_model("tasks", "SandboxSession")
+
+ task = Task.objects.create(team=self.team, title="t", description="", origin_product="user_created")
+ run = TaskRun.objects.create(task=task, team=self.team)
+ defaults: dict = {
+ "team": self.team,
+ "task_run": run,
+ "sandbox_id": f"sb-{SandboxSession.objects.unscoped().count()}",
+ "cpu_cores": 4.0,
+ "memory_gb": 16.0,
+ "ttl_seconds": 6 * 60 * 60,
+ "created_at": datetime(2026, 1, 2, 1, tzinfo=UTC),
+ "user_attributed_at": datetime(2026, 1, 2, 1, tzinfo=UTC),
+ "ended_at": datetime(2026, 1, 2, 2, tzinfo=UTC),
+ }
+ defaults.update(overrides)
+ defaults.setdefault("ttl_expires_at", defaults["created_at"] + timedelta(seconds=defaults["ttl_seconds"]))
+ SandboxSession.objects.unscoped().create(**defaults)
+
+ def test_counts_attributed_in_period_usage_only(self) -> None:
+ from posthog.tasks.usage_report import get_teams_with_task_sandbox_usage_in_period
+
+ self._session()
+ self._session(user_attributed_at=None, ended_at=None)
+ self._session(
+ created_at=datetime(2026, 1, 1, 20, tzinfo=UTC),
+ user_attributed_at=datetime(2026, 1, 1, 22, tzinfo=UTC),
+ ended_at=datetime(2026, 1, 2, 6, tzinfo=UTC),
+ ttl_seconds=24 * 60 * 60,
+ )
+
+ usage = get_teams_with_task_sandbox_usage_in_period(self.PERIOD_START, self.PERIOD_END)
+
+ # 1h fully in period + the in-period 6h slice of the boundary-spanning session.
+ self.assertEqual(usage.seconds, [(self.team.id, 7 * 3600)])
+ self.assertEqual(usage.cpu_core_seconds, [(self.team.id, 7 * 3600 * 4)])
+ self.assertEqual(usage.memory_gib_seconds, [(self.team.id, 7 * 3600 * 16)])
+
+ def test_has_non_zero_usage_counts_task_sandbox_seconds(self) -> None:
+ import dataclasses
+
+ from posthog.tasks.usage_report import UsageReportCounters, has_non_zero_usage
+
+ zero = {field.name: 0 for field in dataclasses.fields(UsageReportCounters)}
+
+ self.assertFalse(has_non_zero_usage(UsageReportCounters(**zero)))
+ self.assertTrue(has_non_zero_usage(UsageReportCounters(**{**zero, "task_sandbox_seconds_in_period": 5})))
+
+
class TestSendUsage(LicensedTestMixin, ClickhouseDestroyTablesMixin, APIBaseTest):
def setUp(self) -> None:
super().setUp()
diff --git a/posthog/tasks/usage_report.py b/posthog/tasks/usage_report.py
index 5b297f011a8c..186786331744 100644
--- a/posthog/tasks/usage_report.py
+++ b/posthog/tasks/usage_report.py
@@ -61,6 +61,7 @@ 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.warehouse_sources.backend.facade.models import DataWarehouseTable, ExternalDataJob, ExternalDataSchema
logger = structlog.get_logger(__name__)
@@ -239,6 +240,12 @@ class UsageReportCounters:
# PostHog Code Billing Credits (PostHog Code product usage — same cost math as ai_credits, scoped to ai_product='posthog_code')
posthog_code_credits_used_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)
+ task_sandbox_seconds_in_period: int
+ task_sandbox_cpu_core_seconds_in_period: int
+ task_sandbox_memory_gib_seconds_in_period: int
+
# CDP Delivery
hog_function_calls_in_period: int
hog_function_fetch_calls_in_period: int
@@ -1693,6 +1700,17 @@ def get_teams_with_posthog_code_credits_used_in_period(
)
+@timed_log()
+@retry(tries=QUERY_RETRIES, delay=QUERY_RETRY_DELAY, backoff=QUERY_RETRY_BACKOFF)
+def get_teams_with_task_sandbox_usage_in_period(begin: datetime, end: datetime) -> SandboxUsageByTeam:
+ """Raw cloud-sandbox compute per team — wall seconds and resource-seconds of the
+ user-attributed window, from the SandboxSession ledger (Postgres, region-local).
+
+ Unpriced: reported for visibility until a sandbox billing model is decided.
+ """
+ return get_task_sandbox_usage_by_team(begin, end)
+
+
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)
@@ -2411,6 +2429,7 @@ def has_non_zero_usage(report: UsageReportCounters) -> bool:
or report.ai_credits_used_in_period > 0
or report.signals_credits_used_in_period > 0
or report.posthog_code_credits_used_in_period > 0
+ or report.task_sandbox_seconds_in_period > 0
or report.logs_bytes_in_period > 0
or report.workflow_emails_sent_in_period > 0
or report.workflow_push_sent_in_period > 0
@@ -2451,6 +2470,7 @@ def _get_all_usage_data(period_start: datetime, period_end: datetime) -> dict[st
exception_metrics_by_library, exception_metrics = get_teams_with_exceptions_captured_in_period(
period_start, period_end
)
+ task_sandbox_usage = get_teams_with_task_sandbox_usage_in_period(period_start, period_end)
return {
"teams_with_event_count_in_period": get_teams_with_billable_event_count_in_period(
@@ -2681,6 +2701,9 @@ def _get_all_usage_data(period_start: datetime, period_end: datetime) -> dict[st
"teams_with_posthog_code_credits_used_in_period": get_teams_with_posthog_code_credits_used_in_period(
period_start, period_end
),
+ "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,
"teams_with_active_hog_destinations_in_period": get_teams_with_active_hog_destinations_in_period(),
"teams_with_active_hog_transformations_in_period": get_teams_with_active_hog_transformations_in_period(),
"teams_with_workflow_emails_sent_in_period": get_teams_with_workflow_emails_sent_in_period(
@@ -2864,6 +2887,13 @@ def _get_team_report(all_data: dict[str, Any], team: Team) -> UsageReportCounter
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),
+ 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, 0
+ ),
+ task_sandbox_memory_gib_seconds_in_period=all_data["teams_with_task_sandbox_memory_gib_seconds_in_period"].get(
+ team.id, 0
+ ),
active_hog_destinations_in_period=all_data["teams_with_active_hog_destinations_in_period"].get(team.id, 0),
active_hog_transformations_in_period=all_data["teams_with_active_hog_transformations_in_period"].get(
team.id, 0
diff --git a/posthog/temporal/tests/usage_report/test_aggregate_activity.py b/posthog/temporal/tests/usage_report/test_aggregate_activity.py
index f6817de8b360..d22a24f7a343 100644
--- a/posthog/temporal/tests/usage_report/test_aggregate_activity.py
+++ b/posthog/temporal/tests/usage_report/test_aggregate_activity.py
@@ -23,7 +23,7 @@ from posthog.storage import object_storage
from posthog.tasks.usage_report import InstanceMetadata
from posthog.temporal.usage_report import storage
from posthog.temporal.usage_report.activities import aggregate_and_chunk_org_reports
-from posthog.temporal.usage_report.queries import QUERIES
+from posthog.temporal.usage_report.queries import QUERIES, QUERY_INDEX
from posthog.temporal.usage_report.storage import queries_key, write_json
from posthog.temporal.usage_report.types import AggregateInputs, RunQueryToS3Result, WorkflowContext
@@ -127,6 +127,11 @@ def _canned_query_payload(query_name: str, team_a_id: int, team_b_id: int, *extr
):
return [{"team_id": team_a_id, "total": 2}, {"team_id": team_b_id, "total": 1}]
+ # Multi specs need a dict shape even when out of focus, or the aggregator's
+ # fan-out breaks on `.get` — empty rows per source key.
+ if QUERY_INDEX[query_name].output == "multi":
+ return {source_key: [] for source_key in QUERY_INDEX[query_name].multi_keys_mapping}
+
# Everything else gets an empty result list — keeps the test focused on
# the few interesting metrics above.
return []
diff --git a/posthog/temporal/usage_report/queries.py b/posthog/temporal/usage_report/queries.py
index db6a21ed0ea5..f79291fd78c8 100644
--- a/posthog/temporal/usage_report/queries.py
+++ b/posthog/temporal/usage_report/queries.py
@@ -83,6 +83,7 @@ from posthog.tasks.usage_report import (
get_teams_with_sdk_logs_records_in_period,
get_teams_with_signals_credits_used_in_period,
get_teams_with_survey_responses_count_in_period,
+ get_teams_with_task_sandbox_usage_in_period,
get_teams_with_workflow_billable_invocations_in_period,
get_teams_with_workflow_emails_sent_in_period,
get_teams_with_workflow_push_sent_in_period,
@@ -193,6 +194,15 @@ def _sdk_logs_records(begin: datetime, end: datetime) -> dict[str, list[tuple[in
return get_teams_with_sdk_logs_records_in_period(begin, end, team_ids_with_logs=team_ids_with_logs)
+def _task_sandbox_usage(begin: datetime, end: datetime) -> dict[str, list[tuple[int, int]]]:
+ usage = get_teams_with_task_sandbox_usage_in_period(begin, end)
+ return {
+ "seconds": usage.seconds,
+ "cpu_core_seconds": usage.cpu_core_seconds,
+ "memory_gib_seconds": usage.memory_gib_seconds,
+ }
+
+
# ---- Registry ---------------------------------------------------------------
@@ -450,6 +460,17 @@ QUERIES: list[QuerySpec] = [
name="teams_with_posthog_code_credits_used_in_period",
fn=get_teams_with_posthog_code_credits_used_in_period,
),
+ # ---- Postgres: task sandbox compute -------------------------------------
+ QuerySpec(
+ name="task_sandbox_usage",
+ fn=_task_sandbox_usage,
+ output="multi",
+ multi_keys_mapping={
+ "seconds": "teams_with_task_sandbox_seconds_in_period",
+ "cpu_core_seconds": "teams_with_task_sandbox_cpu_core_seconds_in_period",
+ "memory_gib_seconds": "teams_with_task_sandbox_memory_gib_seconds_in_period",
+ },
+ ),
# ---- ClickHouse: workflows / messaging ----------------------------------
QuerySpec(
name="teams_with_workflow_emails_sent_in_period",
diff --git a/products/posthog_ai/backend/message_routing.py b/products/posthog_ai/backend/message_routing.py
index 3c370a9b8a91..2f9696664f6a 100644
--- a/products/posthog_ai/backend/message_routing.py
+++ b/products/posthog_ai/backend/message_routing.py
@@ -388,6 +388,10 @@ class SandboxSession(BaseSandboxService):
)
raise Conflict("The sandbox run is no longer accepting messages. Please try again.") from e
+ # Attribution stamp for the sandbox usage ledger: starts the user-attributable
+ # window on a claimed warm Run and records last-activity on every follow-up.
+ tasks_facade.record_task_run_user_activity(run.id, run.team_id)
+
# The Run has received its first human message, so it is no longer speculative — drop the
# warm flag so the warm-pool cap stops counting it (it's now an active Run governed by AI
# credits). Best-effort: a failure only over-counts the warm pool until the Run terminates,
diff --git a/products/tasks/backend/facade/api.py b/products/tasks/backend/facade/api.py
index 769b14ce22ff..2e583a2dbea0 100644
--- a/products/tasks/backend/facade/api.py
+++ b/products/tasks/backend/facade/api.py
@@ -170,6 +170,7 @@ __all__ = [
"presign_task_run_artifact",
"read_task_run_artifact",
"read_task_run_logs",
+ "record_task_run_user_activity",
"redeem_code_invite",
"redispatch_task_run",
"relay_task_run_message",
@@ -2710,9 +2711,24 @@ def signal_task_run_user_message(
logger.warning("Follow-up signal target workflow gone for task run %s", run.id)
return False
raise
+ record_task_run_user_activity(run.id, team_id)
return True
+def record_task_run_user_activity(run_id: str | UUID, team_id: int) -> None:
+ """Stamp a user message against the run's open sandbox usage sessions.
+
+ Best-effort (the ledger swallows its own failures): records last-activity on
+ every message and starts the user-attributable billing window on the first one.
+ Usage ledger only — no workflow side effects.
+ """
+ from products.tasks.backend.logic.services.sandbox_usage import ( # noqa: PLC0415 — keep sandbox deps off the api import path
+ record_task_run_user_activity as _record_user_activity,
+ )
+
+ _record_user_activity(run_id, team_id)
+
+
def get_task_run_sandbox_connection(
run_id: str | UUID, task_id: str | UUID, team_id: int, *, user_id: int, distinct_id: str
) -> contracts.TaskRunSandboxConnectionDTO | None:
diff --git a/products/tasks/backend/facade/billing.py b/products/tasks/backend/facade/billing.py
new file mode 100644
index 000000000000..2388b10c4473
--- /dev/null
+++ b/products/tasks/backend/facade/billing.py
@@ -0,0 +1,9 @@
+"""Billing-facing exports for the tasks product.
+
+The usage reporter (posthog/tasks/usage_report.py) lives in the ``posthog`` module,
+which 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
+
+__all__ = ["SandboxUsageByTeam", "get_task_sandbox_usage_by_team"]
diff --git a/products/tasks/backend/logic/services/sandbox_usage.py b/products/tasks/backend/logic/services/sandbox_usage.py
new file mode 100644
index 000000000000..277f0d832378
--- /dev/null
+++ b/products/tasks/backend/logic/services/sandbox_usage.py
@@ -0,0 +1,168 @@
+"""Raw usage ledger for cloud task sandboxes.
+
+One ``SandboxSession`` row per provisioned sandbox records its resource shape and
+the boundary timestamps of its lifetime (provisioned / user-attributed / last user
+activity / ended). The ledger stores raw usage only — no pricing or credit
+conversion — so any billable-window policy can be computed later without a
+backfill. Pre-warm time is PostHog's cost: a warm sandbox stays unattributed until
+a user claims its run with their first message.
+
+The write helpers swallow and log every failure: the ledger must never break
+sandbox provisioning, cleanup, or user-message delivery.
+"""
+
+from collections.abc import Callable
+from dataclasses import dataclass
+from datetime import datetime, timedelta
+from functools import wraps
+from typing import ParamSpec, TypeVar
+from uuid import UUID
+
+from django.db.models import Q
+from django.utils import timezone
+
+import structlog
+
+from products.tasks.backend.logic.services.sandbox import SandboxConfig
+from products.tasks.backend.models import SandboxSession, TaskRun
+
+logger = structlog.get_logger(__name__)
+
+P = ParamSpec("P")
+R = TypeVar("R")
+
+
+def _best_effort(fn: Callable[P, R]) -> Callable[P, R | None]:
+ @wraps(fn)
+ def wrapper(*args: P.args, **kwargs: P.kwargs) -> R | None:
+ try:
+ return fn(*args, **kwargs)
+ except Exception:
+ logger.exception("sandbox_usage.ledger_write_failed", helper=fn.__name__)
+ return None
+
+ return wrapper
+
+
+@_best_effort
+def open_sandbox_session(
+ *, run_id: str | UUID, sandbox_id: str, config: SandboxConfig, sandbox_created_at: datetime | None = None
+) -> None:
+ """Record a freshly provisioned sandbox against its run.
+
+ ``sandbox_created_at`` is the ``Sandbox.create()`` boundary — the provider's TTL
+ clock starts there, minutes before repo setup finishes and this row is opened, so
+ the TTL deadline must anchor on it rather than on insert time.
+
+ Reads the live ``TaskRun`` row rather than any workflow-start snapshot: a warm
+ run claimed while its sandbox was still provisioning has already lost the
+ ``await_user_message`` marker, so the session is created attributed. Upserts on
+ ``sandbox_id`` so activity retries stay idempotent, and never regresses
+ ``user_attributed_at`` on an existing row.
+ """
+ run = TaskRun.objects.select_related("task").only("id", "team_id", "state", "task__origin_product").get(id=run_id)
+ state = run.state or {}
+ created_at = sandbox_created_at or timezone.now()
+ shape = {
+ "team_id": run.team_id,
+ "task_run_id": run.id,
+ "origin_product": run.task.origin_product,
+ "prewarmed": bool(state.get("prewarmed")),
+ "vm_runtime": config.is_vm,
+ "cpu_cores": config.cpu_cores,
+ "memory_gb": config.memory_gb,
+ "ttl_seconds": config.ttl_seconds,
+ "burstable": config.burstable_resources,
+ "cpu_request_cores": config.cpu_request_cores if config.burstable_resources else None,
+ "memory_request_mb": config.memory_request_mb if config.burstable_resources else None,
+ "created_at": created_at,
+ "ttl_expires_at": created_at + timedelta(seconds=config.ttl_seconds),
+ }
+ SandboxSession.objects.for_team(run.team_id).update_or_create(
+ sandbox_id=sandbox_id,
+ defaults=shape,
+ create_defaults={
+ **shape,
+ "user_attributed_at": None if state.get("await_user_message") else timezone.now(),
+ },
+ )
+
+
+@_best_effort
+def close_sandbox_session(sandbox_id: str, *, reason: str) -> None:
+ """Stamp the sandbox's end. Idempotent — the first stamp wins."""
+ # Unscoped: cleanup/reap activities only carry the globally-unique provider
+ # sandbox id, not team context.
+ SandboxSession.objects.unscoped().filter(sandbox_id=sandbox_id, ended_at__isnull=True).update(
+ ended_at=timezone.now(), ended_reason=reason
+ )
+
+
+@_best_effort
+def record_task_run_user_activity(run_id: str | UUID, team_id: int) -> None:
+ """Stamp a user message against the run's open sandbox sessions.
+
+ Sets ``last_user_activity_at`` on every message and ``user_attributed_at``
+ set-if-NULL, so the first message both claims a warm sandbox and self-heals the
+ race where a claim lands mid-provision (before ``open_sandbox_session`` read the
+ run state).
+ """
+ now = timezone.now()
+ run_uuid = run_id if isinstance(run_id, UUID) else UUID(run_id)
+ open_sessions = SandboxSession.objects.for_team(team_id).filter(task_run_id=run_uuid, ended_at__isnull=True)
+ open_sessions.update(last_user_activity_at=now)
+ open_sessions.filter(user_attributed_at__isnull=True).update(user_attributed_at=now)
+
+
+@dataclass(frozen=True)
+class SandboxUsageByTeam:
+ """Raw per-team sandbox usage over a period, as (team_id, amount) rows."""
+
+ seconds: list[tuple[int, int]]
+ cpu_core_seconds: list[tuple[int, int]]
+ memory_gib_seconds: list[tuple[int, int]]
+
+
+def get_task_sandbox_usage_by_team(begin: datetime, end: datetime) -> SandboxUsageByTeam:
+ """Aggregate user-attributed sandbox time per team over ``[begin, end)``.
+
+ Only the attributed slice of a session bills: ``[user_attributed_at,
+ effective_end)``, clipped to the period so sessions spanning report boundaries
+ apportion across them. Every end is clamped to ``ttl_expires_at`` — the provider
+ kills the sandbox by then regardless, whether cleanup never ran (crashed
+ workflows), stamped late, or the session is genuinely live (clamped to now).
+ Open rows whose TTL expired before the period are excluded in the query itself,
+ so missed close stamps can't grow the scan without bound. Resource-second
+ metrics use the configured limits; burstable request floors are recorded on the
+ row for future pricing policy but don't affect raw usage.
+ """
+ now = timezone.now()
+ # Unscoped: the usage report aggregates across every team in the region.
+ sessions = (
+ SandboxSession.objects.unscoped()
+ .filter(
+ user_attributed_at__isnull=False,
+ user_attributed_at__lt=end,
+ )
+ .filter(Q(ended_at__isnull=True, ttl_expires_at__gt=begin) | Q(ended_at__gt=begin))
+ )
+
+ usage: dict[int, list[float]] = {}
+ for session in sessions.iterator():
+ assert session.user_attributed_at is not None
+ start = max(session.user_attributed_at, begin)
+ effective_end = min(session.ended_at or now, session.ttl_expires_at)
+ stop = min(effective_end, end)
+ if stop <= start:
+ continue
+ seconds = (stop - start).total_seconds()
+ team_usage = usage.setdefault(session.team_id, [0.0, 0.0, 0.0])
+ team_usage[0] += seconds
+ team_usage[1] += seconds * session.cpu_cores
+ team_usage[2] += seconds * session.memory_gb
+
+ return SandboxUsageByTeam(
+ seconds=[(team_id, round(totals[0])) for team_id, totals in usage.items()],
+ cpu_core_seconds=[(team_id, round(totals[1])) for team_id, totals in usage.items()],
+ memory_gib_seconds=[(team_id, round(totals[2])) for team_id, totals in usage.items()],
+ )
diff --git a/products/tasks/backend/logic/services/tests/test_sandbox_usage.py b/products/tasks/backend/logic/services/tests/test_sandbox_usage.py
new file mode 100644
index 000000000000..814630ebe9a7
--- /dev/null
+++ b/products/tasks/backend/logic/services/tests/test_sandbox_usage.py
@@ -0,0 +1,308 @@
+from datetime import UTC, datetime, timedelta
+
+from freezegun import freeze_time
+from posthog.test.base import APIBaseTest
+from unittest.mock import patch
+
+from posthog.models.organization import Organization
+from posthog.models.team.team import Team
+
+from products.tasks.backend.logic.services.sandbox import SandboxConfig
+from products.tasks.backend.logic.services.sandbox_usage import (
+ close_sandbox_session,
+ get_task_sandbox_usage_by_team,
+ open_sandbox_session,
+ record_task_run_user_activity,
+)
+from products.tasks.backend.models import SandboxSession, Task, TaskRun
+
+
+def _config(**overrides) -> SandboxConfig:
+ defaults: dict = {"name": "test-sandbox", "cpu_cores": 4.0, "memory_gb": 16.0, "ttl_seconds": 6 * 60 * 60}
+ defaults.update(overrides)
+ return SandboxConfig(**defaults)
+
+
+class SandboxUsageBase(APIBaseTest):
+ def _run(self, *, state: dict | None = None) -> TaskRun:
+ task = Task.objects.create(
+ team=self.team, title="t", description="", origin_product=Task.OriginProduct.USER_CREATED
+ )
+ return TaskRun.objects.create(task=task, team=self.team, state=state or {})
+
+
+class TestSandboxSessionWrites(SandboxUsageBase):
+ def test_open_attributes_cold_runs_immediately(self):
+ run = self._run()
+
+ open_sandbox_session(run_id=run.id, sandbox_id="sb-cold", config=_config())
+
+ session = SandboxSession.objects.unscoped().get(sandbox_id="sb-cold")
+ assert session.team_id == self.team.id
+ assert session.task_run_id == run.id
+ assert session.origin_product == Task.OriginProduct.USER_CREATED
+ assert session.user_attributed_at is not None
+ assert session.prewarmed is False
+ assert session.vm_runtime is False
+ assert (session.cpu_cores, session.memory_gb, session.ttl_seconds) == (4.0, 16.0, 21600)
+ assert session.burstable is False
+ assert session.cpu_request_cores is None
+
+ def test_open_leaves_warm_runs_unattributed(self):
+ run = self._run(state={"await_user_message": True, "prewarmed": True})
+
+ open_sandbox_session(run_id=run.id, sandbox_id="sb-warm", config=_config())
+
+ session = SandboxSession.objects.unscoped().get(sandbox_id="sb-warm")
+ assert session.user_attributed_at is None
+ assert session.prewarmed is True
+
+ def test_open_records_burstable_request_floors(self):
+ run = self._run()
+
+ open_sandbox_session(
+ run_id=run.id,
+ sandbox_id="sb-burst",
+ config=_config(burstable_resources=True, cpu_request_cores=0.5, memory_request_mb=1024),
+ )
+
+ session = SandboxSession.objects.unscoped().get(sandbox_id="sb-burst")
+ assert session.burstable is True
+ assert session.cpu_request_cores == 0.5
+ assert session.memory_request_mb == 1024
+
+ def test_open_anchors_ttl_deadline_at_the_sandbox_creation_boundary(self):
+ # The provider's TTL clock starts at Sandbox.create(), minutes before repo
+ # setup finishes and the row is opened — the deadline must anchor there.
+ run = self._run()
+ boundary = datetime(2026, 1, 2, 9, tzinfo=UTC)
+
+ open_sandbox_session(run_id=run.id, sandbox_id="sb-anchor", config=_config(), sandbox_created_at=boundary)
+
+ session = SandboxSession.objects.unscoped().get(sandbox_id="sb-anchor")
+ assert session.created_at == boundary
+ assert session.ttl_expires_at == boundary + timedelta(hours=6)
+
+ def test_open_records_vm_runtime(self):
+ run = self._run()
+
+ open_sandbox_session(run_id=run.id, sandbox_id="sb-vm", config=_config(vm_runtime=True))
+
+ assert SandboxSession.objects.unscoped().get(sandbox_id="sb-vm").vm_runtime is True
+
+ def test_open_retry_never_regresses_attribution(self):
+ run = self._run(state={"await_user_message": True})
+ open_sandbox_session(run_id=run.id, sandbox_id="sb-retry", config=_config())
+ record_task_run_user_activity(run.id, self.team.id)
+ attributed_at = SandboxSession.objects.unscoped().get(sandbox_id="sb-retry").user_attributed_at
+ assert attributed_at is not None
+
+ # Activity retry re-runs the open with the run state still carrying the warm marker.
+ open_sandbox_session(run_id=run.id, sandbox_id="sb-retry", config=_config())
+
+ assert SandboxSession.objects.unscoped().count() == 1
+ assert SandboxSession.objects.unscoped().get(sandbox_id="sb-retry").user_attributed_at == attributed_at
+
+ def test_open_swallows_missing_run(self):
+ open_sandbox_session(run_id="00000000-0000-0000-0000-000000000000", sandbox_id="sb-x", config=_config())
+
+ assert SandboxSession.objects.unscoped().count() == 0
+
+ def test_close_stamps_once(self):
+ run = self._run()
+ open_sandbox_session(run_id=run.id, sandbox_id="sb-close", config=_config())
+
+ close_sandbox_session("sb-close", reason=SandboxSession.EndedReason.CLEANUP)
+ first = SandboxSession.objects.unscoped().get(sandbox_id="sb-close")
+ assert first.ended_at is not None
+ assert first.ended_reason == SandboxSession.EndedReason.CLEANUP
+
+ close_sandbox_session("sb-close", reason=SandboxSession.EndedReason.REAPED)
+ again = SandboxSession.objects.unscoped().get(sandbox_id="sb-close")
+ assert again.ended_at == first.ended_at
+ assert again.ended_reason == SandboxSession.EndedReason.CLEANUP
+
+ def test_user_activity_stamps_open_sessions_only(self):
+ run = self._run(state={"await_user_message": True})
+ open_sandbox_session(run_id=run.id, sandbox_id="sb-a", config=_config())
+ open_sandbox_session(run_id=run.id, sandbox_id="sb-b", config=_config())
+ close_sandbox_session("sb-b", reason=SandboxSession.EndedReason.CLEANUP)
+
+ record_task_run_user_activity(run.id, self.team.id)
+
+ live = SandboxSession.objects.unscoped().get(sandbox_id="sb-a")
+ assert live.user_attributed_at is not None
+ assert live.last_user_activity_at is not None
+ ended = SandboxSession.objects.unscoped().get(sandbox_id="sb-b")
+ assert ended.user_attributed_at is None
+ assert ended.last_user_activity_at is None
+
+ def test_user_activity_keeps_first_attribution(self):
+ run = self._run(state={"await_user_message": True})
+ open_sandbox_session(run_id=run.id, sandbox_id="sb-msgs", config=_config())
+
+ with freeze_time("2026-01-02T10:00:00Z"):
+ record_task_run_user_activity(run.id, self.team.id)
+ with freeze_time("2026-01-02T11:00:00Z"):
+ record_task_run_user_activity(run.id, self.team.id)
+
+ session = SandboxSession.objects.unscoped().get(sandbox_id="sb-msgs")
+ assert session.user_attributed_at == datetime(2026, 1, 2, 10, tzinfo=UTC)
+ assert session.last_user_activity_at == datetime(2026, 1, 2, 11, tzinfo=UTC)
+
+ def test_user_activity_is_scoped_to_the_run_team(self):
+ run = self._run(state={"await_user_message": True})
+ open_sandbox_session(run_id=run.id, sandbox_id="sb-scoped", config=_config())
+ other_org = Organization.objects.create(name="other")
+ other_team = Team.objects.create(organization=other_org, name="other")
+
+ record_task_run_user_activity(run.id, other_team.id)
+
+ assert SandboxSession.objects.unscoped().get(sandbox_id="sb-scoped").user_attributed_at is None
+
+ def test_facade_signal_attributes_claimed_warm_run(self):
+ from products.tasks.backend.facade import api as tasks_facade
+
+ run = self._run(state={"await_user_message": True, "prewarmed": True})
+ open_sandbox_session(run_id=run.id, sandbox_id="sb-claim", config=_config())
+ assert SandboxSession.objects.unscoped().get(sandbox_id="sb-claim").user_attributed_at is None
+
+ with patch("products.tasks.backend.temporal.client.signal_task_followup_message"):
+ assert tasks_facade.signal_task_run_user_message(
+ run.id, run.task_id, self.team.id, content="hi", artifact_ids=[]
+ )
+
+ assert SandboxSession.objects.unscoped().get(sandbox_id="sb-claim").user_attributed_at is not None
+
+
+class TestSandboxUsageAggregation(SandboxUsageBase):
+ BEGIN = datetime(2026, 1, 2, tzinfo=UTC)
+ END = datetime(2026, 1, 3, tzinfo=UTC)
+
+ def _session(self, **overrides) -> SandboxSession:
+ run = self._run()
+ defaults: dict = {
+ "team": self.team,
+ "task_run": run,
+ "origin_product": Task.OriginProduct.USER_CREATED,
+ "cpu_cores": 4.0,
+ "memory_gb": 16.0,
+ "ttl_seconds": 6 * 60 * 60,
+ "created_at": datetime(2026, 1, 2, 1, tzinfo=UTC),
+ "user_attributed_at": datetime(2026, 1, 2, 1, tzinfo=UTC),
+ "ended_at": datetime(2026, 1, 2, 2, tzinfo=UTC),
+ }
+ defaults.update(overrides)
+ defaults.setdefault("sandbox_id", f"sb-{SandboxSession.objects.unscoped().count()}")
+ defaults.setdefault("ttl_expires_at", defaults["created_at"] + timedelta(seconds=defaults["ttl_seconds"]))
+ return SandboxSession.objects.unscoped().create(**defaults)
+
+ 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(
+ created_at=datetime(2026, 1, 2, 0, 30, tzinfo=UTC),
+ user_attributed_at=datetime(2026, 1, 2, 1, 30, tzinfo=UTC),
+ ended_at=datetime(2026, 1, 2, 2, 30, tzinfo=UTC),
+ )
+
+ usage = get_task_sandbox_usage_by_team(self.BEGIN, self.END)
+
+ assert usage.seconds == [(self.team.id, 3600)]
+ assert usage.cpu_core_seconds == [(self.team.id, 3600 * 4)]
+ assert usage.memory_gib_seconds == [(self.team.id, 3600 * 16)]
+
+ def test_apportions_sessions_spanning_period_boundaries(self):
+ # Attributed the previous day, ends mid-period: only the in-period slice counts.
+ self._session(
+ created_at=datetime(2026, 1, 1, 20, tzinfo=UTC),
+ user_attributed_at=datetime(2026, 1, 1, 22, tzinfo=UTC),
+ ended_at=datetime(2026, 1, 2, 6, tzinfo=UTC),
+ ttl_seconds=24 * 60 * 60,
+ )
+
+ usage = get_task_sandbox_usage_by_team(self.BEGIN, self.END)
+
+ assert usage.seconds == [(self.team.id, 6 * 3600)]
+
+ def test_never_closed_session_clamps_to_ttl(self):
+ self._session(
+ created_at=datetime(2026, 1, 2, 1, tzinfo=UTC),
+ user_attributed_at=datetime(2026, 1, 2, 1, tzinfo=UTC),
+ ended_at=None,
+ ttl_seconds=6 * 60 * 60,
+ )
+
+ with freeze_time("2026-01-05T00:00:00Z"):
+ usage = get_task_sandbox_usage_by_team(self.BEGIN, self.END)
+
+ # Cleanup never ran; the sandbox died at created_at + 6h regardless.
+ assert usage.seconds == [(self.team.id, 6 * 3600)]
+
+ def test_expired_open_sessions_are_excluded(self):
+ # A row that never got a close stamp and whose TTL expired before the period
+ # is dropped by the query's open-arm TTL bound, not just the Python clamp.
+ self._session(
+ created_at=datetime(2025, 12, 20, 1, tzinfo=UTC),
+ user_attributed_at=datetime(2025, 12, 20, 1, tzinfo=UTC),
+ ended_at=None,
+ )
+
+ usage = get_task_sandbox_usage_by_team(self.BEGIN, self.END)
+
+ assert usage.seconds == []
+
+ def test_late_close_clamps_to_ttl(self):
+ # Cleanup stamped hours after the provider already killed the sandbox at created_at + 6h.
+ self._session(
+ created_at=datetime(2026, 1, 2, 1, tzinfo=UTC),
+ user_attributed_at=datetime(2026, 1, 2, 1, tzinfo=UTC),
+ ended_at=datetime(2026, 1, 2, 10, tzinfo=UTC),
+ ttl_seconds=6 * 60 * 60,
+ )
+
+ usage = get_task_sandbox_usage_by_team(self.BEGIN, self.END)
+
+ assert usage.seconds == [(self.team.id, 6 * 3600)]
+
+ def test_live_session_clamps_to_now(self):
+ self._session(
+ created_at=datetime(2026, 1, 2, 1, tzinfo=UTC),
+ user_attributed_at=datetime(2026, 1, 2, 1, tzinfo=UTC),
+ ended_at=None,
+ )
+
+ with freeze_time("2026-01-02T03:00:00Z"):
+ usage = get_task_sandbox_usage_by_team(self.BEGIN, self.END)
+
+ assert usage.seconds == [(self.team.id, 2 * 3600)]
+
+ def test_excludes_unattributed_and_out_of_period_sessions(self):
+ self._session(user_attributed_at=None, ended_at=None, sandbox_id="sb-unattributed")
+ self._session(
+ created_at=datetime(2026, 1, 1, 1, tzinfo=UTC),
+ user_attributed_at=datetime(2026, 1, 1, 1, tzinfo=UTC),
+ ended_at=datetime(2026, 1, 1, 2, tzinfo=UTC),
+ sandbox_id="sb-ended-before",
+ )
+ self._session(
+ created_at=datetime(2026, 1, 3, 1, tzinfo=UTC),
+ user_attributed_at=datetime(2026, 1, 3, 1, tzinfo=UTC),
+ ended_at=datetime(2026, 1, 3, 2, tzinfo=UTC),
+ sandbox_id="sb-after",
+ )
+
+ usage = get_task_sandbox_usage_by_team(self.BEGIN, self.END)
+
+ assert usage.seconds == []
+ assert usage.cpu_core_seconds == []
+ assert usage.memory_gib_seconds == []
+
+ def test_aggregates_multiple_sessions_per_team(self):
+ self._session(sandbox_id="sb-1") # 1h at 4 cores
+ self._session(sandbox_id="sb-2", cpu_cores=8.0, memory_gb=32.0) # 1h at 8 cores
+
+ usage = get_task_sandbox_usage_by_team(self.BEGIN, self.END)
+
+ assert usage.seconds == [(self.team.id, 2 * 3600)]
+ assert usage.cpu_core_seconds == [(self.team.id, 3600 * 4 + 3600 * 8)]
+ assert usage.memory_gib_seconds == [(self.team.id, 3600 * 16 + 3600 * 32)]
diff --git a/products/tasks/backend/migrations/0070_sandboxsession.py b/products/tasks/backend/migrations/0070_sandboxsession.py
new file mode 100644
index 000000000000..7748c6befe0d
--- /dev/null
+++ b/products/tasks/backend/migrations/0070_sandboxsession.py
@@ -0,0 +1,151 @@
+import django.utils.timezone
+import django.db.models.deletion
+from django.db import migrations, models
+
+import posthog.models.utils
+
+
+class Migration(migrations.Migration):
+ dependencies = [
+ ("posthog", "1231_duckgresserverteam"),
+ ("tasks", "0069_remove_code_home_models"),
+ ]
+
+ operations = [
+ migrations.CreateModel(
+ name="SandboxSession",
+ fields=[
+ (
+ "id",
+ models.UUIDField(
+ default=posthog.models.utils.uuid7, editable=False, primary_key=True, serialize=False
+ ),
+ ),
+ (
+ "sandbox_id",
+ models.CharField(
+ help_text="Provider sandbox id (e.g. Modal object id)", max_length=255, unique=True
+ ),
+ ),
+ (
+ "origin_product",
+ models.CharField(
+ blank=True,
+ choices=[
+ ("onboarding", "Onboarding"),
+ ("error_tracking", "Error Tracking"),
+ ("eval_clusters", "Eval Clusters"),
+ ("user_created", "User Created"),
+ ("automation", "Automation"),
+ ("slack", "Slack"),
+ ("support_queue", "Support Queue"),
+ ("session_summaries", "Session Summaries"),
+ ("posthog_ai", "PostHog AI"),
+ ("experiments", "Experiments"),
+ ("signal_report", "Signal Report"),
+ ("signals_scout", "Signals Scout"),
+ ("support_reply", "Support Reply"),
+ ("hogdesk", "HogDesk"),
+ ("review_hog", "ReviewHog"),
+ ("image_builder", "Image Builder"),
+ ("loop", "Loop"),
+ ],
+ help_text="Task origin at provision time, denormalized for per-origin aggregation",
+ max_length=20,
+ null=True,
+ ),
+ ),
+ (
+ "prewarmed",
+ models.BooleanField(default=False, help_text="Sandbox was provisioned ahead of any user demand"),
+ ),
+ (
+ "vm_runtime",
+ models.BooleanField(
+ default=False, help_text="Modal VM runtime rather than gVisor (billed differently)"
+ ),
+ ),
+ ("cpu_cores", models.FloatField(help_text="CPU core limit")),
+ ("memory_gb", models.FloatField(help_text="Memory limit in GiB")),
+ ("ttl_seconds", models.IntegerField(help_text="Hard TTL after which the provider kills the sandbox")),
+ ("burstable", models.BooleanField(default=False)),
+ (
+ "cpu_request_cores",
+ models.FloatField(blank=True, help_text="Reserved CPU floor when burstable", null=True),
+ ),
+ (
+ "memory_request_mb",
+ models.IntegerField(blank=True, help_text="Reserved memory floor when burstable", null=True),
+ ),
+ (
+ "created_at",
+ models.DateTimeField(default=django.utils.timezone.now, help_text="Sandbox provisioned"),
+ ),
+ (
+ "ttl_expires_at",
+ models.DateTimeField(help_text="Absolute provider kill deadline (creation boundary + TTL)"),
+ ),
+ (
+ "user_attributed_at",
+ models.DateTimeField(
+ blank=True,
+ help_text="Start of the user-attributable window; NULL while (pre)warm and unclaimed",
+ null=True,
+ ),
+ ),
+ (
+ "last_user_activity_at",
+ models.DateTimeField(
+ blank=True, help_text="Most recent user message routed to this sandbox's run", null=True
+ ),
+ ),
+ (
+ "ended_at",
+ models.DateTimeField(
+ blank=True,
+ help_text="Sandbox destroyed; NULL rows are clamped to ttl_expires_at",
+ null=True,
+ ),
+ ),
+ (
+ "ended_reason",
+ models.CharField(
+ blank=True,
+ choices=[
+ ("cleanup", "Cleanup"),
+ ("reaped", "Reaped"),
+ ],
+ max_length=20,
+ null=True,
+ ),
+ ),
+ (
+ "task_run",
+ models.ForeignKey(
+ on_delete=django.db.models.deletion.CASCADE, related_name="sandbox_sessions", to="tasks.taskrun"
+ ),
+ ),
+ (
+ "team",
+ models.ForeignKey(
+ db_constraint=False,
+ on_delete=django.db.models.deletion.CASCADE,
+ related_name="+",
+ to="posthog.team",
+ ),
+ ),
+ ],
+ options={
+ "db_table": "posthog_task_sandbox_session",
+ "indexes": [
+ models.Index(fields=["ended_at"], name="sandbox_session_ended_at_idx"),
+ models.Index(
+ condition=models.Q(("ended_at__isnull", True)),
+ fields=["ttl_expires_at"],
+ name="sandbox_session_open_ttl_idx",
+ ),
+ models.Index(fields=["team", "user_attributed_at"], name="sandbox_session_team_attr_idx"),
+ ],
+ },
+ ),
+ ]
diff --git a/products/tasks/backend/migrations/max_migration.txt b/products/tasks/backend/migrations/max_migration.txt
index d4a712f57d71..f1c26fc2efd7 100644
--- a/products/tasks/backend/migrations/max_migration.txt
+++ b/products/tasks/backend/migrations/max_migration.txt
@@ -1 +1 @@
-0069_remove_code_home_models
+0070_sandboxsession
diff --git a/products/tasks/backend/models.py b/products/tasks/backend/models.py
index 01b8f37e3c8b..3fbfb8a0ee22 100644
--- a/products/tasks/backend/models.py
+++ b/products/tasks/backend/models.py
@@ -1987,6 +1987,89 @@ class TaskArtifact(TeamScopedRootMixin, UUIDModel):
return f"{self.name} ({self.artifact_type})"
+class SandboxSession(TeamScopedRootMixin, UUIDModel):
+ """Usage ledger for one cloud sandbox: when it ran, its resource shape, and which
+ slice of its lifetime is attributable to a user.
+
+ One row per sandbox, keyed on the provider sandbox id and upserted by the
+ provisioning activity so activity retries stay idempotent. Rows record raw usage
+ only — pricing/credit conversion happens downstream at aggregation time
+ (see logic/services/sandbox_usage.py). Pre-warmed sandboxes stay unattributed
+ (``user_attributed_at`` NULL, on PostHog's dime) until a user claims the run with
+ their first message; the boundary timestamps are deliberately redundant so any
+ future billable-window policy (wall-clock, active-plus-grace, ...) can be computed
+ from the ledger without a backfill.
+ """
+
+ class EndedReason(models.TextChoices):
+ CLEANUP = "cleanup", "Cleanup"
+ REAPED = "reaped", "Reaped"
+
+ # db_constraint=False on the team FK: adding an FK constraint to that hot table
+ # locks it and stalls deploys; Django still enforces the relation and on_delete at
+ # the app level (see safe-django-migrations.md).
+ team = models.ForeignKey("posthog.Team", on_delete=models.CASCADE, related_name="+", db_constraint=False)
+ task_run = models.ForeignKey("tasks.TaskRun", on_delete=models.CASCADE, related_name="sandbox_sessions")
+
+ sandbox_id = models.CharField(max_length=255, unique=True, help_text="Provider sandbox id (e.g. Modal object id)")
+ origin_product = models.CharField(
+ max_length=20,
+ choices=Task.OriginProduct,
+ null=True,
+ blank=True,
+ help_text="Task origin at provision time, denormalized for per-origin aggregation",
+ )
+ prewarmed = models.BooleanField(default=False, help_text="Sandbox was provisioned ahead of any user demand")
+ vm_runtime = models.BooleanField(
+ default=False, help_text="Modal VM runtime rather than gVisor (billed differently)"
+ )
+
+ # Resource shape at creation, already clamped by SandboxConfig. Limits are what the
+ # sandbox may consume — raw usage metrics derive from these; the burstable request
+ # floors are recorded for future pricing-policy work only (Modal bills max(request, actual)).
+ cpu_cores = models.FloatField(help_text="CPU core limit")
+ memory_gb = models.FloatField(help_text="Memory limit in GiB")
+ ttl_seconds = models.IntegerField(help_text="Hard TTL after which the provider kills the sandbox")
+ burstable = models.BooleanField(default=False)
+ cpu_request_cores = models.FloatField(null=True, blank=True, help_text="Reserved CPU floor when burstable")
+ memory_request_mb = models.IntegerField(null=True, blank=True, help_text="Reserved memory floor when burstable")
+
+ created_at = models.DateTimeField(default=django_timezone.now, help_text="Sandbox provisioned")
+ # Anchored at the Sandbox.create() boundary, not ledger-row insert time: the
+ # provider's TTL clock starts there, before repo setup runs and the row is opened.
+ ttl_expires_at = models.DateTimeField(help_text="Absolute provider kill deadline (creation boundary + TTL)")
+ user_attributed_at = models.DateTimeField(
+ null=True, blank=True, help_text="Start of the user-attributable window; NULL while (pre)warm and unclaimed"
+ )
+ last_user_activity_at = models.DateTimeField(
+ null=True, blank=True, help_text="Most recent user message routed to this sandbox's run"
+ )
+ ended_at = models.DateTimeField(
+ null=True, blank=True, help_text="Sandbox destroyed; NULL rows are clamped to ttl_expires_at"
+ )
+ ended_reason = models.CharField(max_length=20, choices=EndedReason, null=True, blank=True)
+
+ class Meta:
+ db_table = "posthog_task_sandbox_session"
+ indexes = [
+ # The usage report scans sessions overlapping the period instance-wide:
+ # closed recently (ended_at > begin) or open and not yet past their TTL
+ # (ended_at IS NULL AND ttl_expires_at > begin) — the partial index keeps
+ # rows that never got a close stamp from being re-fetched forever.
+ models.Index(fields=["ended_at"], name="sandbox_session_ended_at_idx"),
+ models.Index(
+ fields=["ttl_expires_at"],
+ condition=models.Q(ended_at__isnull=True),
+ name="sandbox_session_open_ttl_idx",
+ ),
+ # For per-team/per-origin re-aggregation once pricing decides which origins bill.
+ models.Index(fields=["team", "user_attributed_at"], name="sandbox_session_team_attr_idx"),
+ ]
+
+ def __str__(self):
+ return f"Sandbox session {self.sandbox_id} for run {self.task_run_id}"
+
+
class SandboxSnapshot(UUIDModel):
"""Tracks sandbox snapshots used for sandbox environments in tasks."""
diff --git a/products/tasks/backend/temporal/execute_sandbox/activities/reap_orphaned_sandbox.py b/products/tasks/backend/temporal/execute_sandbox/activities/reap_orphaned_sandbox.py
index dd5c83d8aae4..ceed4632851f 100644
--- a/products/tasks/backend/temporal/execute_sandbox/activities/reap_orphaned_sandbox.py
+++ b/products/tasks/backend/temporal/execute_sandbox/activities/reap_orphaned_sandbox.py
@@ -23,7 +23,8 @@ from temporalio import activity
from posthog.temporal.common.utils import asyncify
from products.tasks.backend.logic.services.sandbox import Sandbox
-from products.tasks.backend.models import TaskRun
+from products.tasks.backend.logic.services.sandbox_usage import close_sandbox_session
+from products.tasks.backend.models import SandboxSession, TaskRun
from products.tasks.backend.temporal.execute_sandbox.activities.sandbox_state import SANDBOX_ID_STATE_KEY
from products.tasks.backend.temporal.observability import log_activity_execution
@@ -70,5 +71,10 @@ def reap_orphaned_sandbox(input: ReapOrphanedSandboxInput) -> ReapOrphanedSandbo
# next start doesn't re-reap a dead id forever.
destroy_succeeded = False
+ # Best-effort usage-ledger end stamp (swallows its own failures), regardless of
+ # destroy outcome — the TTL kills any undead sandbox anyway, and the ledger
+ # prefers a slightly early end over an open-ended row.
+ close_sandbox_session(sandbox_id, reason=SandboxSession.EndedReason.REAPED)
+
TaskRun.update_state_atomic(input.run_id, remove_keys=[SANDBOX_ID_STATE_KEY])
return ReapOrphanedSandboxResult(reaped_sandbox_id=sandbox_id, destroy_succeeded=destroy_succeeded)
diff --git a/products/tasks/backend/temporal/process_task/activities/cleanup_sandbox.py b/products/tasks/backend/temporal/process_task/activities/cleanup_sandbox.py
index 3de515144209..22b173cc9f39 100644
--- a/products/tasks/backend/temporal/process_task/activities/cleanup_sandbox.py
+++ b/products/tasks/backend/temporal/process_task/activities/cleanup_sandbox.py
@@ -7,8 +7,9 @@ from posthog.temporal.common.utils import asyncify
from products.tasks.backend.exceptions import SandboxNotFoundError
from products.tasks.backend.logic.services.sandbox import Sandbox
+from products.tasks.backend.logic.services.sandbox_usage import close_sandbox_session
from products.tasks.backend.logic.stream.redis_stream import publish_task_run_stream_complete
-from products.tasks.backend.models import TaskRun
+from products.tasks.backend.models import SandboxSession, TaskRun
from products.tasks.backend.redis import run_uses_dedicated_stream
from products.tasks.backend.temporal.observability import log_activity_execution
@@ -73,6 +74,11 @@ def cleanup_sandbox_now(input: CleanupSandboxInput) -> None:
if strict_cleanup:
raise
+ # Best-effort usage-ledger end stamp (swallows its own failures). Stamped even when
+ # destroy failed or the sandbox was already gone: the TTL kills any undead sandbox
+ # anyway, and the ledger prefers a slightly early end over an open-ended row.
+ close_sandbox_session(input.sandbox_id, reason=SandboxSession.EndedReason.CLEANUP)
+
if input.complete_stream_on_cleanup and input.run_id and stream_completion_safe:
try:
publish_run_stream_completion(input.run_id)
diff --git a/products/tasks/backend/temporal/process_task/activities/forward_pending_message.py b/products/tasks/backend/temporal/process_task/activities/forward_pending_message.py
index fc62c9b3bbd2..b7e334e99ccb 100644
--- a/products/tasks/backend/temporal/process_task/activities/forward_pending_message.py
+++ b/products/tasks/backend/temporal/process_task/activities/forward_pending_message.py
@@ -187,6 +187,15 @@ def forward_pending_user_message(run_id: str) -> None:
)
if result.success or result.turn_in_flight:
+ # Attribution stamp for the sandbox usage ledger: the initial prompt is a
+ # user message, so its delivery starts the user-attributable window even
+ # when the run state carried a warm marker at provision time. A turn in
+ # flight counts: the message reached the sandbox and it is doing work.
+ from products.tasks.backend.logic.services.sandbox_usage import ( # noqa: PLC0415 — matches the file's deferred-import pattern
+ record_task_run_user_activity,
+ )
+
+ record_task_run_user_activity(run_id, task_run.team_id)
logger.info("forward_pending_message_delivered", run_id=run_id)
else:
observe_followup_delivery_failed(task_run, retryable=False)
diff --git a/products/tasks/backend/temporal/process_task/activities/get_sandbox_for_repository.py b/products/tasks/backend/temporal/process_task/activities/get_sandbox_for_repository.py
index e5fc6f3117b5..7f6a2f443e6c 100644
--- a/products/tasks/backend/temporal/process_task/activities/get_sandbox_for_repository.py
+++ b/products/tasks/backend/temporal/process_task/activities/get_sandbox_for_repository.py
@@ -3,6 +3,7 @@ import logging
from dataclasses import dataclass
from django.conf import settings
+from django.utils import timezone
from temporalio import activity
@@ -21,6 +22,7 @@ from products.tasks.backend.logic.services.sandbox import (
SandboxTemplate,
parse_sandbox_repo_mount_map,
)
+from products.tasks.backend.logic.services.sandbox_usage import open_sandbox_session
from products.tasks.backend.models import SandboxSnapshot, Task, TaskRun
from products.tasks.backend.temporal.metrics import StepTimer, increment_snapshot_restore, increment_snapshot_usage
from products.tasks.backend.temporal.oauth import create_oauth_access_token_for_run
@@ -295,6 +297,9 @@ def get_sandbox_for_repository(input: GetSandboxForRepositoryInput) -> GetSandbo
)
with StepTimer("sandbox_creation", used_snapshot=used_snapshot) as sandbox_creation_timer:
sandbox = Sandbox.create(config)
+ # The provider's TTL clock starts here — the usage ledger anchors its
+ # kill deadline on this boundary, not on when the row is opened below.
+ sandbox_created_at = timezone.now()
used_snapshot = bool((resume_snapshot_ext_id or snapshot) and sandbox.config.snapshot_restored)
sandbox_creation_timer.set_used_snapshot(used_snapshot)
snapshot_outcome = "used" if used_snapshot else "fresh" if snapshot_source == "none" else "fallback"
@@ -369,6 +374,13 @@ def get_sandbox_for_repository(input: GetSandboxForRepositoryInput) -> GetSandbo
sandbox_state["sandbox_connect_token"] = credentials.token
TaskRun.update_state_atomic(ctx.run_id, updates=sandbox_state)
+ # Best-effort usage-ledger row (swallows its own failures). Only after the
+ # sandbox is fully reachable, mirroring create_sandbox_for_repository: the
+ # failure paths above destroy the sandbox, and those must not enter the ledger.
+ open_sandbox_session(
+ run_id=ctx.run_id, sandbox_id=sandbox.id, config=sandbox.config, sandbox_created_at=sandbox_created_at
+ )
+
activity.logger.info(f"Created sandbox {sandbox.id} (used_snapshot={used_snapshot})")
return GetSandboxForRepositoryOutput(
diff --git a/products/tasks/backend/temporal/process_task/activities/provision_sandbox.py b/products/tasks/backend/temporal/process_task/activities/provision_sandbox.py
index 710d801ad4b2..cddab3fc97fb 100644
--- a/products/tasks/backend/temporal/process_task/activities/provision_sandbox.py
+++ b/products/tasks/backend/temporal/process_task/activities/provision_sandbox.py
@@ -4,6 +4,7 @@ from dataclasses import dataclass
from typing import Any
from django.conf import settings
+from django.utils import timezone
from temporalio import activity
@@ -18,6 +19,7 @@ from products.tasks.backend.logic.services.connection_token import (
get_sandbox_jwt_public_key,
)
from products.tasks.backend.logic.services.sandbox import Sandbox, SandboxConfig, SandboxTemplate
+from products.tasks.backend.logic.services.sandbox_usage import open_sandbox_session
from products.tasks.backend.models import SandboxSnapshot, Task, TaskRun
from products.tasks.backend.temporal.metrics import (
StepTimer,
@@ -570,6 +572,9 @@ def create_sandbox_for_repository(input: CreateSandboxForRepositoryInput) -> Cre
with StepTimer("sandbox_creation", used_snapshot=prepared.used_snapshot) as sandbox_creation_timer:
sandbox = Sandbox.create(config)
+ # The provider's TTL clock starts here — the usage ledger anchors its
+ # kill deadline on this boundary, not on when the row is opened below.
+ sandbox_created_at = timezone.now()
actual_used_snapshot = bool(
(prepared.snapshot_external_id or prepared.snapshot_id) and sandbox.config.snapshot_restored
)
@@ -603,6 +608,13 @@ def create_sandbox_for_repository(input: CreateSandboxForRepositoryInput) -> Cre
sandbox.destroy()
raise
+ # Best-effort usage-ledger row (swallows its own failures). After the state
+ # write on purpose: the except branch above destroys sandboxes that never
+ # became reachable, and those must not enter the ledger.
+ open_sandbox_session(
+ run_id=ctx.run_id, sandbox_id=sandbox.id, config=sandbox.config, sandbox_created_at=sandbox_created_at
+ )
+
emit_agent_log(ctx.run_id, "debug", f"Sandbox provisioned: {sandbox.id}")
activity.logger.info(f"Created sandbox {sandbox.id} (used_snapshot={actual_used_snapshot})")
diff --git a/products/tasks/backend/temporal/process_task/tests/test_forward_pending_message.py b/products/tasks/backend/temporal/process_task/tests/test_forward_pending_message.py
index a464f25054ab..75441e4e1082 100644
--- a/products/tasks/backend/temporal/process_task/tests/test_forward_pending_message.py
+++ b/products/tasks/backend/temporal/process_task/tests/test_forward_pending_message.py
@@ -1,4 +1,5 @@
import importlib
+from datetime import timedelta
from types import SimpleNamespace
from typing import ClassVar
@@ -6,6 +7,7 @@ from unittest.mock import patch
from django.apps import apps
from django.test import TestCase
+from django.utils import timezone
from parameterized import parameterized
from prometheus_client import REGISTRY
@@ -16,7 +18,7 @@ from posthog.models.organization import Organization
from posthog.models.team.team import Team
from posthog.models.user import User
-from products.tasks.backend.models import Task, TaskRun
+from products.tasks.backend.models import SandboxSession, Task, TaskRun
_module = importlib.import_module("products.tasks.backend.temporal.process_task.activities.forward_pending_message")
@@ -107,6 +109,33 @@ class TestForwardPendingUserMessage(TestCase):
assert "pending_user_message" not in run.state
assert "pending_user_message_id" not in run.state
+ @patch("products.tasks.backend.logic.services.connection_token.create_sandbox_connection_token", return_value="jwt")
+ @patch("products.tasks.backend.logic.services.agent_command.send_user_message")
+ def test_successful_delivery_attributes_sandbox_usage(self, mock_send, mock_token):
+ run = self._make_run(
+ state={
+ "await_user_message": True,
+ "pending_user_message": "fix the tests",
+ "sandbox_url": "https://sandbox.example.com/rpc",
+ }
+ )
+ SandboxSession.objects.unscoped().create(
+ team=self.team,
+ task_run=run,
+ sandbox_id="sb-fwd",
+ cpu_cores=4.0,
+ memory_gb=16.0,
+ ttl_seconds=3600,
+ ttl_expires_at=timezone.now() + timedelta(seconds=3600),
+ )
+ mock_send.return_value = _command_result(success=True, status_code=200)
+
+ forward_pending_user_message(str(run.id))
+
+ session = SandboxSession.objects.unscoped().get(sandbox_id="sb-fwd")
+ assert session.user_attributed_at is not None
+ assert session.last_user_activity_at is not None
+
@patch("products.tasks.backend.logic.services.connection_token.create_sandbox_connection_token", return_value="jwt")
@patch("products.tasks.backend.temporal.observability.posthoganalytics.capture")
@patch("products.tasks.backend.logic.services.agent_command.send_user_message")