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(replay-vision): notify when a scanner pauses on its credit limit (#75439)

Arno Hillen2fa726f15c79
diff --git a/posthog/management/migration_analysis/atomic_false_acknowledged_migrations.txt b/posthog/management/migration_analysis/atomic_false_acknowledged_migrations.txt
index 0b60f00165cc..6b21ef812ab4 100644
--- a/posthog/management/migration_analysis/atomic_false_acknowledged_migrations.txt
+++ b/posthog/management/migration_analysis/atomic_false_acknowledged_migrations.txt
@@ -14,5 +14,6 @@
posthog.1264_delete_revenue_analytics_user_product_list
product_analytics.0004_delete_revenue_analytics_insights
tasks.0079_backfill_task_repositories
+replay_vision.0073_rebackfill_usage_scanner_id
replay_vision.0070_backfill_usage_scanner_id
tasks.0088_backfill_task_search_documents
diff --git a/products/replay_vision/backend/api/scanners.py b/products/replay_vision/backend/api/scanners.py
index e34420fece43..a5c12f89b46d 100644
--- a/products/replay_vision/backend/api/scanners.py
+++ b/products/replay_vision/backend/api/scanners.py
@@ -621,10 +621,16 @@ class ReplayScannerSerializer(UserAccessControlSerializerMixin, serializers.Mode
# The UI PATCHes the whole form on save, so edits are detected by comparing values, not keys.
before = {field: getattr(instance, field) for field in validated_data}
was_enabled = instance.enabled
+ limit_changed = "credit_limit" in validated_data and validated_data["credit_limit"] != instance.credit_limit
try:
scanner = super().update(instance, validated_data)
except IntegrityError as e:
self._reraise_unique_name_violation(e)
+ if limit_changed:
+ # A changed limit starts a fresh notification cycle: reaching the new limit is news.
+ # Targeted update because the model save deliberately never writes this sweep-owned column.
+ ReplayScanner.objects.filter(pk=scanner.pk).update(limit_notified_period_start=None)
+ scanner.limit_notified_period_start = None
# Model save clears `estimated_at` when volume inputs change. Re-enables only refresh inline when
# the background refresher has fallen behind, so a stale number never enters the quota sum.
needs_refresh = scanner.estimated_at is None or (
diff --git a/products/replay_vision/backend/migrations/0072_replayscanner_limit_notified_period_start.py b/products/replay_vision/backend/migrations/0072_replayscanner_limit_notified_period_start.py
new file mode 100644
index 000000000000..1ab6f1bc03d7
--- /dev/null
+++ b/products/replay_vision/backend/migrations/0072_replayscanner_limit_notified_period_start.py
@@ -0,0 +1,21 @@
+# Generated by Django 5.2.14 on 2026-07-30 02:18
+
+from django.db import migrations, models
+
+
+class Migration(migrations.Migration):
+ dependencies = [
+ ("replay_vision", "0071_replayscanner_sweep_read_bytes_by_hour_and_more"),
+ ]
+
+ operations = [
+ migrations.AddField(
+ model_name="replayscanner",
+ name="limit_notified_period_start",
+ field=models.DateTimeField(
+ blank=True,
+ help_text="Billing period start this scanner was last reported as having reached its credit limit. Keeps the notification to one per period.",
+ null=True,
+ ),
+ ),
+ ]
diff --git a/products/replay_vision/backend/migrations/0073_rebackfill_usage_scanner_id.py b/products/replay_vision/backend/migrations/0073_rebackfill_usage_scanner_id.py
new file mode 100644
index 000000000000..980daf046a18
--- /dev/null
+++ b/products/replay_vision/backend/migrations/0073_rebackfill_usage_scanner_id.py
@@ -0,0 +1,53 @@
+import uuid
+
+from django.db import migrations
+
+BATCH_SIZE = 10_000
+
+
+def rebackfill_scanner_id(apps, schema_editor):
+ """Repeat 0070's attribution pass: migrations run before pods roll, so old-code workers kept
+ settling receipts without a scanner_id between 0070 running and the accounting deploy finishing.
+ This PR deploys strictly after that rollout, so one more idempotent pass closes the window."""
+ usage_table = apps.get_model("replay_vision", "ReplayObservationUsage")._meta.db_table
+ observation_table = apps.get_model("replay_vision", "ReplayObservation")._meta.db_table
+ last_id = uuid.UUID("00000000-0000-0000-0000-000000000000")
+ with schema_editor.connection.cursor() as cursor:
+ while True:
+ cursor.execute(
+ f"""
+ WITH batch AS (
+ SELECT u.id AS usage_id, o.scanner_id AS scanner_id
+ FROM {usage_table} u
+ JOIN {observation_table} o ON o.id = u.observation_id
+ WHERE u.scanner_id IS NULL AND u.id > %(last_id)s
+ ORDER BY u.id
+ LIMIT {BATCH_SIZE}
+ )
+ UPDATE {usage_table} AS tgt
+ SET scanner_id = batch.scanner_id
+ FROM batch
+ WHERE tgt.id = batch.usage_id
+ RETURNING batch.usage_id
+ """,
+ {"last_id": last_id},
+ )
+ rows = cursor.fetchall()
+ if not rows:
+ break
+ last_id = max(row[0] for row in rows)
+ if len(rows) < BATCH_SIZE:
+ break
+
+
+class Migration(migrations.Migration):
+ # Batches commit independently so the update never holds long locks on the receipt table.
+ atomic = False
+
+ dependencies = [
+ ("replay_vision", "0072_replayscanner_limit_notified_period_start"),
+ ]
+
+ operations = [
+ migrations.RunPython(rebackfill_scanner_id, migrations.RunPython.noop, elidable=False),
+ ]
diff --git a/products/replay_vision/backend/migrations/max_migration.txt b/products/replay_vision/backend/migrations/max_migration.txt
index 617aa08a7419..ea53eb4abd31 100644
--- a/products/replay_vision/backend/migrations/max_migration.txt
+++ b/products/replay_vision/backend/migrations/max_migration.txt
@@ -1 +1 @@
-0071_replayscanner_sweep_read_bytes_by_hour_and_more
+0073_rebackfill_usage_scanner_id
diff --git a/products/replay_vision/backend/models/replay_scanner.py b/products/replay_vision/backend/models/replay_scanner.py
index 1c1708092248..8d1eeb1bd984 100644
--- a/products/replay_vision/backend/models/replay_scanner.py
+++ b/products/replay_vision/backend/models/replay_scanner.py
@@ -203,6 +203,11 @@ class ReplayScanner(UUIDModel):
validators=[MinValueValidator(1)],
help_text="Optional cap on this scanner's own credit spend per billing period. Null means no scanner-level cap.",
)
+ limit_notified_period_start = models.DateTimeField(
+ null=True,
+ blank=True,
+ help_text="Billing period start this scanner was last reported as having reached its credit limit. Keeps the notification to one per period.",
+ )
created_at = models.DateTimeField(auto_now_add=True)
created_by = models.ForeignKey("posthog.User", on_delete=models.SET_NULL, null=True, blank=True, related_name="+")
@@ -286,10 +291,23 @@ class ReplayScanner(UUIDModel):
type(self)
.all_origins.select_for_update()
.filter(pk=self.pk)
- .only("scanner_version", "enabled", *relevant)
+ .only(
+ "scanner_version",
+ "enabled",
+ "last_swept_at",
+ "last_seen_session_id",
+ "limit_notified_period_start",
+ *relevant,
+ )
.first()
)
if old is not None:
+ if update_fields is None:
+ # The sweep writes these via targeted updates; a stale full save must not
+ # clobber a concurrent sweep's watermark or notification stamp.
+ self.last_swept_at = old.last_swept_at
+ self.last_seen_session_id = old.last_seen_session_id
+ self.limit_notified_period_start = old.limit_notified_period_start
changed = {f for f in relevant if getattr(old, f) != getattr(self, f)}
extra_fields = []
if changed:
diff --git a/products/replay_vision/backend/temporal/activities/check_scanner_budget.py b/products/replay_vision/backend/temporal/activities/check_scanner_budget.py
index 89e8c2a0d3a2..48fda5e03847 100644
--- a/products/replay_vision/backend/temporal/activities/check_scanner_budget.py
+++ b/products/replay_vision/backend/temporal/activities/check_scanner_budget.py
@@ -1,27 +1,105 @@
from temporalio import activity
from products.replay_vision.backend.models.replay_scanner import ReplayScanner, initial_watermark
-from products.replay_vision.backend.quota import compute_scanner_budget
+from products.replay_vision.backend.models.replay_scanner_backfill import BackfillStatus, ReplayScannerBackfill
+from products.replay_vision.backend.quota import compute_scanner_budget, current_period_bounds
from products.replay_vision.backend.temporal.decorators import track_activity
from products.replay_vision.backend.temporal.metrics import record_sweep_outcome
from products.replay_vision.backend.temporal.sweep_types import CheckScannerBudgetInputs, CheckScannerBudgetOutput
+def _notify_limit_reached(scanner: ReplayScanner) -> bool:
+ """Best-effort notification; False only when the send raised. A deliberate skip inside the
+ pipeline (flag off, nobody to notify) counts as sent so it is not retried every tick."""
+ try:
+ from posthog.models import User # noqa: PLC0415
+ from posthog.rbac.user_access_control import UserAccessControl # noqa: PLC0415
+
+ from products.notifications.backend.facade.api import ( # noqa: PLC0415 (keeps the heavy dep off the import path)
+ NotificationData,
+ NotificationType,
+ Priority,
+ RecipientsResolver,
+ TargetType,
+ create_notification,
+ )
+
+ class ScannerViewersResolver(RecipientsResolver):
+ """The pipeline's built-in access filter is resource-type wide; keep only per-scanner viewers."""
+
+ def resolve(self, target_type: TargetType, target_id: str, team_id: int | None) -> list[int]:
+ user_ids = super().resolve(target_type, target_id, team_id)
+ if not user_ids:
+ return user_ids
+ # One probe user answers the org-wide support question; don't load every recipient for it.
+ probe = User.objects.filter(id__in=user_ids).first()
+ if probe is None or not UserAccessControl(probe, scanner.team).access_controls_supported:
+ return user_ids
+ # Per-user checks cost several queries each; without object-level rows on this scanner
+ # the resource-wide filter already applied is the whole answer, so skip them.
+ from ee.models.rbac.access_control import AccessControl # noqa: PLC0415
+
+ has_object_rules = AccessControl.objects.filter(
+ team=scanner.team, resource="replay_scanner", resource_id=str(scanner.id)
+ ).exists()
+ if not has_object_rules:
+ return user_ids
+ return [
+ user.id
+ for user in User.objects.filter(id__in=user_ids)
+ if UserAccessControl(user, scanner.team).check_access_level_for_object(
+ scanner, required_level="viewer"
+ )
+ ]
+
+ body = (
+ "It stopped scanning until its billing period resets. Sessions skipped while capped are not scanned later."
+ )
+ # The cap also holds a running backfill without changing its status; without this line the
+ # notification leaves that backfill looking stalled for no reason.
+ if (
+ ReplayScannerBackfill.objects.for_team(scanner.team_id)
+ .filter(scanner_id=scanner.id, status=BackfillStatus.RUNNING)
+ .exists()
+ ):
+ body += " Its running backfill is on hold and resumes when the limit resets."
+
+ create_notification(
+ NotificationData(
+ team_id=scanner.team_id,
+ # A cap is a usage event, not breakage; it must not surface as a pipeline failure.
+ notification_type=NotificationType.USAGE_SPIKE,
+ priority=Priority.NORMAL,
+ title=f'"{scanner.name}" reached its credit limit',
+ body=body,
+ target_type=TargetType.TEAM,
+ target_id=str(scanner.team_id),
+ resource_type="replay_scanner",
+ resource_id=str(scanner.id),
+ resolver=ScannerViewersResolver(),
+ source_url=f"/project/{scanner.team.project_id}/replay-vision/{scanner.id}",
+ )
+ )
+ except Exception:
+ activity.logger.warning(
+ "Failed to send scanner credit limit notification",
+ extra={"scanner_id": str(scanner.id), "team_id": scanner.team_id},
+ exc_info=True,
+ )
+ return False
+ return True
+
+
@activity.defn
@track_activity()
def check_scanner_budget_activity(inputs: CheckScannerBudgetInputs) -> CheckScannerBudgetOutput:
"""Whether this scanner has room for another observation under its own credit limit.
- On a cap, advances the watermark past the window the scanner is skipping. Freezing it instead would
- make the first uncapped tick fetch a candidate window stretching back to when the limit was hit and
- burn the fresh period's budget on stale recordings, so a spend limit would become a spend spike.
- Mirrors what re-enabling a disabled scanner already does. The reset lives here, not in the workflow,
- because it needs the real clock.
-
- The watermark only advances when settled credits alone exceed the limit. In-flight reservations are
- transient (a failed observation releases its reservation without ever writing a receipt), so a
- transient in-flight spike must not permanently skip a window the scanner could actually afford once
- those reservations clear.
+ On a cap, advances the watermark past the skipped window (as re-enabling a disabled scanner does);
+ freezing it would make the first uncapped tick burn the fresh period's budget on stale recordings.
+ Lives here rather than in the workflow because it needs the real clock. Only settled spend advances
+ the watermark: in-flight reservations can release without settling and must not permanently skip
+ a window the scanner could still afford.
"""
scanner = ReplayScanner.objects.filter(pk=inputs.scanner_id, team_id=inputs.team_id).select_related("team").first()
if scanner is None:
@@ -29,12 +107,13 @@ def check_scanner_budget_activity(inputs: CheckScannerBudgetInputs) -> CheckScan
return CheckScannerBudgetOutput(capped=False)
if scanner.credit_limit is None:
return CheckScannerBudgetOutput(capped=False)
- budget = compute_scanner_budget(scanner)
+ # Resolve the period once so the cap decision and the notification stamp cannot straddle a rollover.
+ period = current_period_bounds(scanner.team.organization_id)
+ budget = compute_scanner_budget(scanner, period)
if not budget.blocked:
return CheckScannerBudgetOutput(capped=False)
if not budget.blocked_by_settled_spend:
- # Only the in-flight portion pushes this over: capped for now, but don't advance the
- # watermark, since those reservations may release without ever settling.
+ # In-flight-only overage: capped for now, but those reservations may release without settling.
record_sweep_outcome("scanner_capped_in_flight")
activity.logger.info(
"Sweep skipped: scanner credit limit reached by in-flight reservations only",
@@ -47,15 +126,26 @@ def check_scanner_budget_activity(inputs: CheckScannerBudgetInputs) -> CheckScan
)
return CheckScannerBudgetOutput(capped=True)
record_sweep_outcome("scanner_capped_settled")
- # `.update` bypasses the model's version-tracking save(), matching how the watermark is advanced.
+ # The WHERE claims the notification stamp: of two racing ticks exactly one wins the send, and a
+ # crash before the send below can only skip a notification, never send an unrecorded one.
watermark = initial_watermark()
- ReplayScanner.objects.filter(pk=scanner.pk).update(
- last_swept_at=watermark,
- last_seen_session_id="",
- # The deep pass walks from its own watermark up to the fast one, so leaving it behind would
- # hand the first uncapped deep sweep exactly the window this reset skips.
- last_deep_swept_at=watermark,
+ stamped = (
+ ReplayScanner.objects.filter(pk=scanner.pk)
+ .exclude(limit_notified_period_start=period.start)
+ .update(
+ last_swept_at=watermark,
+ last_seen_session_id="",
+ # The deep pass walks from its own watermark up to the fast one, so leaving it behind would
+ # hand the first uncapped deep sweep exactly the window this reset skips.
+ last_deep_swept_at=watermark,
+ limit_notified_period_start=period.start,
+ )
)
+ if not stamped:
+ # Already notified this period; still advance the watermark past the skipped window.
+ ReplayScanner.objects.filter(pk=scanner.pk).update(
+ last_swept_at=watermark, last_seen_session_id="", last_deep_swept_at=watermark
+ )
activity.logger.info(
"Sweep skipped: scanner credit limit reached",
extra={
@@ -65,4 +155,10 @@ def check_scanner_budget_activity(inputs: CheckScannerBudgetInputs) -> CheckScan
"credits_used": budget.credits_used,
},
)
+ # Sent only after the stamp commits: a push can't be un-sent, so it must never precede its record.
+ if stamped and not _notify_limit_reached(scanner):
+ # Hand the claim back so a transient outage delays the notification instead of consuming it.
+ ReplayScanner.objects.filter(pk=scanner.pk, limit_notified_period_start=period.start).update(
+ limit_notified_period_start=None
+ )
return CheckScannerBudgetOutput(capped=True)
diff --git a/products/replay_vision/backend/tests/test_api.py b/products/replay_vision/backend/tests/test_api.py
index 787b6eaf1de0..1bd8e70e59b1 100644
--- a/products/replay_vision/backend/tests/test_api.py
+++ b/products/replay_vision/backend/tests/test_api.py
@@ -433,6 +433,24 @@ class TestReplayScannerViewSet(_VisionAPITestCase):
resp = self.client.patch(url, data={"credit_limit": 0}, format="json")
self.assertEqual(resp.status_code, 400, resp.json())
+ def test_changing_the_credit_limit_rearms_the_limit_notification(self) -> None:
+ # The scanner already notified this period; raising the limit makes the next exhaustion news
+ # again, while an unrelated edit leaves the stamp alone.
+ scanner = self._create_scanner()
+ stamp = datetime(2026, 8, 1, tzinfo=UTC)
+ ReplayScanner.objects.filter(pk=scanner.pk).update(credit_limit=500, limit_notified_period_start=stamp)
+ url = f"{self.scanners_url}{scanner.id}/"
+
+ resp = self.client.patch(url, data={"name": "renamed, limit untouched"}, format="json")
+ self.assertEqual(resp.status_code, 200, resp.json())
+ scanner.refresh_from_db()
+ self.assertEqual(scanner.limit_notified_period_start, stamp)
+
+ resp = self.client.patch(url, data={"credit_limit": 1_000}, format="json")
+ self.assertEqual(resp.status_code, 200, resp.json())
+ scanner.refresh_from_db()
+ self.assertIsNone(scanner.limit_notified_period_start)
+
def test_create_accepts_valid_query(self) -> None:
resp = self.client.post(
self.scanners_url,
diff --git a/products/replay_vision/backend/tests/test_models.py b/products/replay_vision/backend/tests/test_models.py
index 5235fc654279..484c512b69fd 100644
--- a/products/replay_vision/backend/tests/test_models.py
+++ b/products/replay_vision/backend/tests/test_models.py
@@ -172,6 +172,23 @@ class TestReplayScanner(BaseTest):
self.assertEqual(scanner.last_seen_session_id, "sess-tie")
self.assertEqual(scanner.last_deep_swept_at, stale)
+ def test_full_save_does_not_clobber_sweep_owned_columns(self) -> None:
+ # A concurrent sweep stamps these via targeted updates; a full save from a stale
+ # in-memory instance (any API PATCH) must not write them back to their old values.
+ scanner = self._create_scanner()
+ watermark = timezone.now() - timedelta(days=3)
+ stamp = timezone.now() - timedelta(days=10)
+ ReplayScanner.objects.filter(pk=scanner.pk).update(
+ last_swept_at=watermark, last_seen_session_id="sess-tie", limit_notified_period_start=stamp
+ )
+ scanner.name = "renamed during a sweep"
+ scanner.save()
+ scanner.refresh_from_db()
+ self.assertEqual(scanner.name, "renamed during a sweep")
+ self.assertEqual(scanner.last_swept_at, watermark)
+ self.assertEqual(scanner.last_seen_session_id, "sess-tie")
+ self.assertEqual(scanner.limit_notified_period_start, stamp)
+
class TestReplayObservation(BaseTest):
def _create_scanner(self, **overrides) -> ReplayScanner:
diff --git a/products/replay_vision/backend/tests/test_quota.py b/products/replay_vision/backend/tests/test_quota.py
index 153da5d55b4a..3aa38e661e23 100644
--- a/products/replay_vision/backend/tests/test_quota.py
+++ b/products/replay_vision/backend/tests/test_quota.py
@@ -431,6 +431,38 @@ class TestBackfillUsageScannerId(_VisionQuotaTestCase):
assert orphan.scanner_id is None
+class TestRebackfillUsageScannerId(_VisionQuotaTestCase):
+ def test_rebackfill_attributes_receipts_across_batches_and_leaves_orphans_null(self) -> None:
+ import uuid
+ import importlib
+
+ from django.apps import apps as django_apps
+ from django.db import connection
+
+ observations = [
+ self._make_observation(status=ObservationStatus.SUCCEEDED, completed_at=timezone.now()) for _ in range(3)
+ ]
+ ReplayObservationUsage.objects.filter(observation_id__in=[o.id for o in observations]).update(scanner_id=None)
+ orphan = ReplayObservationUsage.objects.create(
+ organization_id=self.organization.id,
+ observation_id=uuid.uuid4(),
+ observation_created_at=timezone.now(),
+ )
+
+ migration = importlib.import_module(
+ "products.replay_vision.backend.migrations.0073_rebackfill_usage_scanner_id"
+ )
+ # BATCH_SIZE=1 forces one keyset iteration per receipt, exercising the pagination loop.
+ with patch.object(migration, "BATCH_SIZE", 1):
+ with connection.schema_editor(atomic=False) as schema_editor:
+ migration.rebackfill_scanner_id(django_apps, schema_editor)
+
+ for observation in observations:
+ assert ReplayObservationUsage.objects.get(observation_id=observation.id).scanner_id == self.scanner.id
+ orphan.refresh_from_db()
+ assert orphan.scanner_id is None
+
+
class TestScannerBudgetBlocked(SimpleTestCase):
@parameterized.expand(
[
diff --git a/products/replay_vision/backend/tests/test_sweep.py b/products/replay_vision/backend/tests/test_sweep.py
index 5905792d950d..6077e62214de 100644
--- a/products/replay_vision/backend/tests/test_sweep.py
+++ b/products/replay_vision/backend/tests/test_sweep.py
@@ -16,7 +16,9 @@ from products.replay_vision.backend.models.replay_observation import (
ObservationTrigger,
ReplayObservation,
)
+from products.replay_vision.backend.models.replay_observation_usage import ReplayObservationUsage
from products.replay_vision.backend.models.replay_scanner import ReplayScanner, ScannerModel, ScannerType
+from products.replay_vision.backend.models.replay_scanner_backfill import ReplayScannerBackfill
from products.replay_vision.backend.queries import excluded_sessions
from products.replay_vision.backend.queries.scanner_candidate_query import (
DEFAULT_CANDIDATE_LIMIT,
@@ -42,6 +44,7 @@ from products.replay_vision.backend.temporal.constants import (
SWEEP_READ_BUDGET_BYTES_24H,
build_process_vision_action_workflow_id,
)
+from products.replay_vision.backend.temporal.snapshots import BackfillScannerSnapshot
from products.replay_vision.backend.temporal.sweep_types import (
AdvanceScannerWatermarkInputs,
CandidateSessionPayload,
@@ -651,6 +654,214 @@ def test_check_scanner_budget_activity_capped_by_in_flight_alone_does_not_advanc
assert scanner.last_deep_swept_at == stale
[email protected]_db(transaction=True)
+def test_check_scanner_budget_activity_capped_by_in_flight_alone_does_not_notify() -> None:
+ # A transient in-flight-only cap may clear itself within minutes as reservations release;
+ # notifying there could tell a user their scanner stopped when it's about to resume on its own.
+ limit = 20 * _OBSERVATION_CREDITS
+ scanner = _make_scanner(credit_limit=limit)
+ seed_scanner_spend(scanner, _OBSERVATION_CREDITS, observations=10)
+ _seed_in_flight_observations(scanner, count=10)
+
+ with patch("products.notifications.backend.facade.api.create_notification") as mock_notify:
+ output = check_scanner_budget_activity(CheckScannerBudgetInputs(scanner_id=scanner.id, team_id=scanner.team_id))
+
+ assert output.capped is True
+ mock_notify.assert_not_called()
+
+
[email protected]_db(transaction=True)
+def test_check_scanner_budget_activity_notifies_once_per_period_on_settled_exhaustion() -> None:
+ limit = 20 * _OBSERVATION_CREDITS
+ scanner = _make_scanner(credit_limit=limit)
+ seed_scanner_spend(scanner, _OBSERVATION_CREDITS, observations=20)
+
+ with patch("products.notifications.backend.facade.api.create_notification") as mock_notify:
+ first = check_scanner_budget_activity(CheckScannerBudgetInputs(scanner_id=scanner.id, team_id=scanner.team_id))
+ second = check_scanner_budget_activity(CheckScannerBudgetInputs(scanner_id=scanner.id, team_id=scanner.team_id))
+
+ # The pause is not conditional on the notification: both calls still report capped.
+ assert first.capped is True
+ assert second.capped is True
+ mock_notify.assert_called_once()
+ scanner.refresh_from_db()
+ assert scanner.limit_notified_period_start is not None
+
+
[email protected]("has_running_backfill", [True, False])
[email protected]_db(transaction=True)
+def test_limit_notification_mentions_a_running_backfill_only_when_there_is_one(has_running_backfill: bool) -> None:
+ # The cap holds a running backfill without changing its status, so the notification is the one
+ # place that can say why the backfill stalled; scanners without one must not get that line.
+ limit = 20 * _OBSERVATION_CREDITS
+ scanner = _make_scanner(credit_limit=limit)
+ seed_scanner_spend(scanner, _OBSERVATION_CREDITS, observations=20)
+ if has_running_backfill:
+ ReplayScannerBackfill.objects.for_team(scanner.team_id).create(
+ scanner=scanner,
+ team=scanner.team,
+ window_start=dt.datetime(2026, 4, 1, tzinfo=dt.UTC),
+ window_end=dt.datetime(2026, 5, 1, tzinfo=dt.UTC),
+ scanner_snapshot=BackfillScannerSnapshot.from_scanner(scanner).model_dump(mode="json"),
+ credits_per_observation=_OBSERVATION_CREDITS,
+ total_count=10,
+ )
+
+ with patch("products.notifications.backend.facade.api.create_notification") as mock_notify:
+ check_scanner_budget_activity(CheckScannerBudgetInputs(scanner_id=scanner.id, team_id=scanner.team_id))
+
+ mock_notify.assert_called_once()
+ body = mock_notify.call_args[0][0].body
+ assert ("backfill is on hold" in body) is has_running_backfill
+
+
[email protected]_db(transaction=True)
+def test_scanner_capped_last_period_is_uncapped_after_the_period_resets() -> None:
+ # The cap is per billing period: a scanner that went dark last period resumes on the first
+ # tick of the new one, still collecting into the same scanner.
+ limit = 20 * _OBSERVATION_CREDITS
+ scanner = _make_scanner(credit_limit=limit)
+ seed_scanner_spend(scanner, _OBSERVATION_CREDITS, observations=20)
+ last_period = dt.datetime.now(dt.UTC) - dt.timedelta(days=40)
+ ReplayObservation.objects.filter(scanner=scanner).update(created_at=last_period)
+ ReplayObservationUsage.objects.filter(scanner_id=scanner.id).update(observation_created_at=last_period)
+
+ with patch("products.notifications.backend.facade.api.create_notification") as mock_notify:
+ output = check_scanner_budget_activity(CheckScannerBudgetInputs(scanner_id=scanner.id, team_id=scanner.team_id))
+
+ assert output.capped is False
+ mock_notify.assert_not_called()
+
+
[email protected]_db(transaction=True)
+def test_check_scanner_budget_activity_notifies_again_after_period_rolls_over() -> None:
+ limit = 20 * _OBSERVATION_CREDITS
+ scanner = _make_scanner(credit_limit=limit)
+ seed_scanner_spend(scanner, _OBSERVATION_CREDITS, observations=20)
+ prior_period = dt.datetime(2020, 1, 1, tzinfo=dt.UTC)
+ ReplayScanner.objects.filter(pk=scanner.pk).update(limit_notified_period_start=prior_period)
+
+ with patch("products.notifications.backend.facade.api.create_notification") as mock_notify:
+ output = check_scanner_budget_activity(CheckScannerBudgetInputs(scanner_id=scanner.id, team_id=scanner.team_id))
+
+ assert output.capped is True
+ mock_notify.assert_called_once()
+ scanner.refresh_from_db()
+ assert scanner.limit_notified_period_start is not None
+ assert scanner.limit_notified_period_start > prior_period
+
+
[email protected]_db(transaction=True)
+def test_limit_notification_excludes_users_denied_on_the_scanner() -> None:
+ from posthog.constants import AvailableFeature
+ from posthog.models import OrganizationMembership, User
+
+ from products.notifications.backend.facade.enums import TargetType
+
+ from ee.models.rbac.access_control import AccessControl
+
+ limit = 20 * _OBSERVATION_CREDITS
+ scanner = _make_scanner(credit_limit=limit)
+ seed_scanner_spend(scanner, _OBSERVATION_CREDITS, observations=20)
+ organization = scanner.team.organization
+ organization.available_product_features = [
+ {"key": AvailableFeature.ACCESS_CONTROL, "name": AvailableFeature.ACCESS_CONTROL}
+ ]
+ organization.save()
+ allowed = User.objects.create_and_join(organization, "[email protected]", "testtest")
+ denied = User.objects.create_and_join(organization, "[email protected]", "testtest")
+ AccessControl.objects.create(
+ team=scanner.team,
+ resource="replay_scanner",
+ resource_id=str(scanner.id),
+ access_level="none",
+ organization_member=OrganizationMembership.objects.get(user=denied, organization=organization),
+ )
+
+ with patch("products.notifications.backend.facade.api.create_notification") as mock_notify:
+ check_scanner_budget_activity(CheckScannerBudgetInputs(scanner_id=scanner.id, team_id=scanner.team_id))
+
+ mock_notify.assert_called_once()
+ data = mock_notify.call_args[0][0]
+ assert data.resource_type == "replay_scanner"
+ assert data.resource_id == str(scanner.id)
+ recipients = data.resolver.resolve(TargetType.TEAM, str(scanner.team_id), scanner.team_id)
+ assert allowed.id in recipients
+ assert denied.id not in recipients
+
+
[email protected]_db(transaction=True)
+def test_limit_notification_is_delivered_end_to_end() -> None:
+ # Everything real except the remote feature flag and Kafka: mock-only coverage let the
+ # whole delivery path regress invisibly.
+ from posthog.models import User
+
+ from products.notifications.backend.models import NotificationEvent
+
+ limit = 20 * _OBSERVATION_CREDITS
+ scanner = _make_scanner(credit_limit=limit)
+ seed_scanner_spend(scanner, _OBSERVATION_CREDITS, observations=20)
+ member = User.objects.create_and_join(scanner.team.organization, "[email protected]", "testtest")
+
+ with (
+ patch("products.notifications.backend.logic.posthoganalytics.feature_enabled", return_value=True),
+ patch("products.notifications.backend.logic._publish_to_kafka"),
+ ):
+ output = check_scanner_budget_activity(CheckScannerBudgetInputs(scanner_id=scanner.id, team_id=scanner.team_id))
+
+ assert output.capped is True
+ event = NotificationEvent.objects.get(resource_type="replay_scanner", resource_id=str(scanner.id))
+ assert member.id in event.resolved_user_ids
+ assert event.source_url == f"/project/{scanner.team.project_id}/replay-vision/{scanner.id}"
+ assert scanner.name in event.title
+
+
[email protected]_db(transaction=True)
+def test_failed_send_returns_the_notification_to_the_next_tick() -> None:
+ # A transient pipeline outage must delay the period's one notification, not consume it.
+ limit = 20 * _OBSERVATION_CREDITS
+ scanner = _make_scanner(credit_limit=limit)
+ seed_scanner_spend(scanner, _OBSERVATION_CREDITS, observations=20)
+
+ with patch(
+ "products.notifications.backend.facade.api.create_notification", side_effect=RuntimeError("pipeline down")
+ ):
+ check_scanner_budget_activity(CheckScannerBudgetInputs(scanner_id=scanner.id, team_id=scanner.team_id))
+
+ scanner.refresh_from_db()
+ assert scanner.limit_notified_period_start is None
+
+ with patch("products.notifications.backend.facade.api.create_notification") as mock_notify:
+ check_scanner_budget_activity(CheckScannerBudgetInputs(scanner_id=scanner.id, team_id=scanner.team_id))
+
+ mock_notify.assert_called_once()
+ scanner.refresh_from_db()
+ assert scanner.limit_notified_period_start is not None
+
+
[email protected]_db(transaction=True)
+def test_raising_the_limit_rearms_the_notification_for_the_same_period() -> None:
+ # Editing the limit clears the stamp (see the serializer), so hitting the raised limit later in
+ # the same period notifies again instead of staying silent until the next period.
+ limit = 20 * _OBSERVATION_CREDITS
+ scanner = _make_scanner(credit_limit=limit)
+ seed_scanner_spend(scanner, _OBSERVATION_CREDITS, observations=20)
+
+ with patch("products.notifications.backend.facade.api.create_notification") as mock_notify:
+ check_scanner_budget_activity(CheckScannerBudgetInputs(scanner_id=scanner.id, team_id=scanner.team_id))
+ mock_notify.assert_called_once()
+
+ # The user raises the limit; the serializer clears the stamp alongside.
+ ReplayScanner.objects.filter(pk=scanner.pk).update(credit_limit=2 * limit, limit_notified_period_start=None)
+ seed_scanner_spend(scanner, _OBSERVATION_CREDITS, observations=20)
+
+ with patch("products.notifications.backend.facade.api.create_notification") as mock_notify:
+ output = check_scanner_budget_activity(CheckScannerBudgetInputs(scanner_id=scanner.id, team_id=scanner.team_id))
+
+ assert output.capped is True
+ mock_notify.assert_called_once()
+
+
# SweepScannerWorkflow (mocked-Temporal)
diff --git a/tach.toml b/tach.toml
index 07e50d9948e1..0b4765ac5784 100644
--- a/tach.toml
+++ b/tach.toml
@@ -657,6 +657,7 @@ depends_on = [
"products.cohorts",
"products.experiments",
"products.exports",
+ "products.notifications",
"products.signals",
"products.tasks",
]