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): sample billed sandbox CPU usage (#80976)

Adam Bowker7f7dc6ec1f5e
diff --git a/products/tasks/backend/logic/services/modal_sandbox.py b/products/tasks/backend/logic/services/modal_sandbox.py
index 1023ff261412..0ddfff4b1367 100644
--- a/products/tasks/backend/logic/services/modal_sandbox.py
+++ b/products/tasks/backend/logic/services/modal_sandbox.py
@@ -118,6 +118,9 @@ STREAMLIT_MODAL_APP_NAME = "posthog-sandbox-streamlit"
# a snapshot baked under the default app.
SELF_DRIVING_MODAL_APP_NAME = "posthog-sandbox-self-driving"
+CPU_BILLING_STATE_PATH = "/tmp/posthog-cpu-billing.state"
+CPU_BILLING_SAMPLER_PATH = "/usr/local/bin/posthog-cpu-billing-sampler"
+
SANDBOX_BASE_IMAGE = "ghcr.io/posthog/posthog-sandbox-base"
SANDBOX_NOTEBOOK_IMAGE = "ghcr.io/posthog/posthog-sandbox-notebook"
SANDBOX_VM_IMAGE = "ghcr.io/posthog/posthog-sandbox-vm"
@@ -278,6 +281,7 @@ LOCAL_MODAL_GH_GUARD_SCRIPT = Path("products/tasks/backend/sandbox/images/gh-gua
# so a local build context needs the package and the module that computes the hash.
LOCAL_MODAL_NOTEBOOK_KERNEL_MODULE = Path("products/notebooks/backend/kernel_package.py")
LOCAL_MODAL_NOTEBOOK_KERNEL_DIR = Path("products/notebooks/backend/sandbox/kernel")
+LOCAL_MODAL_CPU_BILLING_SAMPLER = Path("products/tasks/backend/sandbox/images/cpu_billing_sampler.py")
_image_ref_cache: TTLCache = TTLCache(maxsize=3, ttl=300)
@@ -621,6 +625,11 @@ def _prepare_local_modal_build_context(template: SandboxTemplate) -> tuple[str,
destination_gh_guard_path.parent.mkdir(parents=True, exist_ok=True)
shutil.copy2(base_dir / LOCAL_MODAL_GH_GUARD_SCRIPT, destination_gh_guard_path)
+ if template in {SandboxTemplate.DEFAULT_BASE, SandboxTemplate.VM_BASE}:
+ destination_sampler_path = context_dir / LOCAL_MODAL_CPU_BILLING_SAMPLER
+ destination_sampler_path.parent.mkdir(parents=True, exist_ok=True)
+ shutil.copy2(base_dir / LOCAL_MODAL_CPU_BILLING_SAMPLER, destination_sampler_path)
+
if template == SandboxTemplate.DEFAULT_BASE:
source_install_script_path = base_dir / LOCAL_MODAL_INSTALL_SKILLS_SCRIPT
destination_install_script_path = context_dir / LOCAL_MODAL_INSTALL_SKILLS_SCRIPT
@@ -1767,13 +1776,52 @@ class ModalSandbox(SandboxBase):
)
def read_cpu_usage_usec(self) -> int | None:
- cpu_stat = self._sandbox.filesystem.read_text("/sys/fs/cgroup/cpu.stat")
- for line in cpu_stat.splitlines():
- key, _, value = line.partition(" ")
- if key == "usage_usec":
- return int(value)
+ try:
+ cpu_stat = self._sandbox.filesystem.read_text("/sys/fs/cgroup/cpu.stat")
+ except Exception:
+ cpu_stat = None
+ if cpu_stat is not None:
+ for line in cpu_stat.splitlines():
+ key, _, value = line.partition(" ")
+ if key == "usage_usec":
+ return int(value)
+ try:
+ cpuacct_usage = self._sandbox.filesystem.read_text("/sys/fs/cgroup/cpuacct/cpuacct.usage")
+ if cpuacct_usage.strip():
+ return int(cpuacct_usage) // 1000
+ except Exception:
+ pass
return None
+ def start_cpu_billing_sampler(self) -> bool:
+ request_cores = (
+ self.config.effective_cpu_request_cores if self.config.burstable_resources else self.config.cpu_cores
+ )
+ command = (
+ f"rm -f {shlex.quote(CPU_BILLING_STATE_PATH)}; "
+ f"setsid {shlex.quote(CPU_BILLING_SAMPLER_PATH)} "
+ f"{shlex.quote(CPU_BILLING_STATE_PATH)} {shlex.quote(str(request_cores))} "
+ ">/dev/null 2>&1 </dev/null & "
+ f"for _ in $(seq 1 50); do [ -f {shlex.quote(CPU_BILLING_STATE_PATH)} ] && exit 0; sleep 0.02; done; exit 1"
+ )
+ result = self.execute(command, timeout_seconds=10)
+ return result.exit_code == 0
+
+ def read_billed_cpu_usage_usec(self) -> int | None:
+ values = self._sandbox.filesystem.read_text(CPU_BILLING_STATE_PATH).split()
+ if len(values) != 3:
+ return None
+ billed_usec, previous_cpu, previous_time = (int(value) for value in values)
+ current_cpu = self.read_cpu_usage_usec()
+ if current_cpu is None:
+ return None
+ elapsed_ns = max(0, time.time_ns() - previous_time)
+ request_cores = (
+ self.config.effective_cpu_request_cores if self.config.burstable_resources else self.config.cpu_cores
+ )
+ floor_usec = round(request_cores * elapsed_ns / 1000)
+ return billed_usec + max(current_cpu - previous_cpu, floor_usec)
+
def is_running(self) -> bool:
return self.get_status() == SandboxStatus.RUNNING
diff --git a/products/tasks/backend/logic/services/sandbox.py b/products/tasks/backend/logic/services/sandbox.py
index 471c692fb210..2e64fcbac7cc 100644
--- a/products/tasks/backend/logic/services/sandbox.py
+++ b/products/tasks/backend/logic/services/sandbox.py
@@ -551,6 +551,12 @@ class SandboxBase(ABC):
def read_cpu_usage_usec(self) -> int | None:
return None
+ def start_cpu_billing_sampler(self) -> bool:
+ return False
+
+ def read_billed_cpu_usage_usec(self) -> int | None:
+ return None
+
def _read_health_session_init_ms(self, port: int) -> int | None:
try:
result = self.execute(f"curl -s --max-time 5 http://localhost:{port}/health", timeout_seconds=10)
diff --git a/products/tasks/backend/logic/services/sandbox_usage.py b/products/tasks/backend/logic/services/sandbox_usage.py
index 00f2dbeb3c13..6dedb9fac741 100644
--- a/products/tasks/backend/logic/services/sandbox_usage.py
+++ b/products/tasks/backend/logic/services/sandbox_usage.py
@@ -25,6 +25,8 @@ from django.utils import timezone
import structlog
+from posthog.dataclasses import frozen
+
from products.tasks.backend.logic.services.compute_quota import is_billable_compute
from products.tasks.backend.logic.services.sandbox import Sandbox, SandboxBase, SandboxConfig
from products.tasks.backend.logic.services.sandbox_pricing import (
@@ -42,6 +44,13 @@ P = ParamSpec("P")
R = TypeVar("R")
+@frozen
+class SandboxCpuAttribution:
+ cpu_usage_usec: int
+ billed_cpu_usage_usec: int | None
+ measured_at: datetime
+
+
def measure_sandbox_cpu_usage(sandbox: SandboxBase) -> tuple[int | None, datetime | None]:
try:
value = sandbox.read_cpu_usage_usec()
@@ -53,6 +62,15 @@ def measure_sandbox_cpu_usage(sandbox: SandboxBase) -> tuple[int | None, datetim
return value, timezone.now()
+def measure_sandbox_billed_cpu_usage(sandbox: SandboxBase) -> int | None:
+ try:
+ value = sandbox.read_billed_cpu_usage_usec()
+ except Exception:
+ logger.exception("sandbox_usage.billed_cpu_usage_read_failed", sandbox_id=sandbox.id)
+ return None
+ return value if isinstance(value, int) else None
+
+
def _best_effort(fn: Callable[P, R]) -> Callable[P, R | None]:
@wraps(fn)
def wrapper(*args: P.args, **kwargs: P.kwargs) -> R | None:
@@ -66,15 +84,14 @@ def _best_effort(fn: Callable[P, R]) -> Callable[P, R | None]:
@_best_effort
-def measure_task_run_cpu_attribution(run_id: str | UUID, team_id: int) -> dict[str, tuple[int, datetime]]:
+def measure_task_run_cpu_attribution(run_id: str | UUID, team_id: int) -> dict[str, SandboxCpuAttribution]:
run_uuid = run_id if isinstance(run_id, UUID) else UUID(run_id)
sessions = SandboxSession.objects.for_team(team_id).filter(
task_run_id=run_uuid,
ended_at__isnull=True,
user_attributed_at__isnull=True,
- vm_runtime=True,
)
- measurements: dict[str, tuple[int, datetime]] = {}
+ measurements: dict[str, SandboxCpuAttribution] = {}
for session in sessions:
try:
sandbox = Sandbox.get_by_id(session.sandbox_id)
@@ -83,7 +100,11 @@ def measure_task_run_cpu_attribution(run_id: str | UUID, team_id: int) -> dict[s
continue
value, measured_at = measure_sandbox_cpu_usage(sandbox)
if value is not None and measured_at is not None:
- measurements[session.sandbox_id] = (value, measured_at)
+ measurements[session.sandbox_id] = SandboxCpuAttribution(
+ cpu_usage_usec=value,
+ billed_cpu_usage_usec=measure_sandbox_billed_cpu_usage(sandbox),
+ measured_at=measured_at,
+ )
return measurements
@@ -94,6 +115,7 @@ def open_sandbox_session(
config: SandboxConfig,
sandbox_created_at: datetime | None = None,
cpu_usage_attribution_usec: int | None = None,
+ billed_cpu_usage_attribution_usec: int | None = None,
cpu_usage_attribution_measured_at: datetime | None = None,
required: bool = False,
) -> None:
@@ -135,6 +157,9 @@ def open_sandbox_session(
"provider_cpu_usage_attribution_usec": (
None if state.get("await_user_message") else cpu_usage_attribution_usec
),
+ "provider_billed_cpu_usage_attribution_usec": (
+ None if state.get("await_user_message") else billed_cpu_usage_attribution_usec
+ ),
"provider_cpu_usage_attribution_measured_at": (
None if state.get("await_user_message") else cpu_usage_attribution_measured_at
),
@@ -173,6 +198,7 @@ def close_sandbox_session(
*,
reason: str,
cpu_usage_usec: int | None = None,
+ billed_cpu_usage_usec: int | None = None,
cpu_usage_measured_at: datetime | None = None,
) -> None:
"""Stamp the sandbox's end. Idempotent — the first stamp wins."""
@@ -188,6 +214,8 @@ def close_sandbox_session(
if cpu_usage_usec is not None:
updates["provider_cpu_usage_usec"] = cpu_usage_usec
updates["provider_usage_measured_at"] = cpu_usage_measured_at or timezone.now()
+ if billed_cpu_usage_usec is not None:
+ updates["provider_billed_cpu_usage_usec"] = billed_cpu_usage_usec
stamped = (
SandboxSession.objects.unscoped()
.filter(
@@ -204,7 +232,7 @@ def close_sandbox_session(
def record_task_run_user_activity(
run_id: str | UUID,
team_id: int,
- cpu_attribution: dict[str, tuple[int, datetime]] | None = None,
+ cpu_attribution: dict[str, SandboxCpuAttribution] | None = None,
) -> None:
"""Stamp a user message against the run's open sandbox sessions.
@@ -220,10 +248,10 @@ def record_task_run_user_activity(
client_provenance = (
TaskRun.objects.filter(id=run_uuid, team_id=team_id).values_list("task__client_provenance", flat=True).first()
)
- unattributed_sessions = list(open_sessions.filter(user_attributed_at__isnull=True, vm_runtime=True))
+ unattributed_sessions = list(open_sessions.filter(user_attributed_at__isnull=True))
for session in unattributed_sessions:
measurement = (cpu_attribution or {}).get(session.sandbox_id)
- attribution_time = measurement[1] if measurement else now
+ attribution_time = measurement.measured_at if measurement else now
updates: dict[str, object] = {
"user_attributed_at": attribution_time,
"client_provenance": Case(
@@ -232,8 +260,9 @@ def record_task_run_user_activity(
),
}
if measurement:
- updates["provider_cpu_usage_attribution_usec"] = measurement[0]
- updates["provider_cpu_usage_attribution_measured_at"] = measurement[1]
+ updates["provider_cpu_usage_attribution_usec"] = measurement.cpu_usage_usec
+ updates["provider_billed_cpu_usage_attribution_usec"] = measurement.billed_cpu_usage_usec
+ updates["provider_cpu_usage_attribution_measured_at"] = measurement.measured_at
open_sessions.filter(id=session.id, user_attributed_at__isnull=True).update(**updates)
open_sessions.filter(user_attributed_at__isnull=True).update(
diff --git a/products/tasks/backend/logic/services/tests/test_cpu_billing_sampler.py b/products/tasks/backend/logic/services/tests/test_cpu_billing_sampler.py
new file mode 100644
index 000000000000..6454e520aa12
--- /dev/null
+++ b/products/tasks/backend/logic/services/tests/test_cpu_billing_sampler.py
@@ -0,0 +1,22 @@
+from pathlib import Path
+
+import pytest
+
+from products.tasks.backend.sandbox.images import cpu_billing_sampler
+from products.tasks.backend.sandbox.images.cpu_billing_sampler import billed_interval_usec
+
+
+def test_read_cpu_usage_ignores_malformed_lines(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None:
+ cpu_stat = tmp_path / "cpu.stat"
+ cpu_stat.write_text("malformed\ntoo many values here\nusage_usec 1234567\n")
+ monkeypatch.setattr(cpu_billing_sampler, "CPU_STAT_PATH", cpu_stat)
+
+ assert cpu_billing_sampler.read_cpu_usage_usec() == 1_234_567
+
+
+def test_billed_interval_uses_request_floor() -> None:
+ assert billed_interval_usec(0.5, 1_000_000, 1_100_000, 1_000_000_000, 3_000_000_000) == 1_000_000
+
+
+def test_billed_interval_uses_actual_cpu() -> None:
+ assert billed_interval_usec(0.5, 1_000_000, 2_500_000, 1_000_000_000, 3_000_000_000) == 1_500_000
diff --git a/products/tasks/backend/logic/services/tests/test_modal_sandbox.py b/products/tasks/backend/logic/services/tests/test_modal_sandbox.py
index 6f9a51c82f5f..e2f9a75f2bb0 100644
--- a/products/tasks/backend/logic/services/tests/test_modal_sandbox.py
+++ b/products/tasks/backend/logic/services/tests/test_modal_sandbox.py
@@ -17,6 +17,7 @@ from modal.exception import (
ServiceError as ModalServiceError,
TimeoutError as ModalTimeoutError,
)
+from parameterized import parameterized
from requests.exceptions import ConnectionError, Timeout
from products.tasks.backend.constants import DEFAULT_SANDBOX_WORKING_DIR, SNAPSHOT_KIND_DIRECTORY
@@ -36,6 +37,8 @@ from products.tasks.backend.logic.services.modal_provision_diagnostics import (
from products.tasks.backend.logic.services.modal_sandbox import (
_GHCR_RESOLVE_MAX_ATTEMPTS,
AGENT_SERVER_PORT,
+ CPU_BILLING_SAMPLER_PATH,
+ CPU_BILLING_STATE_PATH,
DEFAULT_MODAL_REGION,
DIRECTORY_SNAPSHOT_TIMEOUT_SECONDS,
FILESYSTEM_SNAPSHOT_TIMEOUT_SECONDS,
@@ -1070,6 +1073,68 @@ class TestModalSandboxResourceUsage:
sandbox._sandbox.filesystem.read_text.assert_called_once_with("/sys/fs/cgroup/cpu.stat")
+ def test_reads_cgroup_v1_cpu_usage(self):
+ sandbox = ModalSandbox.__new__(ModalSandbox)
+ sandbox.id = "sb-usage"
+ sandbox.config = SandboxConfig(name="usage")
+ sandbox._sandbox = MagicMock()
+ sandbox._sandbox.filesystem.read_text.side_effect = [FileNotFoundError, "12345678000\n"]
+
+ assert sandbox.read_cpu_usage_usec() == 12_345_678
+
+ def test_returns_none_when_cpu_usage_is_unavailable(self):
+ sandbox = ModalSandbox.__new__(ModalSandbox)
+ sandbox.id = "sb-usage"
+ sandbox.config = SandboxConfig(name="usage")
+ sandbox._sandbox = MagicMock()
+ sandbox._sandbox.filesystem.read_text.side_effect = FileNotFoundError
+
+ assert sandbox.read_cpu_usage_usec() is None
+
+ def test_reads_current_billed_cpu_usage(self, monkeypatch):
+ sandbox = ModalSandbox.__new__(ModalSandbox)
+ sandbox.id = "sb-usage"
+ sandbox.config = SandboxConfig(name="usage", vm_runtime=True, burstable_resources=True)
+ sandbox._sandbox = MagicMock()
+ sandbox._sandbox.filesystem.read_text.side_effect = [
+ "2000000 1000000 1000000000",
+ "usage_usec 2500000\n",
+ ]
+ monkeypatch.setattr("products.tasks.backend.logic.services.modal_sandbox.time.time_ns", lambda: 3000000000)
+
+ assert sandbox.read_billed_cpu_usage_usec() == 3_500_000
+
+ @parameterized.expand(
+ [(True, "0.5"), (False, "4.0")],
+ )
+ def test_starts_cpu_billing_sampler(self, burstable_resources: bool, expected_request: str):
+ sandbox = ModalSandbox.__new__(ModalSandbox)
+ sandbox.id = "sb-usage"
+ sandbox.config = SandboxConfig(
+ name="usage", cpu_cores=4, vm_runtime=True, burstable_resources=burstable_resources
+ )
+ with patch.object(
+ sandbox, "execute", return_value=ExecutionResult(stdout="", stderr="", exit_code=0)
+ ) as execute:
+ assert sandbox.start_cpu_billing_sampler() is True
+ command = execute.call_args.args[0]
+ assert CPU_BILLING_STATE_PATH in command
+ assert CPU_BILLING_SAMPLER_PATH in command
+ assert expected_request in command
+
+ def test_reads_current_billed_cpu_usage_with_fixed_cpu_floor(self, monkeypatch):
+ sandbox = ModalSandbox.__new__(ModalSandbox)
+ sandbox.id = "sb-usage"
+ sandbox.config = SandboxConfig(name="usage", cpu_cores=4, burstable_resources=False)
+ sandbox._sandbox = MagicMock()
+ sandbox._sandbox.filesystem.read_text.side_effect = [
+ "2000000 1000000 1000000000",
+ "usage_usec 1500000\n",
+ ]
+ monkeypatch.setattr("products.tasks.backend.logic.services.modal_sandbox.time.time_ns", lambda: 3000000000)
+
+ assert sandbox.read_billed_cpu_usage_usec() == 10_000_000
+
class TestModalSandboxAgentServerStartupHelpers:
def _make_sandbox(self) -> Any:
diff --git a/products/tasks/backend/logic/services/tests/test_sandbox_usage.py b/products/tasks/backend/logic/services/tests/test_sandbox_usage.py
index 5a249f0922ee..aa1a9fdd321f 100644
--- a/products/tasks/backend/logic/services/tests/test_sandbox_usage.py
+++ b/products/tasks/backend/logic/services/tests/test_sandbox_usage.py
@@ -52,6 +52,7 @@ class TestSandboxSessionWrites(SandboxUsageBase):
sandbox_id="sb-cold",
config=_config(vm_runtime=True),
cpu_usage_attribution_usec=1_234_567,
+ billed_cpu_usage_attribution_usec=1_500_000,
cpu_usage_attribution_measured_at=measured_at,
)
@@ -67,6 +68,7 @@ class TestSandboxSessionWrites(SandboxUsageBase):
assert session.cpu_request_cores is None
assert session.user_attributed_at == measured_at
assert session.provider_cpu_usage_attribution_usec == 1_234_567
+ assert session.provider_billed_cpu_usage_attribution_usec == 1_500_000
assert session.provider_cpu_usage_attribution_measured_at == measured_at
def test_open_leaves_warm_runs_unattributed(self):
@@ -84,11 +86,12 @@ class TestSandboxSessionWrites(SandboxUsageBase):
def test_warm_claim_snapshots_provenance_set_after_provisioning(self):
run = self._run(state={"await_user_message": True, "prewarmed": True})
- open_sandbox_session(run_id=run.id, sandbox_id="sb-warm-claim", config=_config(vm_runtime=True))
+ open_sandbox_session(run_id=run.id, sandbox_id="sb-warm-claim", config=_config(vm_runtime=False))
Task.objects.filter(id=run.task_id).update(client_provenance=TaskClientProvenance.POSTHOG_DESKTOP)
with patch.object(Sandbox, "get_by_id") as get_by_id:
get_by_id.return_value.read_cpu_usage_usec.return_value = 2_345_678
+ get_by_id.return_value.read_billed_cpu_usage_usec.return_value = 3_000_000
cpu_attribution = measure_task_run_cpu_attribution(run.id, self.team.id)
record_task_run_user_activity(run.id, self.team.id, cpu_attribution)
@@ -96,6 +99,7 @@ class TestSandboxSessionWrites(SandboxUsageBase):
assert session.user_attributed_at is not None
assert session.client_provenance == TaskClientProvenance.POSTHOG_DESKTOP
assert session.provider_cpu_usage_attribution_usec == 2_345_678
+ assert session.provider_billed_cpu_usage_attribution_usec == 3_000_000
assert session.provider_cpu_usage_attribution_measured_at == session.user_attributed_at
def test_warm_claim_keeps_provenance_snapshotted_at_provisioning(self):
@@ -232,11 +236,13 @@ class TestSandboxSessionWrites(SandboxUsageBase):
"sb-usage",
reason=SandboxSession.EndedReason.CLEANUP,
cpu_usage_usec=12_345_678,
+ billed_cpu_usage_usec=15_000_000,
cpu_usage_measured_at=measured_at,
)
session = SandboxSession.objects.unscoped().get(sandbox_id="sb-usage")
assert session.provider_cpu_usage_usec == 12_345_678
+ assert session.provider_billed_cpu_usage_usec == 15_000_000
assert session.provider_usage_measured_at == measured_at
def test_user_activity_stamps_open_sessions_only(self):
diff --git a/products/tasks/backend/migrations/0097_sandboxsession_billed_cpu_usage.py b/products/tasks/backend/migrations/0097_sandboxsession_billed_cpu_usage.py
new file mode 100644
index 000000000000..1cbac0cc034a
--- /dev/null
+++ b/products/tasks/backend/migrations/0097_sandboxsession_billed_cpu_usage.py
@@ -0,0 +1,22 @@
+from django.db import migrations, models
+
+
+class Migration(migrations.Migration):
+ dependencies = [("tasks", "0096_taskworkflowdispatch")]
+
+ operations = [
+ migrations.AddField(
+ model_name="sandboxsession",
+ name="provider_billed_cpu_usage_attribution_usec",
+ field=models.PositiveBigIntegerField(
+ blank=True, help_text="Estimated billed CPU time sampled when user attribution starts", null=True
+ ),
+ ),
+ migrations.AddField(
+ model_name="sandboxsession",
+ name="provider_billed_cpu_usage_usec",
+ field=models.PositiveBigIntegerField(
+ blank=True, help_text="Estimated billed CPU time sampled immediately before sandbox cleanup", null=True
+ ),
+ ),
+ ]
diff --git a/products/tasks/backend/migrations/max_migration.txt b/products/tasks/backend/migrations/max_migration.txt
index 37bef8cef259..bf433288d1bb 100644
--- a/products/tasks/backend/migrations/max_migration.txt
+++ b/products/tasks/backend/migrations/max_migration.txt
@@ -1 +1 @@
-0096_taskworkflowdispatch
+0097_sandboxsession_billed_cpu_usage
diff --git a/products/tasks/backend/models.py b/products/tasks/backend/models.py
index 5d2636496580..1b04317a61e5 100644
--- a/products/tasks/backend/models.py
+++ b/products/tasks/backend/models.py
@@ -2791,12 +2791,18 @@ class SandboxSession(TeamScopedRootMixin, UUIDModel):
provider_cpu_usage_attribution_usec = models.PositiveBigIntegerField(
null=True, blank=True, help_text="Cumulative provider CPU time sampled when user attribution starts"
)
+ provider_billed_cpu_usage_attribution_usec = models.PositiveBigIntegerField(
+ null=True, blank=True, help_text="Estimated billed CPU time sampled when user attribution starts"
+ )
provider_cpu_usage_attribution_measured_at = models.DateTimeField(
null=True, blank=True, help_text="When provider CPU usage was sampled at user attribution"
)
provider_cpu_usage_usec = models.PositiveBigIntegerField(
null=True, blank=True, help_text="Cumulative provider CPU time sampled immediately before sandbox cleanup"
)
+ provider_billed_cpu_usage_usec = models.PositiveBigIntegerField(
+ null=True, blank=True, help_text="Estimated billed CPU time sampled immediately before sandbox cleanup"
+ )
provider_usage_measured_at = models.DateTimeField(
null=True, blank=True, help_text="When provider resource usage was sampled"
)
diff --git a/products/tasks/backend/sandbox/images/Dockerfile.sandbox-base b/products/tasks/backend/sandbox/images/Dockerfile.sandbox-base
index 5d0937f57854..731398423156 100644
--- a/products/tasks/backend/sandbox/images/Dockerfile.sandbox-base
+++ b/products/tasks/backend/sandbox/images/Dockerfile.sandbox-base
@@ -179,6 +179,8 @@ RUN chmod +x /opt/posthog/bin/git
# non-interactive `bash -c`; the agent's interactive shell needs this shim).
COPY products/tasks/backend/sandbox/images/gh-guard.sh /opt/posthog/bin/gh
RUN chmod +x /opt/posthog/bin/gh
+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
ENV PATH="/opt/posthog/bin:${PATH}"
# This is required for the Claude Code SDK to allow --dangerously-skip-permissions as the root user
diff --git a/products/tasks/backend/sandbox/images/Dockerfile.sandbox-vm b/products/tasks/backend/sandbox/images/Dockerfile.sandbox-vm
index 9b6a249e697f..d88c1456352a 100644
--- a/products/tasks/backend/sandbox/images/Dockerfile.sandbox-vm
+++ b/products/tasks/backend/sandbox/images/Dockerfile.sandbox-vm
@@ -21,6 +21,9 @@ RUN apt-get update && \
RUN mkdir -p /etc/docker && \
printf '%s\n' '{' ' "storage-driver": "overlay2"' '}' > /etc/docker/daemon.json
+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
+
# There is no init system in the sandbox, so dockerd is launched on demand by
# this idempotent helper rather than by systemd. dockerd is detached with setsid
# and </dev/null so it survives its launching process. On the Modal VM runtime
diff --git a/products/tasks/backend/sandbox/images/cpu_billing_sampler.py b/products/tasks/backend/sandbox/images/cpu_billing_sampler.py
new file mode 100644
index 000000000000..df6aa08eba08
--- /dev/null
+++ b/products/tasks/backend/sandbox/images/cpu_billing_sampler.py
@@ -0,0 +1,57 @@
+#!/usr/bin/env python3
+
+import os
+import sys
+import time
+from pathlib import Path
+
+CPU_STAT_PATH = Path("/sys/fs/cgroup/cpu.stat")
+CPUACCT_USAGE_PATH = Path("/sys/fs/cgroup/cpuacct/cpuacct.usage")
+
+
+def read_cpu_usage_usec() -> int:
+ if CPU_STAT_PATH.exists():
+ for line in CPU_STAT_PATH.read_text().splitlines():
+ parts = line.split()
+ if len(parts) != 2:
+ continue
+ key, value = parts
+ if key == "usage_usec":
+ return int(value)
+ if CPUACCT_USAGE_PATH.exists():
+ return int(CPUACCT_USAGE_PATH.read_text()) // 1000
+ raise RuntimeError("usage_usec missing")
+
+
+def write_state(path: Path, billed_usec: int, cpu_usec: int, time_ns: int) -> None:
+ temporary_path = path.with_suffix(".tmp")
+ temporary_path.write_text(f"{billed_usec} {cpu_usec} {time_ns}")
+ os.replace(temporary_path, path)
+
+
+def billed_interval_usec(
+ request_cores: float, previous_cpu: int, current_cpu: int, previous_time: int, current_time: int
+) -> int:
+ actual_usec = current_cpu - previous_cpu
+ floor_usec = round(request_cores * (current_time - previous_time) / 1000)
+ return max(actual_usec, floor_usec)
+
+
+def run(path: Path, request_cores: float) -> None:
+ previous_cpu = read_cpu_usage_usec()
+ previous_time = time.time_ns()
+ billed_usec = 0
+ write_state(path, billed_usec, previous_cpu, previous_time)
+
+ while True:
+ time.sleep(2)
+ current_cpu = read_cpu_usage_usec()
+ current_time = time.time_ns()
+ billed_usec += billed_interval_usec(request_cores, previous_cpu, current_cpu, previous_time, current_time)
+ write_state(path, billed_usec, current_cpu, current_time)
+ previous_cpu = current_cpu
+ previous_time = current_time
+
+
+if __name__ == "__main__":
+ run(Path(sys.argv[1]), float(sys.argv[2]))
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 0b22caab8e99..2c407269ceb0 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,11 @@ from temporalio import activity
from posthog.temporal.common.utils import asyncify
from products.tasks.backend.logic.services.sandbox import Sandbox
-from products.tasks.backend.logic.services.sandbox_usage import close_sandbox_session, measure_sandbox_cpu_usage
+from products.tasks.backend.logic.services.sandbox_usage import (
+ close_sandbox_session,
+ measure_sandbox_billed_cpu_usage,
+ measure_sandbox_cpu_usage,
+)
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
@@ -65,10 +69,12 @@ def reap_orphaned_sandbox(input: ReapOrphanedSandboxInput) -> ReapOrphanedSandbo
destroy_succeeded = True
cpu_usage_usec = None
+ billed_cpu_usage_usec = None
cpu_usage_measured_at = None
try:
sandbox = Sandbox.get_by_id(sandbox_id)
cpu_usage_usec, cpu_usage_measured_at = measure_sandbox_cpu_usage(sandbox)
+ billed_cpu_usage_usec = measure_sandbox_billed_cpu_usage(sandbox)
sandbox.destroy()
except Exception:
# Modal TTL is the backstop; we still clear state below so the
@@ -82,6 +88,7 @@ def reap_orphaned_sandbox(input: ReapOrphanedSandboxInput) -> ReapOrphanedSandbo
sandbox_id,
reason=SandboxSession.EndedReason.REAPED,
cpu_usage_usec=cpu_usage_usec,
+ billed_cpu_usage_usec=billed_cpu_usage_usec,
cpu_usage_measured_at=cpu_usage_measured_at,
)
diff --git a/products/tasks/backend/temporal/execute_sandbox/activities/tests/test_reap_orphaned_sandbox.py b/products/tasks/backend/temporal/execute_sandbox/activities/tests/test_reap_orphaned_sandbox.py
index ad3972aa4050..90eb68ce664f 100644
--- a/products/tasks/backend/temporal/execute_sandbox/activities/tests/test_reap_orphaned_sandbox.py
+++ b/products/tasks/backend/temporal/execute_sandbox/activities/tests/test_reap_orphaned_sandbox.py
@@ -93,6 +93,7 @@ class TestReapOrphanedSandbox:
):
sandbox = sandbox_cls.get_by_id.return_value
sandbox.read_cpu_usage_usec.return_value = 12_345_678
+ sandbox.read_billed_cpu_usage_usec.return_value = 15_000_000
async_to_sync(activity_environment.run)(
reap_orphaned_sandbox,
@@ -105,6 +106,7 @@ class TestReapOrphanedSandbox:
"sb-orphan",
reason="reaped",
cpu_usage_usec=12_345_678,
+ billed_cpu_usage_usec=15_000_000,
cpu_usage_measured_at=ANY,
)
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 d8a9d5bd16c1..ab550eb850b9 100644
--- a/products/tasks/backend/temporal/process_task/activities/cleanup_sandbox.py
+++ b/products/tasks/backend/temporal/process_task/activities/cleanup_sandbox.py
@@ -7,7 +7,11 @@ 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, measure_sandbox_cpu_usage
+from products.tasks.backend.logic.services.sandbox_usage import (
+ close_sandbox_session,
+ measure_sandbox_billed_cpu_usage,
+ measure_sandbox_cpu_usage,
+)
from products.tasks.backend.logic.stream.redis_stream import publish_task_run_stream_complete
from products.tasks.backend.models import SandboxSession, TaskRun
from products.tasks.backend.redis import run_uses_dedicated_stream
@@ -40,6 +44,7 @@ def cleanup_sandbox_now(input: CleanupSandboxInput) -> None:
strict_cleanup = input.complete_stream_on_cleanup or input.raise_on_error
stream_completion_safe = False
cpu_usage_usec = None
+ billed_cpu_usage_usec = None
cpu_usage_measured_at = None
try:
sandbox = Sandbox.get_by_id(input.sandbox_id)
@@ -69,6 +74,7 @@ def cleanup_sandbox_now(input: CleanupSandboxInput) -> None:
)
cpu_usage_usec, cpu_usage_measured_at = measure_sandbox_cpu_usage(sandbox)
+ billed_cpu_usage_usec = measure_sandbox_billed_cpu_usage(sandbox)
try:
sandbox.destroy()
@@ -80,6 +86,7 @@ def cleanup_sandbox_now(input: CleanupSandboxInput) -> None:
input.sandbox_id,
reason=SandboxSession.EndedReason.CLEANUP,
cpu_usage_usec=cpu_usage_usec,
+ billed_cpu_usage_usec=billed_cpu_usage_usec,
cpu_usage_measured_at=cpu_usage_measured_at,
)
raise
@@ -91,6 +98,7 @@ def cleanup_sandbox_now(input: CleanupSandboxInput) -> None:
input.sandbox_id,
reason=SandboxSession.EndedReason.CLEANUP,
cpu_usage_usec=cpu_usage_usec,
+ billed_cpu_usage_usec=billed_cpu_usage_usec,
cpu_usage_measured_at=cpu_usage_measured_at,
)
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 7f2fd9a14e23..f0af96c9776e 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
@@ -29,7 +29,11 @@ from products.tasks.backend.logic.services.sandbox import (
parse_sandbox_repo_mount_map,
workload_for_origin_product,
)
-from products.tasks.backend.logic.services.sandbox_usage import measure_sandbox_cpu_usage, open_sandbox_session
+from products.tasks.backend.logic.services.sandbox_usage import (
+ measure_sandbox_billed_cpu_usage,
+ measure_sandbox_cpu_usage,
+ open_sandbox_session,
+)
from products.tasks.backend.models import SandboxSnapshot, Task, TaskRun
from products.tasks.backend.temporal.metrics import (
StepTimer,
@@ -336,6 +340,8 @@ def get_sandbox_for_repository(input: GetSandboxForRepositoryInput) -> GetSandbo
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)
+ if not sandbox.start_cpu_billing_sampler():
+ activity.logger.warning("Failed to start sandbox CPU billing sampler", extra={"sandbox_id": sandbox.id})
if sandbox.config.image_fallback:
emit_agent_log(ctx.run_id, "warn", f"Sandbox image downgraded: {sandbox.config.image_fallback}")
if sandbox.launch_dev_stack_bootstrap():
@@ -419,15 +425,15 @@ def get_sandbox_for_repository(input: GetSandboxForRepositoryInput) -> GetSandbo
if credentials.token:
sandbox_state["sandbox_connect_token"] = credentials.token
TaskRun.update_state_atomic(ctx.run_id, updates=sandbox_state)
- cpu_usage_attribution_usec, cpu_usage_attribution_measured_at = (
- measure_sandbox_cpu_usage(sandbox) if sandbox.config.is_vm else (None, None)
- )
+ cpu_usage_attribution_usec, cpu_usage_attribution_measured_at = measure_sandbox_cpu_usage(sandbox)
+ billed_cpu_usage_attribution_usec = measure_sandbox_billed_cpu_usage(sandbox)
open_sandbox_session(
run_id=ctx.run_id,
sandbox_id=sandbox.id,
config=sandbox.config,
sandbox_created_at=sandbox_created_at,
cpu_usage_attribution_usec=cpu_usage_attribution_usec,
+ billed_cpu_usage_attribution_usec=billed_cpu_usage_attribution_usec,
cpu_usage_attribution_measured_at=cpu_usage_attribution_measured_at,
required=ctx.task_runtime == "pi",
)
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 c31b82f4f8ef..540a9b565b57 100644
--- a/products/tasks/backend/temporal/process_task/activities/provision_sandbox.py
+++ b/products/tasks/backend/temporal/process_task/activities/provision_sandbox.py
@@ -56,7 +56,11 @@ from products.tasks.backend.logic.services.sandbox import (
sandbox_repo_path,
workload_for_origin_product,
)
-from products.tasks.backend.logic.services.sandbox_usage import measure_sandbox_cpu_usage, open_sandbox_session
+from products.tasks.backend.logic.services.sandbox_usage import (
+ measure_sandbox_billed_cpu_usage,
+ measure_sandbox_cpu_usage,
+ open_sandbox_session,
+)
from products.tasks.backend.models import SandboxSnapshot, Task, TaskRun
from products.tasks.backend.temporal.metrics import (
StepTimer,
@@ -752,6 +756,8 @@ def _create_sandbox_for_repository(input: CreateSandboxForRepositoryInput) -> Cr
if config.outbound_domain_allowlist is not None:
emit_agent_log(ctx.run_id, "debug", "Modal sandbox created with network policy requested")
record_network_enforcement("sandbox_creation_with_policy_request", runtime, "modal_requested", "success")
+ if not sandbox.start_cpu_billing_sampler():
+ activity.logger.warning("Failed to start sandbox CPU billing sampler", extra={"sandbox_id": sandbox.id})
if sandbox.config.image_fallback:
emit_agent_log(
ctx.run_id,
@@ -795,15 +801,15 @@ def _create_sandbox_for_repository(input: CreateSandboxForRepositoryInput) -> Cr
if credentials.token:
sandbox_state["sandbox_connect_token"] = credentials.token
TaskRun.update_state_atomic(ctx.run_id, updates=sandbox_state)
- cpu_usage_attribution_usec, cpu_usage_attribution_measured_at = (
- measure_sandbox_cpu_usage(sandbox) if sandbox.config.is_vm else (None, None)
- )
+ cpu_usage_attribution_usec, cpu_usage_attribution_measured_at = measure_sandbox_cpu_usage(sandbox)
+ billed_cpu_usage_attribution_usec = measure_sandbox_billed_cpu_usage(sandbox)
open_sandbox_session(
run_id=ctx.run_id,
sandbox_id=sandbox.id,
config=sandbox.config,
sandbox_created_at=sandbox_created_at,
cpu_usage_attribution_usec=cpu_usage_attribution_usec,
+ billed_cpu_usage_attribution_usec=billed_cpu_usage_attribution_usec,
cpu_usage_attribution_measured_at=cpu_usage_attribution_measured_at,
required=ctx.task_runtime == "pi",
)
diff --git a/products/tasks/backend/temporal/process_task/activities/tests/test_cleanup_sandbox.py b/products/tasks/backend/temporal/process_task/activities/tests/test_cleanup_sandbox.py
index f5369ef8b7d8..8215d9cb30f3 100644
--- a/products/tasks/backend/temporal/process_task/activities/tests/test_cleanup_sandbox.py
+++ b/products/tasks/backend/temporal/process_task/activities/tests/test_cleanup_sandbox.py
@@ -29,6 +29,7 @@ def test_cleanup_sandbox_skips_agent_server_shutdown_for_regular_cleanup(activit
def test_cleanup_sandbox_records_cpu_usage_before_destroy(activity_environment, mocker):
sandbox = mocker.Mock(id="sandbox-123")
sandbox.read_cpu_usage_usec.return_value = 12_345_678
+ sandbox.read_billed_cpu_usage_usec.return_value = 15_000_000
mocker.patch.object(Sandbox, "get_by_id", return_value=sandbox)
close_session = mocker.patch(
"products.tasks.backend.temporal.process_task.activities.cleanup_sandbox.close_sandbox_session"
@@ -42,6 +43,7 @@ def test_cleanup_sandbox_records_cpu_usage_before_destroy(activity_environment,
"sandbox-123",
reason="cleanup",
cpu_usage_usec=12_345_678,
+ billed_cpu_usage_usec=15_000_000,
cpu_usage_measured_at=mocker.ANY,
)
@@ -79,6 +81,7 @@ def test_cleanup_sandbox_retries_when_final_destroy_fails(activity_environment,
run_id = str(uuid.uuid4())
sandbox = mocker.Mock(id="sandbox-123")
sandbox.read_cpu_usage_usec.return_value = 12_345_678
+ sandbox.read_billed_cpu_usage_usec.return_value = 15_000_000
sandbox.destroy.side_effect = RuntimeError("destroy failed")
mocker.patch.object(Sandbox, "get_by_id", return_value=sandbox)
close_session = mocker.patch(
@@ -104,6 +107,7 @@ def test_cleanup_sandbox_retries_when_final_destroy_fails(activity_environment,
"sandbox-123",
reason="cleanup",
cpu_usage_usec=12_345_678,
+ billed_cpu_usage_usec=15_000_000,
cpu_usage_measured_at=mocker.ANY,
)
publish_complete.assert_not_called()
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 1ca929ceb7eb..595abc0e63d6 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
@@ -18,6 +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.logic.services.sandbox_usage import SandboxCpuAttribution
from products.tasks.backend.models import SandboxSession, Task, TaskRun
_module = importlib.import_module("products.tasks.backend.temporal.process_task.activities.forward_pending_message")
@@ -142,7 +143,13 @@ class TestForwardPendingUserMessage(TestCase):
def measure(*args):
calls.append("measure")
- return {"sb-fwd": (1_234_567, measured_at)}
+ return {
+ "sb-fwd": SandboxCpuAttribution(
+ cpu_usage_usec=1_234_567,
+ billed_cpu_usage_usec=1_500_000,
+ measured_at=measured_at,
+ )
+ }
def send(*args, **kwargs):
calls.append("send")
@@ -157,6 +164,7 @@ class TestForwardPendingUserMessage(TestCase):
assert session.user_attributed_at is not None
assert session.last_user_activity_at is not None
assert session.provider_cpu_usage_attribution_usec == 1_234_567
+ assert session.provider_billed_cpu_usage_attribution_usec == 1_500_000
assert session.provider_cpu_usage_attribution_measured_at == measured_at
assert calls == ["measure", "send"]
diff --git a/products/tasks/backend/tests/test_api.py b/products/tasks/backend/tests/test_api.py
index 03cef551d9e2..f557c6c2f24c 100644
--- a/products/tasks/backend/tests/test_api.py
+++ b/products/tasks/backend/tests/test_api.py
@@ -7988,7 +7988,12 @@ class TestTaskRunCancelAPI(BaseTaskAPITest):
self.assertEqual(response.status_code, status.HTTP_202_ACCEPTED)
self.assertEqual(
sandbox.method_calls,
- [call.stop_agent_server(), call.read_cpu_usage_usec(), call.destroy()],
+ [
+ call.stop_agent_server(),
+ call.read_cpu_usage_usec(),
+ call.read_billed_cpu_usage_usec(),
+ call.destroy(),
+ ],
)
publish_complete.assert_called_once_with(str(run.id), False)
run.refresh_from_db()
@@ -8021,7 +8026,12 @@ class TestTaskRunCancelAPI(BaseTaskAPITest):
self.assertEqual(response.status_code, status.HTTP_503_SERVICE_UNAVAILABLE)
self.assertEqual(
sandbox.method_calls,
- [call.stop_agent_server(), call.read_cpu_usage_usec(), call.destroy()],
+ [
+ call.stop_agent_server(),
+ call.read_cpu_usage_usec(),
+ call.read_billed_cpu_usage_usec(),
+ call.destroy(),
+ ],
)
publish_complete.assert_not_called()
run.refresh_from_db()
@@ -8053,7 +8063,12 @@ class TestTaskRunCancelAPI(BaseTaskAPITest):
self.assertEqual(second_response.status_code, status.HTTP_200_OK)
self.assertEqual(
sandbox.method_calls,
- [call.stop_agent_server(), call.read_cpu_usage_usec(), call.destroy()],
+ [
+ call.stop_agent_server(),
+ call.read_cpu_usage_usec(),
+ call.read_billed_cpu_usage_usec(),
+ call.destroy(),
+ ],
)
self.assertEqual(publish_complete.call_count, 2)
run.refresh_from_db()