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): add sandbox compute rate card pricing (#76080)

Adam Bowker1b2535988dbd
diff --git a/products/tasks/backend/logic/services/sandbox_pricing.py b/products/tasks/backend/logic/services/sandbox_pricing.py
new file mode 100644
index 000000000000..2f112be4ff12
--- /dev/null
+++ b/products/tasks/backend/logic/services/sandbox_pricing.py
@@ -0,0 +1,187 @@
+from collections.abc import Sequence
+from dataclasses import dataclass
+from datetime import datetime
+from decimal import ROUND_UP, Decimal
+
+from django.utils import timezone
+
+from products.tasks.backend.models import SandboxSession
+
+
+class ComputeRateCardConfigurationError(ValueError):
+ pass
+
+
+@dataclass(frozen=True)
+class ComputeRateCard:
+ version: str
+ effective_at: datetime
+ expires_at: datetime | None
+ cpu_core_second_usd: Decimal
+ memory_gib_second_usd: Decimal
+
+
+@dataclass(frozen=True)
+class ComputeCostLineItem:
+ rate_card: ComputeRateCard
+ billable_seconds: Decimal
+ cpu_core_seconds: Decimal
+ memory_gib_seconds: Decimal
+ cpu_cost_usd: Decimal
+ memory_cost_usd: Decimal
+
+ @property
+ def total_cost_usd(self) -> Decimal:
+ return self.cpu_cost_usd + self.memory_cost_usd
+
+
+@dataclass(frozen=True)
+class SandboxComputeCost:
+ billable_seconds: Decimal
+ cpu_core_seconds: Decimal
+ memory_gib_seconds: Decimal
+ cpu_cost_usd: Decimal
+ memory_cost_usd: Decimal
+ line_items: tuple[ComputeCostLineItem, ...]
+
+ @property
+ def total_cost_usd(self) -> Decimal:
+ return self.cpu_cost_usd + self.memory_cost_usd
+
+
+COMPUTE_RATE_CARDS: tuple[ComputeRateCard, ...] = ()
+
+
+def validate_compute_rate_cards(rate_cards: Sequence[ComputeRateCard]) -> tuple[ComputeRateCard, ...]:
+ cards = tuple(rate_cards)
+ if not cards:
+ raise ComputeRateCardConfigurationError("at least one compute rate card is required")
+
+ versions: set[str] = set()
+ previous: ComputeRateCard | None = None
+ for card in cards:
+ if not card.version or card.version in versions:
+ raise ComputeRateCardConfigurationError("compute rate card versions must be unique and non-empty")
+ if timezone.is_naive(card.effective_at) or (card.expires_at and timezone.is_naive(card.expires_at)):
+ raise ComputeRateCardConfigurationError("compute rate card timestamps must be timezone-aware")
+ if card.expires_at is not None and card.expires_at <= card.effective_at:
+ raise ComputeRateCardConfigurationError("compute rate card expiry must follow its effective timestamp")
+ if card.cpu_core_second_usd <= 0 or card.memory_gib_second_usd <= 0:
+ raise ComputeRateCardConfigurationError("compute rates must be positive")
+ if previous is not None:
+ if previous.expires_at is None:
+ raise ComputeRateCardConfigurationError("only the final compute rate card may omit an expiry")
+ if card.effective_at < previous.expires_at:
+ raise ComputeRateCardConfigurationError("compute rate cards must not overlap")
+ if card.effective_at > previous.expires_at:
+ raise ComputeRateCardConfigurationError("compute rate cards must not contain gaps")
+ versions.add(card.version)
+ previous = card
+
+ if cards[-1].expires_at is not None:
+ raise ComputeRateCardConfigurationError("the final compute rate card must not expire")
+ return cards
+
+
+def calculate_sandbox_compute_cost(
+ session: SandboxSession,
+ reporting_start: datetime,
+ reporting_end: datetime,
+ *,
+ calculated_at: datetime | None = None,
+ rate_cards: Sequence[ComputeRateCard] = COMPUTE_RATE_CARDS,
+) -> SandboxComputeCost:
+ cards = validate_compute_rate_cards(rate_cards)
+ if timezone.is_naive(reporting_start) or timezone.is_naive(reporting_end):
+ raise ValueError("reporting timestamps must be timezone-aware")
+ if reporting_end <= reporting_start:
+ raise ValueError("reporting end must follow reporting start")
+
+ now = calculated_at or timezone.now()
+ if timezone.is_naive(now):
+ raise ValueError("calculation timestamp must be timezone-aware")
+
+ if session.user_attributed_at is None:
+ return _empty_cost()
+
+ pricing_start = max(session.user_attributed_at, cards[0].effective_at)
+ effective_end = min(session.ended_at or now, session.ttl_expires_at)
+ if effective_end <= pricing_start:
+ return _empty_cost()
+
+ actual_duration = _decimal_seconds(effective_end - pricing_start)
+ rounded_duration = actual_duration.to_integral_value(rounding=ROUND_UP)
+
+ def scaled_elapsed(at: datetime) -> Decimal:
+ elapsed = _decimal_seconds(at - pricing_start)
+ if elapsed == 0:
+ return Decimal(0)
+ if elapsed == actual_duration:
+ return rounded_duration
+ return elapsed * rounded_duration / actual_duration
+
+ start = max(pricing_start, reporting_start)
+ stop = min(effective_end, reporting_end)
+ if stop <= start:
+ return _empty_cost()
+
+ segments: list[tuple[ComputeRateCard, Decimal]] = []
+ for card in cards:
+ segment_start = max(start, card.effective_at)
+ segment_stop = min(stop, card.expires_at or stop)
+ if segment_stop > segment_start:
+ segments.append((card, scaled_elapsed(segment_stop) - scaled_elapsed(segment_start)))
+
+ if sum((seconds for _, seconds in segments), Decimal(0)) != scaled_elapsed(stop) - scaled_elapsed(start):
+ raise ComputeRateCardConfigurationError("compute rate cards do not cover the billable window")
+
+ cpu_cores, memory_gib = _billable_resources(session)
+ line_items = tuple(_price_line_item(card, seconds, cpu_cores, memory_gib) for card, seconds in segments)
+ return SandboxComputeCost(
+ billable_seconds=sum((item.billable_seconds for item in line_items), Decimal(0)),
+ cpu_core_seconds=sum((item.cpu_core_seconds for item in line_items), Decimal(0)),
+ memory_gib_seconds=sum((item.memory_gib_seconds for item in line_items), Decimal(0)),
+ cpu_cost_usd=sum((item.cpu_cost_usd for item in line_items), Decimal(0)),
+ memory_cost_usd=sum((item.memory_cost_usd for item in line_items), Decimal(0)),
+ line_items=line_items,
+ )
+
+
+def _decimal_seconds(duration) -> Decimal:
+ return Decimal(duration.days * 86400 + duration.seconds) + Decimal(duration.microseconds) / Decimal(1_000_000)
+
+
+def _billable_resources(session: SandboxSession) -> tuple[Decimal, Decimal]:
+ cpu_cores = session.cpu_request_cores if session.cpu_request_cores is not None else session.cpu_cores
+ memory_gib = (
+ Decimal(session.memory_request_mb) / Decimal(1024)
+ if session.memory_request_mb is not None
+ else Decimal(str(session.memory_gb))
+ )
+ return Decimal(str(cpu_cores)), memory_gib
+
+
+def _price_line_item(
+ card: ComputeRateCard, seconds: Decimal, cpu_cores: Decimal, memory_gib: Decimal
+) -> ComputeCostLineItem:
+ cpu_core_seconds = seconds * cpu_cores
+ memory_gib_seconds = seconds * memory_gib
+ return ComputeCostLineItem(
+ rate_card=card,
+ billable_seconds=seconds,
+ cpu_core_seconds=cpu_core_seconds,
+ memory_gib_seconds=memory_gib_seconds,
+ cpu_cost_usd=cpu_core_seconds * card.cpu_core_second_usd,
+ memory_cost_usd=memory_gib_seconds * card.memory_gib_second_usd,
+ )
+
+
+def _empty_cost() -> SandboxComputeCost:
+ return SandboxComputeCost(
+ billable_seconds=Decimal(0),
+ cpu_core_seconds=Decimal(0),
+ memory_gib_seconds=Decimal(0),
+ cpu_cost_usd=Decimal(0),
+ memory_cost_usd=Decimal(0),
+ line_items=(),
+ )
diff --git a/products/tasks/backend/logic/services/tests/test_sandbox_pricing.py b/products/tasks/backend/logic/services/tests/test_sandbox_pricing.py
new file mode 100644
index 000000000000..04324cdc1343
--- /dev/null
+++ b/products/tasks/backend/logic/services/tests/test_sandbox_pricing.py
@@ -0,0 +1,285 @@
+from datetime import UTC, datetime, timedelta
+from decimal import Decimal
+from types import SimpleNamespace
+
+import pytest
+
+from products.tasks.backend.logic.services.sandbox_pricing import (
+ ComputeRateCard,
+ ComputeRateCardConfigurationError,
+ calculate_sandbox_compute_cost,
+ validate_compute_rate_cards,
+)
+
+EFFECTIVE_AT = datetime(2026, 8, 1, tzinfo=UTC)
+NEXT_RATE_AT = datetime(2026, 9, 1, tzinfo=UTC)
+RATE_V1 = ComputeRateCard(
+ version="2026-08-01",
+ effective_at=EFFECTIVE_AT,
+ expires_at=NEXT_RATE_AT,
+ cpu_core_second_usd=Decimal("0.000011"),
+ memory_gib_second_usd=Decimal("0.0000021"),
+)
+RATE_V2 = ComputeRateCard(
+ version="2026-09-01",
+ effective_at=NEXT_RATE_AT,
+ expires_at=None,
+ cpu_core_second_usd=Decimal("0.000013"),
+ memory_gib_second_usd=Decimal("0.0000024"),
+)
+
+
+def _session(**overrides):
+ defaults = {
+ "created_at": EFFECTIVE_AT,
+ "user_attributed_at": EFFECTIVE_AT,
+ "ended_at": EFFECTIVE_AT + timedelta(seconds=10),
+ "ttl_expires_at": EFFECTIVE_AT + timedelta(hours=6),
+ "vm_runtime": False,
+ "burstable": False,
+ "cpu_cores": 4.0,
+ "memory_gb": 16.0,
+ "cpu_request_cores": None,
+ "memory_request_mb": None,
+ }
+ defaults.update(overrides)
+ return SimpleNamespace(**defaults)
+
+
+def _calculate(session, start=EFFECTIVE_AT, end=EFFECTIVE_AT + timedelta(days=1), **kwargs):
+ return calculate_sandbox_compute_cost(session, start, end, rate_cards=(RATE_V1, RATE_V2), **kwargs)
+
+
+def test_prices_closed_session_from_user_attribution():
+ session = _session(
+ created_at=EFFECTIVE_AT,
+ user_attributed_at=EFFECTIVE_AT + timedelta(seconds=20),
+ ended_at=EFFECTIVE_AT + timedelta(seconds=30),
+ )
+
+ cost = _calculate(session)
+
+ assert cost.billable_seconds == 10
+ assert cost.cpu_core_seconds == Decimal("40.0")
+ assert cost.memory_gib_seconds == Decimal("160.0")
+
+
+def test_unattributed_prewarmed_session_is_not_priced():
+ cost = _calculate(_session(user_attributed_at=None, ended_at=None))
+
+ assert cost.billable_seconds == 0
+ assert cost.total_cost_usd == 0
+
+
+def test_claimed_prewarmed_session_starts_at_attribution():
+ cost = _calculate(
+ _session(
+ created_at=EFFECTIVE_AT,
+ user_attributed_at=EFFECTIVE_AT + timedelta(hours=1),
+ ended_at=EFFECTIVE_AT + timedelta(hours=1, seconds=5),
+ )
+ )
+
+ assert cost.billable_seconds == 5
+
+
+def test_open_session_clamps_to_calculation_time_and_ttl():
+ session = _session(ended_at=None, ttl_expires_at=EFFECTIVE_AT + timedelta(seconds=12))
+
+ before_ttl = _calculate(session, calculated_at=EFFECTIVE_AT + timedelta(seconds=7))
+ after_ttl = _calculate(session, calculated_at=EFFECTIVE_AT + timedelta(seconds=20))
+
+ assert before_ttl.billable_seconds == 7
+ assert after_ttl.billable_seconds == 12
+
+
+def test_reporting_window_clips_cross_period_session_without_negative_duration():
+ session = _session(
+ user_attributed_at=EFFECTIVE_AT - timedelta(hours=1),
+ ended_at=EFFECTIVE_AT + timedelta(hours=2),
+ )
+
+ cost = _calculate(session, EFFECTIVE_AT, EFFECTIVE_AT + timedelta(hours=1))
+ outside = _calculate(session, EFFECTIVE_AT + timedelta(days=1), EFFECTIVE_AT + timedelta(days=2))
+
+ assert cost.billable_seconds == 3600
+ assert outside.billable_seconds == 0
+
+
+ "duration, expected",
+ [(timedelta(microseconds=1), 1), (timedelta(seconds=1), 1), (timedelta(seconds=1, microseconds=1), 2)],
+)
+def test_rounds_each_session_duration_up_to_a_whole_second(duration, expected):
+ assert _calculate(_session(ended_at=EFFECTIVE_AT + duration)).billable_seconds == expected
+
+
+ "resource_overrides, expected_cpu_core_seconds, expected_memory_gib_seconds",
+ [
+ ({"cpu_request_cores": 0.5}, Decimal("5.0"), Decimal("160.0")),
+ ({"memory_request_mb": 1024}, Decimal("40.0"), Decimal("10")),
+ ({}, Decimal("40.0"), Decimal("160.0")),
+ ],
+)
+def test_selects_cpu_and_memory_request_quantities_independently(
+ resource_overrides, expected_cpu_core_seconds, expected_memory_gib_seconds
+):
+ cost = _calculate(_session(**resource_overrides))
+
+ assert cost.cpu_core_seconds == expected_cpu_core_seconds
+ assert cost.memory_gib_seconds == expected_memory_gib_seconds
+
+
+def test_cpu_limit_does_not_change_cost_when_request_is_unchanged():
+ smaller_limit = _calculate(_session(cpu_cores=4.0, cpu_request_cores=0.5))
+ larger_limit = _calculate(_session(cpu_cores=16.0, cpu_request_cores=0.5))
+
+ assert smaller_limit == larger_limit
+
+
+def test_memory_request_mebibytes_are_converted_to_gibibytes_exactly():
+ cost = _calculate(_session(memory_request_mb=384))
+
+ assert cost.memory_gib_seconds == Decimal("3.750")
+
+
[email protected]("vm_runtime", [False, True])
[email protected]("burstable", [False, True])
+def test_runtime_and_burstability_do_not_change_pricing(vm_runtime, burstable):
+ expected = _calculate(_session(cpu_request_cores=0.5, memory_request_mb=1024))
+
+ cost = _calculate(
+ _session(
+ vm_runtime=vm_runtime,
+ burstable=burstable,
+ cpu_request_cores=0.5,
+ memory_request_mb=1024,
+ )
+ )
+
+ assert cost == expected
+
+
+def test_fractional_resources_and_cost_subtotals_remain_exact():
+ cost = _calculate(
+ _session(
+ burstable=True,
+ cpu_request_cores=0.125,
+ memory_request_mb=384,
+ ended_at=EFFECTIVE_AT + timedelta(seconds=3, microseconds=1),
+ )
+ )
+
+ assert cost.cpu_core_seconds == Decimal("0.500")
+ assert cost.memory_gib_seconds == Decimal("1.500")
+ assert cost.cpu_cost_usd == Decimal("0.000005500")
+ assert cost.memory_cost_usd == Decimal("0.0000031500")
+ assert cost.total_cost_usd == cost.cpu_cost_usd + cost.memory_cost_usd
+ assert cost.total_cost_usd == sum((line.total_cost_usd for line in cost.line_items), Decimal(0))
+
+
+def test_rate_boundary_apportions_one_session_without_rounding_twice():
+ session = _session(
+ created_at=NEXT_RATE_AT - timedelta(hours=1),
+ user_attributed_at=NEXT_RATE_AT - timedelta(microseconds=500_000),
+ ended_at=NEXT_RATE_AT + timedelta(microseconds=500_000),
+ ttl_expires_at=NEXT_RATE_AT + timedelta(hours=5),
+ )
+
+ cost = _calculate(session, NEXT_RATE_AT - timedelta(seconds=1), NEXT_RATE_AT + timedelta(seconds=1))
+
+ assert cost.billable_seconds == 1
+ assert len(cost.line_items) == 2
+ assert cost.line_items[0].rate_card.version == RATE_V1.version
+ assert cost.line_items[0].billable_seconds == Decimal("0.5")
+ assert cost.line_items[1].billable_seconds == Decimal("0.5")
+
+
+def test_rate_boundary_apportions_rounded_duration_proportionally():
+ session = _session(
+ created_at=NEXT_RATE_AT - timedelta(hours=1),
+ user_attributed_at=NEXT_RATE_AT - timedelta(microseconds=900_000),
+ ended_at=NEXT_RATE_AT + timedelta(microseconds=300_000),
+ ttl_expires_at=NEXT_RATE_AT + timedelta(hours=5),
+ )
+
+ cost = _calculate(session, NEXT_RATE_AT - timedelta(seconds=1), NEXT_RATE_AT + timedelta(seconds=1))
+
+ assert cost.billable_seconds == 2
+ assert cost.line_items[0].rate_card.version == RATE_V1.version
+ assert cost.line_items[0].billable_seconds == Decimal("1.5")
+ assert cost.line_items[1].rate_card.version == RATE_V2.version
+ assert cost.line_items[1].billable_seconds == Decimal("0.5")
+
+
+def test_rounds_once_before_apportioning_across_reporting_periods():
+ boundary = EFFECTIVE_AT + timedelta(hours=1)
+ session = _session(
+ user_attributed_at=boundary - timedelta(microseconds=600_000),
+ ended_at=boundary + timedelta(microseconds=600_000),
+ )
+
+ first = _calculate(session, EFFECTIVE_AT, boundary)
+ second = _calculate(session, boundary, EFFECTIVE_AT + timedelta(hours=2))
+
+ assert first.billable_seconds == Decimal("1")
+ assert second.billable_seconds == Decimal("1")
+ assert first.billable_seconds + second.billable_seconds == Decimal("2")
+
+
+def test_historical_window_keeps_old_rate_after_new_rate_is_active():
+ historical = _session(
+ created_at=NEXT_RATE_AT - timedelta(hours=1),
+ user_attributed_at=NEXT_RATE_AT - timedelta(seconds=10),
+ ended_at=NEXT_RATE_AT - timedelta(seconds=5),
+ ttl_expires_at=NEXT_RATE_AT + timedelta(hours=5),
+ )
+
+ cost = _calculate(
+ historical,
+ NEXT_RATE_AT - timedelta(days=1),
+ NEXT_RATE_AT,
+ calculated_at=NEXT_RATE_AT + timedelta(days=30),
+ )
+
+ assert cost.line_items[0].rate_card == RATE_V1
+ assert cost.cpu_cost_usd == cost.cpu_core_seconds * RATE_V1.cpu_core_second_usd
+
+
+def test_usage_before_compute_billing_effective_date_is_not_priced():
+ session = _session(
+ user_attributed_at=EFFECTIVE_AT - timedelta(hours=1),
+ ended_at=EFFECTIVE_AT - timedelta(seconds=1),
+ )
+
+ cost = _calculate(session, EFFECTIVE_AT - timedelta(days=1), EFFECTIVE_AT)
+
+ assert cost.billable_seconds == 0
+ assert cost.total_cost_usd == 0
+
+
+ "cards, message",
+ [
+ ((), "at least one"),
+ ((RATE_V1, RATE_V1), "versions"),
+ (
+ (
+ RATE_V1,
+ ComputeRateCard("overlap", NEXT_RATE_AT - timedelta(seconds=1), None, Decimal("1"), Decimal("1")),
+ ),
+ "overlap",
+ ),
+ (
+ (
+ RATE_V1,
+ ComputeRateCard("gap", NEXT_RATE_AT + timedelta(seconds=1), None, Decimal("1"), Decimal("1")),
+ ),
+ "gaps",
+ ),
+ ],
+)
+def test_invalid_missing_overlapping_or_ambiguous_rate_cards_fail_safely(cards, message):
+ with pytest.raises(ComputeRateCardConfigurationError, match=message):
+ validate_compute_rate_cards(cards)