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.

fix(tasks): read eu task token cost from the eu project (#130308)

Vojta Bartoš7028f8554fd9
diff --git a/products/tasks/backend/logic/services/task_usage.py b/products/tasks/backend/logic/services/task_usage.py
index 5ef4d85d8c3d..424795b6bb52 100644
--- a/products/tasks/backend/logic/services/task_usage.py
+++ b/products/tasks/backend/logic/services/task_usage.py
@@ -1,5 +1,4 @@
import hmac
-import json
import time
import hashlib
from collections.abc import Sequence
@@ -12,7 +11,6 @@ from django.conf import settings
from django.core.cache import cache
from django.utils import timezone
-import requests
import structlog
from posthog.hogql import ast
@@ -32,7 +30,6 @@ from products.tasks.backend.models import SandboxSession, Task, TaskClientProven
TASK_USAGE_SIGNATURE_HEADER = "X-PostHog-Task-Usage-Signature"
TASK_USAGE_TIMESTAMP_HEADER = "X-PostHog-Task-Usage-Timestamp"
-TASK_USAGE_CROSS_REGION_TIMEOUT_SECONDS = (3, 15)
TASK_USAGE_INTERNAL_PATH = "/api/code/internal/task_usage/"
TASK_TOKEN_COST_CACHE_TIMEOUT_SECONDS = 60
@@ -79,12 +76,7 @@ def _get_task_token_cost(*, team_id: int, task_id: UUID, task_created_at: dateti
if cached is not None:
return Decimal(str(cached))
- if settings.CLOUD_DEPLOYMENT == "EU":
- token_cost = _get_cross_region_task_token_cost(
- team_id=team_id, task_id=task_id, task_created_at=task_created_at
- )
- else:
- token_cost = get_local_task_token_cost(team_id=team_id, task_id=task_id, task_created_at=task_created_at)
+ token_cost = get_local_task_token_cost(team_id=team_id, task_id=task_id, task_created_at=task_created_at)
cache.set(cache_key, str(token_cost), timeout=TASK_TOKEN_COST_CACHE_TIMEOUT_SECONDS)
return token_cost
@@ -93,35 +85,6 @@ def _task_token_cost_cache_key(*, team_id: int, task_id: UUID, task_created_at:
return f"task_token_cost:v2:{team_id}:{task_id}:{task_created_at.isoformat()}"
-def _get_cross_region_task_token_cost(*, team_id: int, task_id: UUID, task_created_at: datetime) -> Decimal:
- secret = settings.PERSONAL_SPEND_CROSS_REGION_SECRET
- if not secret:
- logger.error("task_usage.cross_region_not_configured")
- raise TaskTokenUsageUnavailable("Cross-region task usage is not configured")
-
- body = json.dumps(
- {"team_id": team_id, "task_id": str(task_id), "task_created_at": task_created_at.isoformat()}
- ).encode()
- signed = sign_task_usage_request(body, secret)
- target = f"{settings.SITE_URL if settings.DEBUG else 'https://us.posthog.com'}{TASK_USAGE_INTERNAL_PATH}"
- try:
- response = requests.post(
- target,
- data=body,
- headers={
- "Content-Type": "application/json",
- TASK_USAGE_SIGNATURE_HEADER: signed.signature,
- TASK_USAGE_TIMESTAMP_HEADER: signed.timestamp,
- },
- timeout=TASK_USAGE_CROSS_REGION_TIMEOUT_SECONDS,
- )
- response.raise_for_status()
- return Decimal(str(response.json()["token_cost_usd"]))
- except (requests.RequestException, ValueError, KeyError, TypeError) as error:
- logger.exception("task_usage.cross_region_request_failed", error_type=type(error).__name__)
- raise TaskTokenUsageUnavailable("Cross-region task usage is unavailable") from error
-
-
# The internal project the gateways capture `$ai_generation` into is region-local: each region's
# generations land in that region's own project. Same mapping AI credit billing reads
# (`CLOUD_REGION_TO_TEAM_ID` in `posthog/tasks/usage_report.py`), kept separately because that
diff --git a/products/tasks/backend/logic/services/tests/test_task_usage.py b/products/tasks/backend/logic/services/tests/test_task_usage.py
index 780239d6ce6e..6111f77cdd47 100644
--- a/products/tasks/backend/logic/services/tests/test_task_usage.py
+++ b/products/tasks/backend/logic/services/tests/test_task_usage.py
@@ -1,4 +1,3 @@
-import json
from datetime import UTC, datetime, timedelta
from decimal import Decimal
from types import SimpleNamespace
@@ -47,6 +46,7 @@ class TestTaskUsageQueryTagging(SimpleTestCase):
# A region's generations are captured into the internal project in that same region, and
# `LLM_ANALYTICS_INTERNAL_TEAM_ID` is 2 in both — reading it in the EU would price every EU
# run at zero.
+ cache.clear()
with (
self.settings(CLOUD_DEPLOYMENT=region, LLM_ANALYTICS_INTERNAL_TEAM_ID=2),
patch.object(task_usage.Team.objects, "get", return_value=object()) as team_get,
@@ -59,8 +59,13 @@ class TestTaskUsageQueryTagging(SimpleTestCase):
generated_after=datetime(2026, 8, 1, tzinfo=UTC),
product=Product.SIGNALS,
)
+ task_usage._get_task_token_cost(
+ team_id=1,
+ task_id=UUID("00000000-0000-0000-0000-000000000002"),
+ task_created_at=datetime(2026, 8, 1, tzinfo=UTC),
+ )
- assert team_get.call_args.kwargs["pk"] == expected_team_id
+ assert [call.kwargs["pk"] for call in team_get.call_args_list] == [expected_team_id, expected_team_id]
def test_costs_are_unavailable_outside_a_billing_region(self) -> None:
with (
@@ -369,39 +374,6 @@ class TestTaskUsage(ClickhouseTestMixin, APIBaseTest):
assert usage.compute_cost_usd == Decimal(0)
assert usage.total_cost_usd == Decimal("2.5")
- def test_eu_token_cost_uses_cross_region_source(self) -> None:
- with (
- self.settings(
- CLOUD_DEPLOYMENT="EU",
- PERSONAL_SPEND_CROSS_REGION_SECRET="secret",
- DEBUG=False,
- ),
- patch.object(task_usage.requests, "post") as post,
- ):
- post.return_value.json.return_value = {"token_cost_usd": 1.25}
- token_cost = task_usage._get_task_token_cost(
- team_id=self.team.id,
- task_id=self.task.id,
- task_created_at=self.task.created_at,
- )
-
- assert token_cost == Decimal("1.25")
- assert post.call_args.args[0] == "https://us.posthog.com/api/code/internal/task_usage/"
- assert json.loads(post.call_args.kwargs["data"]) == {
- "team_id": self.team.id,
- "task_id": str(self.task.id),
- "task_created_at": self.task.created_at.isoformat(),
- }
-
- def test_eu_token_cost_is_unavailable_without_cross_region_secret(self) -> None:
- with (
- self.settings(CLOUD_DEPLOYMENT="EU", PERSONAL_SPEND_CROSS_REGION_SECRET=""),
- self.assertRaises(task_usage.TaskTokenUsageUnavailable),
- ):
- task_usage._get_task_token_cost(
- team_id=self.team.id, task_id=self.task.id, task_created_at=self.task.created_at
- )
-
def test_token_cost_is_cached(self) -> None:
with patch.object(task_usage, "get_local_task_token_cost", return_value=Decimal("1.25")) as get_cost:
first = task_usage._get_task_token_cost(