:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
feat(tasks): CPU billing attribution for hogland sandboxes (#87465)
Tom Owers005ade15f273
diff --git a/products/tasks/backend/logic/services/cpu_billing.py b/products/tasks/backend/logic/services/cpu_billing.pynew file mode 100644index 000000000000..4a09644e6f54--- /dev/null+++ b/products/tasks/backend/logic/services/cpu_billing.py@@ -0,0 +1,57 @@+"""Shared CPU-billing sampler plumbing for sandbox providers.++The in-sandbox sampler (``sandbox/images/cpu_billing_sampler.py``, baked into every+image) accumulates ``billed += max(actual_cpu_delta, request_cores * elapsed)`` per+interval — Modal's burstable billing formula — and writes+``"<billed_usec> <cpu_usec> <time_ns>"`` to the state file. Providers differ only in+how they read files out of the sandbox, so the command construction and the+state/floor math live here and must not fork between backends.+"""++from __future__ import annotations++import shlex++CPU_BILLING_STATE_PATH = "/tmp/posthog-cpu-billing.state"+CPU_BILLING_SAMPLER_PATH = "/usr/local/bin/posthog-cpu-billing-sampler"+++def build_sampler_start_command(request_cores: float) -> str:+ """Detached sampler launch plus a short poll for its first state write."""+ return (+ 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"+ )+++def parse_cpu_stat_usage_usec(cpu_stat: str) -> int | None:+ for line in cpu_stat.splitlines():+ key, _, value = line.partition(" ")+ if key == "usage_usec":+ try:+ return int(value)+ except ValueError:+ return None+ return None+++def compute_billed_cpu_usage_usec(+ state_text: str,+ current_cpu_usec: int,+ request_cores: float,+ now_ns: int,+) -> int | None:+ """Accumulated billed usage, topped up for the window since the sampler's last write."""+ values = state_text.split()+ if len(values) != 3:+ return None+ try:+ billed_usec, previous_cpu, previous_time = (int(value) for value in values)+ except ValueError:+ return None+ elapsed_ns = max(0, now_ns - previous_time)+ floor_usec = round(request_cores * elapsed_ns / 1000)+ return billed_usec + max(current_cpu_usec - previous_cpu, floor_usec)diff --git a/products/tasks/backend/logic/services/hogland_sandbox.py b/products/tasks/backend/logic/services/hogland_sandbox.pyindex e294604dfcfc..0db664a71787 100644--- a/products/tasks/backend/logic/services/hogland_sandbox.py+++ b/products/tasks/backend/logic/services/hogland_sandbox.py@@ -18,6 +18,7 @@ Transport differences from Modal, handled by the callers that readfrom __future__ import annotations+import timeimport uuidimport shleximport logging@@ -41,7 +42,14 @@ from products.tasks.backend.exceptions import ()from products.tasks.backend.logic.services.agent_server_launcher import AGENT_SERVER_PORT, AgentServerLaunchMixinfrom products.tasks.backend.logic.services.agentsh import AGENTSH_DAEMON_PORT+from products.tasks.backend.logic.services.cpu_billing import (+ CPU_BILLING_STATE_PATH,+ build_sampler_start_command,+ compute_billed_cpu_usage_usec,+ parse_cpu_stat_usage_usec,+)from products.tasks.backend.logic.services.sandbox import redact_sandbox_command+from products.tasks.backend.logic.services.sandbox_config import BURSTABLE_REQUEST_CPU_CORESfrom .sandbox import AgentServerResult, ExecutionResult, ExecutionStream, SandboxConfig, SandboxStatus, SandboxTemplate@@ -422,6 +430,37 @@ class HoglandSandbox(AgentServerLaunchMixin):def prune_snapshot_heavy_dirs(self, path: str) -> None:"""No-op: hogland snapshots are block-level and have no file-count cap."""+ def read_cpu_usage_usec(self) -> int | None:+ # Must go through exec: hogpanion's file endpoint sets Content-Length from+ # stat(), and sysfs files stat as size 0, so read_file returns an empty body.+ result = self.execute("cat /sys/fs/cgroup/cpu.stat", timeout_seconds=10)+ if result.exit_code != 0:+ return None+ return parse_cpu_stat_usage_usec(result.stdout)++ def _cpu_billing_request_cores(self) -> float:+ # Hogland reserves request == limit, so its own billing floor would be the full+ # box. Running the sampler with Modal's default burstable floor instead makes+ # provider_billed_* mean "what Modal would have billed this same workload" —+ # the like-for-like number the platform cost comparison needs. Fixed constant+ # rather than config so a get_by_id-synthesized config reads the same floor.+ return BURSTABLE_REQUEST_CPU_CORES++ def start_cpu_billing_sampler(self) -> bool:+ result = self.execute(build_sampler_start_command(self._cpu_billing_request_cores()), timeout_seconds=10)+ return result.exit_code == 0++ def read_billed_cpu_usage_usec(self) -> int | None:+ try:+ # The state file is a regular file, so read_file works here.+ state_text = self._box.read_file(CPU_BILLING_STATE_PATH).decode()+ except Exception:+ return None+ current_cpu = self.read_cpu_usage_usec()+ if current_cpu is None:+ return None+ return compute_billed_cpu_usage_usec(state_text, current_cpu, self._cpu_billing_request_cores(), time.time_ns())+@staticmethoddef delete_snapshot(external_id: str) -> None:logger.info(f"Ignoring delete for hogland snapshot {external_id}; hogland snapshots are unreachable in MVP")diff --git a/products/tasks/backend/logic/services/modal_sandbox.py b/products/tasks/backend/logic/services/modal_sandbox.pyindex 908495c2dd4a..6181e79a652b 100644--- a/products/tasks/backend/logic/services/modal_sandbox.py+++ b/products/tasks/backend/logic/services/modal_sandbox.py@@ -52,6 +52,13 @@ from products.tasks.backend.exceptions import (SnapshotFileLimitExceededError,SnapshotTimeoutError,)+from products.tasks.backend.logic.services.cpu_billing import (+ CPU_BILLING_SAMPLER_PATH as CPU_BILLING_SAMPLER_PATH,+ CPU_BILLING_STATE_PATH,+ build_sampler_start_command,+ compute_billed_cpu_usage_usec,+ parse_cpu_stat_usage_usec,+)from products.tasks.backend.logic.services.local_packages import (LocalPackage,get_local_package_runtime_dependencies,@@ -95,8 +102,6 @@ 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"@@ -1374,11 +1379,8 @@ class ModalSandbox(AgentServerLaunchMixin):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)+ if cpu_stat is not None and (usage := parse_cpu_stat_usage_usec(cpu_stat)) is not None:+ return usagetry:cpuacct_usage = self._sandbox.filesystem.read_text("/sys/fs/cgroup/cpuacct/cpuacct.usage")if cpuacct_usage.strip():@@ -1387,34 +1389,19 @@ class ModalSandbox(AgentServerLaunchMixin):passreturn None+ def _cpu_billing_request_cores(self) -> float:+ return self.config.effective_cpu_request_cores if self.config.burstable_resources else self.config.cpu_cores+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)+ result = self.execute(build_sampler_start_command(self._cpu_billing_request_cores()), timeout_seconds=10)return result.exit_code == 0def 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)+ state_text = self._sandbox.filesystem.read_text(CPU_BILLING_STATE_PATH)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)+ return compute_billed_cpu_usage_usec(state_text, current_cpu, self._cpu_billing_request_cores(), time.time_ns())def is_running(self) -> bool:return self.get_status() == SandboxStatus.RUNNINGdiff --git a/products/tasks/backend/logic/services/sandbox_usage.py b/products/tasks/backend/logic/services/sandbox_usage.pyindex 225ec744fdea..e81dc7ba5ec4 100644--- a/products/tasks/backend/logic/services/sandbox_usage.py+++ b/products/tasks/backend/logic/services/sandbox_usage.py@@ -136,6 +136,7 @@ def open_sandbox_session("origin_product": run.task.origin_product,"prewarmed": bool(state.get("prewarmed")),"vm_runtime": config.is_vm,+ "sandbox_backend": state.get("sandbox_backend"),"cpu_cores": config.cpu_cores,"memory_gb": config.memory_gb,"ttl_seconds": config.ttl_seconds,@@ -349,9 +350,11 @@ def get_task_sandbox_usage_by_team(begin: datetime, end: datetime) -> SandboxUsaOnly 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+ apportion across them. A Modal end is clamped to ``ttl_expires_at`` — the providerkills the sandbox by then regardless, whether cleanup never ran (crashedworkflows), stamped late, or the session is genuinely live (clamped to now).+ Hogland's TTL is an idle timeout, not a kill deadline, so hogland rows keep their+ real end time.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-secondmetrics use the configured limits; burstable request floors are recorded on the@@ -365,14 +368,30 @@ def get_task_sandbox_usage_by_team(begin: datetime, end: datetime) -> SandboxUsauser_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))+ .filter(+ Q(ended_at__isnull=True, ttl_expires_at__gt=begin)+ # An open hogland box extends its idle TTL on every proxied request, so+ # ttl_expires_at can fall before the period while the box still runs. The+ # first clause would drop it and bill zero for every later period. Keep an+ # open hogland row for any period after it started; the loop bills it to now.+ # Bounded by created_at so a never-closed row can't grow the scan without bound.+ | Q(sandbox_backend="hogland", ended_at__isnull=True, created_at__lte=end)+ | Q(ended_at__gt=begin)+ ))usage: dict[int, list[float]] = {}for session in sessions.iterator():assert session.user_attributed_at is not Nonestart = max(session.user_attributed_at, begin)- effective_end = min(session.ended_at or now, session.ttl_expires_at)+ end_time = session.ended_at or now+ # Modal's TTL is a hard kill deadline, so its end clamps to ttl_expires_at. Hogland's+ # TTL is an idle timeout that every proxied request extends, so a hogland box can+ # outlive created_at + ttl_seconds; clamping there would undercount its billed window.+ if session.sandbox_backend == "hogland":+ effective_end = end_time+ else:+ effective_end = min(end_time, session.ttl_expires_at)stop = min(effective_end, end)if stop <= start:continuediff --git a/products/tasks/backend/logic/services/tests/test_hogland_sandbox.py b/products/tasks/backend/logic/services/tests/test_hogland_sandbox.pyindex ce6e9a63bd11..dcc89645b261 100644--- a/products/tasks/backend/logic/services/tests/test_hogland_sandbox.py+++ b/products/tasks/backend/logic/services/tests/test_hogland_sandbox.py@@ -13,6 +13,7 @@ from products.tasks.backend.exceptions import (SandboxTimeoutError,SnapshotCreationError,)+from products.tasks.backend.logic.services.cpu_billing import CPU_BILLING_STATE_PATHfrom products.tasks.backend.logic.services.hogland_sandbox import (_STATIC_BOX_ENV,HoglandSandbox,@@ -226,6 +227,64 @@ class TestSandboxIdPrefixDispatch:assert (resolved is HoglandSandbox) == expect_hogland+class TestHoglandCpuBilling:+ def test_cpu_usage_reads_cgroup_via_exec_not_read_file(self):+ # hogpanion's file endpoint returns an empty body for sysfs paths (stat size 0),+ # so a read_file port of the Modal code would silently zero all attribution.+ box = _mock_box()+ box.exec.return_value = _exec_result(stdout="usage_usec 123456\nuser_usec 100\n")+ sandbox = _running_sandbox(box)++ assert sandbox.read_cpu_usage_usec() == 123456+ assert box.exec.call_args.args[0] == ["bash", "-c", "cat /sys/fs/cgroup/cpu.stat"]+ box.read_file.assert_not_called()++ def test_cpu_usage_returns_none_when_cgroup_read_fails(self):+ box = _mock_box()+ box.exec.return_value = _exec_result(exit_code=1)+ assert _running_sandbox(box).read_cpu_usage_usec() is None++ def test_sampler_and_billed_read_use_the_modal_equivalent_floor(self):+ # The floor must stay Modal's 0.5-core burstable default, not hogland's+ # 4-core reservation — otherwise the like-for-like billed number inflates 8x.+ box = _mock_box()+ box.exec.return_value = _exec_result()+ sandbox = _running_sandbox(box)++ assert sandbox.start_cpu_billing_sampler() is True+ assert " 0.5 " in box.exec.call_args.args[0][2]++ @parameterized.expand(+ [+ # Busy window: actual delta (2_000_000) beats the 0.5-core floor (500_000).+ ("busy", "1000000 5000000 1000", 7_000_000, 1_000_000_000 + 1000, 1_000_000 + 2_000_000),+ # Idle window: floor tops up — 0.5 cores over 1s of elapsed ns = 500_000 usec.+ ("idle", "1000000 5000000 1000", 5_000_100, 1_000_000_000 + 1000, 1_000_000 + 500_000),+ ]+ )+ def test_billed_usage_math(self, _name, state, current_cpu, now_ns, expected):+ box = _mock_box()+ box.read_file.return_value = state.encode()+ box.exec.return_value = _exec_result(stdout=f"usage_usec {current_cpu}\n")+ sandbox = _running_sandbox(box)++ with patch("products.tasks.backend.logic.services.hogland_sandbox.time.time_ns", return_value=now_ns):+ assert sandbox.read_billed_cpu_usage_usec() == expected+ box.read_file.assert_called_once_with(CPU_BILLING_STATE_PATH)++ @parameterized.expand([("malformed_state", "1 2"), ("empty_state", "")])+ def test_billed_usage_returns_none_on_bad_state(self, _name, state):+ box = _mock_box()+ box.read_file.return_value = state.encode()+ box.exec.return_value = _exec_result(stdout="usage_usec 1\n")+ assert _running_sandbox(box).read_billed_cpu_usage_usec() is None++ def test_billed_usage_returns_none_when_state_file_is_gone(self):+ box = _mock_box()+ box.read_file.side_effect = NotFoundError("gone", status_code=404)+ assert _running_sandbox(box).read_billed_cpu_usage_usec() is None++class TestHoglandAuthPrecedence:def test_file_mode_builds_an_uncached_client_from_the_current_file_contents(self, tmp_path):token_path = tmp_path / "token"diff --git a/products/tasks/backend/logic/services/tests/test_sandbox_usage.py b/products/tasks/backend/logic/services/tests/test_sandbox_usage.pyindex aa1a9fdd321f..f32318ace434 100644--- a/products/tasks/backend/logic/services/tests/test_sandbox_usage.py+++ b/products/tasks/backend/logic/services/tests/test_sandbox_usage.py@@ -554,6 +554,45 @@ class TestSandboxUsageAggregation(SandboxUsageBase):assert usage.seconds == [(self.team.id, 6 * 3600)]+ @parameterized.expand([("hogland", 9 * 3600), (None, 6 * 3600)])+ def test_ttl_clamp_skips_hogland_but_holds_for_modal(self, sandbox_backend, expected_seconds):+ # Hogland's ttl_seconds is an idle timeout that every request extends, so a box can+ # end well after created_at + ttl_seconds; its billed window must keep the true end.+ # Modal's hard TTL is a kill deadline, so a Modal row still clamps to it.+ 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,+ sandbox_backend=sandbox_backend,+ )++ usage = get_task_sandbox_usage_by_team(self.BEGIN, self.END)++ assert usage.seconds == [(self.team.id, expected_seconds)]++ @parameterized.expand([("hogland", 24 * 3600), (None, None)])+ def test_open_session_past_its_ttl_bills_for_hogland_but_not_modal(self, sandbox_backend, expected_seconds):+ # An open hogland box keeps extending its idle TTL, so ttl_expires_at can fall before+ # the period while the box still runs. The open-arm TTL bound would drop it, so a+ # hogland arm keeps it and bills the whole period. A Modal row with the same+ # expired-TTL shape stays excluded, since its TTL is a hard kill deadline.+ self._session(+ created_at=datetime(2025, 12, 20, 1, tzinfo=UTC),+ user_attributed_at=datetime(2025, 12, 20, 1, tzinfo=UTC),+ ended_at=None,+ ttl_seconds=6 * 60 * 60,+ sandbox_backend=sandbox_backend,+ )++ with freeze_time("2026-01-05T00:00:00Z"):+ usage = get_task_sandbox_usage_by_team(self.BEGIN, self.END)++ if expected_seconds is None:+ assert usage.seconds == []+ else:+ assert usage.seconds == [(self.team.id, expected_seconds)]+def test_live_session_clamps_to_now(self):self._session(created_at=datetime(2026, 1, 2, 1, tzinfo=UTC),diff --git a/products/tasks/backend/migrations/0106_sandboxsession_sandbox_backend.py b/products/tasks/backend/migrations/0106_sandboxsession_sandbox_backend.pynew file mode 100644index 000000000000..cc1ce8fcd989--- /dev/null+++ b/products/tasks/backend/migrations/0106_sandboxsession_sandbox_backend.py@@ -0,0 +1,18 @@+from django.db import migrations, models+++class Migration(migrations.Migration):+ dependencies = [("tasks", "0105_taskrun_webhook_lookup_indexes")]++ operations = [+ migrations.AddField(+ model_name="sandboxsession",+ name="sandbox_backend",+ field=models.CharField(+ blank=True,+ help_text="Provider backend (e.g. hogland); NULL for Modal. Hogland's TTL is idle, not absolute",+ max_length=32,+ null=True,+ ),+ ),+ ]diff --git a/products/tasks/backend/migrations/max_migration.txt b/products/tasks/backend/migrations/max_migration.txtindex 25bea1ad8b2a..0100e5715935 100644--- a/products/tasks/backend/migrations/max_migration.txt+++ b/products/tasks/backend/migrations/max_migration.txt@@ -1 +1 @@-0105_taskrun_webhook_lookup_indexes+0106_sandboxsession_sandbox_backenddiff --git a/products/tasks/backend/models.py b/products/tasks/backend/models.pyindex 480e614991c0..912178a8162d 100644--- a/products/tasks/backend/models.py+++ b/products/tasks/backend/models.py@@ -3005,6 +3005,12 @@ class SandboxSession(TeamScopedRootMixin, UUIDModel):vm_runtime = models.BooleanField(default=False, help_text="Modal VM runtime rather than gVisor (billed differently)")+ sandbox_backend = models.CharField(+ max_length=32,+ null=True,+ blank=True,+ help_text="Provider backend (e.g. hogland); NULL for Modal. Hogland's TTL is idle, not absolute",+ )# Resource shape at creation, already clamped by SandboxConfig. Limits are what the# sandbox may consume — raw usage metrics derive from these; the burstable requestdiff --git a/products/tasks/backend/temporal/process_task/activities/provision_sandbox.py b/products/tasks/backend/temporal/process_task/activities/provision_sandbox.pyindex da6fb6e12d7f..2968651ad629 100644--- a/products/tasks/backend/temporal/process_task/activities/provision_sandbox.py+++ b/products/tasks/backend/temporal/process_task/activities/provision_sandbox.py@@ -757,7 +757,9 @@ def _create_sandbox_for_repository(input: CreateSandboxForRepositoryInput) -> Cr# default, but the per-run state can opt out to pin a fixed-size box (request == limit).# The decision is captured once in the context at workflow start, so it's stable across# activity retries.- if ctx.burstable_sandbox_resources_enabled:+ # Hogland reserves request == limit (no bursting); recording the burstable+ # floor would misprice its reserved capacity 8-16x in the usage ledger.+ if ctx.burstable_sandbox_resources_enabled and ctx.sandbox_backend != "hogland":config.burstable_resources = Trueemit_agent_log(ctx.run_id,