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): bill on report outcomes instead of LLM spend (#63996)

Joshua Snyder7246676ddff7
diff --git a/posthog/tasks/test/test_usage_report.py b/posthog/tasks/test/test_usage_report.py
index ea2e69ee0267..753853ad464e 100644
--- a/posthog/tasks/test/test_usage_report.py
+++ b/posthog/tasks/test/test_usage_report.py
@@ -4260,77 +4260,48 @@ class TestAIEventsUsageReport(ClickhouseDestroyTablesMixin, TestCase, Clickhouse
self.assertEqual(result, [])
- @patch("posthog.tasks.usage_report.get_instance_region")
- def test_signals_credits_only_counts_signals_events(self, mock_region: MagicMock) -> None:
- """The signals query only counts generations tagged ai_product='signals' for the same team."""
- from posthog.tasks.usage_report import (
- get_teams_with_ai_credits_used_in_period,
- get_teams_with_signals_credits_used_in_period,
- )
+ def test_signals_credits_bills_reports_with_implementation_pr(self) -> None:
+ """Signals credits are a flat charge per report whose implementation shipped a PR (Postgres path)."""
+ from django.apps import apps
+
+ from posthog.tasks.usage_report import get_teams_with_signals_credits_used_in_period
+
+ from products.signals.backend.models import SignalReport, SignalReportTask
+
+ # `products.tasks` is isolated; reach its models via the app registry, not a cross-boundary import.
+ Task = apps.get_model("tasks", "Task")
+ TaskRun = apps.get_model("tasks", "TaskRun")
- mock_region.return_value = "US"
self._setup_teams()
- analytics_org = Organization.objects.create(name="PostHog Analytics")
- analytics_team = Team.objects.create(pk=2, organization=analytics_org, name="Analytics")
- self._setup_instance_group_mapping(analytics_team)
period = get_previous_day(at=now() + relativedelta(days=1))
period_start, period_end = period
- # Signals event — should appear only in signals credits
- _create_event(
- event="$ai_generation",
- team=analytics_team,
- distinct_id="user_signals",
- timestamp=period_start + relativedelta(hours=1),
- properties={
- "team_id": self.org_1_team_1.id,
- "$ai_trace_id": "trace_signals",
- "$ai_total_cost_usd": 2.0,
- "$ai_billable": True,
- "ai_product": "signals",
- "$group_1": "https://us.posthog.com",
- },
- )
+ team = self.org_1_team_1
- # Max AI event — should appear only in ai credits. Max AI is billed via its paired
- # $ai_trace (unlike signals, which never emits one), so create a matching billable trace.
- _create_event(
- event="$ai_trace",
- team=analytics_team,
- distinct_id="user_max",
- timestamp=period_start + relativedelta(hours=2),
- properties={
- "$ai_trace_id": "trace_max",
- "$ai_output_state": {"messages": [{"tool_calls": [{"name": "query_executor"}]}]},
- "$group_1": "https://us.posthog.com",
- },
+ # A report whose implementation task opened a PR within the period — billed flat ($15 = 1500).
+ report = SignalReport.objects.create(
+ team=team, status=SignalReport.Status.READY, signal_count=1, total_weight=1.0
)
-
- _create_event(
- event="$ai_generation",
- team=analytics_team,
- distinct_id="user_max",
- timestamp=period_start + relativedelta(hours=2),
- properties={
- "team_id": self.org_1_team_1.id,
- "$ai_trace_id": "trace_max",
- "$ai_total_cost_usd": 1.0,
- "$ai_billable": True,
- "ai_product": "posthog_ai",
- "$group_1": "https://us.posthog.com",
- },
+ task = Task.objects.create(
+ team=team, title="impl", description="d", origin_product=Task.OriginProduct.SIGNAL_REPORT
+ )
+ SignalReportTask.objects.create(
+ team=team, report=report, task=task, relationship=SignalReportTask.Relationship.IMPLEMENTATION
+ )
+ TaskRun.objects.create(
+ team=team,
+ task=task,
+ output={"pr_url": "https://github.com/x/y/pull/1"},
+ created_at=period_start + relativedelta(hours=1),
)
- flush_persons_and_events()
+ # A report with no implementation PR contributes nothing.
+ SignalReport.objects.create(team=team, status=SignalReport.Status.READY, signal_count=1, total_weight=1.0)
- signals_result = get_teams_with_signals_credits_used_in_period(period_start, period_end)
- ai_result = get_teams_with_ai_credits_used_in_period(period_start, period_end)
+ result = get_teams_with_signals_credits_used_in_period(period_start, period_end)
- # signals: 2.0 USD * 100 * 1.2 = 240
- self.assertEqual(signals_result, [(self.org_1_team_1.id, 240)])
- # ai (posthog_ai only): 1.0 USD * 100 * 1.2 = 120
- self.assertEqual(ai_result, [(self.org_1_team_1.id, 120)])
+ self.assertEqual(result, [(team.id, 1500)])
@patch("posthog.tasks.usage_report.get_instance_region")
def test_ai_credits_counts_billable_generation_with_no_trace(self, mock_region: MagicMock) -> None:
@@ -4418,81 +4389,6 @@ class TestAIEventsUsageReport(ClickhouseDestroyTablesMixin, TestCase, Clickhouse
# 1.0 USD * 100 * 1.2 = 120
self.assertEqual(result, [(self.org_1_team_1.id, 120)])
- @patch("posthog.tasks.usage_report.get_instance_region")
- def test_signals_credits_counts_traceless_generation(self, mock_region: MagicMock) -> None:
- """A billable signals generation with no $ai_trace IS billed via the empty-trace fallback.
-
- Signals never emits $ai_trace events, so the LEFT JOIN never matches; the fallback is
- what makes signals billable at all.
- """
- from posthog.tasks.usage_report import get_teams_with_signals_credits_used_in_period
-
- mock_region.return_value = "US"
- self._setup_teams()
- analytics_org = Organization.objects.create(name="PostHog Analytics")
- analytics_team = Team.objects.create(pk=2, organization=analytics_org, name="Analytics")
- self._setup_instance_group_mapping(analytics_team)
-
- period = get_previous_day(at=now() + relativedelta(days=1))
- period_start, period_end = period
-
- _create_event(
- event="$ai_generation",
- team=analytics_team,
- distinct_id="user_signals",
- timestamp=period_start + relativedelta(hours=1),
- properties={
- "team_id": self.org_1_team_1.id,
- "$ai_trace_id": "trace_signals",
- "$ai_total_cost_usd": 4.0,
- "$ai_billable": True,
- "ai_product": "signals",
- "$group_1": "https://us.posthog.com",
- },
- )
-
- flush_persons_and_events()
-
- result = get_teams_with_signals_credits_used_in_period(period_start, period_end)
-
- # 4.0 USD * 100 * 1.2 = 480
- self.assertEqual(result, [(self.org_1_team_1.id, 480)])
-
- @patch("posthog.tasks.usage_report.get_instance_region")
- def test_signals_credits_excludes_non_billable_generation(self, mock_region: MagicMock) -> None:
- """A signals generation tagged $ai_billable=false is not counted, even for signals."""
- from posthog.tasks.usage_report import get_teams_with_signals_credits_used_in_period
-
- mock_region.return_value = "US"
- self._setup_teams()
- analytics_org = Organization.objects.create(name="PostHog Analytics")
- analytics_team = Team.objects.create(pk=2, organization=analytics_org, name="Analytics")
- self._setup_instance_group_mapping(analytics_team)
-
- period = get_previous_day(at=now() + relativedelta(days=1))
- period_start, period_end = period
-
- _create_event(
- event="$ai_generation",
- team=analytics_team,
- distinct_id="user_signals",
- timestamp=period_start + relativedelta(hours=1),
- properties={
- "team_id": self.org_1_team_1.id,
- "$ai_trace_id": "trace_signals",
- "$ai_total_cost_usd": 4.0,
- "$ai_billable": False,
- "ai_product": "signals",
- "$group_1": "https://us.posthog.com",
- },
- )
-
- flush_persons_and_events()
-
- result = get_teams_with_signals_credits_used_in_period(period_start, period_end)
-
- self.assertEqual(result, [])
-
def test_has_non_zero_usage_counts_signals_credits(self) -> None:
"""A signals-only org must survive has_non_zero_usage so its report still reaches billing."""
import dataclasses
diff --git a/posthog/tasks/usage_report.py b/posthog/tasks/usage_report.py
index bd7bab40295a..a97759dd430d 100644
--- a/posthog/tasks/usage_report.py
+++ b/posthog/tasks/usage_report.py
@@ -51,6 +51,7 @@ from products.dashboards.backend.models.dashboard import Dashboard
from products.data_modeling.backend.models.datawarehouse_saved_query import DataWarehouseSavedQuery
from products.error_tracking.backend.facade import api as error_tracking_api
from products.feature_flags.backend.models.feature_flag import FeatureFlag
+from products.signals.backend.billing import get_signals_billing_credits_by_team
from products.surveys.backend.models import Survey
from products.surveys.backend.util import (
SurveyEventProperties,
@@ -213,7 +214,7 @@ class UsageReportCounters:
# AI Billing Credits (PostHog AI feature usage)
ai_credits_used_in_period: int
- # Signals Billing Credits (Signals product usage — same cost math as ai_credits, scoped to ai_product='signals')
+ # Signals Billing Credits (flat credits per report whose implementation shipped a PR)
signals_credits_used_in_period: int
# CDP Delivery
@@ -1167,9 +1168,6 @@ POSTHOG_AI_PRODUCTS = [
"surveys",
]
-# ai_product values billed as signals credits.
-SIGNALS_AI_PRODUCTS = ["signals"]
-
def get_ai_billing_instance_group_type_index(team_id: int) -> int | None:
"""Resolve the $group_N index that holds the customer cloud URL for the internal AI events team."""
@@ -1383,19 +1381,15 @@ def get_teams_with_ai_credits_used_in_period(
@timed_log()
-@retry(tries=QUERY_RETRIES, delay=QUERY_RETRY_DELAY, backoff=QUERY_RETRY_BACKOFF)
def get_teams_with_signals_credits_used_in_period(
begin: datetime,
end: datetime,
) -> list[tuple[int, int]]:
- """Signals billing credits — only events tagged with ai_product='signals'."""
- return _get_teams_with_ai_credits_for_products(
- begin,
- end,
- ai_products=SIGNALS_AI_PRODUCTS,
- usage_report_tag="signals_credits",
- product_tag=Product.SIGNALS,
- )
+ """Signals billing — a flat credit charge per report whose implementation shipped a PR.
+
+ Outcome-based, not LLM spend: see `products/signals/backend/billing.py`.
+ """
+ return get_signals_billing_credits_by_team(begin, end)
dwh_pricing_free_period_start = datetime(2025, 10, 29, 0, 0, 0, tzinfo=UTC)
diff --git a/products/signals/backend/billing.py b/products/signals/backend/billing.py
new file mode 100644
index 000000000000..2262542b26c6
--- /dev/null
+++ b/products/signals/backend/billing.py
@@ -0,0 +1,112 @@
+"""Signals billing — a flat credit charge per report that ships an implementation PR.
+
+Signals is billed on outcomes, not LLM spend: each signal report whose implementation task
+opens a pull request is charged a flat number of credits, once. The chargeable moment is
+deterministic — the first implementation `TaskRun` with a `pr_url` set — so a report is
+billed exactly once, in the period that PR first appeared, regardless of any later status
+changes, re-judgements, or additional runs.
+
+The PR↔report link lives on the `SignalReportTask` bridge (relationship=IMPLEMENTATION); the
+PR URL itself is written to `TaskRun.output['pr_url']`. There is no artefact that records the
+implementation task or its PR, so the query is rooted on that bridge, not on artefacts.
+
+Because this is a billing source it fails closed: a run only bills when its PR URL is a GitHub
+URL and the run, task, bridge, and report teams all agree, so malformed bridge rows never
+produce a charge.
+
+Credits use the same unit as ai_credits: 1 credit = $0.01, so the flat $15 charge is 1500
+credits.
+"""
+
+import uuid
+from collections import defaultdict
+from datetime import datetime
+
+from django.db.models import F, QuerySet
+
+from products.signals.backend.models import SignalReportTask
+
+_IMPLEMENTATION = SignalReportTask.Relationship.IMPLEMENTATION
+
+# Only PRs hosted on GitHub are billable. The PR URL is GitHub's `html_url`
+# (https://github.com/owner/repo/pull/N), so validate the host prefix to avoid charging
+# for malformed or non-GitHub values written into `output.pr_url`.
+_GITHUB_PR_URL_PREFIX = "https://github.com/"
+
+SIGNALS_CREDITS_PER_DOLLAR = 100 # 1 credit = $0.01, matching ai_credits
+
+# Flat credits charged once per report whose implementation shipped a PR ($15).
+SIGNALS_CREDITS_PER_REPORT_WITH_PR = 15 * SIGNALS_CREDITS_PER_DOLLAR # 1500
+
+
+def _bridges_with_pr_run(**run_created_at: datetime) -> QuerySet[SignalReportTask]:
+ """Implementation bridges whose task shipped a billable PR run matching `run_created_at`.
+
+ Rooted on the signals-owned `SignalReportTask` bridge and traversing to runs via the
+ `task__runs` relation, so the query never imports the tasks product's internals — it stays
+ behind the tasks public interface. Postgres is free to drive the join from the run
+ `created_at` index regardless, so the period scan stays bounded by PRs shipped, not by the
+ number of bridges.
+
+ Fail closed: a bridge only counts when one of its runs carries a GitHub PR URL within the
+ given `created_at` bound and the four teams in the chain — run, task, bridge, and report —
+ all agree. A malformed bridge whose teams disagree is excluded rather than charged to
+ whichever team_id happened to be on it. The run-level conditions sit in one `filter()` so
+ they all resolve against the same `TaskRun` row.
+ """
+ return SignalReportTask.objects.filter(
+ relationship=_IMPLEMENTATION,
+ task__runs__output__pr_url__startswith=_GITHUB_PR_URL_PREFIX,
+ # Fail closed on team disagreement across run / task / bridge / report.
+ task__team_id=F("team_id"),
+ report__team_id=F("team_id"),
+ task__runs__team_id=F("team_id"),
+ # `output__pr_url__startswith` only matches present, string-typed values, so no
+ # separate isnull / empty-string guard is needed.
+ **run_created_at,
+ )
+
+
+def get_signals_billing_credits_by_team(begin: datetime, end: datetime) -> list[tuple[int, int]]:
+ """Signals credits used per team in `[begin, end)`.
+
+ A report is billable in this period when the first implementation PR for it appeared in the
+ window — an implementation `TaskRun` with a `pr_url` was created in `[begin, end)` and no
+ such run exists before `begin`. Each billable report is charged a flat
+ `SIGNALS_CREDITS_PER_REPORT_WITH_PR`. Returns `[(team_id, credits), ...]` for teams with
+ non-zero usage only.
+
+ The entry scan is bounded by PRs shipped in the period (via the `created_at` +
+ `output__pr_url` indexes), not by the total number of reports, task runs, or teams.
+ """
+ # Reports whose implementation produced a billable PR within this period, mapped to the team
+ # that owns the report. The teams are guaranteed equal by `_bridges_with_pr_run()`, so the
+ # bridge's team_id is the report's team.
+ report_team: dict[uuid.UUID, int] = {}
+ for report_id, team_id in _bridges_with_pr_run(
+ task__runs__created_at__gte=begin,
+ task__runs__created_at__lt=end,
+ ).values_list("report_id", "team_id"):
+ report_team.setdefault(report_id, team_id)
+
+ if not report_team:
+ return []
+
+ report_ids = list(report_team)
+
+ # Exclude reports whose first implementation PR predates this period — they were billed in an
+ # earlier period. This is what makes billing idempotent across re-runs and prevents
+ # double-charging when a report ships more PR runs later.
+ billed_earlier = set(
+ _bridges_with_pr_run(task__runs__created_at__lt=begin)
+ .filter(report_id__in=report_ids)
+ .values_list("report_id", flat=True)
+ )
+
+ totals: dict[int, int] = defaultdict(int)
+ for report_id, team_id in report_team.items():
+ if report_id in billed_earlier:
+ continue
+ totals[team_id] += SIGNALS_CREDITS_PER_REPORT_WITH_PR
+
+ return list(totals.items())
diff --git a/products/signals/backend/migrations/0043_signalreporttask_rel_idx.py b/products/signals/backend/migrations/0043_signalreporttask_rel_idx.py
new file mode 100644
index 000000000000..5441afaa3e8d
--- /dev/null
+++ b/products/signals/backend/migrations/0043_signalreporttask_rel_idx.py
@@ -0,0 +1,20 @@
+from django.db import migrations, models
+
+from posthog.migration_helpers import SafeAddIndexConcurrently
+
+
+class Migration(migrations.Migration):
+ # Concurrent index builds cannot run inside a transaction. Lives in its own
+ # migration per PostHog policy (don't mix CONCURRENTLY operations with regular DDL).
+ atomic = False
+
+ dependencies = [
+ ("signals", "0042_signalreport_status_before_suppression"),
+ ]
+
+ operations = [
+ SafeAddIndexConcurrently(
+ model_name="signalreporttask",
+ index=models.Index(fields=["report", "relationship"], name="signals_report_task_rel_idx"),
+ ),
+ ]
diff --git a/products/signals/backend/migrations/max_migration.txt b/products/signals/backend/migrations/max_migration.txt
index 4a7de5ac5b61..d76ee7781678 100644
--- a/products/signals/backend/migrations/max_migration.txt
+++ b/products/signals/backend/migrations/max_migration.txt
@@ -1 +1 @@
-0042_signalreport_status_before_suppression
+0043_signalreporttask_rel_idx
diff --git a/products/signals/backend/models.py b/products/signals/backend/models.py
index 6f79e2b47907..ea614ad27b55 100644
--- a/products/signals/backend/models.py
+++ b/products/signals/backend/models.py
@@ -421,6 +421,10 @@ class SignalReportTask(UUIDModel):
class Meta:
verbose_name = "Signal report task"
verbose_name_plural = "Signal report tasks"
+ indexes = [
+ # Billing and PR-URL lookups traverse this bridge by report filtered on relationship.
+ models.Index(fields=["report", "relationship"], name="signals_report_task_rel_idx"),
+ ]
# ── Signals scout (headless cross-source explorer) ──────────────────────────────
diff --git a/products/signals/backend/test/test_billing.py b/products/signals/backend/test/test_billing.py
new file mode 100644
index 000000000000..e75ddf7878f1
--- /dev/null
+++ b/products/signals/backend/test/test_billing.py
@@ -0,0 +1,278 @@
+from datetime import UTC, datetime
+from typing import TYPE_CHECKING
+
+from posthog.test.base import BaseTest
+
+from django.apps import apps
+
+from parameterized import parameterized
+
+from posthog.models import Team
+
+from products.signals.backend.billing import SIGNALS_CREDITS_PER_REPORT_WITH_PR, get_signals_billing_credits_by_team
+from products.signals.backend.models import SignalReport, SignalReportTask
+
+if TYPE_CHECKING:
+ from products.tasks.backend.models import (
+ Task as TaskModel,
+ TaskRun as TaskRunModel,
+ )
+
+PERIOD_START = datetime(2026, 6, 1, tzinfo=UTC)
+PERIOD_END = datetime(2026, 7, 1, tzinfo=UTC)
+
+# Sentinel so a test can force a raw `output` (e.g. SQL NULL or a non-string pr_url) without
+# colliding with the str | None pr_url path.
+_UNSET = object()
+
+
+def _at(day: int, hour: int = 12) -> datetime:
+ return datetime(2026, 6, day, hour, tzinfo=UTC)
+
+
+# `products.tasks` is an isolated product, so its models are reached at runtime via the app
+# registry rather than imported across the boundary (type-only imports above are ignored by tach).
+def _task_model() -> type["TaskModel"]:
+ return apps.get_model("tasks", "Task")
+
+
+def _task_run_model() -> type["TaskRunModel"]:
+ return apps.get_model("tasks", "TaskRun")
+
+
+class TestSignalsBilling(BaseTest):
+ def _report(self, *, team: Team | None = None, status: str = SignalReport.Status.READY) -> SignalReport:
+ return SignalReport.objects.create(team=team or self.team, status=status, signal_count=1, total_weight=1.0)
+
+ def _pr_run(
+ self,
+ report: SignalReport,
+ *,
+ created_at: datetime,
+ pr_url: str | None = "https://github.com/x/y/pull/1",
+ team: Team | None = None,
+ relationship: str = SignalReportTask.Relationship.IMPLEMENTATION,
+ output: object = _UNSET,
+ ) -> "TaskRunModel":
+ team = team or self.team
+ Task, TaskRun = _task_model(), _task_run_model()
+ task = Task.objects.create(
+ team=team, title="impl", description="d", origin_product=Task.OriginProduct.SIGNAL_REPORT
+ )
+ SignalReportTask.objects.create(team=team, report=report, task=task, relationship=relationship)
+ run_output = output if output is not _UNSET else ({"pr_url": pr_url} if pr_url is not None else {})
+ return TaskRun.objects.create(team=team, task=task, output=run_output, created_at=created_at)
+
+ def _credits(self) -> dict[int, int]:
+ return dict(get_signals_billing_credits_by_team(PERIOD_START, PERIOD_END))
+
+ def test_flat_credit_is_fifteen_dollars(self) -> None:
+ # 1 credit = $0.01, so $15 == 1500 credits.
+ self.assertEqual(SIGNALS_CREDITS_PER_REPORT_WITH_PR, 1500)
+
+ def test_report_with_pr_billed_flat(self) -> None:
+ report = self._report()
+ self._pr_run(report, created_at=_at(10))
+ self.assertEqual(self._credits(), {self.team.id: 1500})
+
+ def test_report_without_pr_not_billed(self) -> None:
+ self._report()
+ self.assertEqual(self._credits(), {})
+
+ @parameterized.expand([("null_pr_url", None), ("empty_pr_url", "")])
+ def test_run_without_usable_pr_url_not_billed(self, _name: str, pr_url: str | None) -> None:
+ report = self._report()
+ self._pr_run(report, created_at=_at(10), pr_url=pr_url)
+ self.assertEqual(self._credits(), {})
+
+ @parameterized.expand(
+ [
+ ("http_not_https", "http://github.com/x/y/pull/1"),
+ ("gitlab", "https://gitlab.com/x/y/-/merge_requests/1"),
+ ("phishy_host", "https://github.com.evil.com/x/y/pull/1"),
+ ("no_scheme", "github.com/x/y/pull/1"),
+ ("garbage", "not-a-url"),
+ ]
+ )
+ def test_non_github_pr_url_not_billed(self, _name: str, pr_url: str) -> None:
+ report = self._report()
+ self._pr_run(report, created_at=_at(10), pr_url=pr_url)
+ self.assertEqual(self._credits(), {})
+
+ def test_run_with_null_output_not_billed(self) -> None:
+ # `output` is null=True, so SQL NULL is the real default for a run with no PR — not {}.
+ report = self._report()
+ self._pr_run(report, created_at=_at(10), output=None)
+ self.assertEqual(self._credits(), {})
+
+ @parameterized.expand(
+ [
+ ("number", 123),
+ ("bool", True),
+ ("object", {"html_url": "https://github.com/x/y/pull/1"}),
+ ("array", ["https://github.com/x/y/pull/1"]),
+ ]
+ )
+ def test_non_string_pr_url_not_billed(self, _name: str, pr_url: object) -> None:
+ # `startswith` must match only present, string-typed values; a non-string pr_url never bills.
+ report = self._report()
+ self._pr_run(report, created_at=_at(10), output={"pr_url": pr_url})
+ self.assertEqual(self._credits(), {})
+
+ def test_bridge_team_mismatch_not_billed(self) -> None:
+ # A malformed bridge whose team disagrees with the run/report must not produce a charge.
+ Task, TaskRun = _task_model(), _task_run_model()
+ other = Team.objects.create(organization=self.organization, name="other")
+ report = self._report()
+ task = Task.objects.create(
+ team=self.team, title="impl", description="d", origin_product=Task.OriginProduct.SIGNAL_REPORT
+ )
+ SignalReportTask.objects.create(
+ team=other, report=report, task=task, relationship=SignalReportTask.Relationship.IMPLEMENTATION
+ )
+ TaskRun.objects.create(
+ team=self.team, task=task, output={"pr_url": "https://github.com/x/y/pull/1"}, created_at=_at(10)
+ )
+ self.assertEqual(self._credits(), {})
+
+ def test_run_team_mismatch_not_billed(self) -> None:
+ # A run whose team disagrees with the task/bridge/report must not produce a charge.
+ Task, TaskRun = _task_model(), _task_run_model()
+ other = Team.objects.create(organization=self.organization, name="other")
+ report = self._report()
+ task = Task.objects.create(
+ team=self.team, title="impl", description="d", origin_product=Task.OriginProduct.SIGNAL_REPORT
+ )
+ SignalReportTask.objects.create(
+ team=self.team, report=report, task=task, relationship=SignalReportTask.Relationship.IMPLEMENTATION
+ )
+ TaskRun.objects.create(
+ team=other, task=task, output={"pr_url": "https://github.com/x/y/pull/1"}, created_at=_at(10)
+ )
+ self.assertEqual(self._credits(), {})
+
+ def test_task_team_mismatch_not_billed(self) -> None:
+ # Bridge/run/report all agree but the task belongs to another team — fail closed.
+ # Isolates the task__team_id check; the bridge-mismatch test breaks every clause at once.
+ Task, TaskRun = _task_model(), _task_run_model()
+ other = Team.objects.create(organization=self.organization, name="other")
+ report = self._report()
+ task = Task.objects.create(
+ team=other, title="impl", description="d", origin_product=Task.OriginProduct.SIGNAL_REPORT
+ )
+ SignalReportTask.objects.create(
+ team=self.team, report=report, task=task, relationship=SignalReportTask.Relationship.IMPLEMENTATION
+ )
+ TaskRun.objects.create(
+ team=self.team, task=task, output={"pr_url": "https://github.com/x/y/pull/1"}, created_at=_at(10)
+ )
+ self.assertEqual(self._credits(), {})
+
+ def test_report_team_mismatch_not_billed(self) -> None:
+ # A bridge/task/run all agree but the report belongs to another team — fail closed.
+ # Isolates the report__team_id check (the other mismatch tests also break the task check).
+ Task, TaskRun = _task_model(), _task_run_model()
+ other = Team.objects.create(organization=self.organization, name="other")
+ report = self._report(team=other)
+ task = Task.objects.create(
+ team=self.team, title="impl", description="d", origin_product=Task.OriginProduct.SIGNAL_REPORT
+ )
+ SignalReportTask.objects.create(
+ team=self.team, report=report, task=task, relationship=SignalReportTask.Relationship.IMPLEMENTATION
+ )
+ TaskRun.objects.create(
+ team=self.team, task=task, output={"pr_url": "https://github.com/x/y/pull/1"}, created_at=_at(10)
+ )
+ self.assertEqual(self._credits(), {})
+
+ @parameterized.expand([("at_period_start", PERIOD_START, True), ("at_period_end", PERIOD_END, False)])
+ def test_period_window_is_half_open(self, _name: str, created_at: datetime, billed: bool) -> None:
+ # begin is inclusive, end is exclusive — a PR exactly at end belongs to the next period.
+ report = self._report()
+ self._pr_run(report, created_at=created_at)
+ self.assertEqual(self._credits(), {self.team.id: 1500} if billed else {})
+
+ def test_pr_before_period_not_billed(self) -> None:
+ report = self._report()
+ self._pr_run(report, created_at=datetime(2026, 5, 28, tzinfo=UTC))
+ self.assertEqual(self._credits(), {})
+
+ def test_pr_after_period_not_billed(self) -> None:
+ report = self._report()
+ self._pr_run(report, created_at=datetime(2026, 7, 2, tzinfo=UTC))
+ self.assertEqual(self._credits(), {})
+
+ def test_report_first_billed_in_prior_period_not_rebilled(self) -> None:
+ # First PR landed last month; a second PR this month must not re-charge.
+ report = self._report()
+ self._pr_run(report, created_at=datetime(2026, 5, 28, tzinfo=UTC))
+ self._pr_run(report, created_at=_at(20))
+ self.assertEqual(self._credits(), {})
+
+ def test_billed_once_across_consecutive_periods(self) -> None:
+ # The production loop runs period after period. A report's first PR is billed in its period;
+ # a later PR in the next period must charge zero. Asserts both halves, not just the second.
+ july_start = PERIOD_END
+ august_start = datetime(2026, 8, 1, tzinfo=UTC)
+ report = self._report()
+ self._pr_run(report, created_at=_at(10))
+ self._pr_run(report, created_at=datetime(2026, 7, 15, tzinfo=UTC))
+ self.assertEqual(dict(get_signals_billing_credits_by_team(PERIOD_START, PERIOD_END)), {self.team.id: 1500})
+ self.assertEqual(get_signals_billing_credits_by_team(july_start, august_start), [])
+
+ def test_earlier_pr_on_different_task_excludes_report(self) -> None:
+ # A report can have several implementation tasks. If any of them shipped a PR before the
+ # period, the report's first PR predates the window and must not be re-billed here.
+ report = self._report()
+ self._pr_run(report, created_at=datetime(2026, 5, 20, tzinfo=UTC)) # task A, last month
+ self._pr_run(report, created_at=_at(15)) # task B, this month
+ self.assertEqual(self._credits(), {})
+
+ def test_multiple_prs_in_period_billed_once(self) -> None:
+ report = self._report()
+ self._pr_run(report, created_at=_at(5))
+ self._pr_run(report, created_at=_at(22))
+ self.assertEqual(self._credits(), {self.team.id: 1500})
+
+ def test_pr_on_non_implementation_task_not_billed(self) -> None:
+ report = self._report()
+ self._pr_run(report, created_at=_at(19), relationship=SignalReportTask.Relationship.RESEARCH)
+ self.assertEqual(self._credits(), {})
+
+ @parameterized.expand(
+ [
+ (SignalReport.Status.RESOLVED,),
+ (SignalReport.Status.SUPPRESSED,),
+ # Billing follows the shipped PR, not the report's lifecycle: a report deleted after its
+ # implementation landed is still charged once (matching "regardless of later status changes").
+ (SignalReport.Status.DELETED,),
+ ]
+ )
+ def test_billed_regardless_of_status_after_landing(self, status: str) -> None:
+ report = self._report(status=status)
+ self._pr_run(report, created_at=_at(8))
+ self.assertEqual(self._credits(), {self.team.id: 1500})
+
+ def test_first_run_with_pr_url_determines_period_not_first_run(self) -> None:
+ # An earlier run with no PR URL must not count as the first PR; the in-period PR run does.
+ report = self._report()
+ self._pr_run(report, created_at=datetime(2026, 5, 3, tzinfo=UTC), pr_url=None)
+ self._pr_run(report, created_at=_at(21))
+ self.assertEqual(self._credits(), {self.team.id: 1500})
+
+ def test_aggregates_across_teams_and_reports(self) -> None:
+ team_b = Team.objects.create(organization=self.organization, name="team-b")
+ for _ in range(3):
+ self._pr_run(self._report(), created_at=_at(10))
+ self._pr_run(self._report(team=team_b), created_at=_at(11), team=team_b)
+ self._pr_run(self._report(team=team_b), created_at=_at(13), team=team_b)
+ self.assertEqual(self._credits(), {self.team.id: 4500, team_b.id: 3000})
+
+ def test_deterministic_across_runs(self) -> None:
+ report = self._report()
+ self._pr_run(report, created_at=_at(5))
+ self._pr_run(report, created_at=_at(22))
+ self.assertEqual(self._credits(), self._credits())
+
+ def test_no_billable_reports_returns_empty(self) -> None:
+ self.assertEqual(get_signals_billing_credits_by_team(PERIOD_START, PERIOD_END), [])
diff --git a/products/tasks/backend/migrations/0041_taskrun_created_at_idx.py b/products/tasks/backend/migrations/0041_taskrun_created_at_idx.py
new file mode 100644
index 000000000000..7dfdf48c2936
--- /dev/null
+++ b/products/tasks/backend/migrations/0041_taskrun_created_at_idx.py
@@ -0,0 +1,20 @@
+from django.db import migrations, models
+
+from posthog.migration_helpers import SafeAddIndexConcurrently
+
+
+class Migration(migrations.Migration):
+ # Concurrent index builds cannot run inside a transaction. Lives in its own
+ # migration per PostHog policy (don't mix CONCURRENTLY operations with regular DDL).
+ atomic = False
+
+ dependencies = [
+ ("tasks", "0040_alter_task_origin_product"),
+ ]
+
+ operations = [
+ SafeAddIndexConcurrently(
+ model_name="taskrun",
+ index=models.Index(fields=["created_at"], name="task_run_created_at_idx"),
+ ),
+ ]
diff --git a/products/tasks/backend/migrations/max_migration.txt b/products/tasks/backend/migrations/max_migration.txt
index a616661a1e83..3266ac806c43 100644
--- a/products/tasks/backend/migrations/max_migration.txt
+++ b/products/tasks/backend/migrations/max_migration.txt
@@ -1 +1 @@
-0040_alter_task_origin_product
+0041_taskrun_created_at_idx
diff --git a/products/tasks/backend/models.py b/products/tasks/backend/models.py
index 47be770898a9..56f0c10cee3f 100644
--- a/products/tasks/backend/models.py
+++ b/products/tasks/backend/models.py
@@ -777,6 +777,9 @@ class TaskRun(models.Model):
name="task_run_output_pr_url_idx",
condition=models.Q(output__pr_url__isnull=False),
),
+ # Time-range scans over runs (default ordering, recent-runs lookups, and the
+ # signals outcome-billing query that buckets PR runs into a period).
+ models.Index(fields=["created_at"], name="task_run_created_at_idx"),
]
def __str__(self):