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): scope task usage costs to team (#85508)

Adam Bowker0dfcb76dd852
diff --git a/products/desktop/packages/agent/src/adapters/claude/session/options.test.ts b/products/desktop/packages/agent/src/adapters/claude/session/options.test.ts
index 8e0d939a8c73..de17f5fdf484 100644
--- a/products/desktop/packages/agent/src/adapters/claude/session/options.test.ts
+++ b/products/desktop/packages/agent/src/adapters/claude/session/options.test.ts
@@ -373,7 +373,7 @@ describe("buildSessionOptions", () => {
it.each([
{
- name: "omits the team_id header when POSTHOG_PROJECT_ID is unset",
+ name: "omits the project-scope header when POSTHOG_PROJECT_ID is unset",
projectId: undefined,
existingHeaders: undefined,
expected: [
@@ -392,7 +392,7 @@ describe("buildSessionOptions", () => {
].join("\n"),
},
{
- name: "preserves pre-existing custom headers ahead of the team_id header",
+ name: "preserves pre-existing custom headers ahead of the project-scope header",
projectId: "42",
existingHeaders: "x-posthog-property-task_id: task-abc",
expected: [
diff --git a/products/desktop/packages/agent/src/adapters/claude/session/options.ts b/products/desktop/packages/agent/src/adapters/claude/session/options.ts
index b6f199d45e9b..62f8587d5d72 100644
--- a/products/desktop/packages/agent/src/adapters/claude/session/options.ts
+++ b/products/desktop/packages/agent/src/adapters/claude/session/options.ts
@@ -60,11 +60,11 @@ export type GatewayEnv = {
/**
* Same task-metadata attribution headers as {@link anthropicCustomHeaders},
* in record form for the codex/OpenAI path (which sets provider
- * `http_headers` rather than `ANTHROPIC_CUSTOM_HEADERS`). Includes `team_id`,
- * which the Claude path instead appends in {@link buildEnvironment}.
+ * `http_headers` rather than `ANTHROPIC_CUSTOM_HEADERS`). Project authorization
+ * uses the separate `X-PostHog-Project-Id` header.
*/
openaiCustomHeaders?: Record<string, string>;
- /** PostHog project ID for per-team attribution headers. */
+ /** PostHog project ID used to build the gateway project-scope header. */
posthogProjectId?: string;
};
diff --git a/products/desktop/packages/agent/src/server/agent-server.configure-environment.test.ts b/products/desktop/packages/agent/src/server/agent-server.configure-environment.test.ts
index 55709a006e05..7327c0b92a52 100644
--- a/products/desktop/packages/agent/src/server/agent-server.configure-environment.test.ts
+++ b/products/desktop/packages/agent/src/server/agent-server.configure-environment.test.ts
@@ -79,10 +79,9 @@ describe("AgentServer.configureEnvironment", () => {
);
});
- // The Claude session builder reads posthogProjectId from GatewayEnv to emit
- // the `x-posthog-property-team_id` attribution header (see
- // adapters/claude/session/options.ts), so the cloud path must include it.
- it("includes posthogProjectId for the team_id attribution header", () => {
+ // The Claude session builder reads posthogProjectId from GatewayEnv to scope
+ // the request to a project, so the cloud path must include it.
+ it("includes posthogProjectId for the gateway project scope", () => {
const env = buildServer("background").configureEnvironment({
isInternal: false,
});
@@ -199,9 +198,8 @@ describe("AgentServer.configureEnvironment", () => {
// The codex/OpenAI path sets provider http_headers rather than
// ANTHROPIC_CUSTOM_HEADERS, so the same task metadata must be exposed as a
- // record — including team_id, which the Claude path adds separately in
- // buildEnvironment.
- it("forwards task metadata (plus team_id) as openaiCustomHeaders", () => {
+ // record. It carries both the selected project scope and event attribution.
+ it("forwards task metadata and project scope as openaiCustomHeaders", () => {
const env = buildServer("background").configureEnvironment({
isInternal: true,
originProduct: "signal_report",
@@ -510,7 +508,7 @@ describe("AgentServer.configureEnvironment on the Go ai-gateway", () => {
it("emits attribution as one X-PostHog-Properties blob, not per-property headers", () => {
// Asserts the gateway env this function produces. The Claude adapter's
- // buildEnvironment later appends `x-posthog-property-team_id` and
+ // buildEnvironment later appends `X-PostHog-Project-Id` and
// `x-posthog-use-bedrock-fallback` as separate header lines; the Go gateway
// reads only the blob (team_id is already in it, and it does Bedrock
// failover itself), so those extra lines are inert on this path.
diff --git a/products/desktop/packages/agent/src/server/agent-server.ts b/products/desktop/packages/agent/src/server/agent-server.ts
index c5284f79694d..b4fad19029e5 100644
--- a/products/desktop/packages/agent/src/server/agent-server.ts
+++ b/products/desktop/packages/agent/src/server/agent-server.ts
@@ -4244,17 +4244,17 @@ ${commonInstructions}
task_user_id: taskUserId,
task_title: taskTitle,
};
- // The Claude path appends `team_id` in buildEnvironment from
- // POSTHOG_PROJECT_ID; the codex path has no such hook, so fold it into the
- // record here to keep team attribution working for both adapters.
+ // The Claude path appends the project scope in buildEnvironment from
+ // POSTHOG_PROJECT_ID; the codex path has no such hook, so its record below
+ // carries the same scope.
let customHeaders: string;
let openaiCustomHeaders: Record<string, string>;
if (isAiGateway) {
// The Go gateway reads one X-PostHog-Properties JSON blob and ignores
// per-property headers, and it has no product route, so `ai_product`
// has to travel in the blob or the spend lands unattributed. `team_id`
- // is included for both adapters since the Claude hook sets it as a
- // per-property header the Go gateway does not read.
+ // is included for both adapters because the Go gateway does not read
+ // the Python gateway's project-scope header.
const properties = {
...gatewayProperties,
ai_product: aiProduct,
diff --git a/products/tasks/backend/logic/services/task_usage.py b/products/tasks/backend/logic/services/task_usage.py
index 3b1bb3482397..56d0de4b744c 100644
--- a/products/tasks/backend/logic/services/task_usage.py
+++ b/products/tasks/backend/logic/services/task_usage.py
@@ -51,7 +51,7 @@ class TaskUsage:
def get_task_usage(*, team_id: int, task_id: UUID, task_created_at: datetime) -> TaskUsage:
return TaskUsage(
- token_cost_usd=_get_task_token_cost(task_id=task_id, task_created_at=task_created_at),
+ token_cost_usd=_get_task_token_cost(team_id=team_id, task_id=task_id, task_created_at=task_created_at),
compute_cost_usd=_get_task_compute_cost(team_id=team_id, task_id=task_id),
)
@@ -73,31 +73,35 @@ def sign_task_usage_request(body: bytes, secret: str, *, timestamp: int | None =
return TaskUsageRequestSignature(signature=signature, timestamp=request_timestamp)
-def _get_task_token_cost(*, task_id: UUID, task_created_at: datetime) -> Decimal:
- cache_key = _task_token_cost_cache_key(task_id=task_id, task_created_at=task_created_at)
+def _get_task_token_cost(*, team_id: int, task_id: UUID, task_created_at: datetime) -> Decimal:
+ cache_key = _task_token_cost_cache_key(team_id=team_id, task_id=task_id, task_created_at=task_created_at)
cached = cache.get(cache_key)
if cached is not None:
return Decimal(str(cached))
if settings.CLOUD_DEPLOYMENT == "EU":
- token_cost = _get_cross_region_task_token_cost(task_id=task_id, task_created_at=task_created_at)
+ 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(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
-def _task_token_cost_cache_key(*, task_id: UUID, task_created_at: datetime) -> str:
- return f"task_token_cost:v1:{task_id}:{task_created_at.isoformat()}"
+def _task_token_cost_cache_key(*, team_id: int, task_id: UUID, task_created_at: datetime) -> str:
+ return f"task_token_cost:v2:{team_id}:{task_id}:{task_created_at.isoformat()}"
-def _get_cross_region_task_token_cost(*, task_id: UUID, task_created_at: datetime) -> Decimal:
+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({"task_id": str(task_id), "task_created_at": task_created_at.isoformat()}).encode()
+ 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:
@@ -118,7 +122,7 @@ def _get_cross_region_task_token_cost(*, task_id: UUID, task_created_at: datetim
raise TaskTokenUsageUnavailable("Cross-region task usage is unavailable") from error
-def get_local_task_token_cost(*, task_id: UUID, task_created_at: datetime) -> Decimal:
+def get_local_task_token_cost(*, team_id: int, task_id: UUID, task_created_at: datetime) -> Decimal:
query = parse_select(
"""
SELECT round(sum(toFloat(properties.$ai_total_cost_usd)), 6)
@@ -126,6 +130,7 @@ def get_local_task_token_cost(*, task_id: UUID, task_created_at: datetime) -> De
WHERE equals(event, '$ai_generation')
AND greaterOrEquals(timestamp, {task_created_at})
AND equals(properties.ai_product, 'posthog_code')
+ AND equals(toString(properties.team_id), {team_id})
AND (
equals(properties.task_id, {task_id})
OR equals(properties.$ai_session_id, {task_id})
@@ -137,6 +142,7 @@ def get_local_task_token_cost(*, task_id: UUID, task_created_at: datetime) -> De
query=query,
placeholders={
"task_created_at": ast.Constant(value=task_created_at),
+ "team_id": ast.Constant(value=str(team_id)),
"task_id": ast.Constant(value=str(task_id)),
},
team=Team.objects.get(pk=settings.LLM_ANALYTICS_INTERNAL_TEAM_ID),
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 f4da7aada498..845a56b9b248 100644
--- a/products/tasks/backend/logic/services/tests/test_task_usage.py
+++ b/products/tasks/backend/logic/services/tests/test_task_usage.py
@@ -1,3 +1,4 @@
+import json
from datetime import UTC, datetime, timedelta
from decimal import Decimal
from types import SimpleNamespace
@@ -32,6 +33,7 @@ class TestTaskUsageQueryTagging(SimpleTestCase):
patch.object(task_usage, "execute_hogql_query", side_effect=capture_query_tags),
):
task_usage.get_local_task_token_cost(
+ team_id=1,
task_id=UUID("00000000-0000-0000-0000-000000000001"),
task_created_at=datetime(2026, 8, 1, tzinfo=UTC),
)
@@ -53,17 +55,23 @@ class TestTaskUsage(ClickhouseTestMixin, APIBaseTest):
)
def test_token_cost_only_includes_generations_for_the_task_and_product(self) -> None:
- for task_id, product, cost in (
- (str(self.task.id), "posthog_code", 2.5),
- (str(self.task.id), "background_agents", 10),
- ("00000000-0000-0000-0000-000000000001", "posthog_code", 20),
+ for team_id, task_id, product, cost in (
+ (self.team.id, str(self.task.id), "posthog_code", 2.5),
+ (self.team.id, str(self.task.id), "background_agents", 10),
+ (self.team.id, "00000000-0000-0000-0000-000000000001", "posthog_code", 20),
+ (self.team.id + 1, str(self.task.id), "posthog_code", 40),
):
_create_event(
event="$ai_generation",
team=self.team,
distinct_id=str(self.user.distinct_id),
timestamp=self.task.created_at + timedelta(seconds=1),
- properties={"task_id": task_id, "ai_product": product, "$ai_total_cost_usd": cost},
+ properties={
+ "team_id": team_id,
+ "task_id": task_id,
+ "ai_product": product,
+ "$ai_total_cost_usd": cost,
+ },
)
flush_persons_and_events()
@@ -129,24 +137,36 @@ class TestTaskUsage(ClickhouseTestMixin, APIBaseTest):
):
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(task_id=self.task.id, task_created_at=self.task.created_at)
+ 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(task_id=self.task.id, task_created_at=self.task.created_at)
- second = task_usage._get_task_token_cost(task_id=self.task.id, task_created_at=self.task.created_at)
+ first = task_usage._get_task_token_cost(
+ team_id=self.team.id, task_id=self.task.id, task_created_at=self.task.created_at
+ )
+ second = task_usage._get_task_token_cost(
+ team_id=self.team.id, task_id=self.task.id, task_created_at=self.task.created_at
+ )
assert first == second == Decimal("1.25")
get_cost.assert_called_once()
diff --git a/products/tasks/backend/presentation/serializers.py b/products/tasks/backend/presentation/serializers.py
index b5960e31ee38..31d67047558e 100644
--- a/products/tasks/backend/presentation/serializers.py
+++ b/products/tasks/backend/presentation/serializers.py
@@ -2028,6 +2028,7 @@ class TaskUsageResponseSerializer(serializers.Serializer):
class InternalTaskUsageRequestSerializer(serializers.Serializer):
+ team_id = serializers.IntegerField(help_text="Team identifier used to scope attributed model generations.")
task_id = serializers.UUIDField(help_text="Task identifier used to attribute model generations.")
task_created_at = serializers.DateTimeField(help_text="Lower timestamp bound for attributed model generations.")
diff --git a/products/tasks/backend/tests/test_task_usage_api.py b/products/tasks/backend/tests/test_task_usage_api.py
index 677c17ad9b6a..309712801baa 100644
--- a/products/tasks/backend/tests/test_task_usage_api.py
+++ b/products/tasks/backend/tests/test_task_usage_api.py
@@ -18,11 +18,12 @@ class TestInternalTaskUsageViewSet(SimpleTestCase):
"products.tasks.backend.presentation.views.task_usage_api.get_local_task_token_cost",
return_value=Decimal("1.25"),
)
- def test_create_returns_token_cost(self, _get_token_cost) -> None:
+ def test_create_returns_token_cost(self, get_token_cost) -> None:
request = Request(
APIRequestFactory().post(
"/",
{
+ "team_id": 42,
"task_id": str(UUID("00000000-0000-0000-0000-000000000001")),
"task_created_at": datetime(2026, 8, 1, tzinfo=UTC).isoformat(),
},
@@ -35,3 +36,8 @@ class TestInternalTaskUsageViewSet(SimpleTestCase):
assert response.status_code == 200
assert response.data == {"token_cost_usd": 1.25}
+ get_token_cost.assert_called_once_with(
+ team_id=42,
+ task_id=UUID("00000000-0000-0000-0000-000000000001"),
+ task_created_at=datetime(2026, 8, 1, tzinfo=UTC),
+ )
diff --git a/services/llm-gateway/tests/callbacks/test_posthog.py b/services/llm-gateway/tests/callbacks/test_posthog.py
index 6a1bb43831e5..e77c52f82817 100644
--- a/services/llm-gateway/tests/callbacks/test_posthog.py
+++ b/services/llm-gateway/tests/callbacks/test_posthog.py
@@ -183,6 +183,7 @@ class TestPostHogCallback:
assert props["$ai_effort"] == expected
@pytest.mark.asyncio
+ @pytest.mark.parametrize("event_method", ["_on_success", "_on_failure"])
@pytest.mark.parametrize(
"auth_method,is_staff,team_id,expected_team_id",
[
@@ -192,11 +193,12 @@ class TestPostHogCallback:
("oauth_access_token", False, None, None),
],
)
- async def test_on_success_team_attribution(
+ async def test_team_attribution(
self,
callback: PostHogCallback,
standard_logging_object: dict,
mock_posthog_client: tuple,
+ event_method: str,
auth_method: str,
is_staff: bool,
team_id: int | None,
@@ -217,7 +219,7 @@ class TestPostHogCallback:
patch("llm_gateway.callbacks.posthog.get_product", return_value="signals"),
patch("llm_gateway.callbacks.posthog.get_posthog_properties", return_value={"team_id": "999"}),
):
- await callback._on_success(kwargs, None, 0.0, 1.0, end_user_id=None)
+ await getattr(callback, event_method)(kwargs, None, 0.0, 1.0, end_user_id=None)
call_kwargs = mock_client.capture.call_args.kwargs
props = mock_client.capture.call_args.kwargs["properties"]