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): mirror daily spend to direct reporting (#128006)

Oliver Browne65ef67737f3f
diff --git a/.semgrep/rules/security/idor-team-scoped-models.yaml b/.semgrep/rules/security/idor-team-scoped-models.yaml
index ec3ba54a703c..2fadd5e98a3b 100644
--- a/.semgrep/rules/security/idor-team-scoped-models.yaml
+++ b/.semgrep/rules/security/idor-team-scoped-models.yaml
@@ -407,6 +407,7 @@ rules:
|SharingConfiguration
|SignalEmissionRecord
|SignalFirstReportNotification
+ |SignalRatedUsage
|SignalReport
|SignalReportAction
|SignalReportArtefact
@@ -916,6 +917,7 @@ rules:
|SharingConfiguration
|SignalEmissionRecord
|SignalFirstReportNotification
+ |SignalRatedUsage
|SignalReport
|SignalReportAction
|SignalReportArtefact
diff --git a/ee/billing/billing_manager.py b/ee/billing/billing_manager.py
index 1707c91f0e81..bb6e9e8e99c9 100644
--- a/ee/billing/billing_manager.py
+++ b/ee/billing/billing_manager.py
@@ -1120,6 +1120,23 @@ class BillingManager:
return res.json()
+ def record_rated_usage(self, organization: Organization, items: list[dict[str, str | int]]) -> None:
+ res = http_session.post(
+ f"{BILLING_SERVICE_URL}/api/rated-usage",
+ headers=self.get_auth_headers(organization, service_action="rated_usage"),
+ json={"items": items},
+ timeout=30,
+ )
+ handle_billing_service_error(res, valid_codes=(200,))
+ body = res.json()
+ results = body.get("results") if isinstance(body, dict) else None
+ if (
+ not isinstance(results, list)
+ or len(results) != len(items)
+ or any(result not in ("created", "replayed") for result in results)
+ ):
+ raise ValueError("Billing did not accept every rated usage item")
+
def _system_auth_headers(self, service_action: str) -> dict[str, str]:
if not self.license: # mypy
raise Exception("No license found")
diff --git a/posthog/tasks/scheduled.py b/posthog/tasks/scheduled.py
index 531ef0a2c259..ad8d1025eb50 100644
--- a/posthog/tasks/scheduled.py
+++ b/posthog/tasks/scheduled.py
@@ -121,6 +121,7 @@ from products.notebooks.backend.facade.tasks import cleanup_widget_snapshots
from products.pulse.backend.tasks import mark_stale_pulse_briefs_failed
from products.reminders.backend.tasks import process_due_reminders
from products.signals.backend.facade.tasks import (
+ enqueue_signals_rated_usage,
pause_inactive_signal_scouts,
prune_expired_scratchpad_entries_task,
reconcile_report_inbox_state_cache,
@@ -456,6 +457,14 @@ def setup_periodic_tasks(sender: Celery, **kwargs: Any) -> None:
expires_seconds=2 * 60,
)
+ if settings.CLOUD_DEPLOYMENT:
+ add_periodic_task_with_expiry(
+ sender,
+ crontab(hour="3", minute="17"),
+ enqueue_signals_rated_usage.s(),
+ name="report self-driving rated usage",
+ )
+
add_periodic_task_with_expiry(
sender,
crontab(minute="*/5"),
diff --git a/posthog/tasks/test/test_scheduled.py b/posthog/tasks/test/test_scheduled.py
index 9414d54f4f60..f9315ec90da3 100644
--- a/posthog/tasks/test/test_scheduled.py
+++ b/posthog/tasks/test/test_scheduled.py
@@ -65,3 +65,23 @@ class TestInstanceSpreadMinute(SimpleTestCase):
with self.settings(SITE_URL=site_url):
minutes.add(instance_spread_minute("send license usage", 40))
assert len(minutes) > 1
+
+
+class TestSignalsRatedUsageScheduling(SimpleTestCase):
+ @parameterized.expand([("self_hosted", None, 0), ("cloud", "US", 1)])
+ def test_rated_usage_runs_daily_in_cloud(self, _name: str, deployment: str | None, expected_count: int) -> None:
+ sender = MagicMock()
+ with self.settings(CLOUD_DEPLOYMENT=deployment):
+ setup_periodic_tasks(sender)
+ calls = [
+ call
+ for call in sender.add_periodic_task.call_args_list
+ if call.kwargs.get("name") == "report self-driving rated usage"
+ ]
+ assert len(calls) == expected_count
+ if calls:
+ schedule, signature = calls[0].args
+ assert schedule.hour == {3}
+ assert schedule.minute == {17}
+ assert signature.type.name == "products.signals.backend.rated_usage_tasks.enqueue_signals_rated_usage"
+ assert signature.type.queue == "usage_reports"
diff --git a/products/signals/backend/facade/tasks.py b/products/signals/backend/facade/tasks.py
index 58cc78750afe..93cc27e09652 100644
--- a/products/signals/backend/facade/tasks.py
+++ b/products/signals/backend/facade/tasks.py
@@ -5,6 +5,7 @@ Importing this module loads the signals task module. Import it only from code th
"""
from products.signals.backend.tasks import (
+ enqueue_signals_rated_usage,
pause_inactive_signal_scouts,
prune_expired_scratchpad_entries_task,
reconcile_report_inbox_state_cache,
@@ -18,6 +19,7 @@ from products.signals.backend.tasks import (
)
__all__ = [
+ "enqueue_signals_rated_usage",
"pause_inactive_signal_scouts",
"prune_expired_scratchpad_entries_task",
"reconcile_report_inbox_state_cache",
diff --git a/products/signals/backend/migrations/0238_rated_usage_delivery.py b/products/signals/backend/migrations/0238_rated_usage_delivery.py
new file mode 100644
index 000000000000..d3e57c716e99
--- /dev/null
+++ b/products/signals/backend/migrations/0238_rated_usage_delivery.py
@@ -0,0 +1,47 @@
+# Generated by Django 6.1.2 on 2026-11-02 12:56
+
+from django.db import migrations, models
+
+import posthog.uuidt
+
+
+class Migration(migrations.Migration):
+ dependencies = [("signals", "0237_signalreport_inbox_sort_indexes")]
+
+ operations = [
+ migrations.CreateModel(
+ name="SignalRatedUsage",
+ fields=[
+ (
+ "id",
+ models.UUIDField(
+ default=posthog.uuidt.uuid7,
+ editable=False,
+ primary_key=True,
+ serialize=False,
+ ),
+ ),
+ ("team_id", models.BigIntegerField()),
+ ("organization_id", models.UUIDField()),
+ ("day", models.DateField(db_index=True)),
+ ("cents", models.PositiveBigIntegerField()),
+ ("reported_at", models.DateTimeField(null=True)),
+ ],
+ options={
+ "indexes": [
+ models.Index(
+ fields=["organization_id", "day"],
+ name="signals_rated_usage_org_day",
+ ),
+ models.Index(
+ fields=["day"],
+ condition=models.Q(reported_at__isnull=True),
+ name="signals_rated_usage_pending",
+ ),
+ ],
+ "constraints": [
+ models.UniqueConstraint(fields=("team_id", "day"), name="signals_rated_usage_team_day")
+ ],
+ },
+ ),
+ ]
diff --git a/products/signals/backend/migrations/max_migration.txt b/products/signals/backend/migrations/max_migration.txt
index 1ae1a3298a8f..e42438ebc0a4 100644
--- a/products/signals/backend/migrations/max_migration.txt
+++ b/products/signals/backend/migrations/max_migration.txt
@@ -1 +1 @@
-0237_signalreport_inbox_sort_indexes
+0238_rated_usage_delivery
diff --git a/products/signals/backend/models.py b/products/signals/backend/models.py
index b71823fa4443..12cd6f00a4f3 100644
--- a/products/signals/backend/models.py
+++ b/products/signals/backend/models.py
@@ -58,6 +58,7 @@ from products.signals.backend.filter_catalog import (
SignalFilterCatalogVersion as SignalFilterCatalogVersion,
SignalFilterSourceDefinition as SignalFilterSourceDefinition,
)
+from products.signals.backend.rated_usage_models import SignalRatedUsage as SignalRatedUsage
from products.signals.backend.report_checks import MAX_CHECK_TITLE_LENGTH
from products.signals.backend.report_monitoring_aggregation import MonitoringAggregation
diff --git a/products/signals/backend/rated_usage_models.py b/products/signals/backend/rated_usage_models.py
new file mode 100644
index 000000000000..0a808fda13af
--- /dev/null
+++ b/products/signals/backend/rated_usage_models.py
@@ -0,0 +1,22 @@
+from django.db import models
+
+from posthog.models.scoping.root_mixin import TeamScopedRootMixin
+from posthog.models.utils import UUIDModel
+
+
+class SignalRatedUsage(TeamScopedRootMixin, UUIDModel):
+ # Keep the first delivery's identity even if its project moves or is deleted.
+ team_id = models.BigIntegerField()
+ organization_id = models.UUIDField()
+ day = models.DateField(db_index=True)
+ cents = models.PositiveBigIntegerField()
+ reported_at = models.DateTimeField(null=True)
+
+ class Meta:
+ indexes = [
+ models.Index(fields=["organization_id", "day"], name="signals_rated_usage_org_day"),
+ models.Index(
+ fields=["day"], condition=models.Q(reported_at__isnull=True), name="signals_rated_usage_pending"
+ ),
+ ]
+ constraints = [models.UniqueConstraint(fields=["team_id", "day"], name="signals_rated_usage_team_day")]
diff --git a/products/signals/backend/rated_usage_tasks.py b/products/signals/backend/rated_usage_tasks.py
new file mode 100644
index 000000000000..0ffdcd4896e5
--- /dev/null
+++ b/products/signals/backend/rated_usage_tasks.py
@@ -0,0 +1,117 @@
+from datetime import UTC, date, datetime, time, timedelta
+from itertools import batched
+from uuid import UUID
+
+from django.db.models import Q
+from django.db.models.functions import TruncDate
+from django.utils import timezone
+
+from celery import shared_task
+
+from posthog.celery_queues import CeleryQueue
+from posthog.models import Organization
+from posthog.scoping_audit import skip_team_scope_audit
+
+from products.signals.backend.models import SignalSpend
+from products.signals.backend.rated_usage_models import SignalRatedUsage
+from products.signals.backend.spend_billing import get_signals_spend_billing_credits_by_team
+
+from ee.billing.billing_manager import BillingManager
+
+
+def _report_day(organization_id: UUID, day: date) -> None:
+ if day >= timezone.now().date():
+ raise ValueError("Rated usage requires a closed UTC day")
+ organization = Organization.objects.filter(id=organization_id).first()
+ if organization is None:
+ return
+ begin = datetime.combine(day, time.min, UTC)
+ credits = get_signals_spend_billing_credits_by_team(
+ begin, begin + timedelta(days=1), organization_id=organization_id
+ )
+ SignalRatedUsage.objects.unscoped().bulk_create(
+ [
+ SignalRatedUsage(team_id=team_id, organization_id=organization_id, day=day, cents=cents)
+ for team_id, cents in credits
+ ],
+ ignore_conflicts=True,
+ )
+ # Snapshot the customer and amount before POST so retries survive project moves.
+ deliveries = (
+ SignalRatedUsage.objects.unscoped()
+ .filter(organization_id=organization_id, day=day)
+ .order_by("team_id")
+ .values_list("team_id", "cents")
+ )
+ # Grant allocation belongs to the trial integration. This path reports all metered usage as billable.
+ items: list[dict[str, str | int]] = [
+ {"team_id": team_id, "product": "inbox_usage", "day": day.isoformat(), "cents": cents}
+ for team_id, cents in deliveries
+ ]
+ manager = BillingManager(None)
+ for batch in batched(items, 1000, strict=False):
+ manager.record_rated_usage(organization, list(batch))
+ SignalRatedUsage.objects.unscoped().filter(
+ organization_id=organization_id,
+ day=day,
+ team_id__in=[item["team_id"] for item in batch],
+ reported_at__isnull=True,
+ ).update(reported_at=timezone.now())
+
+
+@shared_task(
+ ignore_result=True,
+ queue=CeleryQueue.USAGE_REPORTS.value,
+ autoretry_for=(Exception,),
+ retry_backoff=True,
+ max_retries=5,
+ soft_time_limit=270,
+ time_limit=300,
+)
+@skip_team_scope_audit
+def report_signals_rated_usage(organization_id: str, day: str) -> None:
+ _report_day(UUID(organization_id), date.fromisoformat(day))
+
+
+@shared_task(
+ ignore_result=True,
+ queue=CeleryQueue.USAGE_REPORTS.value,
+ autoretry_for=(Exception,),
+ retry_backoff=True,
+ max_retries=3,
+ soft_time_limit=270,
+ time_limit=300,
+)
+@skip_team_scope_audit
+def enqueue_signals_rated_usage(day: str | None = None) -> None:
+ end = datetime.combine(date.fromisoformat(day) + timedelta(days=1) if day else timezone.now().date(), time.min, UTC)
+ if end > timezone.now():
+ raise ValueError("Rated usage requires a closed UTC day")
+ # Replaying closed days repairs missed deliveries; Billing deduplicates each team/day.
+ begin = end - timedelta(days=1 if day else 7)
+ org_days = (
+ SignalSpend.objects.unscoped()
+ .filter(
+ usage_billing=True,
+ finalized_at__gte=begin,
+ finalized_at__lt=end,
+ billing_exempt=False,
+ spend__gt=0,
+ )
+ .annotate(day=TruncDate("finalized_at", tzinfo=UTC))
+ .values_list("team__organization_id", "day")
+ .order_by()
+ )
+ delivery_window = Q(day__gte=begin.date())
+ if day is None:
+ delivery_window |= Q(reported_at__isnull=True)
+ deliveries = (
+ SignalRatedUsage.objects.unscoped()
+ .filter(delivery_window, day__lt=end.date())
+ .values_list("organization_id", "day")
+ .order_by()
+ )
+ for organization_id, usage_day in (
+ org_days.union(deliveries).order_by("team__organization_id", "day").iterator(chunk_size=1000)
+ ):
+ report_signals_rated_usage.delay(str(organization_id), usage_day.isoformat())
diff --git a/products/signals/backend/tasks.py b/products/signals/backend/tasks.py
index 8bc4a7e5f2c6..9d29ef864928 100644
--- a/products/signals/backend/tasks.py
+++ b/products/signals/backend/tasks.py
@@ -65,6 +65,10 @@ from products.signals.backend.pr_origin import write_origin_section
from products.signals.backend.pull_request_body import BodyEditOutcome
from products.signals.backend.pull_request_label import apply_pull_request_label
from products.signals.backend.pull_requests import update_pull_request_review_decision, update_pull_request_state
+from products.signals.backend.rated_usage_tasks import (
+ enqueue_signals_rated_usage as enqueue_signals_rated_usage,
+ report_signals_rated_usage as report_signals_rated_usage,
+)
from products.signals.backend.report_generation.repo_activity import (
ACTIVITY_KEEP_WARM_WINDOW,
rebuild_repository_activity,
diff --git a/products/signals/backend/test/test_rated_usage.py b/products/signals/backend/test/test_rated_usage.py
new file mode 100644
index 000000000000..3c2fe7b5e6f3
--- /dev/null
+++ b/products/signals/backend/test/test_rated_usage.py
@@ -0,0 +1,225 @@
+from contextlib import nullcontext
+from datetime import date
+from decimal import Decimal
+from uuid import uuid4
+
+import pytest
+import time_machine
+from posthog.test.base import BaseTest
+from unittest.mock import MagicMock, patch
+
+import jwt
+from parameterized import parameterized
+
+from posthog.models import Organization, Team
+
+from products.signals.backend.models import SignalSpend
+from products.signals.backend.rated_usage_models import SignalRatedUsage
+from products.signals.backend.rated_usage_tasks import enqueue_signals_rated_usage, report_signals_rated_usage
+from products.signals.backend.spend_billing import get_signals_spend_billing_credits_by_team
+from products.signals.backend.test.test_billing import _at
+
+from ee.models.license import License
+
+
+@time_machine.travel(_at(12), tick=False)
+class TestSignalsRatedUsage(BaseTest):
+ def setUp(self) -> None:
+ super().setUp()
+ self.organization.usage = {"signals_spend_credits": {"billing_start_date": "2026-06-10"}}
+ self.organization.save(update_fields=["usage"])
+ self.license = License(key="synthetic-license::synthetic-secret", plan="enterprise")
+ self.license_cache = patch("posthog.cloud_utils.instance_license_cached", self.license)
+ self.license_cache.start()
+ self.addCleanup(self.license_cache.stop)
+
+ def _spend(
+ self, amount: str, *, team: Team | None = None, day: int = 10, exempt: bool = False, usage_billing: bool = True
+ ) -> None:
+ with time_machine.travel(_at(day), tick=False):
+ SignalSpend.objects.for_team((team or self.team).id).create(
+ team=team or self.team,
+ signal_id=uuid4(),
+ kind=SignalSpend.Kind.AD_HOC,
+ spend=Decimal(amount),
+ finalized_at=_at(day),
+ billing_exempt=exempt,
+ usage_billing=usage_billing,
+ )
+
+ @patch("ee.billing.billing_manager.http_session.post")
+ def test_direct_report_matches_meter_and_replays_the_same_day(self, post: MagicMock) -> None:
+ self._spend("1.49")
+ self._spend("1.49")
+ self._spend("50", exempt=True)
+ self._spend("60", day=9)
+ self._spend("70", day=11)
+ other_org = Organization.objects.create(name="Another organization", usage=self.organization.usage)
+ other_team = Team.objects.create(organization=other_org)
+ self._spend("80", team=other_team)
+ post.side_effect = [
+ MagicMock(status_code=200, json=lambda: {"results": ["created"]}),
+ MagicMock(status_code=200, json=lambda: {"results": ["replayed"]}),
+ ]
+
+ report_signals_rated_usage.run(str(self.organization.id), "2026-06-10")
+ report_signals_rated_usage.run(str(self.organization.id), "2026-06-10")
+ assert SignalRatedUsage.objects.for_team(self.team.id).get().reported_at == _at(12)
+
+ expected = {"items": [{"team_id": self.team.id, "product": "inbox_usage", "day": "2026-06-10", "cents": 3}]}
+ assert dict(get_signals_spend_billing_credits_by_team(_at(10, 0), _at(11, 0), self.organization.id)) == {
+ self.team.id: 3
+ }
+ assert post.call_count == 2
+ for call in post.call_args_list:
+ assert call.args[0].endswith("/api/rated-usage")
+ assert call.kwargs["json"] == expected
+ assert call.kwargs["timeout"] == 30
+ token = call.kwargs["headers"]["Authorization"].removeprefix("Bearer ")
+ claims = jwt.decode(token, "synthetic-secret", algorithms=["HS256"], audience="posthog:license-key")
+ assert claims["organization_id"] == str(self.organization.id)
+ assert claims["service_action"] == "rated_usage"
+ assert "distinct_id" not in claims
+
+ @parameterized.expand([("complete", False), ("second_batch_fails", True)])
+ @patch("ee.billing.billing_manager.http_session.post")
+ def test_report_respects_the_endpoint_batch_limit(
+ self, _name: str, second_batch_fails: bool, post: MagicMock
+ ) -> None:
+ teams = Team.objects.bulk_create(
+ [Team(organization=self.organization, project=self.team.project) for _ in range(1001)]
+ )
+ SignalSpend.objects.unscoped().bulk_create(
+ [
+ SignalSpend(
+ team=team,
+ signal_id=uuid4(),
+ kind=SignalSpend.Kind.AD_HOC,
+ spend=1,
+ finalized_at=_at(10),
+ usage_billing=True,
+ )
+ for team in teams
+ ]
+ )
+ post.side_effect = [
+ MagicMock(status_code=200, json=lambda: {"results": ["created"] * 1000}),
+ TimeoutError("synthetic failure of the second batch")
+ if second_batch_fails
+ else MagicMock(status_code=200, json=lambda: {"results": ["created"]}),
+ ]
+ with pytest.raises(TimeoutError) if second_batch_fails else nullcontext():
+ report_signals_rated_usage.run(str(self.organization.id), "2026-06-10")
+ assert [len(call.kwargs["json"]["items"]) for call in post.call_args_list] == [1000, 1]
+ assert {item["team_id"] for call in post.call_args_list for item in call.kwargs["json"]["items"]} == {
+ team.id for team in teams
+ }
+ assert (
+ SignalRatedUsage.objects.unscoped()
+ .filter(organization_id=self.organization.id, reported_at__isnull=False)
+ .count()
+ ) == (1000 if second_batch_fails else 1001)
+
+ @parameterized.expand(
+ [
+ ("missing_endpoint", 404, {}),
+ ("unauthorized", 401, {}),
+ ("server_error", 500, {}),
+ ("conflict", 200, {"results": ["conflict"]}),
+ ("missing_results", 200, {}),
+ ("incomplete_results", 200, {"results": []}),
+ ]
+ )
+ def test_failed_or_conflicting_delivery_raises(self, _name: str, status: int, body: dict) -> None:
+ self._spend("3")
+ response = MagicMock(status_code=status, json=lambda: body, ok=status == 200)
+ with patch("ee.billing.billing_manager.http_session.post", return_value=response), pytest.raises(Exception):
+ report_signals_rated_usage.run(str(self.organization.id), "2026-06-10")
+ assert SignalRatedUsage.objects.for_team(self.team.id).get().reported_at is None
+
+ @patch("ee.billing.billing_manager.http_session.post")
+ def test_sweep_retries_unacknowledged_usage_after_seven_days(self, post: MagicMock) -> None:
+ self._spend("250")
+ post.side_effect = TimeoutError("synthetic timeout after acceptance")
+ with pytest.raises(TimeoutError):
+ report_signals_rated_usage.run(str(self.organization.id), "2026-06-10")
+ original_payload = post.call_args.kwargs["json"]
+
+ with time_machine.travel(_at(20), tick=False):
+ with patch("products.signals.backend.rated_usage_tasks.report_signals_rated_usage.delay") as enqueue:
+ enqueue_signals_rated_usage.run()
+ enqueue.assert_called_once_with(str(self.organization.id), "2026-06-10")
+
+ post.side_effect = None
+ post.return_value = MagicMock(status_code=200, json=lambda: {"results": ["replayed"]})
+ report_signals_rated_usage.run(*enqueue.call_args.args)
+ assert post.call_args.kwargs["json"] == original_payload
+ assert SignalRatedUsage.objects.for_team(self.team.id).get().reported_at == _at(20)
+
+ with patch("products.signals.backend.rated_usage_tasks.report_signals_rated_usage.delay") as enqueue:
+ enqueue_signals_rated_usage.run()
+ enqueue.assert_not_called()
+
+ @parameterized.expand([("today", "2026-06-12"), ("future", "2026-06-13")])
+ def test_open_days_are_rejected(self, _name: str, day: str) -> None:
+ with patch("ee.billing.billing_manager.http_session.post") as post, pytest.raises(ValueError):
+ report_signals_rated_usage.run(str(self.organization.id), day)
+ post.assert_not_called()
+
+ def test_sweep_enqueues_only_recent_closed_days_with_metered_usage(self) -> None:
+ self._spend("1")
+ self._spend("2")
+ self._spend("3", day=11)
+ self._spend("4", day=12)
+ self._spend("5", day=4)
+ self._spend("6", day=8, exempt=True)
+ self._spend("7", day=9, usage_billing=False)
+ with patch("products.signals.backend.rated_usage_tasks.report_signals_rated_usage.delay") as enqueue:
+ enqueue_signals_rated_usage.run()
+ assert [call.args for call in enqueue.call_args_list] == [
+ (str(self.organization.id), "2026-06-10"),
+ (str(self.organization.id), "2026-06-11"),
+ ]
+ with patch("products.signals.backend.rated_usage_tasks.report_signals_rated_usage.delay") as enqueue:
+ enqueue_signals_rated_usage.run(day=date(2026, 6, 10).isoformat())
+ enqueue.assert_called_once_with(str(self.organization.id), "2026-06-10")
+
+ @parameterized.expand([(True,), (False,)])
+ def test_sweep_preserves_the_work_meter_after_a_plan_change(self, usage_billing: bool) -> None:
+ self._spend("25", usage_billing=usage_billing)
+ self.organization.usage = {"signals_spend_credits": {"usage": 0, "limit": 0}}
+ self.organization.save(update_fields=["usage"])
+ with patch("products.signals.backend.rated_usage_tasks.report_signals_rated_usage.delay") as enqueue:
+ enqueue_signals_rated_usage.run()
+ assert [call.args for call in enqueue.call_args_list] == (
+ [(str(self.organization.id), "2026-06-10")] if usage_billing else []
+ )
+
+ @parameterized.expand([("successful_delivery", False), ("lost_acknowledgment", True)])
+ @patch("ee.billing.billing_manager.http_session.post")
+ def test_project_move_does_not_change_the_customer_on_replay(
+ self, _name: str, lost_acknowledgment: bool, post: MagicMock
+ ) -> None:
+ self._spend("250")
+ post.return_value = MagicMock(status_code=200, json=lambda: {"results": ["replayed"]})
+ if lost_acknowledgment:
+ post.side_effect = TimeoutError("synthetic timeout after acceptance")
+ with pytest.raises(TimeoutError):
+ report_signals_rated_usage.run(str(self.organization.id), "2026-06-10")
+ post.side_effect = None
+ else:
+ report_signals_rated_usage.run(str(self.organization.id), "2026-06-10")
+ original_payload = post.call_args.kwargs["json"]
+ other_org = Organization.objects.create(name="Destination", usage=self.organization.usage)
+ Team.objects.filter(id=self.team.id).update(organization=other_org)
+ post.reset_mock()
+ with patch("products.signals.backend.rated_usage_tasks.report_signals_rated_usage.delay") as enqueue:
+ enqueue_signals_rated_usage.run(day="2026-06-10")
+ assert {call.args[0] for call in enqueue.call_args_list} == {str(self.organization.id), str(other_org.id)}
+ for call in enqueue.call_args_list:
+ report_signals_rated_usage.run(*call.args)
+ post.assert_called_once()
+ assert post.call_args.kwargs["json"] == original_payload
+ token = post.call_args.kwargs["headers"]["Authorization"].removeprefix("Bearer ")
+ claims = jwt.decode(token, "synthetic-secret", algorithms=["HS256"], audience="posthog:license-key")
+ assert claims["organization_id"] == str(self.organization.id)