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(signals): read what each scout spent over the last 7 days (#97562)

posthog[bot]0a63a29356b5
diff --git a/products/signals/backend/scout_harness/AGENTS.md b/products/signals/backend/scout_harness/AGENTS.md
index 5b6c7ea136fd..dc06b5fc4481 100644
--- a/products/signals/backend/scout_harness/AGENTS.md
+++ b/products/signals/backend/scout_harness/AGENTS.md
@@ -77,13 +77,15 @@ In production it is driven by `SignalsScoutCoordinatorWorkflow` (periodic tick e
A batch of runs costs one query, and each run's answer is cached: an hour once the total is final, and a minute while it can still move.
A total can still move for three reasons — the run is still generating, the run settled inside `RUN_COST_INGESTION_GRACE` so its last generations may not have reached ClickHouse yet, or nothing is attributed to the run at all and the answer is not yet a number.
Two things it will not do. It never reports a run with no attributed generation as `$0.00`, since a free run and an unattributed one are not the same thing — such a run carries no cost at all. And it never reports zero where there is no internal project to read: the batch comes back `available=false` instead. The read is region-local (`INTERNAL_LLM_ANALYTICS_TEAM_ID_BY_REGION` in `task_usage.py`), so both clouds price their own runs and neither needs the cross-region proxy the per-task desktop read uses.
+- `scout_costs.py`
+ What each scout spent during the roster's seven-day window. It groups run costs by the scout skill name on each run row. It also returns run counts, priced run counts, and recorded report counts. The staff-only `runs/costs` action caches this project-level result for 15 minutes.
- `serializers.py`
DRF serializers for the harness HTTP surface (runs, scratchpad, project profile).
Annotated for drf-spectacular so the generated MCP tools have informative schemas.
- `views.py`
`SignalScoutRunViewSet`, `SignalScoutConfigViewSet`, `SignalScratchpadViewSet`, `SignalScoutNoteViewSet`, `SignalProjectProfileViewSet`, `SignalScoutMetadataViewSet`, `SignalScoutMembersViewSet`, `SignalScoutViewSet`.
Routed under `project_signals_scout_*` basenames in `products/signals/backend/routes.py` and exposed as `scout-*` MCP tools via `products/signals/mcp/tools.yaml`.
- `SignalScoutRunViewSet` also carries the staff-only `token-costs` batch action (`run_costs.py`), which sits in `tools.yaml` as `enabled: false` — codegen registers every operation, and this one stays off, because fleet spend is an internal operating number and the events it sums sit in a project other than the one in the path.
+ `SignalScoutRunViewSet` carries two staff-only cost actions. The `token-costs` action uses `run_costs.py`. The `costs` action uses `scout_costs.py`. Both actions sit in `tools.yaml` as `enabled: false`. Code generation registers each operation, but fleet spend stays outside the public MCP catalog.
`SignalScoutViewSet` backs `scout-create`: it creates a custom `signals-scout-*` skill and its runnable config atomically, grants the report-channel tools server-side, and treats an identical definition as a retry while rejecting conflicting definitions.
`SignalScoutMembersViewSet` (`scout-members-list`) is the reviewer-routing roster:
it returns the project's members (those with access to the team) with `user_uuid` / `email` / `github_login` so a report-channel scout can populate `suggested_reviewers` at cold start. The roster is member PII the scout needs to route, gated on the internal `signal_scout_internal` scope object (`scope_object = "signal_scout_internal"`, default `list` → `signal_scout_internal:read`, satisfied by the sandbox token's `…:write`) — so, like `emit-signal`, it is reachable only inside a scout run and never enters a customer's public MCP catalog. (The narrower `signal_scout_report` scope was considered but is transient — kept only while emit-signal and emit-report coexist — so the durable tool stays on `signal_scout_internal`.) Membership is resolved server-side via `report_generation/resolve_reviewers.list_project_members` (through `Team.all_users_with_access()`, so private-project access control is honored), the project-nested path that the org-nested `org-members-list` tool (stripped + 403'd for a scoped-team token) can't provide.
diff --git a/products/signals/backend/scout_harness/scout_costs.py b/products/signals/backend/scout_harness/scout_costs.py
new file mode 100644
index 000000000000..98a02aadaab7
--- /dev/null
+++ b/products/signals/backend/scout_harness/scout_costs.py
@@ -0,0 +1,176 @@
+"""Model spend per scout over a window, for the staff-only cost readout on the roster.
+
+`run_costs.py` prices a named set of runs, which answers "what did this run cost". This module
+answers the question next to it: what a scout costs over a span, and what it produced for that
+spend. Both numbers come from the same place — the run rows in Postgres, joined by `task_run_id` to
+the `$ai_generation` sums in the internal AI observability project. The join has to happen here
+rather than in the events, because a team-authored scout's generations all carry the same
+`ai_stage`, so the events alone cannot name it.
+
+The response is facts, not ratios: spend, how many runs, how many of those were priced, and how
+many reports the scout touched. Cost per day, per run, and per report are derived from those four
+numbers where they are rendered, so the definitions live in one place.
+"""
+
+from __future__ import annotations
+
+from collections import defaultdict
+from datetime import timedelta
+from decimal import Decimal, InvalidOperation
+from typing import Any
+
+from django.core.cache import cache
+from django.utils import timezone
+
+from posthog.clickhouse.query_tagging import Product
+from posthog.dataclasses import frozen
+
+from products.signals.backend.models import SignalScoutRun
+from products.signals.backend.scout_harness.run_costs import RUN_COST_LOOKBACK_MARGIN
+from products.tasks.backend.facade import api as tasks_facade
+from products.tasks.backend.facade.billing import TaskTokenUsageUnavailable, get_local_task_run_token_costs
+
+# The window the roster's fleet headline already spans, so every number on the page describes one
+# span. It also bounds the per-team read on the largest fleets.
+SCOUT_COST_WINDOW_DAYS = 7
+# The window's trailing edge moves and the newest runs may still be settling, so this is a roughly
+# current number, not a live one. Fifteen minutes keeps a page open on the roster off the events
+# read while still tracking the day's spend.
+SCOUT_COSTS_CACHE_TIMEOUT_SECONDS = 15 * 60
+
+
+@frozen
+class ScoutCost:
+ skill_name: str
+ # Sum over the scout's runs that had spend attributed. Zero when none did, which
+ # `priced_run_count` tells apart from a scout that really spent nothing.
+ spend_usd: Decimal
+ run_count: int
+ priced_run_count: int
+ # Distinct inbox reports the scout filed or added to. A report authored in one run and edited in
+ # three counts once.
+ reports_touched: int
+
+
+@frozen
+class ScoutCosts:
+ window_days: int
+ scouts: list[ScoutCost]
+ # False when this deployment has no internal AI observability project to read, so every spend is
+ # unknown rather than zero.
+ available: bool
+
+
+def _serialize_scout_costs(costs: ScoutCosts) -> dict[str, Any]:
+ return {
+ "window_days": costs.window_days,
+ "available": costs.available,
+ "scouts": [
+ {
+ "skill_name": scout.skill_name,
+ "spend_usd": str(scout.spend_usd),
+ "run_count": scout.run_count,
+ "priced_run_count": scout.priced_run_count,
+ "reports_touched": scout.reports_touched,
+ }
+ for scout in costs.scouts
+ ],
+ }
+
+
+def _deserialize_scout_costs(value: object) -> ScoutCosts | None:
+ if not isinstance(value, dict):
+ return None
+ window_days = value.get("window_days")
+ available = value.get("available")
+ scouts_value = value.get("scouts")
+ if type(window_days) is not int or type(available) is not bool or not isinstance(scouts_value, list):
+ return None
+
+ scouts: list[ScoutCost] = []
+ try:
+ for scout_value in scouts_value:
+ if not isinstance(scout_value, dict):
+ return None
+ skill_name = scout_value["skill_name"]
+ spend_usd = Decimal(scout_value["spend_usd"])
+ counts = (
+ scout_value["run_count"],
+ scout_value["priced_run_count"],
+ scout_value["reports_touched"],
+ )
+ if (
+ not isinstance(skill_name, str)
+ or not spend_usd.is_finite()
+ or spend_usd < 0
+ or any(type(count) is not int or count < 0 for count in counts)
+ ):
+ return None
+ scouts.append(
+ ScoutCost(
+ skill_name=skill_name,
+ spend_usd=spend_usd,
+ run_count=counts[0],
+ priced_run_count=counts[1],
+ reports_touched=counts[2],
+ )
+ )
+ except (InvalidOperation, KeyError, TypeError, ValueError):
+ return None
+ return ScoutCosts(window_days=window_days, scouts=scouts, available=available)
+
+
+def scout_costs(*, team_id: int, window_days: int) -> ScoutCosts:
+ """Sum this team's scout spend and output per scout over the last `window_days`."""
+ cache_key = f"scout_costs:v1:{team_id}:{window_days}"
+ cached = cache.get(cache_key)
+ if cached is not None:
+ cached_costs = _deserialize_scout_costs(cached)
+ if cached_costs is not None:
+ return cached_costs
+
+ window_start = timezone.now() - timedelta(days=window_days)
+ task_run_ids_by_skill: dict[str, list[str]] = defaultdict(list)
+ report_ids_by_skill: dict[str, set[str]] = defaultdict(set)
+ for skill_name, task_run_id, emitted_report_ids, edited_report_ids in SignalScoutRun.objects.filter(
+ team_id=team_id, created_at__gte=window_start
+ ).values_list("skill_name", "task_run_id", "emitted_report_ids", "edited_report_ids"):
+ task_run_ids_by_skill[skill_name].append(str(task_run_id))
+ report_ids_by_skill[skill_name].update(
+ str(report_id) for report_id in [*(emitted_report_ids or []), *(edited_report_ids or [])]
+ )
+
+ if not task_run_ids_by_skill:
+ return ScoutCosts(window_days=window_days, scouts=[], available=True)
+
+ try:
+ spend_by_task_run_id = get_local_task_run_token_costs(
+ team_id=team_id,
+ origin_product=tasks_facade.TaskOriginProduct.SIGNALS_SCOUT.value,
+ # No id list: the team filter and the window bound the read, and a per-team list would
+ # be tens of thousands of ids on the largest fleets. The margin absorbs clock skew
+ # between a run row and the generations stamped against it.
+ generated_after=window_start - RUN_COST_LOOKBACK_MARGIN,
+ product=Product.SIGNALS,
+ )
+ except TaskTokenUsageUnavailable:
+ return ScoutCosts(window_days=window_days, scouts=[], available=False)
+
+ scouts = []
+ for skill_name, task_run_ids in sorted(task_run_ids_by_skill.items()):
+ priced = [
+ spend_by_task_run_id[task_run_id] for task_run_id in task_run_ids if task_run_id in spend_by_task_run_id
+ ]
+ scouts.append(
+ ScoutCost(
+ skill_name=skill_name,
+ spend_usd=sum(priced, Decimal(0)),
+ run_count=len(task_run_ids),
+ priced_run_count=len(priced),
+ reports_touched=len(report_ids_by_skill[skill_name]),
+ )
+ )
+
+ costs = ScoutCosts(window_days=window_days, scouts=scouts, available=True)
+ cache.set(cache_key, _serialize_scout_costs(costs), timeout=SCOUT_COSTS_CACHE_TIMEOUT_SECONDS)
+ return costs
diff --git a/products/signals/backend/scout_harness/serializers.py b/products/signals/backend/scout_harness/serializers.py
index f2ec9f707a4c..b9574f5773b4 100644
--- a/products/signals/backend/scout_harness/serializers.py
+++ b/products/signals/backend/scout_harness/serializers.py
@@ -41,6 +41,7 @@ from products.signals.backend.scout_harness.derived_metadata import DERIVED_FLAG
from products.signals.backend.scout_harness.fleet_sync import SYNC_SURFACES
from products.signals.backend.scout_harness.model_selection import scout_model_config_enabled, scout_model_pin_catalog
from products.signals.backend.scout_harness.note_targets import PIPELINE_AUDIENCES
+from products.signals.backend.scout_harness.scout_costs import SCOUT_COST_WINDOW_DAYS
from products.signals.backend.scout_harness.skill_loader import reserved_scout_name_error
from products.signals.backend.scout_harness.slack_delivery import MAX_SCOUT_SLACK_DM_TARGETS
from products.signals.backend.scout_harness.tags import slugify_tag
@@ -417,6 +418,67 @@ class ScoutRunTokenCostsSerializer(serializers.Serializer):
)
+class ScoutCostsQuerySerializer(serializers.Serializer):
+ """Query parameters for the `runs/costs` action."""
+
+ window_days = serializers.IntegerField(
+ required=False,
+ # Bounded to the one supported window rather than left open, so a client that asks for 30
+ # gets a 400 instead of a number silently computed over 7 days.
+ min_value=SCOUT_COST_WINDOW_DAYS,
+ max_value=SCOUT_COST_WINDOW_DAYS,
+ help_text=(
+ f"Window in days over runs' `created_at` (default {SCOUT_COST_WINDOW_DAYS}). Only "
+ f"{SCOUT_COST_WINDOW_DAYS} is accepted today — it matches the window the roster's fleet "
+ "headline spans, so every number on the page describes one span."
+ ),
+ )
+
+
+class ScoutCostSerializer(serializers.Serializer):
+ """What one scout spent in the window, and what it produced for that spend."""
+
+ skill_name = serializers.CharField(help_text="Full skill name of the scout, e.g. `signals-scout-error-tracking`.")
+ spend_usd = serializers.FloatField(
+ help_text=(
+ "Model spend attributed to the scout's runs in the window, in US dollars. Zero when none "
+ "of its runs had spend attributed, which `priced_run_count` tells apart from a scout that "
+ "really spent nothing."
+ ),
+ )
+ run_count = serializers.IntegerField(help_text="Runs the scout started in the window.")
+ priced_run_count = serializers.IntegerField(
+ help_text=(
+ "Runs of the scout that had spend attributed. Lower than `run_count` where a run failed "
+ "before its first model call, or its generations haven't landed yet. Divide `spend_usd` by "
+ "this, not by `run_count`, for cost per run."
+ ),
+ )
+ reports_touched = serializers.IntegerField(
+ help_text=(
+ "Distinct inbox reports the scout filed or added to in the window. A report it authored in "
+ "one run and edited in three counts once. Zero means the scout produced no reports, so "
+ "cost per report has no value rather than a value of zero."
+ ),
+ )
+
+
+class ScoutCostsSerializer(serializers.Serializer):
+ """Model spend and output per scout over a window."""
+
+ window_days = serializers.IntegerField(help_text="Window the rows describe, in days.")
+ scouts = ScoutCostSerializer(
+ many=True,
+ help_text="One row per scout that started at least one run on this project in the window.",
+ )
+ available = serializers.BooleanField(
+ help_text=(
+ "False when this deployment has no internal AI observability project to read the "
+ "generations from, so `scouts` is empty and every spend is unknown rather than zero."
+ ),
+ )
+
+
class RecentEmissionsQuerySerializer(serializers.Serializer):
"""Query parameters for `recent-emissions` — recent findings across every run on the team.
diff --git a/products/signals/backend/scout_harness/views.py b/products/signals/backend/scout_harness/views.py
index 16a1a89d3d3e..af6b007e941a 100644
--- a/products/signals/backend/scout_harness/views.py
+++ b/products/signals/backend/scout_harness/views.py
@@ -77,6 +77,7 @@ from products.signals.backend.scout_harness.run_gates import (
check_run_in_flight,
check_spend_gates,
)
+from products.signals.backend.scout_harness.scout_costs import SCOUT_COST_WINDOW_DAYS, scout_costs
from products.signals.backend.scout_harness.serializers import (
EditReportRequestSerializer,
EditReportResponseSerializer,
@@ -96,6 +97,8 @@ from products.signals.backend.scout_harness.serializers import (
RecordStructuredOutputRequestSerializer,
RecordStructuredOutputResponseSerializer,
RememberRequestSerializer,
+ ScoutCostsQuerySerializer,
+ ScoutCostsSerializer,
ScoutEmissionReportLinkSerializer,
ScoutFleetSyncQuerySerializer,
ScoutMemberSerializer,
@@ -443,12 +446,35 @@ def _resolve_emission_report_links(
return links
+class ScoutCanonicalTeamAccessPermission(BasePermission):
+ """Authorize requests against the project that owns the scout data."""
+
+ message = "You don't have access to the project that owns this data."
+
+ def has_permission(self, request: Request, view) -> bool:
+ if not request.user.is_authenticated:
+ return True
+ team = view.team
+ if team.parent_team_id is None or team.parent_team_id == team.id or team.parent_team is None:
+ return True
+ authenticator = request.successful_authenticator
+ scoped_teams = None
+ if isinstance(authenticator, OAuthAccessTokenAuthentication):
+ scoped_teams = authenticator.access_token.scoped_teams
+ elif isinstance(authenticator, PersonalAPIKeyAuthentication):
+ scoped_teams = authenticator.personal_api_key.scoped_teams
+ if scoped_teams and team.parent_team_id not in scoped_teams:
+ return False
+ level = view.user_permissions.team(team.parent_team).effective_membership_level
+ return level is not None
+
+
class SignalScoutRunViewSet(TeamAndOrgViewSetMixin, viewsets.GenericViewSet):
"""Run history + finding emission for the headless agent."""
serializer_class = SignalScoutRunSummarySerializer
authentication_classes = [SessionAuthentication, PersonalAPIKeyAuthentication, OAuthAccessTokenAuthentication]
- permission_classes = [IsAuthenticated, APIScopePermission]
+ permission_classes = [IsAuthenticated, APIScopePermission, ScoutCanonicalTeamAccessPermission]
scope_object = "signal_scout"
# `.unscoped()` bypasses the fail-closed TeamScopedManager; this class-attribute queryset
# evaluates at module-load time (before any request → no team context). All read paths
@@ -850,6 +876,48 @@ class SignalScoutRunViewSet(TeamAndOrgViewSetMixin, viewsets.GenericViewSet):
).data
)
+ @validated_request(
+ query_serializer=ScoutCostsQuerySerializer,
+ responses={
+ 200: OpenApiResponse(
+ response=ScoutCostsSerializer,
+ description="Model spend and output per scout over the window.",
+ ),
+ 403: OpenApiResponse(description="Caller is not PostHog staff."),
+ },
+ summary="Get what each scout spent over a window",
+ description=(
+ "Return what every scout on this project spent on model calls over the last `window_days`, "
+ "with how many runs it started, how many of those had spend attributed, and how many inbox "
+ "reports it filed or added to. Cost per day, per run, and per report are derived from those "
+ "numbers by the caller, so the endpoint stays a fact table and the definitions live in one "
+ "place. Spend is summed from the `$ai_generation` events the runs' sandboxes produced and "
+ "joined to the run rows by task run id, because a team-authored scout's generations all "
+ "carry the same stage tag and so cannot name it. Cached per project for 15 minutes: the "
+ "window's trailing edge moves and the newest runs may still be settling, so this is a "
+ "roughly current number, not a live one. `available` is false where the internal AI "
+ "observability project holding those events can't be read, so an unknown spend never reads "
+ "as zero. Staff-only, same gate as the per-run cost read. Strictly team-scoped."
+ ),
+ operation_id="signals_scout_runs_costs",
+ )
+ @action(
+ detail=False,
+ methods=["get"],
+ url_path="costs",
+ required_scopes=["signal_scout:read"],
+ pagination_class=None,
+ )
+ def costs(self, request: Request, **kwargs) -> Response:
+ if not cast(User, request.user).is_staff:
+ raise exceptions.PermissionDenied("Only PostHog staff can read scout costs.")
+ validated = getattr(request, "validated_query_data", {}) or {}
+ costs = scout_costs(
+ team_id=_canonical_team_id(self),
+ window_days=validated.get("window_days") or SCOUT_COST_WINDOW_DAYS,
+ )
+ return Response(ScoutCostsSerializer(dataclasses.asdict(costs)).data)
+
@validated_request(
request_serializer=EmitFindingRequestSerializer,
parameters=[_RUN_ID_PATH_PARAMETER],
@@ -1343,42 +1411,6 @@ class SignalScratchpadViewSet(TeamAndOrgViewSetMixin, viewsets.GenericViewSet):
return Response(ForgetResponseSerializer({"deleted": removed}).data)
-class ScoutCanonicalTeamAccessPermission(BasePermission):
- """Authorize against the canonical (data-owning) team, not just the URL environment team.
-
- Scout notes are `TeamScopedRootMixin` rows that canonicalize to the parent (project-root)
- team on save, so a request made against a child environment reads and writes the PARENT's
- rows (`_canonical_team_id`). The default team gate only checks membership / token
- team-scope for the URL team, so a user or key scoped solely to a child environment would
- be authorized against one team while touching another's rows. Re-anchor both checks to
- the canonical team. Mirrors `StamphogCanonicalTeamAccessPermission`. Root teams (no
- parent) are unaffected — the default checks already cover them.
- """
-
- message = "You don't have access to the project that owns this data."
-
- def has_permission(self, request: Request, view) -> bool:
- if not request.user.is_authenticated:
- return True # IsAuthenticated handles the unauthenticated case first
- team = view.team
- if team.parent_team_id is None or team.parent_team_id == team.id or team.parent_team is None:
- return True
- # A team-scoped token must cover the CANONICAL team too: the default scope check
- # accepted the URL (child) team, but the rows read and written belong to the parent.
- authenticator = request.successful_authenticator
- scoped_teams = None
- if isinstance(authenticator, OAuthAccessTokenAuthentication):
- scoped_teams = authenticator.access_token.scoped_teams
- elif isinstance(authenticator, PersonalAPIKeyAuthentication):
- scoped_teams = authenticator.personal_api_key.scoped_teams
- if scoped_teams and team.parent_team_id not in scoped_teams:
- return False
- # Same helper the default gate uses, re-pointed at the parent. It accounts for a
- # private parent team, so None means genuinely no access -> 403.
- level = view.user_permissions.team(team.parent_team).effective_membership_level
- return level is not None
-
-
class SignalScoutNoteViewSet(TeamAndOrgViewSetMixin, viewsets.GenericViewSet):
"""Steering notes for the scout fleet (`SignalScoutNote`) — list, leave, and delete.
diff --git a/products/signals/backend/test/test_scout_harness.py b/products/signals/backend/test/test_scout_harness.py
index dadef2a49e7b..ee016f0b710c 100644
--- a/products/signals/backend/test/test_scout_harness.py
+++ b/products/signals/backend/test/test_scout_harness.py
@@ -36,7 +36,7 @@ from products.signals.backend.daily_limit import DailyReportLimitGate
from products.signals.backend.models import SignalScoutConfig, SignalScoutRun
from products.signals.backend.quota import SelfDrivingQuotaGate
from products.signals.backend.report_charts import ReportChart
-from products.signals.backend.scout_harness import run_costs
+from products.signals.backend.scout_harness import run_costs, scout_costs
from products.signals.backend.scout_harness.derived_metadata import DERIVED_METADATA_KEY
from products.signals.backend.scout_harness.lazy_seed import HARNESS_SEEDED_BY, _compute_row_hash
from products.signals.backend.scout_harness.limits import STALE_RUN_CUTOFF_S, failure_streak_pause_threshold
@@ -2738,6 +2738,141 @@ async def test_workflow_delivers_scout_outcomes_even_when_the_run_activity_canno
assert resume.call_args.kwargs["raise_on_error"] is True
+class TestScoutCosts(BaseTest):
+ def setUp(self) -> None:
+ super().setUp()
+ cache.clear()
+
+ def _run(
+ self,
+ *,
+ skill_name: str = "signals-scout-general",
+ team: Team | None = None,
+ created_days_ago: float = 1,
+ emitted_report_ids: list[str] | None = None,
+ edited_report_ids: list[str] | None = None,
+ ) -> SignalScoutRun:
+ team = team or self.team
+ config, _ = SignalScoutConfig.objects.get_or_create(team=team, skill_name=skill_name)
+ run = SignalScoutRun.objects.create(
+ team=team,
+ task_run=_make_task_run(team),
+ scout_config=config,
+ skill_name=skill_name,
+ skill_version=1,
+ emitted_report_ids=emitted_report_ids or [],
+ edited_report_ids=edited_report_ids or [],
+ )
+ SignalScoutRun.objects.filter(pk=run.pk).update(created_at=timezone.now() - timedelta(days=created_days_ago))
+ run.refresh_from_db()
+ return run
+
+ def test_sums_spend_runs_and_distinct_reports_per_scout(self) -> None:
+ # A team-authored scout has to be named as itself: its generations all carry the same stage
+ # tag, so only the run rows can separate it from every other custom scout.
+ canonical_a = self._run(emitted_report_ids=["r-1"])
+ canonical_b = self._run(emitted_report_ids=["r-1"], edited_report_ids=["r-2"])
+ custom = self._run(skill_name="my-own-scout", edited_report_ids=["r-3"])
+ with patch.object(
+ scout_costs,
+ "get_local_task_run_token_costs",
+ return_value={
+ str(canonical_a.task_run_id): Decimal("1.2"),
+ str(canonical_b.task_run_id): Decimal("0.48"),
+ str(custom.task_run_id): Decimal("0.1"),
+ },
+ ) as query:
+ costs = scout_costs.scout_costs(team_id=self.team.id, window_days=7)
+
+ assert costs.available
+ assert costs.window_days == 7
+ by_skill = {scout.skill_name: scout for scout in costs.scouts}
+ assert by_skill["signals-scout-general"] == scout_costs.ScoutCost(
+ skill_name="signals-scout-general",
+ spend_usd=Decimal("1.68"),
+ run_count=2,
+ priced_run_count=2,
+ # `r-1` was filed by one run and touched again by another, so it counts once.
+ reports_touched=2,
+ )
+ assert by_skill["my-own-scout"].spend_usd == Decimal("0.1")
+ assert by_skill["my-own-scout"].reports_touched == 1
+ # One window read for the whole team rather than a list of every run id, which would be tens
+ # of thousands of ids on the largest fleets.
+ assert query.call_args.kwargs.get("task_run_ids") is None
+ assert query.call_args.kwargs["generated_after"] < min(canonical_a.created_at, custom.created_at)
+
+ def test_run_without_attributed_spend_is_left_out_of_the_priced_count(self) -> None:
+ # Cost per run divides by the runs that were priced, so a run that failed before its first
+ # model call must not pull the average down.
+ priced = self._run()
+ self._run()
+ with patch.object(
+ scout_costs, "get_local_task_run_token_costs", return_value={str(priced.task_run_id): Decimal("2")}
+ ):
+ costs = scout_costs.scout_costs(team_id=self.team.id, window_days=7)
+
+ assert [(scout.run_count, scout.priced_run_count, scout.spend_usd) for scout in costs.scouts] == [
+ (2, 1, Decimal("2"))
+ ]
+
+ def test_runs_outside_the_window_and_other_teams_runs_are_absent(self) -> None:
+ other_team = Team.objects.create(organization=self.organization, name="Other")
+ mine = self._run()
+ self._run(created_days_ago=9)
+ self._run(team=other_team, skill_name="signals-scout-general")
+ with patch.object(
+ scout_costs, "get_local_task_run_token_costs", return_value={str(mine.task_run_id): Decimal("3")}
+ ):
+ costs = scout_costs.scout_costs(team_id=self.team.id, window_days=7)
+
+ assert [(scout.skill_name, scout.run_count) for scout in costs.scouts] == [("signals-scout-general", 1)]
+
+ def test_second_read_is_served_from_the_cache(self) -> None:
+ # The window's trailing edge moves and the newest runs may still be settling, so the number
+ # is roughly current by design and every roster poll must not re-read the events.
+ run = self._run()
+ with patch.object(
+ scout_costs, "get_local_task_run_token_costs", return_value={str(run.task_run_id): Decimal("1")}
+ ) as query:
+ first = scout_costs.scout_costs(team_id=self.team.id, window_days=7)
+ second = scout_costs.scout_costs(team_id=self.team.id, window_days=7)
+
+ assert second == first
+ query.assert_called_once()
+
+ cached = cache.get(f"scout_costs:v1:{self.team.id}:7")
+ assert cached == {
+ "window_days": 7,
+ "available": True,
+ "scouts": [
+ {
+ "skill_name": "signals-scout-general",
+ "spend_usd": "1",
+ "run_count": 1,
+ "priced_run_count": 1,
+ "reports_touched": 0,
+ }
+ ],
+ }
+
+ def test_unreadable_cost_project_is_reported_rather_than_priced_at_zero(self) -> None:
+ self._run()
+ with patch.object(scout_costs, "get_local_task_run_token_costs", side_effect=TaskTokenUsageUnavailable()):
+ costs = scout_costs.scout_costs(team_id=self.team.id, window_days=7)
+
+ assert costs.available is False
+ assert costs.scouts == []
+
+ def test_team_with_no_runs_in_the_window_reads_as_available_and_empty(self) -> None:
+ with patch.object(scout_costs, "get_local_task_run_token_costs") as query:
+ costs = scout_costs.scout_costs(team_id=self.team.id, window_days=7)
+
+ assert costs.available
+ assert costs.scouts == []
+ query.assert_not_called()
+
+
class TestScoutRunTokenCosts(BaseTest):
"""The staff-only per-run cost read behind the roster's run tooltips."""
diff --git a/products/signals/backend/test/test_scout_harness_api.py b/products/signals/backend/test/test_scout_harness_api.py
index 27c230bf13ca..4925909455b9 100644
--- a/products/signals/backend/test/test_scout_harness_api.py
+++ b/products/signals/backend/test/test_scout_harness_api.py
@@ -9,6 +9,7 @@ from posthog.test.base import APIBaseTest
from unittest.mock import AsyncMock, patch
from django.apps import apps
+from django.core.cache import cache
from django.test import SimpleTestCase
from django.utils import timezone
@@ -331,6 +332,7 @@ class TestScoutHarnessRunEmissionsAPI(APIBaseTest):
# Patch target: the helper is hot-imported into the view module, so patch it there, not at source.
_FETCH_REPORT_IDS = "products.signals.backend.temporal.signal_queries.fetch_report_ids_for_source_ids"
_RUN_TOKEN_COSTS_QUERY = "products.signals.backend.scout_harness.run_costs.get_local_task_run_token_costs"
+_SCOUT_COSTS_QUERY = "products.signals.backend.scout_harness.scout_costs.get_local_task_run_token_costs"
class TestScoutHarnessEmissionReportsAPI(APIBaseTest):
@@ -530,6 +532,84 @@ class TestScoutHarnessRunTokenCostsAPI(APIBaseTest):
query.assert_not_called()
+class TestScoutHarnessScoutCostsAPI(APIBaseTest):
+ def setUp(self) -> None:
+ super().setUp()
+ cache.clear()
+
+ def _url(self, query: str = "") -> str:
+ return f"/api/projects/{self.team.id}/signals/scout/runs/costs/{query}"
+
+ def _make_staff(self) -> None:
+ self.user.is_staff = True
+ self.user.save()
+
+ def test_staff_reads_spend_counts_and_reports_per_scout(self) -> None:
+ self._make_staff()
+ priced = _make_run(self.team, emitted_report_ids=["r-1"], edited_report_ids=["r-1", "r-2"])
+ _make_run(self.team)
+ with patch(_SCOUT_COSTS_QUERY, return_value={str(priced.task_run_id): Decimal("1.68")}):
+ response = self.client.get(self._url())
+ assert response.status_code == status.HTTP_200_OK
+ body = response.json()
+ assert body["available"] is True
+ assert body["window_days"] == 7
+ assert body["scouts"] == [
+ {
+ "skill_name": "signals-scout-general",
+ "spend_usd": 1.68,
+ "run_count": 2,
+ # The run that spent nothing is out of the per-run divisor, not priced at zero.
+ "priced_run_count": 1,
+ # `r-1` was filed and then edited by the same run, so it counts once.
+ "reports_touched": 2,
+ }
+ ]
+
+ def test_non_staff_is_refused(self) -> None:
+ # Fleet spend is an internal operating number, and the generations sit in a project other
+ # than the one in the path. Same gate as the per-run cost read.
+ _make_run(self.team)
+ with patch(_SCOUT_COSTS_QUERY) as query:
+ response = self.client.get(self._url())
+ assert response.status_code == status.HTTP_403_FORBIDDEN
+ query.assert_not_called()
+
+ def test_child_scoped_api_key_cannot_read_parent_costs(self) -> None:
+ from posthog.models.personal_api_key import PersonalAPIKey
+ from posthog.models.utils import generate_random_token_personal, hash_key_value
+
+ self._make_staff()
+ child = Team.objects.create(organization=self.organization, parent_team=self.team, name="Child")
+ raw = generate_random_token_personal()
+ PersonalAPIKey.objects.create(
+ label="child-scoped",
+ user=self.user,
+ secure_value=hash_key_value(raw),
+ scopes=["signal_scout:read"],
+ scoped_teams=[child.id],
+ )
+ self.client.logout()
+
+ with patch(_SCOUT_COSTS_QUERY) as query:
+ response = self.client.get(
+ f"/api/projects/{child.id}/signals/scout/runs/costs/",
+ HTTP_AUTHORIZATION=f"Bearer {raw}",
+ )
+
+ assert response.status_code == status.HTTP_403_FORBIDDEN
+ query.assert_not_called()
+
+ def test_unsupported_window_is_refused_rather_than_silently_widened(self) -> None:
+ # The parameter exists so a detail page can ask for 30 days later. Until it can, a request
+ # for 30 must not come back as a 7-day number labelled 30.
+ self._make_staff()
+ with patch(_SCOUT_COSTS_QUERY) as query:
+ response = self.client.get(self._url("?window_days=30"))
+ assert response.status_code == status.HTTP_400_BAD_REQUEST
+ query.assert_not_called()
+
+
class TestScoutHarnessRecentEmissionsAPI(APIBaseTest):
def _url(self) -> str:
return f"/api/projects/{self.team.id}/signals/scout/runs/emissions/recent/"
diff --git a/products/signals/frontend/generated/api.schemas.ts b/products/signals/frontend/generated/api.schemas.ts
index d4cb57014879..373bd1a781f3 100644
--- a/products/signals/frontend/generated/api.schemas.ts
+++ b/products/signals/frontend/generated/api.schemas.ts
@@ -3929,6 +3929,34 @@ export interface RecordStructuredOutputResponseApi {
record_ids: string[]
}
+/**
+ * What one scout spent in the window, and what it produced for that spend.
+ */
+export interface ScoutCostApi {
+ /** Full skill name of the scout, e.g. `signals-scout-error-tracking`. */
+ skill_name: string
+ /** Model spend attributed to the scout's runs in the window, in US dollars. Zero when none of its runs had spend attributed, which `priced_run_count` tells apart from a scout that really spent nothing. */
+ spend_usd: number
+ /** Runs the scout started in the window. */
+ run_count: number
+ /** Runs of the scout that had spend attributed. Lower than `run_count` where a run failed before its first model call, or its generations haven't landed yet. Divide `spend_usd` by this, not by `run_count`, for cost per run. */
+ priced_run_count: number
+ /** Distinct inbox reports the scout filed or added to in the window. A report it authored in one run and edited in three counts once. Zero means the scout produced no reports, so cost per report has no value rather than a value of zero. */
+ reports_touched: number
+}
+
+/**
+ * Model spend and output per scout over a window.
+ */
+export interface ScoutCostsApi {
+ /** Window the rows describe, in days. */
+ window_days: number
+ /** One row per scout that started at least one run on this project in the window. */
+ scouts: ScoutCostApi[]
+ /** False when this deployment has no internal AI observability project to read the generations from, so `scouts` is empty and every spend is unknown rather than zero. */
+ available: boolean
+}
+
/**
* Request body for the batched emissions / emission-reports lookups: the set of run UUIDs to
* resolve in one call. Collapses the findings UI's old per-run fan-out (one request — and for the
@@ -4684,6 +4712,15 @@ export type SignalsScoutRunsListParams = {
text?: string
}
+export type SignalsScoutRunsCostsParams = {
+ /**
+ * Window in days over runs' `created_at` (default 7). Only 7 is accepted today — it matches the window the roster's fleet headline spans, so every number on the page describes one span.
+ * @minimum 7
+ * @maximum 7
+ */
+ window_days?: number
+}
+
export type SignalsScoutRunsRecentEmissionsParams = {
/**
* ISO-8601 inclusive lower bound on `emitted_at`. Omit to skip the lower bound.
diff --git a/products/signals/frontend/generated/api.ts b/products/signals/frontend/generated/api.ts
index b5f6f3e2fa3c..69eff98a0b9e 100644
--- a/products/signals/frontend/generated/api.ts
+++ b/products/signals/frontend/generated/api.ts
@@ -44,6 +44,7 @@ import type {
ReportSignalsResponseApi,
ScoutChatTaskApi,
ScoutChatTaskCreateApi,
+ ScoutCostsApi,
ScoutEmissionReportLinkApi,
ScoutMemberApi,
ScoutMetadataApi,
@@ -88,6 +89,7 @@ import type {
SignalsScoutMembersListParams,
SignalsScoutNotesListParams,
SignalsScoutProjectProfileGetParams,
+ SignalsScoutRunsCostsParams,
SignalsScoutRunsFindingsSummaryParams,
SignalsScoutRunsListParams,
SignalsScoutRunsRecentEmissionsParams,
@@ -1273,6 +1275,37 @@ export const signalsScoutRecordOutput = async (
})
}
+export const getSignalsScoutRunsCostsUrl = (projectId: string, params?: SignalsScoutRunsCostsParams) => {
+ const normalizedParams = new URLSearchParams()
+
+ Object.entries(params || {}).forEach(([key, value]) => {
+ if (value !== undefined) {
+ normalizedParams.append(key, value === null ? 'null' : String(value))
+ }
+ })
+
+ const stringifiedParams = normalizedParams.toString()
+
+ return stringifiedParams.length > 0
+ ? `/api/projects/${projectId}/signals/scout/runs/costs/?${stringifiedParams}`
+ : `/api/projects/${projectId}/signals/scout/runs/costs/`
+}
+
+/**
+ * Return what every scout on this project spent on model calls over the last `window_days`, with how many runs it started, how many of those had spend attributed, and how many inbox reports it filed or added to. Cost per day, per run, and per report are derived from those numbers by the caller, so the endpoint stays a fact table and the definitions live in one place. Spend is summed from the `$ai_generation` events the runs' sandboxes produced and joined to the run rows by task run id, because a team-authored scout's generations all carry the same stage tag and so cannot name it. Cached per project for 15 minutes: the window's trailing edge moves and the newest runs may still be settling, so this is a roughly current number, not a live one. `available` is false where the internal AI observability project holding those events can't be read, so an unknown spend never reads as zero. Staff-only, same gate as the per-run cost read. Strictly team-scoped.
+ * @summary Get what each scout spent over a window
+ */
+export const signalsScoutRunsCosts = async (
+ projectId: string,
+ params?: SignalsScoutRunsCostsParams,
+ options?: RequestInit
+): Promise<ScoutCostsApi> => {
+ return apiMutator<ScoutCostsApi>(getSignalsScoutRunsCostsUrl(projectId, params), {
+ ...options,
+ method: 'GET',
+ })
+}
+
export const getSignalsScoutRunsEmissionsBatchUrl = (projectId: string) => {
return `/api/projects/${projectId}/signals/scout/runs/emissions/batch/`
}
diff --git a/products/signals/mcp/tools.yaml b/products/signals/mcp/tools.yaml
index 4968b69ec127..72d8d7093e67 100644
--- a/products/signals/mcp/tools.yaml
+++ b/products/signals/mcp/tools.yaml
@@ -1102,6 +1102,9 @@ tools:
description:
'DEPRECATED: renamed to scout-run-now. This alias forwards to the same endpoint and will be removed. Call
scout-run-now directly with the same arguments.'
+ signals-scout-runs-costs:
+ operation: signals_scout_runs_costs
+ enabled: false
signals-scout-runs-emission-reports:
operation: signals_scout_runs_emission_reports
enabled: true
diff --git a/products/tasks/backend/logic/services/task_usage.py b/products/tasks/backend/logic/services/task_usage.py
index c4a6f580f6c6..e49bb94fb844 100644
--- a/products/tasks/backend/logic/services/task_usage.py
+++ b/products/tasks/backend/logic/services/task_usage.py
@@ -17,7 +17,7 @@ import requests
import structlog
from posthog.hogql import ast
-from posthog.hogql.parser import parse_select
+from posthog.hogql.parser import parse_expr, parse_select
from posthog.hogql.query import execute_hogql_query
from posthog.clickhouse.query_tagging import Feature, Product, tags_context
@@ -127,7 +127,7 @@ def _get_cross_region_task_token_cost(*, team_id: int, task_id: UUID, task_creat
# 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
# module imports this product's facade. `LLM_ANALYTICS_INTERNAL_TEAM_ID` is 2 in every region, so
-# it can't answer this on its own — it stays the fallback for a deployment that isn't US or EU.
+# it cannot identify a billing project outside US or EU Cloud.
INTERNAL_LLM_ANALYTICS_TEAM_ID_BY_REGION = {"EU": 1, "US": 2}
@@ -137,9 +137,15 @@ def _internal_llm_analytics_team() -> Team:
A deployment with no such project has nothing to read, and callers must surface that as
unknown rather than as zero spend.
"""
- team_id = INTERNAL_LLM_ANALYTICS_TEAM_ID_BY_REGION.get(
- settings.CLOUD_DEPLOYMENT or "", settings.LLM_ANALYTICS_INTERNAL_TEAM_ID
- )
+ region = (settings.CLOUD_DEPLOYMENT or "").upper()
+ team_id = INTERNAL_LLM_ANALYTICS_TEAM_ID_BY_REGION.get(region)
+ if team_id is None:
+ # Tests override this value with their fixture project. Other deployments do not have a
+ # configured region-local billing project, so project 2 can be an unrelated project.
+ if settings.TEST:
+ team_id = settings.LLM_ANALYTICS_INTERNAL_TEAM_ID
+ else:
+ raise TaskTokenUsageUnavailable("This deployment has no internal AI observability project")
try:
return Team.objects.get(pk=team_id)
except Team.DoesNotExist as error:
@@ -177,15 +183,26 @@ def get_local_task_token_cost(*, team_id: int, task_id: UUID, task_created_at: d
return Decimal(str(value or 0))
+# A window read asks for every run of one origin product on one team, so its row count is bounded
+# by that team's runs rather than by a requested id list. The cap is far above the busiest fleet's
+# week of runs, and only stops a pathological read from materializing without limit.
+MAX_TASK_RUN_COST_ROWS = 50_000
+
+
def get_local_task_run_token_costs(
*,
team_id: int,
origin_product: str,
- task_run_ids: Sequence[UUID],
generated_after: datetime,
product: Product,
+ task_run_ids: Sequence[UUID] | None = None,
) -> dict[str, Decimal]:
- """Model spend per task run, for every run in `task_run_ids` that has any attributed to it.
+ """Model spend per task run, for every run that has any attributed to it.
+
+ Pass `task_run_ids` to price a known set of runs. Pass nothing to price every run of
+ `origin_product` this team generated since `generated_after` — the team filter and the time
+ window bound that read, so a caller that would otherwise send tens of thousands of ids does not
+ have to.
Keyed on `task_origin_product` rather than `ai_product`, because `ai_product` names the agent
that made the generation, not the product the run belongs to: one origin product spans several
@@ -197,19 +214,36 @@ def get_local_task_run_token_costs(
is unknown, not zero. A run priced in part still reports the sum of what was priced, which is a
lower bound.
"""
- if not task_run_ids:
+ if task_run_ids is not None and not task_run_ids:
return {}
+ placeholders: dict[str, ast.Expr] = {
+ "generated_after": ast.Constant(value=generated_after),
+ "origin_product": ast.Constant(value=origin_product),
+ "team_id": ast.Constant(value=str(team_id)),
+ # The group-by yields at most one row per run, but a limit-less select is capped at 100
+ # rows, and both paths can cover more runs than that.
+ "row_limit": ast.Constant(value=len(task_run_ids) if task_run_ids is not None else MAX_TASK_RUN_COST_ROWS),
+ "run_filter": (
+ parse_expr(
+ "in(toString(properties.task_run_id), {task_run_ids})",
+ placeholders={"task_run_ids": ast.Constant(value=[str(run_id) for run_id in task_run_ids])},
+ )
+ if task_run_ids is not None
+ else ast.Constant(value=True)
+ ),
+ }
query = parse_select(
"""
SELECT toString(properties.task_run_id) AS task_run_id,
- round(sum(toFloat(properties.$ai_total_cost_usd)), 6) AS token_cost_usd
+ round(sum(toFloat(properties.$ai_total_cost_usd)), 6) AS token_cost_usd,
+ count() OVER () AS total_run_count
FROM events
WHERE equals(event, '$ai_generation')
AND greaterOrEquals(timestamp, {generated_after})
AND equals(properties.task_origin_product, {origin_product})
AND equals(toString(properties.team_id), {team_id})
- AND in(toString(properties.task_run_id), {task_run_ids})
+ AND {run_filter}
GROUP BY task_run_id
LIMIT {row_limit}
"""
@@ -217,19 +251,14 @@ def get_local_task_run_token_costs(
with tags_context(product=product, feature=Feature.QUERY):
result = execute_hogql_query(
query=query,
- placeholders={
- "generated_after": ast.Constant(value=generated_after),
- "origin_product": ast.Constant(value=origin_product),
- "team_id": ast.Constant(value=str(team_id)),
- "task_run_ids": ast.Constant(value=[str(task_run_id) for task_run_id in task_run_ids]),
- # The group-by yields at most one row per requested run, but a limit-less select
- # is capped at 100 rows, and a caller may ask about more runs than that.
- "row_limit": ast.Constant(value=len(task_run_ids)),
- },
+ placeholders=placeholders,
team=_internal_llm_analytics_team(),
query_type="TaskRunUsageTokenCost",
)
- return {str(row[0]): Decimal(str(row[1])) for row in (result.results or []) if row[0] and row[1] is not None}
+ rows = result.results or []
+ if task_run_ids is None and rows and int(rows[0][2]) > MAX_TASK_RUN_COST_ROWS:
+ raise TaskTokenUsageUnavailable("The task-run cost result exceeded its safe row limit")
+ return {str(row[0]): Decimal(str(row[1])) for row in rows if row[0] and row[1] is not None}
def _get_task_compute_cost(*, team_id: int, task_id: UUID) -> Decimal:
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 6fe877a5201e..08f55a9cbbbb 100644
--- a/products/tasks/backend/logic/services/tests/test_task_usage.py
+++ b/products/tasks/backend/logic/services/tests/test_task_usage.py
@@ -62,6 +62,39 @@ class TestTaskUsageQueryTagging(SimpleTestCase):
assert team_get.call_args.kwargs["pk"] == expected_team_id
+ def test_costs_are_unavailable_outside_a_billing_region(self) -> None:
+ with (
+ self.settings(CLOUD_DEPLOYMENT="DEV", TEST=False),
+ patch.object(task_usage.Team.objects, "get") as team_get,
+ ):
+ with self.assertRaises(task_usage.TaskTokenUsageUnavailable):
+ task_usage.get_local_task_run_token_costs(
+ team_id=1,
+ origin_product="signals_scout",
+ generated_after=datetime(2026, 8, 1, tzinfo=UTC),
+ product=Product.SIGNALS,
+ )
+
+ team_get.assert_not_called()
+
+ def test_window_costs_fail_when_the_safe_row_limit_is_exceeded(self) -> None:
+ # HogQL returns at most the configured limit. The window count still reports that a row was
+ # omitted, so the caller does not mistake a truncated result for the complete cost.
+ rows = [("run-1", 1, 3), ("run-2", 2, 3)]
+ with (
+ self.settings(CLOUD_DEPLOYMENT="US"),
+ patch.object(task_usage, "MAX_TASK_RUN_COST_ROWS", 2),
+ patch.object(task_usage.Team.objects, "get", return_value=object()),
+ patch.object(task_usage, "execute_hogql_query", return_value=SimpleNamespace(results=rows)),
+ ):
+ with self.assertRaises(task_usage.TaskTokenUsageUnavailable):
+ task_usage.get_local_task_run_token_costs(
+ team_id=1,
+ origin_product="signals_scout",
+ generated_after=datetime(2026, 8, 1, tzinfo=UTC),
+ product=Product.SIGNALS,
+ )
+
class TestTaskUsage(ClickhouseTestMixin, APIBaseTest):
def setUp(self) -> None:
@@ -150,6 +183,47 @@ class TestTaskUsage(ClickhouseTestMixin, APIBaseTest):
# can tell it from a run that really spent nothing.
assert costs == {priced_run: Decimal("3.5"), second_run: Decimal("4")}
+ def test_run_token_costs_without_run_ids_price_every_run_of_the_origin_product(self) -> None:
+ # The per-scout read asks about a whole window rather than a known set of runs, because a
+ # per-team id list would be tens of thousands of ids on the largest fleets. The team filter
+ # and the window are what bound that read, so they still have to exclude another team's and
+ # another product's generations.
+ mine = "66666666-6666-6666-6666-666666666666"
+ also_mine = "77777777-7777-7777-7777-777777777777"
+ theirs = "88888888-8888-8888-8888-888888888888"
+ other_product = "99999999-9999-9999-9999-999999999999"
+ for team_id, task_run_id, origin_product, offset_seconds in (
+ (self.team.id, mine, "signals_scout", 1),
+ (self.team.id, also_mine, "signals_scout", 1),
+ (self.team.id + 1, theirs, "signals_scout", 1),
+ (self.team.id, other_product, "user_created", 1),
+ # Before the window opens, so it must not count.
+ (self.team.id, mine, "signals_scout", -60),
+ ):
+ _create_event(
+ event="$ai_generation",
+ team=self.team,
+ distinct_id=str(self.user.distinct_id),
+ timestamp=self.task.created_at + timedelta(seconds=offset_seconds),
+ properties={
+ "team_id": team_id,
+ "task_run_id": task_run_id,
+ "task_origin_product": origin_product,
+ "$ai_total_cost_usd": 1,
+ },
+ )
+ flush_persons_and_events()
+
+ with self.settings(LLM_ANALYTICS_INTERNAL_TEAM_ID=self.team.id):
+ costs = task_usage.get_local_task_run_token_costs(
+ team_id=self.team.id,
+ origin_product="signals_scout",
+ generated_after=self.task.created_at,
+ product=Product.SIGNALS,
+ )
+
+ assert costs == {mine: Decimal("1"), also_mine: Decimal("1")}
+
def test_run_token_costs_price_a_full_batch_rather_than_the_default_row_limit(self) -> None:
# `execute_hogql_query` caps a limit-less select at 100 rows, but the endpoint takes 200 run
# ids per call. Without an explicit limit the runs past the hundredth read as unattributed.
diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.ts
index b17d072b9dd5..ad61c411b43f 100644
--- a/services/mcp/src/api/generated.ts
+++ b/services/mcp/src/api/generated.ts
@@ -78643,6 +78643,34 @@ export namespace Schemas {
suggestion_id?: string;
}
+ /**
+ * What one scout spent in the window, and what it produced for that spend.
+ */
+ export interface ScoutCost {
+ /** Full skill name of the scout, e.g. `signals-scout-error-tracking`. */
+ skill_name: string;
+ /** Model spend attributed to the scout's runs in the window, in US dollars. Zero when none of its runs had spend attributed, which `priced_run_count` tells apart from a scout that really spent nothing. */
+ spend_usd: number;
+ /** Runs the scout started in the window. */
+ run_count: number;
+ /** Runs of the scout that had spend attributed. Lower than `run_count` where a run failed before its first model call, or its generations haven't landed yet. Divide `spend_usd` by this, not by `run_count`, for cost per run. */
+ priced_run_count: number;
+ /** Distinct inbox reports the scout filed or added to in the window. A report it authored in one run and edited in three counts once. Zero means the scout produced no reports, so cost per report has no value rather than a value of zero. */
+ reports_touched: number;
+ }
+
+ /**
+ * Model spend and output per scout over a window.
+ */
+ export interface ScoutCosts {
+ /** Window the rows describe, in days. */
+ window_days: number;
+ /** One row per scout that started at least one run on this project in the window. */
+ scouts: ScoutCost[];
+ /** False when this deployment has no internal AI observability project to read the generations from, so `scouts` is empty and every spend is unknown rather than zero. */
+ available: boolean;
+ }
+
/**
* One finding the run emitted, paired with the inbox report (if any) its signal grouped into.
*
@@ -101662,6 +101690,15 @@ export namespace Schemas {
text?: string;
};
+ export type SignalsScoutRunsCostsParams = {
+ /**
+ * Window in days over runs' `created_at` (default 7). Only 7 is accepted today — it matches the window the roster's fleet headline spans, so every number on the page describes one span.
+ * @minimum 7
+ * @maximum 7
+ */
+ window_days?: number;
+ };
+
export type SignalsScoutRunsRecentEmissionsParams = {
/**
* ISO-8601 inclusive lower bound on `emitted_at`. Omit to skip the lower bound.