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): credit billing and scanner editor rework (#68625)

Tue Haulund6be4d771ded5
diff --git a/.semgrep/rules/security/idor-team-scoped-models.yaml b/.semgrep/rules/security/idor-team-scoped-models.yaml
index e432fbcc240a..8ab093dd0016 100644
--- a/.semgrep/rules/security/idor-team-scoped-models.yaml
+++ b/.semgrep/rules/security/idor-team-scoped-models.yaml
@@ -213,6 +213,7 @@ rules:
|QuickFilterContext
|ReplayObservation
|ReplayObservationLabel
+ |ReplayObservationUsage
|ReplayScanner
|ReplayScannerPromptSuggestion
|Repo
@@ -495,6 +496,7 @@ rules:
|QuickFilterContext
|ReplayObservation
|ReplayObservationLabel
+ |ReplayObservationUsage
|ReplayScanner
|ReplayScannerPromptSuggestion
|Repo
@@ -665,7 +667,6 @@ rules:
|Plugin
|Project
|ProxyRecord
- |ReplayObservationUsage
|ReplayQuotaGrant
|Role
|RoleExternalReference
@@ -734,7 +735,6 @@ rules:
|Plugin
|Project
|ProxyRecord
- |ReplayObservationUsage
|ReplayQuotaGrant
|Role
|RoleExternalReference
diff --git a/ee/billing/billing_manager.py b/ee/billing/billing_manager.py
index 0491332f7b9c..6c09d3a68d39 100644
--- a/ee/billing/billing_manager.py
+++ b/ee/billing/billing_manager.py
@@ -449,6 +449,7 @@ class BillingManager:
workflow_emails=usage_summary.get("workflow_emails", {}),
workflow_destinations_dispatched=usage_summary.get("workflow_destinations_dispatched", {}),
logs_mb_ingested=usage_summary.get("logs_mb_ingested", {}),
+ replay_vision_credits=usage_summary.get("replay_vision_credits", {}),
period=[
data["billing_period"]["current_period_start"],
data["billing_period"]["current_period_end"],
diff --git a/ee/billing/quota_limiting.py b/ee/billing/quota_limiting.py
index 818fcdd61240..9342572dd6db 100644
--- a/ee/billing/quota_limiting.py
+++ b/ee/billing/quota_limiting.py
@@ -35,6 +35,7 @@ from posthog.tasks.usage_report import (
get_teams_with_feature_flag_requests_count_in_period,
get_teams_with_logs_bytes_in_period,
get_teams_with_recording_count_in_period,
+ get_teams_with_replay_vision_credits_used_in_period,
get_teams_with_rows_exported_in_period,
get_teams_with_rows_synced_in_period,
get_teams_with_signals_credits_used_in_period,
@@ -87,6 +88,7 @@ class QuotaResource(Enum):
WORKFLOW_EMAILS = "workflow_emails"
WORKFLOW_DESTINATIONS = "workflow_destinations_dispatched"
LOGS_MB_INGESTED = "logs_mb_ingested"
+ REPLAY_VISION_CREDITS = "replay_vision_credits"
class QuotaLimitingCaches(Enum):
@@ -110,12 +112,14 @@ OVERAGE_BUFFER = {
QuotaResource.WORKFLOW_EMAILS: 0,
QuotaResource.WORKFLOW_DESTINATIONS: 0,
QuotaResource.LOGS_MB_INGESTED: 0,
+ QuotaResource.REPLAY_VISION_CREDITS: 0,
}
# These resources are exempt from any grace periods, whether trust-based or never_drop_data
GRACE_PERIOD_EXEMPT_RESOURCES: set[QuotaResource] = {
QuotaResource.AI_CREDITS,
QuotaResource.SIGNALS_CREDITS,
+ QuotaResource.REPLAY_VISION_CREDITS,
}
@@ -136,6 +140,7 @@ class UsageCounters(TypedDict):
workflow_emails: int
workflow_destinations_dispatched: int
logs_mb_ingested: int
+ replay_vision_credits: int
# -------------------------------------------------------------------------------------------------
@@ -916,6 +921,14 @@ def update_all_orgs_billing_quotas(
"workflow_invocations", get_teams_with_workflow_billable_invocations_in_period, period_start, period_end
)
),
+ "teams_with_replay_vision_credits_used_in_period": convert_team_usage_rows_to_dict(
+ _timed_query(
+ "replay_vision_credits",
+ get_teams_with_replay_vision_credits_used_in_period,
+ period_start,
+ period_end,
+ )
+ ),
"teams_with_logs_mb_in_period": {
team_id: int(bytes_val // 1_000_000)
for team_id, bytes_val in convert_team_usage_rows_to_dict(
@@ -976,6 +989,7 @@ def update_all_orgs_billing_quotas(
workflow_emails=all_data["teams_with_workflow_emails_sent_in_period"].get(team.id, 0),
workflow_destinations_dispatched=all_data["teams_with_workflow_destinations_in_period"].get(team.id, 0),
logs_mb_ingested=all_data["teams_with_logs_mb_in_period"].get(team.id, 0),
+ replay_vision_credits=all_data["teams_with_replay_vision_credits_used_in_period"].get(team.id, 0),
)
org_id = str(team.organization.id)
diff --git a/ee/billing/test/test_billing_manager.py b/ee/billing/test/test_billing_manager.py
index 887ecdda42f1..acdf376fb8b6 100644
--- a/ee/billing/test/test_billing_manager.py
+++ b/ee/billing/test/test_billing_manager.py
@@ -175,6 +175,7 @@ class TestBillingManager(BaseTest):
"llm_events": {"usage": 50, "limit": 1000, "todays_usage": 2},
"ai_credits": {"usage": 1200, "limit": 20000, "todays_usage": 150},
"signals_credits": {},
+ "replay_vision_credits": {},
"cdp_trigger_events": {"usage": 10, "limit": 100, "todays_usage": 5},
"workflow_emails": {"usage": 100, "limit": 10000, "todays_usage": 10},
"workflow_destinations_dispatched": {"usage": 50, "limit": 10000, "todays_usage": 5},
@@ -245,6 +246,7 @@ class TestBillingManager(BaseTest):
"llm_events": {"usage": 50, "limit": 1000, "todays_usage": 2},
"ai_credits": {"usage": 1200, "limit": 20000, "todays_usage": 150},
"signals_credits": {},
+ "replay_vision_credits": {},
"workflow_emails": {"usage": 100, "limit": 10000, "todays_usage": 10},
"workflow_destinations_dispatched": {"usage": 50, "limit": 10000, "todays_usage": 5},
"logs_mb_ingested": {"usage": 5500, "limit": 50000, "todays_usage": 500},
diff --git a/ee/billing/test/test_quota_limiting.py b/ee/billing/test/test_quota_limiting.py
index 7f312e6be0cf..9a1fbb81eed0 100644
--- a/ee/billing/test/test_quota_limiting.py
+++ b/ee/billing/test/test_quota_limiting.py
@@ -2312,6 +2312,7 @@ def _full_usage_counters(**overrides: int) -> UsageCounters:
workflow_emails=0,
workflow_destinations_dispatched=0,
logs_mb_ingested=0,
+ replay_vision_credits=0,
)
base.update(overrides) # type: ignore[typeddict-item]
return base
diff --git a/frontend/src/products.tsx b/frontend/src/products.tsx
index 9056a69c577c..75b8c3b2965e 100644
--- a/frontend/src/products.tsx
+++ b/frontend/src/products.tsx
@@ -307,6 +307,7 @@ export const productRoutes: Record<string, [string, string]> = {
'/replay-vision/:id/template': ['ReplayVisionScannerEditor', 'replayVisionScannerTemplate'],
'/replay-vision/:id/configure': ['ReplayVisionScannerEditor', 'replayVisionScannerConfigure'],
'/replay-vision/:id/triggers': ['ReplayVisionScannerEditor', 'replayVisionScannerTriggers'],
+ '/replay-vision/:id/self-driving': ['ReplayVisionScannerEditor', 'replayVisionScannerSelfDriving'],
'/replay-vision/:id': ['ReplayVisionScanner', 'replayVision'],
'/revenue_analytics': ['RevenueAnalytics', 'revenueAnalytics'],
'/session-summaries': ['SessionGroupSummariesTable', 'sessionGroupSummariesTable'],
@@ -1341,6 +1342,7 @@ export const productUrls = {
replayVisionScannerTemplate: (id: string): string => `/replay-vision/${id}/template`,
replayVisionScannerConfigure: (id: string): string => `/replay-vision/${id}/configure`,
replayVisionScannerTriggers: (id: string): string => `/replay-vision/${id}/triggers`,
+ replayVisionScannerSelfDriving: (id: string): string => `/replay-vision/${id}/self-driving`,
replayVisionObservation: (observationId: string): string => `/replay-vision/observations/${observationId}`,
replayVisionAction: (actionId: string): string => `/replay-vision/actions/${actionId}`,
replayVisionActionRun: (actionId: string, runId: string): string =>
diff --git a/posthog/models/organization.py b/posthog/models/organization.py
index c064a68db8c9..d7705b3f153a 100644
--- a/posthog/models/organization.py
+++ b/posthog/models/organization.py
@@ -58,6 +58,7 @@ class OrganizationUsageInfo(TypedDict):
workflow_emails: OrganizationUsageResource | None
workflow_destinations_dispatched: OrganizationUsageResource | None
logs_mb_ingested: OrganizationUsageResource | None
+ replay_vision_credits: OrganizationUsageResource | None
period: list[str] | None
diff --git a/posthog/models/scoping/baseline_unmigrated.txt b/posthog/models/scoping/baseline_unmigrated.txt
index dc26a7357212..7f426f8a5191 100644
--- a/posthog/models/scoping/baseline_unmigrated.txt
+++ b/posthog/models/scoping/baseline_unmigrated.txt
@@ -135,6 +135,7 @@ QuickFilterContext
Reminder
ReplayObservation
ReplayObservationLabel
+ReplayObservationUsage
ReplayScanner
ReplayScannerPromptSuggestion
RepoRoutingRule
diff --git a/posthog/tasks/test/__snapshots__/test_usage_report.ambr b/posthog/tasks/test/__snapshots__/test_usage_report.ambr
index 8d0a67552af9..9702699d5a2b 100644
--- a/posthog/tasks/test/__snapshots__/test_usage_report.ambr
+++ b/posthog/tasks/test/__snapshots__/test_usage_report.ambr
@@ -1018,13 +1018,15 @@
# name: TestFeatureFlagsUsageReport.test_usage_report_decide_requests.59
'''
- SELECT team_id,
- count(distinct uuid) as count
+ SELECT distinct_id as team,
+ sum(JSONExtractInt(properties, 'count')) as sum
FROM events
- WHERE event = '$recording_observed'
+ WHERE team_id = 99999
+ AND event='decide usage'
AND timestamp >= '2022-01-10 00:00:00'
AND timestamp < '2022-01-10 23:59:59'
- GROUP BY team_id
+ AND has(['correct'], replaceRegexpAll(JSONExtractRaw(properties, 'token'), '^"|"$', ''))
+ GROUP BY team
'''
# ---
# name: TestFeatureFlagsUsageReport.test_usage_report_decide_requests.6
@@ -1069,7 +1071,7 @@
sum(JSONExtractInt(properties, 'count')) as sum
FROM events
WHERE team_id = 99999
- AND event='decide usage'
+ AND event='local evaluation usage'
AND timestamp >= '2022-01-10 00:00:00'
AND timestamp < '2022-01-10 23:59:59'
AND has(['correct'], replaceRegexpAll(JSONExtractRaw(properties, 'token'), '^"|"$', ''))
@@ -1078,16 +1080,21 @@
# ---
# name: TestFeatureFlagsUsageReport.test_usage_report_decide_requests.61
'''
-
- SELECT distinct_id as team,
- sum(JSONExtractInt(properties, 'count')) as sum
- FROM events
- WHERE team_id = 99999
- AND event='local evaluation usage'
- AND timestamp >= '2022-01-10 00:00:00'
- AND timestamp < '2022-01-10 23:59:59'
- AND has(['correct'], replaceRegexpAll(JSONExtractRaw(properties, 'token'), '^"|"$', ''))
- GROUP BY team
+ WITH JSONExtractInt(log_comment, 'team_id') as team_id,
+ JSONExtractString(log_comment, 'query_type') as query_type,
+ JSONExtractString(log_comment, 'access_method') as access_method
+ SELECT team_id,
+ sum(read_bytes) as count
+ FROM clusterAllReplicas(posthog, system.query_log)
+ WHERE (type = 'QueryFinish'
+ OR type = 'ExceptionWhileProcessing')
+ AND is_initial_query = 1
+ AND event_time >= 'today 00:00:00'
+ AND event_time < '2022-01-11 05:59:59'
+ AND query_start_time >= '2022-01-10 00:00:00'
+ AND query_start_time < '2022-01-10 23:59:59'
+ AND access_method = ''
+ GROUP BY team_id
'''
# ---
# name: TestFeatureFlagsUsageReport.test_usage_report_decide_requests.62
@@ -1096,7 +1103,7 @@
JSONExtractString(log_comment, 'query_type') as query_type,
JSONExtractString(log_comment, 'access_method') as access_method
SELECT team_id,
- sum(read_bytes) as count
+ sum(read_rows) as count
FROM clusterAllReplicas(posthog, system.query_log)
WHERE (type = 'QueryFinish'
OR type = 'ExceptionWhileProcessing')
@@ -1115,7 +1122,7 @@
JSONExtractString(log_comment, 'query_type') as query_type,
JSONExtractString(log_comment, 'access_method') as access_method
SELECT team_id,
- sum(read_rows) as count
+ sum(query_duration_ms) as count
FROM clusterAllReplicas(posthog, system.query_log)
WHERE (type = 'QueryFinish'
OR type = 'ExceptionWhileProcessing')
@@ -1134,7 +1141,7 @@
JSONExtractString(log_comment, 'query_type') as query_type,
JSONExtractString(log_comment, 'access_method') as access_method
SELECT team_id,
- sum(query_duration_ms) as count
+ sum(read_bytes) as count
FROM clusterAllReplicas(posthog, system.query_log)
WHERE (type = 'QueryFinish'
OR type = 'ExceptionWhileProcessing')
@@ -1143,7 +1150,7 @@
AND event_time < '2022-01-11 05:59:59'
AND query_start_time >= '2022-01-10 00:00:00'
AND query_start_time < '2022-01-10 23:59:59'
- AND access_method = ''
+ AND access_method = 'personal_api_key'
GROUP BY team_id
'''
# ---
@@ -1153,7 +1160,7 @@
JSONExtractString(log_comment, 'query_type') as query_type,
JSONExtractString(log_comment, 'access_method') as access_method
SELECT team_id,
- sum(read_bytes) as count
+ sum(read_rows) as count
FROM clusterAllReplicas(posthog, system.query_log)
WHERE (type = 'QueryFinish'
OR type = 'ExceptionWhileProcessing')
@@ -1172,7 +1179,7 @@
JSONExtractString(log_comment, 'query_type') as query_type,
JSONExtractString(log_comment, 'access_method') as access_method
SELECT team_id,
- sum(read_rows) as count
+ sum(query_duration_ms) as count
FROM clusterAllReplicas(posthog, system.query_log)
WHERE (type = 'QueryFinish'
OR type = 'ExceptionWhileProcessing')
@@ -1191,16 +1198,17 @@
JSONExtractString(log_comment, 'query_type') as query_type,
JSONExtractString(log_comment, 'access_method') as access_method
SELECT team_id,
- sum(query_duration_ms) as count
+ sum(read_bytes) as count
FROM clusterAllReplicas(posthog, system.query_log)
WHERE (type = 'QueryFinish'
OR type = 'ExceptionWhileProcessing')
AND is_initial_query = 1
+ AND query_type IN (['EventsQuery'])
AND event_time >= 'today 00:00:00'
AND event_time < '2022-01-11 05:59:59'
AND query_start_time >= '2022-01-10 00:00:00'
AND query_start_time < '2022-01-10 23:59:59'
- AND access_method = 'personal_api_key'
+ AND access_method = ''
GROUP BY team_id
'''
# ---
@@ -1210,7 +1218,7 @@
JSONExtractString(log_comment, 'query_type') as query_type,
JSONExtractString(log_comment, 'access_method') as access_method
SELECT team_id,
- sum(read_bytes) as count
+ sum(read_rows) as count
FROM clusterAllReplicas(posthog, system.query_log)
WHERE (type = 'QueryFinish'
OR type = 'ExceptionWhileProcessing')
@@ -1230,7 +1238,7 @@
JSONExtractString(log_comment, 'query_type') as query_type,
JSONExtractString(log_comment, 'access_method') as access_method
SELECT team_id,
- sum(read_rows) as count
+ sum(query_duration_ms) as count
FROM clusterAllReplicas(posthog, system.query_log)
WHERE (type = 'QueryFinish'
OR type = 'ExceptionWhileProcessing')
@@ -1280,26 +1288,6 @@
'''
# ---
# name: TestFeatureFlagsUsageReport.test_usage_report_decide_requests.70
- '''
- WITH JSONExtractInt(log_comment, 'team_id') as team_id,
- JSONExtractString(log_comment, 'query_type') as query_type,
- JSONExtractString(log_comment, 'access_method') as access_method
- SELECT team_id,
- sum(query_duration_ms) as count
- FROM clusterAllReplicas(posthog, system.query_log)
- WHERE (type = 'QueryFinish'
- OR type = 'ExceptionWhileProcessing')
- AND is_initial_query = 1
- AND query_type IN (['EventsQuery'])
- AND event_time >= 'today 00:00:00'
- AND event_time < '2022-01-11 05:59:59'
- AND query_start_time >= '2022-01-10 00:00:00'
- AND query_start_time < '2022-01-10 23:59:59'
- AND access_method = ''
- GROUP BY team_id
- '''
-# ---
-# name: TestFeatureFlagsUsageReport.test_usage_report_decide_requests.71
'''
WITH JSONExtractInt(log_comment, 'team_id') as team_id,
JSONExtractString(log_comment, 'query_type') as query_type,
@@ -1319,7 +1307,7 @@
GROUP BY team_id
'''
# ---
-# name: TestFeatureFlagsUsageReport.test_usage_report_decide_requests.72
+# name: TestFeatureFlagsUsageReport.test_usage_report_decide_requests.71
'''
WITH JSONExtractInt(log_comment, 'team_id') as team_id,
JSONExtractString(log_comment, 'query_type') as query_type,
@@ -1339,7 +1327,7 @@
GROUP BY team_id
'''
# ---
-# name: TestFeatureFlagsUsageReport.test_usage_report_decide_requests.73
+# name: TestFeatureFlagsUsageReport.test_usage_report_decide_requests.72
'''
WITH JSONExtractInt(log_comment, 'team_id') as team_id,
JSONExtractString(log_comment, 'query_type') as query_type,
@@ -1359,7 +1347,7 @@
GROUP BY team_id
'''
# ---
-# name: TestFeatureFlagsUsageReport.test_usage_report_decide_requests.74
+# name: TestFeatureFlagsUsageReport.test_usage_report_decide_requests.73
'''
SELECT team_id,
@@ -1383,7 +1371,7 @@
GROUP BY team_id
'''
# ---
-# name: TestFeatureFlagsUsageReport.test_usage_report_decide_requests.75
+# name: TestFeatureFlagsUsageReport.test_usage_report_decide_requests.74
'''
SELECT team_id,
@@ -1398,7 +1386,7 @@
metric_name
'''
# ---
-# name: TestFeatureFlagsUsageReport.test_usage_report_decide_requests.76
+# name: TestFeatureFlagsUsageReport.test_usage_report_decide_requests.75
'''
SELECT team_id,
@@ -1412,7 +1400,7 @@
metric_name
'''
# ---
-# name: TestFeatureFlagsUsageReport.test_usage_report_decide_requests.77
+# name: TestFeatureFlagsUsageReport.test_usage_report_decide_requests.76
'''
SELECT team_id,
@@ -1425,7 +1413,7 @@
GROUP BY team_id
'''
# ---
-# name: TestFeatureFlagsUsageReport.test_usage_report_decide_requests.78
+# name: TestFeatureFlagsUsageReport.test_usage_report_decide_requests.77
'''
SELECT team_id,
@@ -1442,7 +1430,7 @@
GROUP BY team_id
'''
# ---
-# name: TestFeatureFlagsUsageReport.test_usage_report_decide_requests.79
+# name: TestFeatureFlagsUsageReport.test_usage_report_decide_requests.78
'''
SELECT team_id,
@@ -1456,6 +1444,20 @@
GROUP BY team_id
'''
# ---
+# name: TestFeatureFlagsUsageReport.test_usage_report_decide_requests.79
+ '''
+
+ SELECT team_id,
+ SUM(count) as count
+ FROM app_metrics2
+ WHERE app_source='hog_flow'
+ AND metric_name IN ('billable_invocation')
+ AND metric_kind IN ('push')
+ AND timestamp >= '2022-01-10 00:00:00'
+ AND timestamp < '2022-01-10 23:59:59'
+ GROUP BY team_id
+ '''
+# ---
# name: TestFeatureFlagsUsageReport.test_usage_report_decide_requests.8
'''
@@ -1494,20 +1496,6 @@
# name: TestFeatureFlagsUsageReport.test_usage_report_decide_requests.80
'''
- SELECT team_id,
- SUM(count) as count
- FROM app_metrics2
- WHERE app_source='hog_flow'
- AND metric_name IN ('billable_invocation')
- AND metric_kind IN ('push')
- AND timestamp >= '2022-01-10 00:00:00'
- AND timestamp < '2022-01-10 23:59:59'
- GROUP BY team_id
- '''
-# ---
-# name: TestFeatureFlagsUsageReport.test_usage_report_decide_requests.81
- '''
-
SELECT team_id,
SUM(count) as count
FROM app_metrics2
@@ -1519,7 +1507,7 @@
GROUP BY team_id
'''
# ---
-# name: TestFeatureFlagsUsageReport.test_usage_report_decide_requests.82
+# name: TestFeatureFlagsUsageReport.test_usage_report_decide_requests.81
'''
SELECT team_id,
@@ -1533,7 +1521,7 @@
GROUP BY team_id
'''
# ---
-# name: TestFeatureFlagsUsageReport.test_usage_report_decide_requests.83
+# name: TestFeatureFlagsUsageReport.test_usage_report_decide_requests.82
'''
SELECT team_id,
diff --git a/posthog/tasks/test/test_usage_report.py b/posthog/tasks/test/test_usage_report.py
index 6534596ddd1a..233dbf051f34 100644
--- a/posthog/tasks/test/test_usage_report.py
+++ b/posthog/tasks/test/test_usage_report.py
@@ -663,7 +663,7 @@ class TestUsageReport(APIBaseTest, ClickhouseTestMixin, ClickhouseDestroyTablesM
"mobile_recording_bytes_in_period": 6,
"mobile_recording_count_in_period": 1,
"mobile_billable_recording_count_in_period": 0,
- "recording_observations_count_in_period": 0,
+ "replay_vision_credits_used_in_period": 0,
"group_types_total": 2,
"dashboard_count": 2,
"dashboard_template_count": 0,
@@ -739,7 +739,7 @@ class TestUsageReport(APIBaseTest, ClickhouseTestMixin, ClickhouseDestroyTablesM
"mobile_recording_bytes_in_period": 0,
"mobile_recording_count_in_period": 0,
"mobile_billable_recording_count_in_period": 0,
- "recording_observations_count_in_period": 0,
+ "replay_vision_credits_used_in_period": 0,
"group_types_total": 2,
"dashboard_count": 2,
"dashboard_template_count": 0,
@@ -809,7 +809,7 @@ class TestUsageReport(APIBaseTest, ClickhouseTestMixin, ClickhouseDestroyTablesM
"mobile_recording_bytes_in_period": 6,
"mobile_recording_count_in_period": 1,
"mobile_billable_recording_count_in_period": 0,
- "recording_observations_count_in_period": 0,
+ "replay_vision_credits_used_in_period": 0,
"group_types_total": 0,
"dashboard_count": 0,
"dashboard_template_count": 0,
@@ -902,7 +902,7 @@ class TestUsageReport(APIBaseTest, ClickhouseTestMixin, ClickhouseDestroyTablesM
"mobile_recording_bytes_in_period": 0,
"mobile_recording_count_in_period": 0,
"mobile_billable_recording_count_in_period": 0,
- "recording_observations_count_in_period": 0,
+ "replay_vision_credits_used_in_period": 0,
"group_types_total": 0,
"dashboard_count": 0,
"dashboard_template_count": 0,
@@ -978,7 +978,7 @@ class TestUsageReport(APIBaseTest, ClickhouseTestMixin, ClickhouseDestroyTablesM
"mobile_recording_bytes_in_period": 0,
"mobile_recording_count_in_period": 0,
"mobile_billable_recording_count_in_period": 0,
- "recording_observations_count_in_period": 0,
+ "replay_vision_credits_used_in_period": 0,
"group_types_total": 0,
"dashboard_count": 0,
"dashboard_template_count": 0,
diff --git a/posthog/tasks/usage_report.py b/posthog/tasks/usage_report.py
index e74e98023d59..ac91dda3afb7 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.facade.models 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.replay_vision.backend.billing import get_replay_vision_credits_by_team
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 (
@@ -135,7 +136,7 @@ class UsageReportCounters:
mobile_billable_recording_count_in_period: int
# Replay Vision
- recording_observations_count_in_period: int
+ replay_vision_credits_used_in_period: int
# Persons and Groups
group_types_total: int
@@ -913,23 +914,9 @@ def get_teams_with_recording_count_in_period(
@timed_log()
@retry(tries=QUERY_RETRIES, delay=QUERY_RETRY_DELAY, backoff=QUERY_RETRY_BACKOFF)
-def get_teams_with_recording_observations_count_in_period(begin: datetime, end: datetime) -> list[tuple[int, int]]:
- # Replay Vision emits one `$recording_observed` event per observation into the team's events table,
- # with `event_uuid` set to the observation id. Count distinct uuids so at-least-once ingestion
- # duplicates (same observation, same uuid) aren't over-counted — this is a billing input.
- with tags_context(product=Product.REPLAY_VISION, feature=Feature.USAGE_REPORT):
- return sync_execute(
- """
- SELECT team_id, count(distinct uuid) as count
- FROM events
- WHERE event = '$recording_observed' AND timestamp >= %(begin)s AND timestamp < %(end)s
- GROUP BY team_id
- """,
- {"begin": begin, "end": end},
- workload=Workload.OFFLINE,
- settings=CH_BILLING_SETTINGS,
- ch_user=ClickHouseUser.BILLING,
- )
+def get_teams_with_replay_vision_credits_used_in_period(begin: datetime, end: datetime) -> list[tuple[int, int]]:
+ # Billed from the ReplayObservationUsage receipt ledger, the same source the in-product quota meter reads.
+ return get_replay_vision_credits_by_team(begin, end)
@timed_log()
@@ -2260,7 +2247,7 @@ def has_non_zero_usage(report: UsageReportCounters) -> bool:
or report.workflow_push_sent_in_period > 0
or report.workflow_sms_sent_in_period > 0
or report.workflow_billable_invocations_in_period > 0
- or report.recording_observations_count_in_period > 0
+ or report.replay_vision_credits_used_in_period > 0
)
@@ -2349,7 +2336,7 @@ def _get_all_usage_data(period_start: datetime, period_end: datetime) -> dict[st
"teams_with_mobile_billable_recording_count_in_period": get_teams_with_mobile_billable_recording_count_in_period(
period_start, period_end
),
- "teams_with_recording_observations_count_in_period": get_teams_with_recording_observations_count_in_period(
+ "teams_with_replay_vision_credits_used_in_period": get_teams_with_replay_vision_credits_used_in_period(
period_start, period_end
),
"teams_with_decide_requests_count_in_period": get_teams_with_feature_flag_requests_count_in_period(
@@ -2604,7 +2591,7 @@ def _get_team_report(all_data: dict[str, Any], team: Team) -> UsageReportCounter
mobile_billable_recording_count_in_period=all_data["teams_with_mobile_billable_recording_count_in_period"].get(
team.id, 0
),
- recording_observations_count_in_period=all_data["teams_with_recording_observations_count_in_period"].get(
+ replay_vision_credits_used_in_period=all_data["teams_with_replay_vision_credits_used_in_period"].get(
team.id, 0
),
group_types_total=all_data["teams_with_group_types_total"].get(team.id, 0),
diff --git a/posthog/temporal/usage_report/queries.py b/posthog/temporal/usage_report/queries.py
index d81adf7788df..00a8f9682e64 100644
--- a/posthog/temporal/usage_report/queries.py
+++ b/posthog/temporal/usage_report/queries.py
@@ -76,7 +76,7 @@ from posthog.tasks.usage_report import (
get_teams_with_query_metric,
get_teams_with_recording_bytes_in_period,
get_teams_with_recording_count_in_period,
- get_teams_with_recording_observations_count_in_period,
+ get_teams_with_replay_vision_credits_used_in_period,
get_teams_with_rows_exported_in_period,
get_teams_with_rows_synced_in_period,
get_teams_with_sdk_logs_records_in_period,
@@ -291,8 +291,8 @@ QUERIES: list[QuerySpec] = [
fn=get_teams_with_mobile_billable_recording_count_in_period,
),
QuerySpec(
- name="teams_with_recording_observations_count_in_period",
- fn=get_teams_with_recording_observations_count_in_period,
+ name="teams_with_replay_vision_credits_used_in_period",
+ fn=get_teams_with_replay_vision_credits_used_in_period,
),
# ---- ClickHouse: feature flag requests -----------------------------------
QuerySpec(
diff --git a/products/replay_vision/backend/api/observations.py b/products/replay_vision/backend/api/observations.py
index c3cb98d27a3b..79174a27d6a3 100644
--- a/products/replay_vision/backend/api/observations.py
+++ b/products/replay_vision/backend/api/observations.py
@@ -30,8 +30,10 @@ from products.replay_vision.backend.api.observation_stats import compute_observa
from products.replay_vision.backend.api.trigger import (
WorkflowStartOutcome,
check_observation_quota,
+ check_team_in_flight_capacity,
start_apply_scanner_workflow,
)
+from products.replay_vision.backend.billing import observation_credits_for_model
from products.replay_vision.backend.error_kinds import ERROR_REASON_HELP_TEXT
from products.replay_vision.backend.feature_flag import ReplayVisionEnabledPermission, is_replay_vision_quality_enabled
from products.replay_vision.backend.models.replay_observation import (
@@ -626,7 +628,8 @@ class ReplayObservationViewSet(
self.check_object_permissions(self.request, scanner)
if observation.status != ObservationStatus.FAILED:
raise ValidationError("Only failed observations can be retried.")
- check_observation_quota(self.team.organization_id)
+ check_observation_quota(self.team.organization_id, observation_credits_for_model(scanner.model))
+ check_team_in_flight_capacity(self.team.id)
session_id = observation.session_id
# Free the UNIQUE(scanner, session_id) slot; the usage ledger is immutable, so the failed attempt stays counted.
observation.delete()
diff --git a/products/replay_vision/backend/api/quota.py b/products/replay_vision/backend/api/quota.py
index b5ce491f4bde..78cd800af8a5 100644
--- a/products/replay_vision/backend/api/quota.py
+++ b/products/replay_vision/backend/api/quota.py
@@ -15,21 +15,23 @@ from products.replay_vision.backend.quota import compute_quota_snapshot
# `many=False` stops drf-spectacular wrapping the response as `VisionQuotaApi[]` for the `list` action.
@extend_schema_serializer(many=False)
class VisionQuotaSerializer(serializers.Serializer):
- monthly_quota = serializers.IntegerField(
+ credit_limit = serializers.IntegerField(
read_only=True,
- help_text="Total observations the org may complete per calendar month.",
+ allow_null=True,
+ help_text="Credits the org may spend per billing period (1 credit = $0.01). Null when billing has synced the product with no spend limit: uncapped.",
)
- usage_this_month = serializers.IntegerField(
+ credits_used = serializers.IntegerField(
read_only=True,
- help_text="Observations created this month that are in flight or have succeeded, counted against the quota.",
+ help_text="Credits spent this period: succeeded observations from the receipt ledger plus reserved in-flight observations.",
)
remaining = serializers.IntegerField(
read_only=True,
- help_text="`monthly_quota - usage_this_month`, floored at 0.",
+ allow_null=True,
+ help_text="`credit_limit - credits_used`, floored at 0. Null when uncapped.",
)
exhausted = serializers.BooleanField(
read_only=True,
- help_text="True when `usage_this_month >= monthly_quota`; further observations are skipped until next period.",
+ help_text="True when `credits_used >= credit_limit`; further observations are skipped until next period. Always false when uncapped.",
)
period_start = serializers.DateTimeField(
read_only=True,
@@ -39,10 +41,10 @@ class VisionQuotaSerializer(serializers.Serializer):
read_only=True,
help_text="First moment of the next quota period (UTC); the current period's exclusive upper bound.",
)
- projected_monthly_observations = serializers.IntegerField(
+ projected_monthly_credits = serializers.IntegerField(
read_only=True,
help_text=(
- "Sum of enabled scanners' projected observations/month across the organization. "
+ "Credit-weighted sum of enabled scanners' projected observations/month across the organization. "
"Scanners without a computed estimate contribute 0."
),
)
diff --git a/products/replay_vision/backend/api/scanners.py b/products/replay_vision/backend/api/scanners.py
index 74b7d55e06c5..29e38f6db1d2 100644
--- a/products/replay_vision/backend/api/scanners.py
+++ b/products/replay_vision/backend/api/scanners.py
@@ -32,8 +32,10 @@ from products.replay_vision.backend.api.filters import (
from products.replay_vision.backend.api.trigger import (
WorkflowStartOutcome,
check_observation_quota,
+ check_team_in_flight_capacity,
start_apply_scanner_workflow,
)
+from products.replay_vision.backend.billing import observation_credits_for_model
from products.replay_vision.backend.digest import provision_scanner_digest
from products.replay_vision.backend.feature_flag import ReplayVisionEnabledPermission, is_replay_vision_actions_enabled
from products.replay_vision.backend.models.replay_scanner import (
@@ -51,7 +53,7 @@ from products.replay_vision.backend.queries import (
project_monthly_observations,
refresh_scanner_estimate,
)
-from products.replay_vision.backend.quota import sum_enabled_scanner_estimates
+from products.replay_vision.backend.quota import sum_enabled_scanner_estimated_credits
from products.replay_vision.backend.tag_suggestions import SuggestionError, suggest_classifier_tags
from products.replay_vision.backend.tags import slugify_tag
from products.replay_vision.backend.temporal.constants import MAX_SESSION_ID_LENGTH
@@ -196,6 +198,12 @@ class ReplayScannerSerializer(serializers.ModelSerializer):
allow_null=True,
help_text="Latest projected observations/month for this scanner. Null until first computed.",
)
+ credits_per_observation = serializers.SerializerMethodField(
+ help_text="Credits one observation by this scanner costs (1 credit = $0.01), derived from `model`.",
+ )
+ estimated_monthly_credits = serializers.SerializerMethodField(
+ help_text="`estimated_monthly_observations` priced at `credits_per_observation`. Null until the estimate is first computed.",
+ )
last_swept_at = serializers.DateTimeField(
read_only=True,
help_text="Watermark for the scanner's last scheduled fire. Mirrors Temporal schedule state for recovery.",
@@ -223,6 +231,8 @@ class ReplayScannerSerializer(serializers.ModelSerializer):
"emits_signals",
"scanner_version",
"estimated_monthly_observations",
+ "credits_per_observation",
+ "estimated_monthly_credits",
"last_swept_at",
"created_at",
"created_by",
@@ -232,12 +242,24 @@ class ReplayScannerSerializer(serializers.ModelSerializer):
"id",
"scanner_version",
"estimated_monthly_observations",
+ "credits_per_observation",
+ "estimated_monthly_credits",
"last_swept_at",
"created_at",
"created_by",
"updated_at",
]
+ @extend_schema_field(serializers.IntegerField())
+ def get_credits_per_observation(self, scanner: ReplayScanner) -> int:
+ return observation_credits_for_model(scanner.model)
+
+ @extend_schema_field(serializers.IntegerField(allow_null=True))
+ def get_estimated_monthly_credits(self, scanner: ReplayScanner) -> int | None:
+ if scanner.estimated_monthly_observations is None:
+ return None
+ return scanner.estimated_monthly_observations * observation_credits_for_model(scanner.model)
+
def validate(self, attrs: dict[str, Any]) -> dict[str, Any]:
# Surface the (team_id, name) uniqueness as a 400 instead of letting the DB raise 500.
name = attrs.get("name")
@@ -489,10 +511,16 @@ class EstimateRequestSerializer(serializers.Serializer):
required=False,
allow_null=True,
help_text=(
- "The scanner being edited, excluded from `other_enabled_scanners_monthly` so its stored estimate isn't "
- "double-counted in the forecast. Omit (or null) when estimating a brand-new scanner."
+ "The scanner being edited, excluded from `other_enabled_scanners_monthly_credits` so its stored estimate "
+ "isn't double-counted in the forecast. Omit (or null) when estimating a brand-new scanner."
),
)
+ model = serializers.ChoiceField(
+ choices=ScannerModel.choices,
+ required=False,
+ default=ScannerModel.GEMINI_3_FLASH,
+ help_text="Proposed model; determines `credits_per_observation` in the response.",
+ )
def validate_query(self, value: dict[str, Any]) -> dict[str, Any]:
try:
@@ -541,7 +569,7 @@ class ScannerCreatorsResponseSerializer(serializers.Serializer):
class EstimateResponseSerializer(serializers.Serializer):
- """Forward-looking observation-volume estimate for a proposed scanner. Pricing-agnostic."""
+ """Forward-looking volume and credit-cost estimate for a proposed scanner."""
matched_sessions_in_window = serializers.IntegerField(
help_text=(
@@ -559,11 +587,17 @@ class EstimateResponseSerializer(serializers.Serializer):
"Projected monthly observations: quality-filtered matched sessions scaled to 30 days, times sampling_rate."
),
)
- other_enabled_scanners_monthly = serializers.IntegerField(
+ credits_per_observation = serializers.IntegerField(
+ help_text="Credits one observation costs at the proposed `model` (1 credit = $0.01).",
+ )
+ estimated_credits_per_month = serializers.IntegerField(
+ help_text="`estimated_observations_per_month` priced at `credits_per_observation`.",
+ )
+ other_enabled_scanners_monthly_credits = serializers.IntegerField(
help_text=(
- "Summed projected monthly observations of the org's other enabled scanners (excluding `scanner_id`), from "
- "their cached estimates. Read from the same snapshot as this estimate so the forecast can't double-count "
- "the edited scanner."
+ "Credit-weighted projected monthly spend of the org's other enabled scanners (excluding `scanner_id`), "
+ "from their cached estimates. Read from the same snapshot as this estimate so the forecast can't "
+ "double-count the edited scanner."
),
)
sampling_rate = serializers.FloatField(
@@ -733,7 +767,8 @@ class ReplayScannerViewSet(TeamAndOrgViewSetMixin, viewsets.ModelViewSet):
if not self.user_access_control.check_access_level_for_resource("session_recording", required_level="viewer"):
raise PermissionDenied("Triggering an on-demand observation requires session_recording read access.")
- check_observation_quota(self.team.organization_id)
+ check_observation_quota(self.team.organization_id, observation_credits_for_model(scanner.model))
+ check_team_in_flight_capacity(self.team.id)
body = ObserveRequestSerializer(data=request.data)
body.is_valid(raise_exception=True)
@@ -787,10 +822,11 @@ class ReplayScannerViewSet(TeamAndOrgViewSetMixin, viewsets.ModelViewSet):
team=self.team, query=recordings_query, sampling_mode=body.validated_data["sampling_mode"]
)
observations_per_month = project_monthly_observations(estimate, sampling_rate)
+ credits_per_observation = observation_credits_for_model(body.validated_data["model"])
# The OTHER enabled scanners' projected total (same source as the quota snapshot), so the editor adds this
# estimate on top of a consistent snapshot instead of subtracting a possibly-stale per-scanner field.
- other_enabled_scanners_monthly = sum_enabled_scanner_estimates(
+ other_enabled_scanners_monthly_credits = sum_enabled_scanner_estimated_credits(
self.team.organization_id, exclude_scanner_id=scanner_id
)
@@ -800,7 +836,9 @@ class ReplayScannerViewSet(TeamAndOrgViewSetMixin, viewsets.ModelViewSet):
"matched_sessions_in_window": estimate.matched_sessions,
"window_days": estimate.effective_window_days,
"estimated_observations_per_month": observations_per_month,
- "other_enabled_scanners_monthly": other_enabled_scanners_monthly,
+ "credits_per_observation": credits_per_observation,
+ "estimated_credits_per_month": observations_per_month * credits_per_observation,
+ "other_enabled_scanners_monthly_credits": other_enabled_scanners_monthly_credits,
"sampling_rate": sampling_rate,
}
).data
diff --git a/products/replay_vision/backend/api/trigger.py b/products/replay_vision/backend/api/trigger.py
index ba38a76b8ba0..ccff8eca0fe1 100644
--- a/products/replay_vision/backend/api/trigger.py
+++ b/products/replay_vision/backend/api/trigger.py
@@ -7,6 +7,7 @@ from django.conf import settings
import structlog
from asgiref.sync import async_to_sync
+from rest_framework.exceptions import Throttled
from temporalio.common import SearchAttributePair, TypedSearchAttributes
from temporalio.exceptions import WorkflowAlreadyStartedError
@@ -18,12 +19,13 @@ from posthog.temporal.common.search_attributes import (
POSTHOG_TEAM_ID_KEY,
)
-from products.replay_vision.backend.models.replay_observation import ObservationTrigger
+from products.replay_vision.backend.models.replay_observation import ObservationTrigger, ReplayObservation
from products.replay_vision.backend.models.replay_scanner import ReplayScanner
from products.replay_vision.backend.quota import compute_quota_snapshot
from products.replay_vision.backend.temporal.constants import (
APPLY_SCANNER_EXECUTION_TIMEOUT,
APPLY_SCANNER_WORKFLOW_NAME,
+ MAX_IN_FLIGHT_APPLIES_PER_TEAM,
build_apply_scanner_workflow_id,
)
from products.replay_vision.backend.temporal.types import ApplyScannerInputs
@@ -38,14 +40,24 @@ class WorkflowStartOutcome(enum.Enum):
FAILED = "failed"
-def check_observation_quota(organization_id: UUID) -> None:
- """Raise 402 when the org's monthly observation quota is exhausted."""
+def check_team_in_flight_capacity(team_id: int) -> None:
+ """Raise 429 when the team is already at its in-flight apply cap."""
+ count = ReplayObservation.in_flight_for_team(team_id).count()
+ if count >= MAX_IN_FLIGHT_APPLIES_PER_TEAM:
+ raise Throttled(detail=f"This team already has {count} observations running. Try again in a few minutes.")
+
+
+def check_observation_quota(organization_id: UUID, observation_credits: int) -> None:
+ """Raise 402 when starting an observation of this credit cost would exceed the org's monthly limit."""
snapshot = compute_quota_snapshot(organization_id=organization_id)
- if snapshot.exhausted:
+ if snapshot.would_exceed(observation_credits):
+ # would_exceed is only ever true when a limit is set, so credit_limit is non-None here.
+ assert snapshot.credit_limit is not None
raise QuotaLimitExceeded(
detail=(
- f"Monthly Replay Vision quota of {snapshot.monthly_quota:,} observations reached. "
- f"Resets {snapshot.period_end.strftime('%b')} {snapshot.period_end.day}."
+ f"Starting this observation would exceed your monthly Replay vision limit of "
+ f"${snapshot.credit_limit / 100:,.2f}. Resets {snapshot.period_end.strftime('%b')} "
+ f"{snapshot.period_end.day}."
)
)
diff --git a/products/replay_vision/backend/billing.py b/products/replay_vision/backend/billing.py
new file mode 100644
index 000000000000..f43a066bee60
--- /dev/null
+++ b/products/replay_vision/backend/billing.py
@@ -0,0 +1,53 @@
+"""Bills replay vision credits from the immutable `ReplayObservationUsage` receipt ledger, the same source the in-product quota meter reads.
+
+Credits use the same unit as ai_credits: 1 credit = $0.01. Each observation costs a
+model-dependent number of credits, frozen onto its receipt at success time so later
+price changes never reprice history.
+"""
+
+from datetime import datetime
+from typing import cast
+
+from django.db.models import IntegerField, Sum
+from django.db.models.functions import Coalesce
+
+import structlog
+
+from products.replay_vision.backend.models.replay_observation_usage import ReplayObservationUsage
+from products.replay_vision.backend.models.replay_scanner import ScannerModel
+
+logger = structlog.get_logger(__name__)
+
+CREDITS_PER_DOLLAR = 100 # 1 credit = $0.01, matching ai_credits
+
+# Keyed on the raw model-id string (not the enum) because frozen `scanner_snapshot`s and
+# receipts outlive enum members; retired ids must keep pricing in-flight observations.
+OBSERVATION_CREDITS_BY_MODEL: dict[str, int] = {
+ ScannerModel.GEMINI_2_5_FLASH: 2,
+ ScannerModel.GEMINI_3_FLASH: 5,
+ ScannerModel.GEMINI_3_5_FLASH: 15,
+ # Retired ids, kept for observations frozen before the lineup change.
+ "gemini-3.1-flash-lite-preview": 2,
+}
+
+# Unknown models bill at the highest known price: never underbill on a mapping gap.
+_FALLBACK_CREDITS = max(OBSERVATION_CREDITS_BY_MODEL.values())
+
+
+def observation_credits_for_model(model: str) -> int:
+ credits = OBSERVATION_CREDITS_BY_MODEL.get(model)
+ if credits is None:
+ logger.warning("replay_vision.unknown_model_credits", model=model, fallback=_FALLBACK_CREDITS)
+ return _FALLBACK_CREDITS
+ return credits
+
+
+def get_replay_vision_credits_by_team(begin: datetime, end: datetime) -> list[tuple[int, int]]:
+ # Bucket by receipt write time so a late receipt is never dropped from an already-run daily report.
+ rows = (
+ ReplayObservationUsage.objects.filter(created_at__gte=begin, created_at__lt=end, team_id__isnull=False)
+ .values("team_id")
+ .annotate(total_credits=Coalesce(Sum("credits"), 0, output_field=IntegerField()))
+ .values_list("team_id", "total_credits")
+ )
+ return cast(list[tuple[int, int]], list(rows))
diff --git a/products/replay_vision/backend/migrations/0031_replayobservationusage_team_id.py b/products/replay_vision/backend/migrations/0031_replayobservationusage_team_id.py
new file mode 100644
index 000000000000..97da0cbd4f9e
--- /dev/null
+++ b/products/replay_vision/backend/migrations/0031_replayobservationusage_team_id.py
@@ -0,0 +1,18 @@
+from django.db import migrations, models
+
+
+class Migration(migrations.Migration):
+ dependencies = [
+ ("replay_vision", "0030_vision_action_unique_scanner_digest"),
+ ]
+
+ operations = [
+ migrations.AddField(
+ model_name="replayobservationusage",
+ name="team_id",
+ field=models.BigIntegerField(
+ help_text="The observation's team; the per-team billing usage report groups on this (plain id, no FK).",
+ null=True,
+ ),
+ ),
+ ]
diff --git a/products/replay_vision/backend/migrations/0032_replayobservationusage_rlou_created_team_idx.py b/products/replay_vision/backend/migrations/0032_replayobservationusage_rlou_created_team_idx.py
new file mode 100644
index 000000000000..ec1cff8cb56b
--- /dev/null
+++ b/products/replay_vision/backend/migrations/0032_replayobservationusage_rlou_created_team_idx.py
@@ -0,0 +1,18 @@
+from django.db import migrations, models
+
+from posthog.migration_helpers import SafeAddIndexConcurrently
+
+
+class Migration(migrations.Migration):
+ atomic = False
+
+ dependencies = [
+ ("replay_vision", "0031_replayobservationusage_team_id"),
+ ]
+
+ operations = [
+ SafeAddIndexConcurrently(
+ model_name="replayobservationusage",
+ index=models.Index(fields=["created_at", "team_id"], name="rlou_created_team_idx"),
+ ),
+ ]
diff --git a/products/replay_vision/backend/migrations/0033_backfill_replayobservationusage_team_id.py b/products/replay_vision/backend/migrations/0033_backfill_replayobservationusage_team_id.py
new file mode 100644
index 000000000000..77c2256883e1
--- /dev/null
+++ b/products/replay_vision/backend/migrations/0033_backfill_replayobservationusage_team_id.py
@@ -0,0 +1,32 @@
+from django.db import migrations
+from django.db.models import OuterRef, Subquery
+
+_BATCH_SIZE = 2000
+
+
+def backfill_team_id(apps, schema_editor):
+ ReplayObservation = apps.get_model("replay_vision", "ReplayObservation")
+ ReplayObservationUsage = apps.get_model("replay_vision", "ReplayObservationUsage")
+ team_id_subquery = Subquery(ReplayObservation.objects.filter(pk=OuterRef("observation_id")).values("team_id")[:1])
+ # Keyset-paginate by pk rather than re-querying team_id__isnull: an orphaned receipt (its observation
+ # was deleted) resolves the subquery to NULL, so a shrinking-filter loop would never make progress on it.
+ last_pk = None
+ while True:
+ rows = ReplayObservationUsage.objects.filter(team_id__isnull=True)
+ if last_pk is not None:
+ rows = rows.filter(pk__gt=last_pk)
+ chunk = list(rows.order_by("pk").values_list("pk", flat=True)[:_BATCH_SIZE])
+ if not chunk:
+ break
+ ReplayObservationUsage.objects.filter(pk__in=chunk).update(team_id=team_id_subquery)
+ last_pk = chunk[-1]
+
+
+class Migration(migrations.Migration):
+ dependencies = [
+ ("replay_vision", "0032_replayobservationusage_rlou_created_team_idx"),
+ ]
+
+ operations = [
+ migrations.RunPython(backfill_team_id, migrations.RunPython.noop, elidable=True),
+ ]
diff --git a/products/replay_vision/backend/migrations/0034_alter_replayscanner_model.py b/products/replay_vision/backend/migrations/0034_alter_replayscanner_model.py
new file mode 100644
index 000000000000..03e17654772f
--- /dev/null
+++ b/products/replay_vision/backend/migrations/0034_alter_replayscanner_model.py
@@ -0,0 +1,24 @@
+# Generated by Django 5.2.14 on 2026-07-07 14:55
+
+from django.db import migrations, models
+
+
+class Migration(migrations.Migration):
+ dependencies = [
+ ("replay_vision", "0033_backfill_replayobservationusage_team_id"),
+ ]
+
+ operations = [
+ migrations.AlterField(
+ model_name="replayscanner",
+ name="model",
+ field=models.CharField(
+ choices=[
+ ("gemini-2.5-flash", "Gemini 2.5 Flash"),
+ ("gemini-3-flash-preview", "Gemini 3 Flash"),
+ ("gemini-3.5-flash", "Gemini 3.5 Flash"),
+ ],
+ max_length=64,
+ ),
+ ),
+ ]
diff --git a/products/replay_vision/backend/migrations/0035_remap_scanner_models.py b/products/replay_vision/backend/migrations/0035_remap_scanner_models.py
new file mode 100644
index 000000000000..757db1c608a3
--- /dev/null
+++ b/products/replay_vision/backend/migrations/0035_remap_scanner_models.py
@@ -0,0 +1,22 @@
+from django.db import migrations
+
+# Lite is retired from the lineup; existing Lite scanners move to the new cheap tier.
+_MODEL_REMAP = {
+ "gemini-3.1-flash-lite-preview": "gemini-2.5-flash",
+}
+
+
+def remap_scanner_models(apps, schema_editor):
+ ReplayScanner = apps.get_model("replay_vision", "ReplayScanner")
+ for old, new in _MODEL_REMAP.items():
+ ReplayScanner.objects.filter(model=old).update(model=new)
+
+
+class Migration(migrations.Migration):
+ dependencies = [
+ ("replay_vision", "0034_alter_replayscanner_model"),
+ ]
+
+ operations = [
+ migrations.RunPython(remap_scanner_models, migrations.RunPython.noop, elidable=True),
+ ]
diff --git a/products/replay_vision/backend/migrations/0036_replayobservationusage_credits_and_more.py b/products/replay_vision/backend/migrations/0036_replayobservationusage_credits_and_more.py
new file mode 100644
index 000000000000..7dff10c5d0d4
--- /dev/null
+++ b/products/replay_vision/backend/migrations/0036_replayobservationusage_credits_and_more.py
@@ -0,0 +1,29 @@
+# Generated by Django 5.2.14 on 2026-07-07 15:55
+
+from django.db import migrations, models
+
+
+class Migration(migrations.Migration):
+ dependencies = [
+ ("replay_vision", "0035_remap_scanner_models"),
+ ]
+
+ operations = [
+ migrations.AddField(
+ model_name="replayobservationusage",
+ name="credits",
+ field=models.PositiveIntegerField(
+ help_text="Credits billed for this observation (1 credit = $0.01), frozen at success time so price changes never reprice history.",
+ null=True,
+ ),
+ ),
+ migrations.AddField(
+ model_name="replayobservationusage",
+ name="model",
+ field=models.CharField(
+ help_text="Model id frozen from the observation's scanner_snapshot; kept for audit and re-pricing analysis.",
+ max_length=64,
+ null=True,
+ ),
+ ),
+ ]
diff --git a/products/replay_vision/backend/migrations/0037_backfill_replayobservationusage_credits.py b/products/replay_vision/backend/migrations/0037_backfill_replayobservationusage_credits.py
new file mode 100644
index 000000000000..2a67fa4eaa71
--- /dev/null
+++ b/products/replay_vision/backend/migrations/0037_backfill_replayobservationusage_credits.py
@@ -0,0 +1,63 @@
+from django.db import migrations
+from django.db.models import OuterRef, Subquery
+from django.db.models.fields.json import KeyTextTransform
+
+# Frozen copy of billing.OBSERVATION_CREDITS_BY_MODEL at backfill time; the live table may change later.
+_CREDITS_BY_MODEL = {
+ "gemini-3-flash-preview": 5,
+ "gemini-3.1-flash-lite-preview": 2,
+}
+_DEFAULT_CREDITS = 5
+_BATCH_SIZE = 2000
+
+
+def backfill_model_and_credits(apps, schema_editor):
+ ReplayObservation = apps.get_model("replay_vision", "ReplayObservation")
+ ReplayObservationUsage = apps.get_model("replay_vision", "ReplayObservationUsage")
+
+ # Model: keyset-paginate by pk. An orphaned receipt resolves the snapshot subquery to NULL, so a
+ # shrinking model__isnull filter would loop forever on it; walking pk visits every row exactly once.
+ # KeyTextTransform (->>), not scanner_snapshot__model (->): the latter stores the JSON-quoted value
+ # ('"gemini-3-flash-preview"') into the text column, which then never matches the credit map.
+ model_subquery = Subquery(
+ ReplayObservation.objects.filter(pk=OuterRef("observation_id"))
+ .annotate(_m=KeyTextTransform("model", "scanner_snapshot"))
+ .values("_m")[:1]
+ )
+ last_pk = None
+ while True:
+ rows = ReplayObservationUsage.objects.filter(model__isnull=True)
+ if last_pk is not None:
+ rows = rows.filter(pk__gt=last_pk)
+ chunk = list(rows.order_by("pk").values_list("pk", flat=True)[:_BATCH_SIZE])
+ if not chunk:
+ break
+ ReplayObservationUsage.objects.filter(pk__in=chunk).update(model=model_subquery)
+ last_pk = chunk[-1]
+
+ # Credits: every pass sets a non-null value, so a shrinking credits__isnull filter terminates.
+ def backfill_credits(credits, **extra_filter):
+ while True:
+ chunk = list(
+ ReplayObservationUsage.objects.filter(credits__isnull=True, **extra_filter).values_list(
+ "pk", flat=True
+ )[:_BATCH_SIZE]
+ )
+ if not chunk:
+ break
+ ReplayObservationUsage.objects.filter(pk__in=chunk).update(credits=credits)
+
+ for model_id, credits in _CREDITS_BY_MODEL.items():
+ backfill_credits(credits, model=model_id)
+ # Orphaned receipts (observation deleted) and unknown models bill at the pre-differentiation baseline.
+ backfill_credits(_DEFAULT_CREDITS)
+
+
+class Migration(migrations.Migration):
+ dependencies = [
+ ("replay_vision", "0036_replayobservationusage_credits_and_more"),
+ ]
+
+ operations = [
+ migrations.RunPython(backfill_model_and_credits, migrations.RunPython.noop, elidable=True),
+ ]
diff --git a/products/replay_vision/backend/migrations/0038_redenominate_quota_grants_to_credits.py b/products/replay_vision/backend/migrations/0038_redenominate_quota_grants_to_credits.py
new file mode 100644
index 000000000000..8fa592ba818d
--- /dev/null
+++ b/products/replay_vision/backend/migrations/0038_redenominate_quota_grants_to_credits.py
@@ -0,0 +1,20 @@
+from django.db import migrations
+from django.db.models import F
+
+# Grants were denominated in observations; credits are 5 per baseline observation.
+_CREDITS_PER_LEGACY_OBSERVATION = 5
+
+
+def redenominate_grants(apps, schema_editor):
+ ReplayQuotaGrant = apps.get_model("replay_vision", "ReplayQuotaGrant")
+ ReplayQuotaGrant.objects.update(amount=F("amount") * _CREDITS_PER_LEGACY_OBSERVATION)
+
+
+class Migration(migrations.Migration):
+ dependencies = [
+ ("replay_vision", "0037_backfill_replayobservationusage_credits"),
+ ]
+
+ operations = [
+ migrations.RunPython(redenominate_grants, migrations.RunPython.noop, elidable=True),
+ ]
diff --git a/products/replay_vision/backend/migrations/0039_alter_replayquotagrant_amount.py b/products/replay_vision/backend/migrations/0039_alter_replayquotagrant_amount.py
new file mode 100644
index 000000000000..e426b61f0751
--- /dev/null
+++ b/products/replay_vision/backend/migrations/0039_alter_replayquotagrant_amount.py
@@ -0,0 +1,24 @@
+# Generated by Django 5.2.14 on 2026-07-07 16:00
+
+import django.core.validators
+from django.db import migrations, models
+
+
+class Migration(migrations.Migration):
+ dependencies = [
+ ("replay_vision", "0038_redenominate_quota_grants_to_credits"),
+ ]
+
+ operations = [
+ migrations.AlterField(
+ model_name="replayquotagrant",
+ name="amount",
+ field=models.PositiveIntegerField(
+ help_text="Extra credits granted on top of the base monthly credit limit (1–1,000,000).",
+ validators=[
+ django.core.validators.MinValueValidator(1),
+ django.core.validators.MaxValueValidator(1000000),
+ ],
+ ),
+ ),
+ ]
diff --git a/products/replay_vision/backend/migrations/0040_replayobservation_rlo_team_in_flight_idx.py b/products/replay_vision/backend/migrations/0040_replayobservation_rlo_team_in_flight_idx.py
new file mode 100644
index 000000000000..70d8d947a12d
--- /dev/null
+++ b/products/replay_vision/backend/migrations/0040_replayobservation_rlo_team_in_flight_idx.py
@@ -0,0 +1,24 @@
+from django.db import migrations, models
+
+from posthog.migration_helpers import SafeAddIndexConcurrently
+
+
+class Migration(migrations.Migration):
+ # CONCURRENTLY so building the partial index doesn't take an ACCESS EXCLUSIVE lock on
+ # replay_observation. Concurrent builds can't run in a transaction, so this is non-atomic.
+ atomic = False
+
+ dependencies = [
+ ("replay_vision", "0039_alter_replayquotagrant_amount"),
+ ]
+
+ operations = [
+ SafeAddIndexConcurrently(
+ model_name="replayobservation",
+ index=models.Index(
+ condition=models.Q(("status__in", ("pending", "running"))),
+ fields=["team", "scanner"],
+ name="rlo_team_in_flight_idx",
+ ),
+ ),
+ ]
diff --git a/products/replay_vision/backend/migrations/max_migration.txt b/products/replay_vision/backend/migrations/max_migration.txt
index 6351d13da9bc..8f3654f9acb3 100644
--- a/products/replay_vision/backend/migrations/max_migration.txt
+++ b/products/replay_vision/backend/migrations/max_migration.txt
@@ -1 +1 @@
-0030_vision_action_unique_scanner_digest
+0040_replayobservation_rlo_team_in_flight_idx
diff --git a/products/replay_vision/backend/models/replay_observation.py b/products/replay_vision/backend/models/replay_observation.py
index 11402d1af761..e759b61adbf9 100644
--- a/products/replay_vision/backend/models/replay_observation.py
+++ b/products/replay_vision/backend/models/replay_observation.py
@@ -15,6 +15,10 @@ class ObservationStatus(models.TextChoices):
INELIGIBLE = "ineligible", "Ineligible"
+# Not-yet-terminal statuses: what the quota meter reserves and the concurrency caps count as "in flight".
+IN_FLIGHT_STATUSES = (ObservationStatus.PENDING, ObservationStatus.RUNNING)
+
+
class ObservationTrigger(models.TextChoices):
SCHEDULE = "schedule", "Schedule"
ON_DEMAND = "on_demand", "On demand"
@@ -101,8 +105,20 @@ class ReplayObservation(UUIDModel):
name="rlo_workflow_id_idx",
condition=~models.Q(workflow_id=""),
),
+ # Serves the per-team in-flight concurrency count (sweep headroom + on-demand 429). Partial on the
+ # in-flight statuses only, since terminal rows dominate and are never counted.
+ models.Index(
+ fields=["team", "scanner"],
+ name="rlo_team_in_flight_idx",
+ condition=models.Q(status__in=("pending", "running")),
+ ),
]
+ @classmethod
+ def in_flight_for_team(cls, team_id: int) -> "models.QuerySet[ReplayObservation]":
+ """A team's not-yet-terminal observations; the one predicate the quota meter and concurrency caps share."""
+ return cls.objects.filter(team_id=team_id, status__in=IN_FLIGHT_STATUSES)
+
def save(self, *args, **kwargs) -> None:
# Tenant invariant: observation.team_id must match scanner.team_id.
if self._state.adding:
diff --git a/products/replay_vision/backend/models/replay_observation_usage.py b/products/replay_vision/backend/models/replay_observation_usage.py
index 5eb4a00db60f..e272a0fe93a3 100644
--- a/products/replay_vision/backend/models/replay_observation_usage.py
+++ b/products/replay_vision/backend/models/replay_observation_usage.py
@@ -15,14 +15,29 @@ class ReplayObservationUsage(UUIDModel):
unique=True,
help_text="The observation this receipt accounts for (plain id, no FK).",
)
+ team_id = models.BigIntegerField(
+ null=True,
+ help_text="The observation's team; the per-team billing usage report groups on this (plain id, no FK).",
+ )
observation_created_at = models.DateTimeField(
help_text="The observation's created_at; the monthly quota window filters on this.",
)
+ model = models.CharField(
+ max_length=64,
+ null=True,
+ help_text="Model id frozen from the observation's scanner_snapshot; kept for audit and re-pricing analysis.",
+ )
+ credits = models.PositiveIntegerField(
+ null=True,
+ help_text="Credits billed for this observation (1 credit = $0.01), frozen at success time so price changes never reprice history.",
+ )
created_at = models.DateTimeField(auto_now_add=True)
class Meta:
indexes = [
models.Index(fields=["organization", "observation_created_at"]),
+ # Drives the daily per-team billing usage query, which buckets receipts by write time.
+ models.Index(fields=["created_at", "team_id"], name="rlou_created_team_idx"),
]
def __str__(self) -> str:
diff --git a/products/replay_vision/backend/models/replay_quota_grant.py b/products/replay_vision/backend/models/replay_quota_grant.py
index 2a79ae824b9b..e2883dfd7b45 100644
--- a/products/replay_vision/backend/models/replay_quota_grant.py
+++ b/products/replay_vision/backend/models/replay_quota_grant.py
@@ -10,9 +10,9 @@ MAX_GRANT_AMOUNT = 1_000_000
class ReplayQuotaGrant(UUIDModel):
- """Bonus observation budget for an organization, valid until `expires_at`.
+ """Bonus credit budget for an organization, valid until `expires_at`.
- Active grants are summed into the organization's effective `monthly_quota` — see
+ Active grants are summed into the organization's effective credit limit; see
`products.replay_vision.backend.quota.compute_quota_snapshot`. At and after `expires_at`, grants stop counting.
"""
@@ -23,7 +23,7 @@ class ReplayQuotaGrant(UUIDModel):
)
amount = models.PositiveIntegerField(
validators=[MinValueValidator(1), MaxValueValidator(MAX_GRANT_AMOUNT)],
- help_text=f"Extra observations granted on top of the base monthly quota (1–{MAX_GRANT_AMOUNT:,}).",
+ help_text=f"Extra credits granted on top of the base monthly credit limit (1–{MAX_GRANT_AMOUNT:,}).",
)
expires_at = models.DateTimeField(
help_text="Grant is valid up to but not including this timestamp. Defaults to the start of next month.",
diff --git a/products/replay_vision/backend/models/replay_scanner.py b/products/replay_vision/backend/models/replay_scanner.py
index c4457cdf9f77..9186dbff44ec 100644
--- a/products/replay_vision/backend/models/replay_scanner.py
+++ b/products/replay_vision/backend/models/replay_scanner.py
@@ -32,8 +32,11 @@ class ScannerProvider(models.TextChoices):
class ScannerModel(models.TextChoices):
+ """Priced per observation in `billing.OBSERVATION_CREDITS_BY_MODEL`; new members need a price there."""
+
+ GEMINI_2_5_FLASH = "gemini-2.5-flash", "Gemini 2.5 Flash"
GEMINI_3_FLASH = "gemini-3-flash-preview", "Gemini 3 Flash"
- GEMINI_3_FLASH_LITE = "gemini-3.1-flash-lite-preview", "Gemini 3 Flash Lite"
+ GEMINI_3_5_FLASH = "gemini-3.5-flash", "Gemini 3.5 Flash"
def initial_watermark() -> "datetime":
diff --git a/products/replay_vision/backend/quota.py b/products/replay_vision/backend/quota.py
index dc854e8d5368..f8b445f43b26 100644
--- a/products/replay_vision/backend/quota.py
+++ b/products/replay_vision/backend/quota.py
@@ -1,42 +1,58 @@
+from collections import Counter
from dataclasses import dataclass
from datetime import UTC, datetime
from uuid import UUID
-from django.db.models import Sum, Value
+from django.db.models import IntegerField, Sum, Value
from django.db.models.functions import Coalesce
+import structlog
from dateutil.relativedelta import relativedelta
from posthog.date_util import start_of_month
+from posthog.models.organization import Organization
from posthog.settings.utils import get_from_env
-from products.replay_vision.backend.models.replay_observation import ObservationStatus, ReplayObservation
+from products.replay_vision.backend.billing import observation_credits_for_model
+from products.replay_vision.backend.models.replay_observation import IN_FLIGHT_STATUSES, ReplayObservation
from products.replay_vision.backend.models.replay_observation_usage import ReplayObservationUsage
from products.replay_vision.backend.models.replay_quota_grant import ReplayQuotaGrant
from products.replay_vision.backend.models.replay_scanner import ReplayScanner
-MONTHLY_OBSERVATION_QUOTA = get_from_env("REPLAY_VISION_MONTHLY_OBSERVATION_QUOTA", 3000, type_cast=int)
+logger = structlog.get_logger(__name__)
-# usage = ledger(succeeded) + live(in-flight); every quota-counting status must belong to exactly one source.
-_IN_FLIGHT_STATUSES = (ObservationStatus.PENDING, ObservationStatus.RUNNING)
+# Fallback monthly credit cap for orgs billing has never synced (self-hosted, pre-launch beta).
+MONTHLY_CREDIT_QUOTA = get_from_env("REPLAY_VISION_MONTHLY_CREDIT_QUOTA", 15000, type_cast=int)
+
+# Billing's usage_key for this product; see ee/billing/quota_limiting.QuotaResource.REPLAY_VISION_CREDITS.
+USAGE_KEY = "replay_vision_credits"
@dataclass(frozen=True)
class QuotaSnapshot:
- monthly_quota: int
- usage_this_month: int
+ """All amounts are credits (1 credit = $0.01)."""
+
+ # None means billing synced the product with no spend limit set: uncapped.
+ credit_limit: int | None
+ credits_used: int
period_start: datetime
period_end: datetime
- # Sum of enabled scanners' persisted per-scanner estimates across the org; uncomputed estimates count 0.
- projected_monthly_observations: int
+ # Credit-weighted sum of enabled scanners' persisted estimates across the org; uncomputed estimates count 0.
+ projected_monthly_credits: int
@property
- def remaining(self) -> int:
- return max(0, self.monthly_quota - self.usage_this_month)
+ def remaining(self) -> int | None:
+ if self.credit_limit is None:
+ return None
+ return max(0, self.credit_limit - self.credits_used)
@property
def exhausted(self) -> bool:
- return self.usage_this_month >= self.monthly_quota
+ return self.credit_limit is not None and self.credits_used >= self.credit_limit
+
+ def would_exceed(self, credits: int) -> bool:
+ """Whether starting an observation costing `credits` would push usage past the limit (uncapped never does)."""
+ return self.credit_limit is not None and self.credits_used + credits > self.credit_limit
def next_month_start(now: datetime) -> datetime:
@@ -48,41 +64,84 @@ def _current_month_bounds(now: datetime) -> tuple[datetime, datetime]:
return start_of_month(now), next_month_start(now)
-def sum_enabled_scanner_estimates(organization_id: UUID, exclude_scanner_id: UUID | None = None) -> int:
- """Projected monthly observation volume from the org's enabled scanners' cached estimates."""
+def _as_utc(value: datetime) -> datetime:
+ """Treat a tz-naive billing timestamp as UTC so it can be compared against tz-aware now."""
+ return value if value.tzinfo else value.replace(tzinfo=UTC)
+
+
+def sum_enabled_scanner_estimated_credits(organization_id: UUID, exclude_scanner_id: UUID | None = None) -> int:
+ """Projected monthly credit spend from the org's enabled scanners' cached estimates."""
scanners = ReplayScanner.objects.filter(team__organization_id=organization_id, enabled=True)
if exclude_scanner_id is not None:
scanners = scanners.exclude(pk=exclude_scanner_id)
- return scanners.aggregate(total=Coalesce(Sum("estimated_monthly_observations"), Value(0)))["total"]
+ # Credit weighting happens in Python: the per-model price table lives in code, and orgs have few scanners.
+ rows = scanners.values_list("model", "estimated_monthly_observations")
+ return sum(observation_credits_for_model(model) * (estimate or 0) for model, estimate in rows)
+
+
+def _billing_synced_limit(organization: Organization | None) -> tuple[bool, int | None]:
+ """(synced, limit): whether billing has synced this product, and the credit limit it synced (None = uncapped)."""
+ if organization is None or not organization.usage:
+ return False, None
+ usage = organization.usage.get(USAGE_KEY)
+ # Billing syncs `{}` for products it doesn't know about; only a summary that carries a
+ # `limit` key (even a null one) means billing actually manages this product.
+ if not usage or "limit" not in usage:
+ return False, None
+ limit = usage.get("limit")
+ if limit is None:
+ return True, None
+ if isinstance(limit, (int, float)) and not isinstance(limit, bool):
+ return True, int(limit)
+ # A malformed limit must fail toward the env cap, never toward uncapped.
+ logger.warning("replay_vision.malformed_billing_limit", organization_id=str(organization.id), limit=repr(limit))
+ return False, None
def compute_quota_snapshot(organization_id: UUID) -> QuotaSnapshot:
# Single `now` so the usage window, bonus expiry, and any caller comparisons are computed from one instant.
now = datetime.now(UTC)
- period_start, period_end = _current_month_bounds(now)
+ organization = Organization.objects.filter(pk=organization_id).only("usage").first()
+ # Billing is the source of truth once synced, falling back to the env cap and calendar months otherwise.
+ billing_period = organization.current_billing_period if organization else None
+ if billing_period:
+ billing_period = (_as_utc(billing_period[0]), _as_utc(billing_period[1]))
+ if billing_period and billing_period[0] <= now < billing_period[1]:
+ period_start, period_end = billing_period
+ else:
+ period_start, period_end = _current_month_bounds(now)
# Permanently-spent (succeeded) from the immutable ledger; deletes can't refund it.
consumed = ReplayObservationUsage.objects.filter(
organization_id=organization_id,
observation_created_at__gte=period_start,
observation_created_at__lt=period_end,
- ).count()
- # In-flight rows aren't in the ledger yet (receipt is written on success), so add them live.
- in_flight = ReplayObservation.objects.filter(
- team__organization_id=organization_id,
- status__in=_IN_FLIGHT_STATUSES,
- created_at__gte=period_start,
- created_at__lt=period_end,
- ).count()
+ ).aggregate(total=Coalesce(Sum("credits"), Value(0), output_field=IntegerField()))["total"]
+ # In-flight rows aren't in the ledger yet (receipt is written on success), so reserve their credits live,
+ # priced from the frozen snapshot model exactly as the eventual receipt will be.
+ in_flight_models = Counter(
+ ReplayObservation.objects.filter(
+ team__organization_id=organization_id,
+ status__in=IN_FLIGHT_STATUSES,
+ created_at__gte=period_start,
+ created_at__lt=period_end,
+ ).values_list("scanner_snapshot__model", flat=True)
+ )
+ in_flight = sum(observation_credits_for_model(model or "") * count for model, count in in_flight_models.items())
usage = consumed + in_flight
bonus = ReplayQuotaGrant.objects.filter(
organization_id=organization_id,
expires_at__gt=now,
).aggregate(total=Coalesce(Sum("amount"), Value(0)))["total"]
- projected = sum_enabled_scanner_estimates(organization_id)
+ projected = sum_enabled_scanner_estimated_credits(organization_id)
+ synced, base_limit = _billing_synced_limit(organization)
+ if not synced:
+ base_limit = MONTHLY_CREDIT_QUOTA
+ # An uncapped synced org stays uncapped: bonuses only extend a real limit.
+ credit_limit = base_limit + bonus if base_limit is not None else None
return QuotaSnapshot(
- monthly_quota=MONTHLY_OBSERVATION_QUOTA + bonus,
- usage_this_month=usage,
+ credit_limit=credit_limit,
+ credits_used=usage,
period_start=period_start,
period_end=period_end,
- projected_monthly_observations=projected,
+ projected_monthly_credits=projected,
)
diff --git a/products/replay_vision/backend/temporal/__init__.py b/products/replay_vision/backend/temporal/__init__.py
index 749207558430..c1264e585224 100644
--- a/products/replay_vision/backend/temporal/__init__.py
+++ b/products/replay_vision/backend/temporal/__init__.py
@@ -6,6 +6,7 @@ from products.replay_vision.backend.temporal.activities import (
call_scanner_provider_activity,
cleanup_gemini_file_activity,
count_in_flight_applies_activity,
+ count_in_flight_by_team_activity,
create_observation_activity,
delete_scanner_schedule_activity,
embed_observation_activity,
@@ -71,6 +72,7 @@ ACTIVITIES: list[Callable[..., Any]] = [
cleanup_gemini_file_activity,
find_scanner_candidates_activity,
count_in_flight_applies_activity,
+ count_in_flight_by_team_activity,
advance_scanner_watermark_activity,
refresh_prompt_suggestion_activity,
list_enabled_scanners_activity,
@@ -109,6 +111,7 @@ __all__ = [
"call_scanner_provider_activity",
"cleanup_gemini_file_activity",
"count_in_flight_applies_activity",
+ "count_in_flight_by_team_activity",
"create_observation_activity",
"delete_scanner_schedule_activity",
"embed_observation_activity",
diff --git a/products/replay_vision/backend/temporal/activities/__init__.py b/products/replay_vision/backend/temporal/activities/__init__.py
index 2f45f10902da..2097aafe2cc6 100644
--- a/products/replay_vision/backend/temporal/activities/__init__.py
+++ b/products/replay_vision/backend/temporal/activities/__init__.py
@@ -3,7 +3,10 @@ from products.replay_vision.backend.temporal.activities.advance_scanner_watermar
)
from products.replay_vision.backend.temporal.activities.call_scanner_provider import call_scanner_provider_activity
from products.replay_vision.backend.temporal.activities.cleanup_gemini_file import cleanup_gemini_file_activity
-from products.replay_vision.backend.temporal.activities.count_in_flight_applies import count_in_flight_applies_activity
+from products.replay_vision.backend.temporal.activities.count_in_flight_applies import (
+ count_in_flight_applies_activity,
+ count_in_flight_by_team_activity,
+)
from products.replay_vision.backend.temporal.activities.create_observation import create_observation_activity
from products.replay_vision.backend.temporal.activities.embed_observation import embed_observation_activity
from products.replay_vision.backend.temporal.activities.emit_classifier_tags import emit_classifier_tags_activity
@@ -44,6 +47,7 @@ __all__ = [
"call_scanner_provider_activity",
"cleanup_gemini_file_activity",
"count_in_flight_applies_activity",
+ "count_in_flight_by_team_activity",
"create_observation_activity",
"delete_scanner_schedule_activity",
"embed_observation_activity",
diff --git a/products/replay_vision/backend/temporal/activities/count_in_flight_applies.py b/products/replay_vision/backend/temporal/activities/count_in_flight_applies.py
index bccbfcdcd775..a36fc906fef6 100644
--- a/products/replay_vision/backend/temporal/activities/count_in_flight_applies.py
+++ b/products/replay_vision/backend/temporal/activities/count_in_flight_applies.py
@@ -1,10 +1,13 @@
+from django.db.models import Count, Q
+
import structlog
from temporalio import activity
from posthog.temporal.common.client import async_connect
+from products.replay_vision.backend.models.replay_observation import ReplayObservation
from products.replay_vision.backend.temporal.decorators import track_activity
-from products.replay_vision.backend.temporal.sweep_types import CountInFlightAppliesInputs
+from products.replay_vision.backend.temporal.sweep_types import CountInFlightAppliesInputs, InFlightApplyCounts
logger = structlog.get_logger(__name__)
@@ -12,7 +15,8 @@ logger = structlog.get_logger(__name__)
@activity.defn
@track_activity()
async def count_in_flight_applies_activity(inputs: CountInFlightAppliesInputs) -> int:
- """Count this scanner's running apply-scanner workflows (PostHogScannerId is stamped only on those).
+ """Legacy visibility-based scanner counter, retained so pre-deploy sweeps can replay their recorded
+ int result; the wf.patched branch in the workflow routes new executions to the team-aware activity below.
Fails open (returns 0) so a visibility hiccup lets the sweep proceed rather than wedging it.
"""
@@ -23,3 +27,19 @@ async def count_in_flight_applies_activity(inputs: CountInFlightAppliesInputs) -
except Exception as exc:
logger.warning("replay_vision.count_in_flight_failed", scanner_id=str(inputs.scanner_id), error=str(exc))
return 0
+
+
+@track_activity()
+def count_in_flight_by_team_activity(inputs: CountInFlightAppliesInputs) -> InFlightApplyCounts:
+ """Count in-flight (pending/running) observations for this scanner and for its whole team.
+
+ Counts DB rows rather than Temporal visibility so concurrency shares the quota system's
+ single notion of in-flight. Rows stranded by failed workflows keep counting until the orphan
+ reaper clears them, which throttles sweeps during an incident instead of piling on new work.
+ """
+ counts = ReplayObservation.in_flight_for_team(inputs.team_id).aggregate(
+ team=Count("id"),
+ scanner=Count("id", filter=Q(scanner_id=inputs.scanner_id)),
+ )
+ return InFlightApplyCounts(scanner=counts["scanner"], team=counts["team"])
diff --git a/products/replay_vision/backend/temporal/activities/create_observation.py b/products/replay_vision/backend/temporal/activities/create_observation.py
index 15331b5b4086..01b44ff94552 100644
--- a/products/replay_vision/backend/temporal/activities/create_observation.py
+++ b/products/replay_vision/backend/temporal/activities/create_observation.py
@@ -8,6 +8,7 @@ from temporalio.exceptions import ApplicationError
from posthog.models.organization import OrganizationMembership
+from products.replay_vision.backend.billing import observation_credits_for_model
from products.replay_vision.backend.models.replay_observation import ObservationStatus, ReplayObservation
from products.replay_vision.backend.models.replay_scanner import ReplayScanner
from products.replay_vision.backend.quota import compute_quota_snapshot
@@ -50,7 +51,7 @@ def create_observation_activity(inputs: CreateObservationInputs) -> CreateObserv
f"User {inputs.triggered_by_user_id} is not a member of scanner {inputs.scanner_id}'s organization"
)
- if compute_quota_snapshot(scanner.team.organization_id).exhausted:
+ if compute_quota_snapshot(scanner.team.organization_id).would_exceed(observation_credits_for_model(scanner.model)):
activity.logger.info(
"Skipping observation: monthly quota exhausted",
extra={"scanner_id": str(inputs.scanner_id), "team_id": inputs.team_id, "session_id": inputs.session_id},
diff --git a/products/replay_vision/backend/temporal/activities/observation_state.py b/products/replay_vision/backend/temporal/activities/observation_state.py
index 45bc5544468c..fc7e6bfa0feb 100644
--- a/products/replay_vision/backend/temporal/activities/observation_state.py
+++ b/products/replay_vision/backend/temporal/activities/observation_state.py
@@ -7,6 +7,7 @@ from django.utils import timezone
import structlog
from temporalio import activity
+from products.replay_vision.backend.billing import observation_credits_for_model
from products.replay_vision.backend.models.replay_observation import ObservationStatus, ReplayObservation
from products.replay_vision.backend.models.replay_observation_usage import ReplayObservationUsage
from products.replay_vision.backend.temporal.decorators import track_activity
@@ -129,12 +130,18 @@ def mark_observation_succeeded_activity(inputs: MarkObservationSucceededInputs)
if not updated:
return # No state transition — retry against an already-terminal row.
# Write the usage receipt in the same transaction as the transition so a crash can't undercount.
- obs = ReplayObservation.objects.values("team__organization_id", "created_at").get(pk=inputs.observation_id)
+ obs = ReplayObservation.objects.values(
+ "team_id", "team__organization_id", "created_at", "scanner_snapshot__model"
+ ).get(pk=inputs.observation_id)
+ model = obs["scanner_snapshot__model"] or ""
ReplayObservationUsage.objects.get_or_create(
observation_id=inputs.observation_id,
defaults={
"organization_id": obs["team__organization_id"],
+ "team_id": obs["team_id"],
"observation_created_at": obs["created_at"],
+ "model": model,
+ "credits": observation_credits_for_model(model),
},
)
REPLAY_VISION_OBSERVATIONS.labels(status="succeeded", scanner_type=inputs.scanner_type).inc()
diff --git a/products/replay_vision/backend/temporal/constants.py b/products/replay_vision/backend/temporal/constants.py
index 5cf8b1784635..d25ee1f9aee1 100644
--- a/products/replay_vision/backend/temporal/constants.py
+++ b/products/replay_vision/backend/temporal/constants.py
@@ -78,7 +78,10 @@ VISION_SIGNALS_SOURCE_TYPE = "scanner_finding"
# Hard ceiling on a single scanner's concurrently-running apply-scanner workflows. Bounds one bad config
# (broad filter on a high-volume team) from monopolising the shared rasterizer queue + provider concurrency.
-MAX_IN_FLIGHT_APPLIES_PER_SCANNER = 50
+MAX_IN_FLIGHT_APPLIES_PER_SCANNER = 150
+# Team-wide ceiling across all of a team's scanners and on-demand triggers, so N scanners can't hold
+# N x 150 rasterizer slots. Fairness only; the rasterizer scales horizontally for total throughput.
+MAX_IN_FLIGHT_APPLIES_PER_TEAM = 300
COUNT_IN_FLIGHT_APPLIES_TIMEOUT = dt.timedelta(seconds=30)
diff --git a/products/replay_vision/backend/temporal/sweep_types.py b/products/replay_vision/backend/temporal/sweep_types.py
index 2b35041b021f..fd5993bc408a 100644
--- a/products/replay_vision/backend/temporal/sweep_types.py
+++ b/products/replay_vision/backend/temporal/sweep_types.py
@@ -22,6 +22,12 @@ class FindScannerCandidatesInputs(BaseModel, frozen=True):
class CountInFlightAppliesInputs(BaseModel, frozen=True):
scanner_id: UUID
+ team_id: int
+
+
+class InFlightApplyCounts(BaseModel, frozen=True):
+ scanner: int
+ team: int
class CandidateSessionPayload(BaseModel, frozen=True):
diff --git a/products/replay_vision/backend/temporal/sweep_workflow.py b/products/replay_vision/backend/temporal/sweep_workflow.py
index 02acd4dfa29f..5509539884b0 100644
--- a/products/replay_vision/backend/temporal/sweep_workflow.py
+++ b/products/replay_vision/backend/temporal/sweep_workflow.py
@@ -22,6 +22,7 @@ from products.replay_vision.backend.models.replay_observation import Observation
from products.replay_vision.backend.temporal.activities import (
advance_scanner_watermark_activity,
count_in_flight_applies_activity,
+ count_in_flight_by_team_activity,
find_scanner_candidates_activity,
refresh_prompt_suggestion_activity,
)
@@ -30,6 +31,7 @@ from products.replay_vision.backend.temporal.constants import (
APPLY_SCANNER_WORKFLOW_NAME,
COUNT_IN_FLIGHT_APPLIES_TIMEOUT,
MAX_IN_FLIGHT_APPLIES_PER_SCANNER,
+ MAX_IN_FLIGHT_APPLIES_PER_TEAM,
PROCESS_VISION_ACTION_EXECUTION_TIMEOUT,
PROCESS_VISION_ACTION_WORKFLOW_NAME,
REFRESH_PROMPT_SUGGESTION_TIMEOUT,
@@ -85,19 +87,42 @@ class SweepScannerWorkflow(PostHogWorkflow):
"replay_vision.prompt_suggestion_refresh_failed", extra={"scanner_id": str(inputs.scanner_id)}
)
- # Hard per-scanner concurrency cap: don't fetch more than the in-flight headroom, and skip entirely
- # when saturated. Keeps one bad config from flooding the shared rasterizer + provider concurrency.
- # The activity fails open (returns 0 on any error), so there's nothing to retry.
- in_flight = await wf.execute_activity(
- count_in_flight_applies_activity,
- CountInFlightAppliesInputs(scanner_id=inputs.scanner_id),
- start_to_close_timeout=COUNT_IN_FLIGHT_APPLIES_TIMEOUT,
- retry_policy=common.RetryPolicy(maximum_attempts=1),
+ # Hard concurrency caps: per scanner (one bad config) and per team (many scanners), enforced as the
+ # min of the two headrooms. Skip entirely when saturated. Keeps any single tenant from flooding the
+ # shared rasterizer + provider concurrency. A DB error fails the count (single attempt), so the sweep
+ # skips this tick rather than dispatching against an unknown load; the next tick retries in 5 minutes.
+ count_inputs = CountInFlightAppliesInputs(scanner_id=inputs.scanner_id, team_id=inputs.team_id)
+ if wf.patched("replay-vision-team-in-flight-caps"):
+ in_flight = await wf.execute_activity(
+ count_in_flight_by_team_activity,
+ count_inputs,
+ start_to_close_timeout=COUNT_IN_FLIGHT_APPLIES_TIMEOUT,
+ retry_policy=common.RetryPolicy(maximum_attempts=1),
+ )
+ scanner_in_flight, team_in_flight = in_flight.scanner, in_flight.team
+ else:
+ # Pre-deploy sweeps replay the legacy scanner-only counter's recorded int; no team cap for them.
+ scanner_in_flight = await wf.execute_activity(
+ count_in_flight_applies_activity,
+ count_inputs,
+ start_to_close_timeout=COUNT_IN_FLIGHT_APPLIES_TIMEOUT,
+ retry_policy=common.RetryPolicy(maximum_attempts=1),
+ )
+ team_in_flight = 0
+ headroom = min(
+ MAX_IN_FLIGHT_APPLIES_PER_SCANNER - scanner_in_flight,
+ MAX_IN_FLIGHT_APPLIES_PER_TEAM - team_in_flight,
)
- headroom = MAX_IN_FLIGHT_APPLIES_PER_SCANNER - in_flight
if headroom <= 0:
- # At the cap — drain before fetching more. Don't advance the watermark; resume next tick.
- wf.logger.info("replay_vision.sweep_throttled", extra={"scanner_id": str(inputs.scanner_id)})
+ # At a cap — drain before fetching more. Don't advance the watermark; resume next tick.
+ wf.logger.info(
+ "replay_vision.sweep_throttled",
+ extra={
+ "scanner_id": str(inputs.scanner_id),
+ "scanner_in_flight": scanner_in_flight,
+ "team_in_flight": team_in_flight,
+ },
+ )
return
find_result = await wf.execute_activity(
diff --git a/products/replay_vision/backend/tests/test_api.py b/products/replay_vision/backend/tests/test_api.py
index 7c5192f1ba0c..c66f3095f00e 100644
--- a/products/replay_vision/backend/tests/test_api.py
+++ b/products/replay_vision/backend/tests/test_api.py
@@ -1603,7 +1603,7 @@ class TestRetryActions(_VisionAPITestCase):
mock_async_to_sync.return_value = start_workflow
observation = self._create_failed("sess-quota")
- exhausted = MagicMock(exhausted=True, monthly_quota=500, period_end=timezone.now())
+ exhausted = MagicMock(exhausted=True, credit_limit=500, period_end=timezone.now())
with patch("products.replay_vision.backend.api.trigger.compute_quota_snapshot", return_value=exhausted):
resp = self.client.post(self.retry_url(str(observation.id)))
self.assertEqual(resp.status_code, 402, resp.json())
@@ -1832,6 +1832,21 @@ class TestReplayScannerEstimateAction(ClickhouseTestMixin, _VisionAPITestCase):
self.assertEqual(body["matched_sessions_in_window"], 3)
self.assertEqual(body["window_days"], 30)
self.assertEqual(body["estimated_observations_per_month"], 3)
+ # Defaults to the baseline model when the request names none.
+ self.assertEqual(body["credits_per_observation"], 5)
+ self.assertEqual(body["estimated_credits_per_month"], 15)
+
+ def test_estimate_prices_credits_at_proposed_model(self) -> None:
+ for index in range(3):
+ self._ingest_session(days_ago=index + 1)
+ self._ingest_session(days_ago=40)
+
+ resp = self.client.post(self.estimate_url, data={"model": "gemini-3.5-flash"}, format="json")
+ self.assertEqual(resp.status_code, 200)
+
+ body = resp.json()
+ self.assertEqual(body["credits_per_observation"], 15)
+ self.assertEqual(body["estimated_credits_per_month"], body["estimated_observations_per_month"] * 15)
def test_estimate_applies_sampling(self) -> None:
for index in range(4):
@@ -1866,13 +1881,13 @@ class TestReplayScannerEstimateAction(ClickhouseTestMixin, _VisionAPITestCase):
make("b", enabled=True, estimate=250)
make("disabled", enabled=False, estimate=999) # disabled scanners don't count
- # New scanner (no scanner_id): others = both enabled scanners.
+ # New scanner (no scanner_id): others = both enabled scanners, credit-weighted at 5/observation.
new_body = self.client.post(self.estimate_url, data={}, format="json").json()
- self.assertEqual(new_body["other_enabled_scanners_monthly"], 350)
+ self.assertEqual(new_body["other_enabled_scanners_monthly_credits"], 350 * 5)
# Editing scanner `a`: its own stored estimate is excluded so the forecast won't double-count it.
edit_body = self.client.post(self.estimate_url, data={"scanner_id": str(a.id)}, format="json").json()
- self.assertEqual(edit_body["other_enabled_scanners_monthly"], 250)
+ self.assertEqual(edit_body["other_enabled_scanners_monthly_credits"], 250 * 5)
def test_estimate_rejects_scanner_id_outside_the_request_team(self) -> None:
# A scanner_id from another team (even same org) must be rejected, not silently excluded from the others-sum.
diff --git a/products/replay_vision/backend/tests/test_billing.py b/products/replay_vision/backend/tests/test_billing.py
new file mode 100644
index 000000000000..4154c9a4be11
--- /dev/null
+++ b/products/replay_vision/backend/tests/test_billing.py
@@ -0,0 +1,80 @@
+from datetime import UTC, datetime, timedelta
+from uuid import uuid4
+
+from posthog.test.base import APIBaseTest
+
+from django.utils import timezone
+
+from products.replay_vision.backend.billing import (
+ _FALLBACK_CREDITS,
+ OBSERVATION_CREDITS_BY_MODEL,
+ get_replay_vision_credits_by_team,
+ observation_credits_for_model,
+)
+from products.replay_vision.backend.models.replay_observation_usage import ReplayObservationUsage
+from products.replay_vision.backend.models.replay_scanner import ScannerModel
+
+
+class TestReplayVisionBillingUsage(APIBaseTest):
+ def _receipt(
+ self,
+ *,
+ team_id: int | None,
+ created_at: datetime,
+ model: str = ScannerModel.GEMINI_3_FLASH,
+ credits: int | None = None,
+ ) -> None:
+ receipt = ReplayObservationUsage.objects.create(
+ observation_id=uuid4(),
+ organization_id=self.organization.id,
+ team_id=team_id,
+ observation_created_at=created_at,
+ model=model,
+ credits=credits if credits is not None else observation_credits_for_model(model),
+ )
+ # created_at is auto_now_add, so set it explicitly to control the billing window.
+ ReplayObservationUsage.objects.filter(pk=receipt.pk).update(created_at=created_at)
+
+ def test_sums_credits_per_team_within_window_by_created_at(self) -> None:
+ now = timezone.now()
+ begin = now - timedelta(days=1)
+ end = now + timedelta(days=1)
+ # Two in-window at different model prices, one out-of-window, one for another team.
+ self._receipt(team_id=self.team.id, created_at=now, model=ScannerModel.GEMINI_3_FLASH)
+ self._receipt(team_id=self.team.id, created_at=now, model=ScannerModel.GEMINI_3_5_FLASH)
+ self._receipt(team_id=self.team.id, created_at=now - timedelta(days=3))
+ self._receipt(team_id=self.team.id + 1, created_at=now, model=ScannerModel.GEMINI_2_5_FLASH)
+
+ result = dict(get_replay_vision_credits_by_team(begin, end))
+ assert result == {self.team.id: 5 + 15, self.team.id + 1: 2}
+
+ def test_sums_frozen_receipt_credits_not_live_prices(self) -> None:
+ # A receipt priced before a table change keeps billing at its frozen amount.
+ now = timezone.now()
+ self._receipt(team_id=self.team.id, created_at=now, credits=7)
+ result = get_replay_vision_credits_by_team(now - timedelta(hours=1), now + timedelta(hours=1))
+ assert result == [(self.team.id, 7)]
+
+ def test_excludes_legacy_receipts_without_team(self) -> None:
+ now = timezone.now()
+ self._receipt(team_id=None, created_at=now)
+ self._receipt(team_id=self.team.id, created_at=now)
+
+ result = get_replay_vision_credits_by_team(now - timedelta(hours=1), now + timedelta(hours=1))
+ assert result == [(self.team.id, 5)]
+
+ def test_window_is_end_exclusive(self) -> None:
+ boundary = datetime(2026, 7, 1, tzinfo=UTC)
+ self._receipt(team_id=self.team.id, created_at=boundary)
+ result = get_replay_vision_credits_by_team(boundary - timedelta(days=1), boundary)
+ assert result == []
+
+ def test_unknown_model_bills_at_highest_known_price(self) -> None:
+ assert observation_credits_for_model("gemini-99-ultra") == _FALLBACK_CREDITS
+ assert _FALLBACK_CREDITS == max(OBSERVATION_CREDITS_BY_MODEL.values())
+
+
+def test_every_scanner_model_has_a_credit_price() -> None:
+ # A new ScannerModel member without a price would bill at the max fallback; catch it at PR time.
+ unpriced = set(ScannerModel.values) - set(OBSERVATION_CREDITS_BY_MODEL)
+ assert not unpriced, f"ScannerModel members missing from OBSERVATION_CREDITS_BY_MODEL: {unpriced}"
diff --git a/products/replay_vision/backend/tests/test_migration_backfill.py b/products/replay_vision/backend/tests/test_migration_backfill.py
new file mode 100644
index 000000000000..681b749b0014
--- /dev/null
+++ b/products/replay_vision/backend/tests/test_migration_backfill.py
@@ -0,0 +1,67 @@
+import uuid
+import importlib
+
+from posthog.test.base import APIBaseTest
+
+from django.apps import apps
+from django.utils import timezone
+
+from products.replay_vision.backend.models.replay_observation import (
+ ObservationStatus,
+ 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
+
+m33 = importlib.import_module("products.replay_vision.backend.migrations.0033_backfill_replayobservationusage_team_id")
+m37 = importlib.import_module("products.replay_vision.backend.migrations.0037_backfill_replayobservationusage_credits")
+
+
+class TestReceiptBackfillMigrations(APIBaseTest):
+ def test_backfills_team_model_and_credits_and_survives_orphans(self) -> None:
+ # A retired beta model (KeyTextTransform must extract it unquoted so it matches the credit map),
+ # plus an orphaned receipt whose observation was deleted (subquery -> NULL): the keyset loop must
+ # not spin on it, and it must land on the baseline credits.
+ scanner = ReplayScanner.objects.create(
+ team=self.team,
+ name="s",
+ scanner_type=ScannerType.MONITOR,
+ scanner_config={"prompt": "p"},
+ model=ScannerModel.GEMINI_3_FLASH,
+ )
+ obs = ReplayObservation.objects.create(
+ scanner=scanner,
+ team=self.team,
+ session_id="s1",
+ status=ObservationStatus.SUCCEEDED,
+ scanner_snapshot={
+ "model": "gemini-3.1-flash-lite-preview",
+ "name": "s",
+ "scanner_type": "monitor",
+ "scanner_version": 1,
+ "provider": "google",
+ "emits_signals": False,
+ "scanner_config": {},
+ },
+ triggered_by=ObservationTrigger.ON_DEMAND,
+ completed_at=timezone.now(),
+ )
+ live = ReplayObservationUsage.objects.create(
+ observation_id=obs.id,
+ organization_id=self.organization.id,
+ observation_created_at=timezone.now(),
+ )
+ orphan = ReplayObservationUsage.objects.create(
+ observation_id=uuid.uuid4(),
+ organization_id=self.organization.id,
+ observation_created_at=timezone.now(),
+ )
+
+ m33.backfill_team_id(apps, None)
+ m37.backfill_model_and_credits(apps, None)
+
+ live.refresh_from_db()
+ orphan.refresh_from_db()
+ assert (live.team_id, live.model, live.credits) == (self.team.id, "gemini-3.1-flash-lite-preview", 2)
+ assert (orphan.team_id, orphan.model, orphan.credits) == (None, None, 5)
diff --git a/products/replay_vision/backend/tests/test_models.py b/products/replay_vision/backend/tests/test_models.py
index d0153dfc8e87..e15413f4560f 100644
--- a/products/replay_vision/backend/tests/test_models.py
+++ b/products/replay_vision/backend/tests/test_models.py
@@ -85,7 +85,7 @@ class TestReplayScanner(BaseTest):
("scanner_config", {"prompt": "different prompt"}),
("query", {"properties": [{"key": "foo"}]}),
("sampling_rate", 0.25),
- ("model", ScannerModel.GEMINI_3_FLASH_LITE),
+ ("model", ScannerModel.GEMINI_2_5_FLASH),
("emits_signals", True),
]
)
diff --git a/products/replay_vision/backend/tests/test_quota.py b/products/replay_vision/backend/tests/test_quota.py
index c3fb882e3627..1f3a34c822bc 100644
--- a/products/replay_vision/backend/tests/test_quota.py
+++ b/products/replay_vision/backend/tests/test_quota.py
@@ -8,8 +8,10 @@ from django.utils import timezone
from parameterized import parameterized
+from posthog.date_util import start_of_month
from posthog.models import Organization, Team
+from products.replay_vision.backend.billing import observation_credits_for_model
from products.replay_vision.backend.models.replay_observation import (
ObservationStatus,
ObservationTrigger,
@@ -18,7 +20,7 @@ from products.replay_vision.backend.models.replay_observation import (
from products.replay_vision.backend.models.replay_observation_usage import ReplayObservationUsage
from products.replay_vision.backend.models.replay_quota_grant import ReplayQuotaGrant
from products.replay_vision.backend.models.replay_scanner import ReplayScanner, ScannerModel, ScannerType
-from products.replay_vision.backend.quota import MONTHLY_OBSERVATION_QUOTA, compute_quota_snapshot
+from products.replay_vision.backend.quota import MONTHLY_CREDIT_QUOTA, compute_quota_snapshot
from products.replay_vision.backend.tests.helpers import snapshot_for as _snapshot_for
@@ -68,11 +70,16 @@ class _VisionQuotaTestCase(APIBaseTest):
@staticmethod
def _make_receipt(observation: ReplayObservation) -> None:
+ # Mirror production: the receipt freezes the snapshot model and its credit price.
+ model = observation.scanner_snapshot.get("model", "")
ReplayObservationUsage.objects.get_or_create(
observation_id=observation.id,
defaults={
"organization_id": observation.team.organization_id,
+ "team_id": observation.team_id,
"observation_created_at": observation.created_at,
+ "model": model,
+ "credits": observation_credits_for_model(model),
},
)
@@ -80,28 +87,32 @@ class _VisionQuotaTestCase(APIBaseTest):
class TestComputeQuotaSnapshot(_VisionQuotaTestCase):
@parameterized.expand(
[
- (ObservationStatus.SUCCEEDED, 1),
- (ObservationStatus.PENDING, 1),
- (ObservationStatus.RUNNING, 1),
- (ObservationStatus.FAILED, 0),
- (ObservationStatus.INELIGIBLE, 0),
+ (ObservationStatus.SUCCEEDED, ScannerModel.GEMINI_2_5_FLASH, 2),
+ (ObservationStatus.SUCCEEDED, ScannerModel.GEMINI_3_FLASH, 5),
+ (ObservationStatus.SUCCEEDED, ScannerModel.GEMINI_3_5_FLASH, 15),
+ (ObservationStatus.PENDING, ScannerModel.GEMINI_3_5_FLASH, 15),
+ (ObservationStatus.RUNNING, ScannerModel.GEMINI_3_FLASH, 5),
+ (ObservationStatus.FAILED, ScannerModel.GEMINI_3_FLASH, 0),
+ (ObservationStatus.INELIGIBLE, ScannerModel.GEMINI_3_FLASH, 0),
]
)
- def test_counts_only_succeeded_and_in_flight_this_month(
- self, status: ObservationStatus, expected_count: int
+ def test_credits_priced_by_model_for_succeeded_and_in_flight(
+ self, status: ObservationStatus, model: ScannerModel, expected_credits: int
) -> None:
+ ReplayScanner.objects.filter(pk=self.scanner.pk).update(model=model)
+ self.scanner.refresh_from_db()
self._make_observation(
status=status,
completed_at=timezone.now()
if status != ObservationStatus.PENDING and status != ObservationStatus.RUNNING
else None,
)
- assert compute_quota_snapshot(organization_id=self.organization.id).usage_this_month == expected_count
+ assert compute_quota_snapshot(organization_id=self.organization.id).credits_used == expected_credits
def test_excludes_observations_created_in_a_previous_month(self) -> None:
last_month = (datetime.now(UTC).replace(day=1, hour=0, minute=0, second=0, microsecond=0)) - timedelta(days=1)
self._make_observation(status=ObservationStatus.SUCCEEDED, completed_at=last_month, created_at=last_month)
- assert compute_quota_snapshot(organization_id=self.organization.id).usage_this_month == 0
+ assert compute_quota_snapshot(organization_id=self.organization.id).credits_used == 0
def test_period_bounds_are_first_of_month_utc(self) -> None:
snapshot = compute_quota_snapshot(organization_id=self.organization.id)
@@ -127,7 +138,7 @@ class TestComputeQuotaSnapshot(_VisionQuotaTestCase):
self._make_observation(
status=ObservationStatus.SUCCEEDED, completed_at=timezone.now(), created_at=snapshot.period_end
)
- assert compute_quota_snapshot(organization_id=self.organization.id).usage_this_month == 1
+ assert compute_quota_snapshot(organization_id=self.organization.id).credits_used == 5
def test_other_orgs_observations_not_counted(self) -> None:
other_org = Organization.objects.create(name="other-org")
@@ -151,16 +162,16 @@ class TestComputeQuotaSnapshot(_VisionQuotaTestCase):
self._make_receipt(other_obs)
snapshot = compute_quota_snapshot(organization_id=self.organization.id)
- assert snapshot.usage_this_month == 0
+ assert snapshot.credits_used == 0
def test_exhausted_when_usage_meets_quota(self) -> None:
- with patch("products.replay_vision.backend.quota.MONTHLY_OBSERVATION_QUOTA", 2):
+ with patch("products.replay_vision.backend.quota.MONTHLY_CREDIT_QUOTA", 10):
self._make_observation(status=ObservationStatus.SUCCEEDED, completed_at=timezone.now())
self._make_observation(status=ObservationStatus.SUCCEEDED, completed_at=timezone.now())
snapshot = compute_quota_snapshot(organization_id=self.organization.id)
- assert snapshot.usage_this_month == 2
+ assert snapshot.credits_used == 10
assert snapshot.exhausted is True
assert snapshot.remaining == 0
@@ -168,41 +179,134 @@ class TestComputeQuotaSnapshot(_VisionQuotaTestCase):
# Deleting a scanner cascade-deletes its observations, but the usage they spent must not be refunded.
for _ in range(3):
self._make_observation(status=ObservationStatus.SUCCEEDED, completed_at=timezone.now())
- assert compute_quota_snapshot(organization_id=self.organization.id).usage_this_month == 3
+ assert compute_quota_snapshot(organization_id=self.organization.id).credits_used == 15
self.scanner.delete()
assert ReplayObservation.objects.filter(team=self.team).count() == 0 # observations cascade-deleted
- assert compute_quota_snapshot(organization_id=self.organization.id).usage_this_month == 3 # receipts survive
+ assert compute_quota_snapshot(organization_id=self.organization.id).credits_used == 15 # receipts survive
def test_deleting_observation_does_not_refund_spent_usage(self) -> None:
observation = self._make_observation(status=ObservationStatus.SUCCEEDED, completed_at=timezone.now())
- assert compute_quota_snapshot(organization_id=self.organization.id).usage_this_month == 1
+ assert compute_quota_snapshot(organization_id=self.organization.id).credits_used == 5
observation.delete() # e.g. the admin recording-delete flow
- assert compute_quota_snapshot(organization_id=self.organization.id).usage_this_month == 1
+ assert compute_quota_snapshot(organization_id=self.organization.id).credits_used == 5
def test_no_double_count_across_pending_to_succeeded(self) -> None:
observation = self._make_observation(status=ObservationStatus.PENDING)
- assert compute_quota_snapshot(organization_id=self.organization.id).usage_this_month == 1 # counted in-flight
+ assert compute_quota_snapshot(organization_id=self.organization.id).credits_used == 5 # reserved in-flight
- # The success transition flips status and writes the receipt, so the total stays 1.
+ # The success transition flips status and writes the receipt, so the total stays 5.
ReplayObservation.objects.filter(pk=observation.pk).update(
status=ObservationStatus.SUCCEEDED, completed_at=timezone.now()
)
self._make_receipt(observation)
- assert compute_quota_snapshot(organization_id=self.organization.id).usage_this_month == 1
+ assert compute_quota_snapshot(organization_id=self.organization.id).credits_used == 5
+
+
+class TestBillingSyncedQuota(_VisionQuotaTestCase):
+ @parameterized.expand(
+ [
+ ("billing_limit_wins", {"replay_vision_credits": {"limit": 42, "usage": 0}}, 42),
+ (
+ "synced_without_limit_is_uncapped",
+ {"replay_vision_credits": {"limit": None, "usage": 0}},
+ None,
+ ),
+ ("float_limit_honored", {"replay_vision_credits": {"limit": 42.0, "usage": 0}}, 42),
+ (
+ "malformed_limit_falls_back_not_uncapped",
+ {"replay_vision_credits": {"limit": "42", "usage": 0}},
+ MONTHLY_CREDIT_QUOTA,
+ ),
+ # Billing writes `{}` for products it doesn't manage yet; that's unsynced, not uncapped.
+ ("empty_summary_falls_back", {"replay_vision_credits": {}}, MONTHLY_CREDIT_QUOTA),
+ ("key_missing_falls_back", {"events": {"limit": 100, "usage": 0}}, MONTHLY_CREDIT_QUOTA),
+ ("usage_empty_falls_back", None, MONTHLY_CREDIT_QUOTA),
+ ]
+ )
+ def test_credit_limit_source(self, _name: str, usage: dict | None, expected_quota: int | None) -> None:
+ self.organization.usage = usage
+ self.organization.save()
+ snapshot = compute_quota_snapshot(organization_id=self.organization.id)
+ assert snapshot.credit_limit == expected_quota
+
+ def test_uncapped_org_is_never_exhausted(self) -> None:
+ self.organization.usage = {"replay_vision_credits": {"limit": None, "usage": 0}}
+ self.organization.save()
+ self._make_observation(status=ObservationStatus.SUCCEEDED, completed_at=timezone.now())
+
+ snapshot = compute_quota_snapshot(organization_id=self.organization.id)
+
+ assert snapshot.credit_limit is None
+ assert snapshot.remaining is None
+ assert not snapshot.exhausted
+
+ def test_grants_stack_on_billing_limit(self) -> None:
+ self.organization.usage = {"replay_vision_credits": {"limit": 42, "usage": 0}}
+ self.organization.save()
+ ReplayQuotaGrant.objects.create(
+ organization=self.organization, amount=8, expires_at=timezone.now() + timedelta(days=10)
+ )
+ assert compute_quota_snapshot(organization_id=self.organization.id).credit_limit == 50
+
+ def test_billing_period_bounds_used_when_current(self) -> None:
+ now = datetime.now(UTC)
+ start = now - timedelta(days=10)
+ end = now + timedelta(days=20)
+ self.organization.usage = {"period": [start.isoformat(), end.isoformat()]}
+ self.organization.save()
+ snapshot = compute_quota_snapshot(organization_id=self.organization.id)
+ assert snapshot.period_start == start
+ assert snapshot.period_end == end
+ # Usage is counted against the billing window, not the calendar month.
+ self._make_observation(
+ status=ObservationStatus.SUCCEEDED, completed_at=timezone.now(), created_at=start - timedelta(days=1)
+ )
+ assert compute_quota_snapshot(organization_id=self.organization.id).credits_used == 0
+
+ def test_naive_billing_period_does_not_crash(self) -> None:
+ now = datetime.now(UTC)
+ start = now - timedelta(days=5)
+ end = now + timedelta(days=25)
+ # A period stored without a tz offset must not raise when compared against tz-aware now.
+ self.organization.usage = {
+ "period": [start.replace(tzinfo=None).isoformat(), end.replace(tzinfo=None).isoformat()]
+ }
+ self.organization.save()
+ snapshot = compute_quota_snapshot(organization_id=self.organization.id)
+ assert snapshot.period_start == start
+ assert snapshot.period_end == end
+
+ def test_stale_billing_period_falls_back_to_calendar_month(self) -> None:
+ now = datetime.now(UTC)
+ self.organization.usage = {
+ "period": [(now - timedelta(days=70)).isoformat(), (now - timedelta(days=40)).isoformat()]
+ }
+ self.organization.save()
+ snapshot = compute_quota_snapshot(organization_id=self.organization.id)
+ assert snapshot.period_start == start_of_month(now)
+ assert snapshot.period_end > now
class TestProjectedMonthlyObservations(_VisionQuotaTestCase):
- def _make_scanner(self, *, team: Team, name: str, enabled: bool = True, estimate: int | None = None) -> None:
+ def _make_scanner(
+ self,
+ *,
+ team: Team,
+ name: str,
+ enabled: bool = True,
+ estimate: int | None = None,
+ model: ScannerModel = ScannerModel.GEMINI_3_FLASH,
+ ) -> None:
scanner = ReplayScanner.objects.create(
team=team,
name=name,
scanner_type=ScannerType.MONITOR,
scanner_config={"prompt": "p"},
- model=ScannerModel.GEMINI_3_FLASH,
+ model=model,
enabled=enabled,
)
if estimate is not None:
@@ -210,36 +314,36 @@ class TestProjectedMonthlyObservations(_VisionQuotaTestCase):
estimated_monthly_observations=estimate, estimated_at=timezone.now()
)
- def test_sums_enabled_scanners_across_org_teams(self) -> None:
+ def test_sums_credit_weighted_estimates_across_org_teams(self) -> None:
other_team = Team.objects.create(organization=self.organization, name="second-team")
- self._make_scanner(team=self.team, name="a", estimate=100)
- self._make_scanner(team=other_team, name="b", estimate=250)
+ self._make_scanner(team=self.team, name="a", estimate=100) # 100 × 5 credits
+ self._make_scanner(team=other_team, name="b", estimate=250, model=ScannerModel.GEMINI_3_5_FLASH) # 250 × 15
snapshot = compute_quota_snapshot(organization_id=self.organization.id)
- assert snapshot.projected_monthly_observations == 350
+ assert snapshot.projected_monthly_credits == 100 * 5 + 250 * 15
def test_disabled_and_unestimated_scanners_contribute_zero(self) -> None:
self._make_scanner(team=self.team, name="disabled", enabled=False, estimate=500)
self._make_scanner(team=self.team, name="unestimated", estimate=None)
snapshot = compute_quota_snapshot(organization_id=self.organization.id)
- assert snapshot.projected_monthly_observations == 0
+ assert snapshot.projected_monthly_credits == 0
def test_other_orgs_scanners_not_counted(self) -> None:
other_org = Organization.objects.create(name="other-projection-org")
other_team = Team.objects.create(organization=other_org, name="other-projection-team")
self._make_scanner(team=other_team, name="other", estimate=999)
snapshot = compute_quota_snapshot(organization_id=self.organization.id)
- assert snapshot.projected_monthly_observations == 0
+ assert snapshot.projected_monthly_credits == 0
class TestQuotaGrants(_VisionQuotaTestCase):
- def test_active_grant_adds_to_monthly_quota(self) -> None:
+ def test_active_grant_adds_to_credit_limit(self) -> None:
ReplayQuotaGrant.objects.create(
organization=self.organization,
amount=500,
expires_at=timezone.now() + timedelta(days=10),
)
snapshot = compute_quota_snapshot(organization_id=self.organization.id)
- assert snapshot.monthly_quota == MONTHLY_OBSERVATION_QUOTA + 500
+ assert snapshot.credit_limit == MONTHLY_CREDIT_QUOTA + 500
def test_multiple_active_grants_stack(self) -> None:
for amount in (100, 200, 700):
@@ -249,7 +353,7 @@ class TestQuotaGrants(_VisionQuotaTestCase):
expires_at=timezone.now() + timedelta(days=10),
)
snapshot = compute_quota_snapshot(organization_id=self.organization.id)
- assert snapshot.monthly_quota == MONTHLY_OBSERVATION_QUOTA + 1000
+ assert snapshot.credit_limit == MONTHLY_CREDIT_QUOTA + 1000
def test_expired_grant_does_not_count(self) -> None:
grant = ReplayQuotaGrant(
@@ -259,7 +363,7 @@ class TestQuotaGrants(_VisionQuotaTestCase):
)
grant.save() # bypass full_clean — simulate the case where a grant has aged past its expiry
snapshot = compute_quota_snapshot(organization_id=self.organization.id)
- assert snapshot.monthly_quota == MONTHLY_OBSERVATION_QUOTA
+ assert snapshot.credit_limit == MONTHLY_CREDIT_QUOTA
def test_other_orgs_grants_not_counted(self) -> None:
other_org = Organization.objects.create(name="other-grant-org")
@@ -269,7 +373,7 @@ class TestQuotaGrants(_VisionQuotaTestCase):
expires_at=timezone.now() + timedelta(days=10),
)
snapshot = compute_quota_snapshot(organization_id=self.organization.id)
- assert snapshot.monthly_quota == MONTHLY_OBSERVATION_QUOTA
+ assert snapshot.credit_limit == MONTHLY_CREDIT_QUOTA
@parameterized.expand(
[
@@ -290,7 +394,7 @@ class TestQuotaGrants(_VisionQuotaTestCase):
assert expected_field in cm.exception.message_dict
def test_grant_pushes_exhaustion_back(self) -> None:
- with patch("products.replay_vision.backend.quota.MONTHLY_OBSERVATION_QUOTA", 2):
+ with patch("products.replay_vision.backend.quota.MONTHLY_CREDIT_QUOTA", 10):
self._make_observation(status=ObservationStatus.SUCCEEDED, completed_at=timezone.now())
self._make_observation(status=ObservationStatus.SUCCEEDED, completed_at=timezone.now())
assert compute_quota_snapshot(organization_id=self.organization.id).exhausted is True
@@ -340,11 +444,11 @@ class TestVisionQuotaEndpoint(_VisionQuotaTestCase):
resp = self.client.get(self.quota_url)
assert resp.status_code == 200, resp.json()
body = resp.json()
- assert body["monthly_quota"] == MONTHLY_OBSERVATION_QUOTA
- assert body["usage_this_month"] == 0
- assert body["remaining"] == MONTHLY_OBSERVATION_QUOTA
+ assert body["credit_limit"] == MONTHLY_CREDIT_QUOTA
+ assert body["credits_used"] == 0
+ assert body["remaining"] == MONTHLY_CREDIT_QUOTA
assert body["exhausted"] is False
- assert body["projected_monthly_observations"] == 0
+ assert body["projected_monthly_credits"] == 0
assert "period_start" in body
assert "period_end" in body
@@ -353,15 +457,15 @@ class TestVisionQuotaEndpoint(_VisionQuotaTestCase):
estimated_monthly_observations=120, estimated_at=timezone.now()
)
resp = self.client.get(self.quota_url)
- assert resp.json()["projected_monthly_observations"] == 120
+ assert resp.json()["projected_monthly_credits"] == 120 * 5
def test_reflects_recent_succeeded_observations(self) -> None:
for _ in range(3):
self._make_observation(status=ObservationStatus.SUCCEEDED, completed_at=timezone.now())
resp = self.client.get(self.quota_url)
- assert resp.json()["usage_this_month"] == 3
- assert resp.json()["remaining"] == MONTHLY_OBSERVATION_QUOTA - 3
+ assert resp.json()["credits_used"] == 15
+ assert resp.json()["remaining"] == MONTHLY_CREDIT_QUOTA - 15
def test_requires_feature_flag(self) -> None:
with patch(
@@ -382,7 +486,7 @@ class TestObserveQuotaEnforcement(_VisionQuotaTestCase):
def test_returns_402_when_quota_exhausted(
self, mock_sync_connect: MagicMock, mock_async_to_sync: MagicMock
) -> None:
- with patch("products.replay_vision.backend.quota.MONTHLY_OBSERVATION_QUOTA", 1):
+ with patch("products.replay_vision.backend.quota.MONTHLY_CREDIT_QUOTA", 5):
self._make_observation(status=ObservationStatus.SUCCEEDED, completed_at=timezone.now())
resp = self.client.post(self.observe_url, data={"session_id": "sess-blocked"}, format="json")
@@ -390,14 +494,44 @@ class TestObserveQuotaEnforcement(_VisionQuotaTestCase):
assert resp.status_code == 402, resp.json()
body = resp.json()
assert body["code"] == "quota_limit_exceeded"
- assert "Monthly Replay Vision quota of 1 observations reached" in body["detail"]
+ assert "would exceed your monthly Replay vision limit of $0.05" in body["detail"]
mock_sync_connect.assert_not_called()
mock_async_to_sync.assert_not_called()
+ def test_returns_402_when_observation_would_exceed_remaining(
+ self, mock_sync_connect: MagicMock, mock_async_to_sync: MagicMock
+ ) -> None:
+ # Not exhausted (5 of 8 used), but the next 5-credit observation would land at 10 > 8. The precheck
+ # must reject it rather than only blocking once fully exhausted.
+ with patch("products.replay_vision.backend.quota.MONTHLY_CREDIT_QUOTA", 8):
+ self._make_observation(status=ObservationStatus.SUCCEEDED, completed_at=timezone.now())
+ assert not compute_quota_snapshot(organization_id=self.organization.id).exhausted
+
+ resp = self.client.post(self.observe_url, data={"session_id": "sess-would-exceed"}, format="json")
+
+ assert resp.status_code == 402, resp.json()
+ mock_sync_connect.assert_not_called()
+
def test_allows_observe_when_under_quota(self, mock_sync_connect: MagicMock, mock_async_to_sync: MagicMock) -> None:
mock_sync_connect.return_value = MagicMock()
mock_async_to_sync.return_value = MagicMock()
resp = self.client.post(self.observe_url, data={"session_id": "sess-ok"}, format="json")
assert resp.status_code == 202, resp.json()
+ # Only the workflow start hits Temporal now; the team capacity check counts DB rows.
mock_sync_connect.assert_called_once()
+
+ def test_returns_429_when_team_at_in_flight_cap(
+ self, mock_sync_connect: MagicMock, mock_async_to_sync: MagicMock
+ ) -> None:
+ mock_sync_connect.return_value = MagicMock()
+ mock_async_to_sync.return_value = MagicMock()
+ with patch("products.replay_vision.backend.api.trigger.MAX_IN_FLIGHT_APPLIES_PER_TEAM", 1):
+ self._make_observation(status=ObservationStatus.RUNNING)
+
+ resp = self.client.post(self.observe_url, data={"session_id": "sess-capped"}, format="json")
+
+ assert resp.status_code == 429, resp.json()
+ assert "observations running" in resp.json()["detail"]
+ # Blocked before any workflow start.
+ mock_sync_connect.assert_not_called()
diff --git a/products/replay_vision/backend/tests/test_sweep.py b/products/replay_vision/backend/tests/test_sweep.py
index 505ce2341371..bf6410cca80a 100644
--- a/products/replay_vision/backend/tests/test_sweep.py
+++ b/products/replay_vision/backend/tests/test_sweep.py
@@ -3,7 +3,7 @@ import datetime as dt
from typing import Any
import pytest
-from unittest.mock import AsyncMock, MagicMock, patch
+from unittest.mock import MagicMock, patch
from temporalio.exceptions import ApplicationError, WorkflowAlreadyStartedError
@@ -15,21 +15,25 @@ from products.replay_vision.backend.temporal import SweepScannerWorkflow
from products.replay_vision.backend.temporal.activities.advance_scanner_watermark import (
advance_scanner_watermark_activity,
)
-from products.replay_vision.backend.temporal.activities.count_in_flight_applies import count_in_flight_applies_activity
+from products.replay_vision.backend.temporal.activities.count_in_flight_applies import (
+ count_in_flight_applies_activity,
+ count_in_flight_by_team_activity,
+)
from products.replay_vision.backend.temporal.activities.find_scanner_candidates import find_scanner_candidates_activity
from products.replay_vision.backend.temporal.activities.refresh_prompt_suggestion import (
refresh_prompt_suggestion_activity,
)
from products.replay_vision.backend.temporal.constants import (
MAX_IN_FLIGHT_APPLIES_PER_SCANNER,
+ MAX_IN_FLIGHT_APPLIES_PER_TEAM,
build_process_vision_action_workflow_id,
)
from products.replay_vision.backend.temporal.sweep_types import (
AdvanceScannerWatermarkInputs,
CandidateSessionPayload,
- CountInFlightAppliesInputs,
FindScannerCandidatesInputs,
FindScannerCandidatesOutput,
+ InFlightApplyCounts,
SweepScannerInputs,
)
from products.replay_vision.backend.temporal.vision_actions.activities import evaluate_due_vision_actions_activity
@@ -253,8 +257,8 @@ class _SweepMocks:
async def execute_activity(self, activity_fn: Any, activity_input: Any, **_: Any) -> Any:
self.activity_calls.append((activity_fn, activity_input))
# Default to 0 in-flight (full headroom) unless a test overrides it.
- if activity_fn is count_in_flight_applies_activity and activity_fn not in self.activity_results:
- return 0
+ if activity_fn is count_in_flight_by_team_activity and activity_fn not in self.activity_results:
+ return InFlightApplyCounts(scanner=0, team=0)
# Default to no due vision actions unless a test overrides it.
if activity_fn is evaluate_due_vision_actions_activity and activity_fn not in self.activity_results:
return []
@@ -276,7 +280,7 @@ def _sweep_inputs() -> SweepScannerInputs:
return SweepScannerInputs(scanner_id=uuid.uuid4(), team_id=42)
-async def _run_sweep(mocks: _SweepMocks, inputs: SweepScannerInputs | None = None) -> None:
+async def _run_sweep(mocks: _SweepMocks, inputs: SweepScannerInputs | None = None, patched: bool = True) -> None:
# `workflow.logger` reaches into the workflow runtime, which isn't set up here.
fake_logger = type(
"Logger",
@@ -292,7 +296,7 @@ async def _run_sweep(mocks: _SweepMocks, inputs: SweepScannerInputs | None = Non
patch("temporalio.workflow.start_child_workflow", side_effect=mocks.start_child_workflow),
patch("temporalio.workflow.logger", fake_logger),
# `workflow.patched` also needs the runtime; new executions take the patched branch.
- patch("temporalio.workflow.patched", return_value=True),
+ patch("temporalio.workflow.patched", return_value=patched),
):
await SweepScannerWorkflow().run(inputs or _sweep_inputs())
@@ -310,7 +314,7 @@ async def test_empty_batch_skips_dispatch_and_advance() -> None:
assert [fn for fn, _ in mocks.activity_calls] == [
evaluate_due_vision_actions_activity,
refresh_prompt_suggestion_activity,
- count_in_flight_applies_activity,
+ count_in_flight_by_team_activity,
find_scanner_candidates_activity,
]
assert mocks.child_calls == []
@@ -401,17 +405,25 @@ async def test_child_start_failure_propagates_and_skips_advance() -> None:
@pytest.mark.parametrize(
"in_flight, expected_candidate_limit",
[
- (MAX_IN_FLIGHT_APPLIES_PER_SCANNER, None), # at the cap → throttled
- (MAX_IN_FLIGHT_APPLIES_PER_SCANNER + 10, None), # over the cap (negative headroom) → throttled
- (MAX_IN_FLIGHT_APPLIES_PER_SCANNER - 10, 10), # partial headroom → fetch is capped to it
- (0, MAX_IN_FLIGHT_APPLIES_PER_SCANNER), # idle → full headroom
+ (InFlightApplyCounts(scanner=MAX_IN_FLIGHT_APPLIES_PER_SCANNER, team=0), None), # scanner cap → throttled
+ (InFlightApplyCounts(scanner=MAX_IN_FLIGHT_APPLIES_PER_SCANNER + 10, team=0), None), # over → throttled
+ (InFlightApplyCounts(scanner=0, team=MAX_IN_FLIGHT_APPLIES_PER_TEAM), None), # team cap → throttled
+ (InFlightApplyCounts(scanner=MAX_IN_FLIGHT_APPLIES_PER_SCANNER - 10, team=0), 10), # partial scanner headroom
+ (
+ # Team headroom smaller than scanner headroom → team cap binds the fetch.
+ InFlightApplyCounts(scanner=0, team=MAX_IN_FLIGHT_APPLIES_PER_TEAM - 5),
+ 5,
+ ),
+ (InFlightApplyCounts(scanner=0, team=0), MAX_IN_FLIGHT_APPLIES_PER_SCANNER), # idle → full headroom
],
)
@pytest.mark.asyncio
-async def test_inflight_cap_gates_the_sweep(in_flight: int, expected_candidate_limit: int | None) -> None:
+async def test_inflight_cap_gates_the_sweep(
+ in_flight: InFlightApplyCounts, expected_candidate_limit: int | None
+) -> None:
mocks = _SweepMocks(
activity_results={
- count_in_flight_applies_activity: in_flight,
+ count_in_flight_by_team_activity: in_flight,
find_scanner_candidates_activity: FindScannerCandidatesOutput(candidates=[], saturated=False),
},
)
@@ -424,13 +436,34 @@ async def test_inflight_cap_gates_the_sweep(in_flight: int, expected_candidate_l
assert [fn for fn, _ in mocks.activity_calls] == [
evaluate_due_vision_actions_activity,
refresh_prompt_suggestion_activity,
- count_in_flight_applies_activity,
+ count_in_flight_by_team_activity,
]
assert mocks.child_calls == []
else:
assert find_calls[0].candidate_limit == expected_candidate_limit
+async def test_unpatched_sweep_replays_legacy_scanner_counter() -> None:
+ # A sweep that started before the team-cap patch must replay the legacy scanner-only counter (its
+ # recorded int result), never the team-aware activity that returns a different type; otherwise the
+ # in-flight execution wedges on a deserialization mismatch across the deploy.
+ mocks = _SweepMocks(
+ activity_results={
+ count_in_flight_applies_activity: 3,
+ find_scanner_candidates_activity: FindScannerCandidatesOutput(candidates=[], saturated=False),
+ },
+ )
+
+ await _run_sweep(mocks, patched=False)
+
+ called = [fn for fn, _ in mocks.activity_calls]
+ assert count_in_flight_applies_activity in called
+ assert count_in_flight_by_team_activity not in called
+ find_calls = [inp for fn, inp in mocks.activity_calls if fn == find_scanner_candidates_activity]
+ assert find_calls[0].candidate_limit == MAX_IN_FLIGHT_APPLIES_PER_SCANNER - 3
+
+
# SweepScannerWorkflow vision-action dispatch (the "and then…" trigger riding the sweep)
@@ -512,33 +545,3 @@ async def test_sweep_swallows_already_running_vision_action() -> None:
# An already-running action is skipped, not a failure.
await _run_sweep(mocks)
-
-
-# count_in_flight_applies_activity
-
-
-async def test_count_in_flight_queries_by_scanner_id_search_attribute() -> None:
- scanner_id = uuid.uuid4()
- client = MagicMock()
- client.count_workflows = AsyncMock(return_value=MagicMock(count=7))
- with patch(
- "products.replay_vision.backend.temporal.activities.count_in_flight_applies.async_connect",
- AsyncMock(return_value=client),
- ):
- result = await count_in_flight_applies_activity(CountInFlightAppliesInputs(scanner_id=scanner_id))
-
- assert result == 7
- query = client.count_workflows.await_args.args[0]
- assert f'PostHogScannerId = "{scanner_id}"' in query
- assert 'ExecutionStatus = "Running"' in query
-
-
-async def test_count_in_flight_returns_zero_on_failure() -> None:
- with patch(
- "products.replay_vision.backend.temporal.activities.count_in_flight_applies.async_connect",
- AsyncMock(side_effect=RuntimeError("visibility down")),
- ):
- result = await count_in_flight_applies_activity(CountInFlightAppliesInputs(scanner_id=uuid.uuid4()))
- assert result == 0
diff --git a/products/replay_vision/backend/tests/test_temporal.py b/products/replay_vision/backend/tests/test_temporal.py
index 6e7fe0230e97..a3c8ea69062d 100644
--- a/products/replay_vision/backend/tests/test_temporal.py
+++ b/products/replay_vision/backend/tests/test_temporal.py
@@ -29,6 +29,7 @@ from posthog.session_recordings.queries.session_replay_events import SessionRepl
from products.exports.backend.models.exported_asset import ExportedAsset
from products.replay_vision.backend.api.observation_progress import stream_observation_progress
+from products.replay_vision.backend.billing import observation_credits_for_model
from products.replay_vision.backend.models.replay_observation import (
ObservationStatus,
ObservationTrigger,
@@ -44,6 +45,7 @@ from products.replay_vision.backend.temporal.activities.call_scanner_provider im
call_scanner_provider_activity,
)
from products.replay_vision.backend.temporal.activities.cleanup_gemini_file import cleanup_gemini_file_activity
+from products.replay_vision.backend.temporal.activities.count_in_flight_applies import count_in_flight_by_team_activity
from products.replay_vision.backend.temporal.activities.create_observation import create_observation_activity
from products.replay_vision.backend.temporal.activities.embed_observation import embed_observation_activity
from products.replay_vision.backend.temporal.activities.emit_classifier_tags import emit_classifier_tags_activity
@@ -84,6 +86,7 @@ from products.replay_vision.backend.temporal.state import (
get_data_class_from_redis,
store_data_in_redis,
)
+from products.replay_vision.backend.temporal.sweep_types import CountInFlightAppliesInputs, InFlightApplyCounts
from products.replay_vision.backend.temporal.types import (
ApplyScannerInputs,
CleanupGeminiFileInputs,
@@ -160,6 +163,33 @@ def _make_observation(scanner: ReplayScanner, **overrides) -> ReplayObservation:
return ReplayObservation.objects.create(**defaults)
[email protected]_db(transaction=True)
+class TestCountInFlightAppliesActivity:
+ def test_counts_pending_and_running_rows_per_scanner_and_team(self) -> None:
+ scanner = _make_scanner()
+ sibling = ReplayScanner.objects.create(
+ team=scanner.team,
+ name="sibling",
+ scanner_type=ScannerType.MONITOR,
+ scanner_config={"prompt": "p"},
+ model=ScannerModel.GEMINI_3_FLASH,
+ )
+ other_team_scanner = _make_scanner() # fresh org+team
+ _make_observation(scanner, session_id="s1", status=ObservationStatus.PENDING)
+ _make_observation(scanner, session_id="s2", status=ObservationStatus.RUNNING)
+ _make_observation(
+ scanner, session_id="s3", status=ObservationStatus.SUCCEEDED, completed_at=timezone.now()
+ ) # terminal: not counted
+ _make_observation(sibling, session_id="s4", status=ObservationStatus.PENDING) # team only
+ _make_observation(other_team_scanner, session_id="s5", status=ObservationStatus.PENDING) # other team
+
+ result = count_in_flight_by_team_activity(
+ CountInFlightAppliesInputs(scanner_id=scanner.id, team_id=scanner.team_id)
+ )
+
+ assert result == InFlightApplyCounts(scanner=2, team=3)
+
+
@pytest.mark.django_db(transaction=True)
class TestCreateObservationActivity:
def test_creates_row_in_pending_with_workflow_id_and_snapshot(self) -> None:
@@ -349,11 +379,11 @@ class TestCreateObservationActivity:
"products.replay_vision.backend.temporal.activities.create_observation.compute_quota_snapshot"
) as mock_snapshot:
mock_snapshot.return_value = QuotaSnapshot(
- monthly_quota=1,
- usage_this_month=1,
+ credit_limit=5,
+ credits_used=5,
period_start=dt.datetime.now(dt.UTC),
period_end=dt.datetime.now(dt.UTC),
- projected_monthly_observations=0,
+ projected_monthly_credits=0,
)
result = create_observation_activity(
CreateObservationInputs(
@@ -507,7 +537,10 @@ class TestObservationStateActivities:
assert receipts.count() == 1
receipt = receipts.get()
assert receipt.organization_id == observation.team.organization_id
+ assert receipt.team_id == observation.team_id # billing usage report groups on this
assert receipt.observation_created_at == observation.created_at
+ assert receipt.model == observation.scanner_snapshot["model"]
+ assert receipt.credits == observation_credits_for_model(observation.scanner_snapshot["model"])
def test_mark_succeeded_usage_receipt_is_idempotent(self) -> None:
scanner = _make_scanner()
diff --git a/products/replay_vision/frontend/generated/api.schemas.ts b/products/replay_vision/frontend/generated/api.schemas.ts
index 30abc88c7060..d5de608c92c4 100644
--- a/products/replay_vision/frontend/generated/api.schemas.ts
+++ b/products/replay_vision/frontend/generated/api.schemas.ts
@@ -550,20 +550,26 @@ export interface RetryResponseApi {
}
export interface VisionQuotaApi {
- /** Total observations the org may complete per calendar month. */
- readonly monthly_quota: number
- /** Observations created this month that are in flight or have succeeded, counted against the quota. */
- readonly usage_this_month: number
- /** `monthly_quota - usage_this_month`, floored at 0. */
- readonly remaining: number
- /** True when `usage_this_month >= monthly_quota`; further observations are skipped until next period. */
+ /**
+ * Credits the org may spend per billing period (1 credit = $0.01). Null when billing has synced the product with no spend limit: uncapped.
+ * @nullable
+ */
+ readonly credit_limit: number | null
+ /** Credits spent this period: succeeded observations from the receipt ledger plus reserved in-flight observations. */
+ readonly credits_used: number
+ /**
+ * `credit_limit - credits_used`, floored at 0. Null when uncapped.
+ * @nullable
+ */
+ readonly remaining: number | null
+ /** True when `credits_used >= credit_limit`; further observations are skipped until next period. Always false when uncapped. */
readonly exhausted: boolean
/** First moment of the current quota period (UTC). */
readonly period_start: string
/** First moment of the next quota period (UTC); the current period's exclusive upper bound. */
readonly period_end: string
- /** Sum of enabled scanners' projected observations/month across the organization. Scanners without a computed estimate contribute 0. */
- readonly projected_monthly_observations: number
+ /** Credit-weighted sum of enabled scanners' projected observations/month across the organization. Scanners without a computed estimate contribute 0. */
+ readonly projected_monthly_credits: number
}
/**
@@ -589,14 +595,16 @@ export const ScannerProviderEnumApi = {
} as const
/**
+ * * `gemini-2.5-flash` - Gemini 2.5 Flash
* * `gemini-3-flash-preview` - Gemini 3 Flash
- * * `gemini-3.1-flash-lite-preview` - Gemini 3 Flash Lite
+ * * `gemini-3.5-flash` - Gemini 3.5 Flash
*/
export type ScannerModelEnumApi = (typeof ScannerModelEnumApi)[keyof typeof ScannerModelEnumApi]
export const ScannerModelEnumApi = {
+ Gemini25Flash: 'gemini-2.5-flash',
Gemini3FlashPreview: 'gemini-3-flash-preview',
- Gemini31FlashLitePreview: 'gemini-3.1-flash-lite-preview',
+ Gemini35Flash: 'gemini-3.5-flash',
} as const
export interface ReplayScannerApi {
@@ -640,8 +648,9 @@ export interface ReplayScannerApi {
provider?: ScannerProviderEnumApi
/** Concrete model to use for this scanner.
*
+ * * `gemini-2.5-flash` - Gemini 2.5 Flash
* * `gemini-3-flash-preview` - Gemini 3 Flash
- * * `gemini-3.1-flash-lite-preview` - Gemini 3 Flash Lite */
+ * * `gemini-3.5-flash` - Gemini 3.5 Flash */
model: ScannerModelEnumApi
/** When false, the reconciler removes the scanner's Temporal schedule. On-demand triggers still work. */
enabled?: boolean
@@ -654,6 +663,13 @@ export interface ReplayScannerApi {
* @nullable
*/
readonly estimated_monthly_observations: number | null
+ /** Credits one observation by this scanner costs (1 credit = $0.01), derived from `model`. */
+ readonly credits_per_observation: number
+ /**
+ * `estimated_monthly_observations` priced at `credits_per_observation`. Null until the estimate is first computed.
+ * @nullable
+ */
+ readonly estimated_monthly_credits: number | null
/** Watermark for the scanner's last scheduled fire. Mirrors Temporal schedule state for recovery. */
readonly last_swept_at: string
readonly created_at: string
@@ -712,8 +728,9 @@ export interface PatchedReplayScannerApi {
provider?: ScannerProviderEnumApi
/** Concrete model to use for this scanner.
*
+ * * `gemini-2.5-flash` - Gemini 2.5 Flash
* * `gemini-3-flash-preview` - Gemini 3 Flash
- * * `gemini-3.1-flash-lite-preview` - Gemini 3 Flash Lite */
+ * * `gemini-3.5-flash` - Gemini 3.5 Flash */
model?: ScannerModelEnumApi
/** When false, the reconciler removes the scanner's Temporal schedule. On-demand triggers still work. */
enabled?: boolean
@@ -726,6 +743,13 @@ export interface PatchedReplayScannerApi {
* @nullable
*/
readonly estimated_monthly_observations?: number | null
+ /** Credits one observation by this scanner costs (1 credit = $0.01), derived from `model`. */
+ readonly credits_per_observation?: number
+ /**
+ * `estimated_monthly_observations` priced at `credits_per_observation`. Null until the estimate is first computed.
+ * @nullable
+ */
+ readonly estimated_monthly_credits?: number | null
/** Watermark for the scanner's last scheduled fire. Mirrors Temporal schedule state for recovery. */
readonly last_swept_at?: string
readonly created_at?: string
@@ -982,14 +1006,20 @@ export interface EstimateRequestApi {
* * `comprehensive` - Comprehensive */
sampling_mode?: SamplingModeEnumApi
/**
- * The scanner being edited, excluded from `other_enabled_scanners_monthly` so its stored estimate isn't double-counted in the forecast. Omit (or null) when estimating a brand-new scanner.
+ * The scanner being edited, excluded from `other_enabled_scanners_monthly_credits` so its stored estimate isn't double-counted in the forecast. Omit (or null) when estimating a brand-new scanner.
* @nullable
*/
scanner_id?: string | null
+ /** Proposed model; determines `credits_per_observation` in the response.
+ *
+ * * `gemini-2.5-flash` - Gemini 2.5 Flash
+ * * `gemini-3-flash-preview` - Gemini 3 Flash
+ * * `gemini-3.5-flash` - Gemini 3.5 Flash */
+ model?: ScannerModelEnumApi
}
/**
- * Forward-looking observation-volume estimate for a proposed scanner. Pricing-agnostic.
+ * Forward-looking volume and credit-cost estimate for a proposed scanner.
*/
export interface EstimateResponseApi {
/** Distinct sessions matching the query within the 30-day lookback, after the sampling_mode quality filter but before random sampling. */
@@ -998,8 +1028,12 @@ export interface EstimateResponseApi {
window_days: number
/** Projected monthly observations: quality-filtered matched sessions scaled to 30 days, times sampling_rate. */
estimated_observations_per_month: number
- /** Summed projected monthly observations of the org's other enabled scanners (excluding `scanner_id`), from their cached estimates. Read from the same snapshot as this estimate so the forecast can't double-count the edited scanner. */
- other_enabled_scanners_monthly: number
+ /** Credits one observation costs at the proposed `model` (1 credit = $0.01). */
+ credits_per_observation: number
+ /** `estimated_observations_per_month` priced at `credits_per_observation`. */
+ estimated_credits_per_month: number
+ /** Credit-weighted projected monthly spend of the org's other enabled scanners (excluding `scanner_id`), from their cached estimates. Read from the same snapshot as this estimate so the forecast can't double-count the edited scanner. */
+ other_enabled_scanners_monthly_credits: number
/** Sampling rate applied to the projection. Echoed from the request. */
sampling_rate: number
}
diff --git a/products/replay_vision/frontend/generated/api.zod.ts b/products/replay_vision/frontend/generated/api.zod.ts
index b2441715415f..7e7f2a3666f7 100644
--- a/products/replay_vision/frontend/generated/api.zod.ts
+++ b/products/replay_vision/frontend/generated/api.zod.ts
@@ -318,12 +318,12 @@ export const VisionScannersCreateBody = /* @__PURE__ */ zod.object({
.optional()
.describe('LLM provider. v1 is Google-only.\n\n\* `google` - Google'),
model: zod
- .enum(['gemini-3-flash-preview', 'gemini-3.1-flash-lite-preview'])
+ .enum(['gemini-2.5-flash', 'gemini-3-flash-preview', 'gemini-3.5-flash'])
.describe(
- '\* `gemini-3-flash-preview` - Gemini 3 Flash\n\* `gemini-3.1-flash-lite-preview` - Gemini 3 Flash Lite'
+ '\* `gemini-2.5-flash` - Gemini 2.5 Flash\n\* `gemini-3-flash-preview` - Gemini 3 Flash\n\* `gemini-3.5-flash` - Gemini 3.5 Flash'
)
.describe(
- 'Concrete model to use for this scanner.\n\n\* `gemini-3-flash-preview` - Gemini 3 Flash\n\* `gemini-3.1-flash-lite-preview` - Gemini 3 Flash Lite'
+ 'Concrete model to use for this scanner.\n\n\* `gemini-2.5-flash` - Gemini 2.5 Flash\n\* `gemini-3-flash-preview` - Gemini 3 Flash\n\* `gemini-3.5-flash` - Gemini 3.5 Flash'
),
enabled: zod
.boolean()
@@ -400,13 +400,13 @@ export const VisionScannersPartialUpdateBody = /* @__PURE__ */ zod.object({
.optional()
.describe('LLM provider. v1 is Google-only.\n\n\* `google` - Google'),
model: zod
- .enum(['gemini-3-flash-preview', 'gemini-3.1-flash-lite-preview'])
+ .enum(['gemini-2.5-flash', 'gemini-3-flash-preview', 'gemini-3.5-flash'])
.describe(
- '\* `gemini-3-flash-preview` - Gemini 3 Flash\n\* `gemini-3.1-flash-lite-preview` - Gemini 3 Flash Lite'
+ '\* `gemini-2.5-flash` - Gemini 2.5 Flash\n\* `gemini-3-flash-preview` - Gemini 3 Flash\n\* `gemini-3.5-flash` - Gemini 3.5 Flash'
)
.optional()
.describe(
- 'Concrete model to use for this scanner.\n\n\* `gemini-3-flash-preview` - Gemini 3 Flash\n\* `gemini-3.1-flash-lite-preview` - Gemini 3 Flash Lite'
+ 'Concrete model to use for this scanner.\n\n\* `gemini-2.5-flash` - Gemini 2.5 Flash\n\* `gemini-3-flash-preview` - Gemini 3 Flash\n\* `gemini-3.5-flash` - Gemini 3.5 Flash'
),
enabled: zod
.boolean()
@@ -461,6 +461,7 @@ export const visionScannersEstimateCreateBodySamplingRateMin = 0
export const visionScannersEstimateCreateBodySamplingRateMax = 1
export const visionScannersEstimateCreateBodySamplingModeDefault = `comprehensive`
+export const visionScannersEstimateCreateBodyModelDefault = `gemini-3-flash-preview`
export const VisionScannersEstimateCreateBody = /* @__PURE__ */ zod
.object({
@@ -487,7 +488,16 @@ export const VisionScannersEstimateCreateBody = /* @__PURE__ */ zod
.uuid()
.nullish()
.describe(
- "The scanner being edited, excluded from `other_enabled_scanners_monthly` so its stored estimate isn't double-counted in the forecast. Omit (or null) when estimating a brand-new scanner."
+ "The scanner being edited, excluded from `other_enabled_scanners_monthly_credits` so its stored estimate isn't double-counted in the forecast. Omit (or null) when estimating a brand-new scanner."
+ ),
+ model: zod
+ .enum(['gemini-2.5-flash', 'gemini-3-flash-preview', 'gemini-3.5-flash'])
+ .describe(
+ '\* `gemini-2.5-flash` - Gemini 2.5 Flash\n\* `gemini-3-flash-preview` - Gemini 3 Flash\n\* `gemini-3.5-flash` - Gemini 3.5 Flash'
+ )
+ .default(visionScannersEstimateCreateBodyModelDefault)
+ .describe(
+ 'Proposed model; determines `credits_per_observation` in the response.\n\n\* `gemini-2.5-flash` - Gemini 2.5 Flash\n\* `gemini-3-flash-preview` - Gemini 3 Flash\n\* `gemini-3.5-flash` - Gemini 3.5 Flash'
),
})
.describe('Body of POST \/vision\/scanners\/estimate\/ — a proposed, unsaved scanner config.')
diff --git a/products/replay_vision/frontend/logics/visionQuotaLogic.test.ts b/products/replay_vision/frontend/logics/visionQuotaLogic.test.ts
index 39e2aa5cff95..a31df3bb38e4 100644
--- a/products/replay_vision/frontend/logics/visionQuotaLogic.test.ts
+++ b/products/replay_vision/frontend/logics/visionQuotaLogic.test.ts
@@ -7,10 +7,10 @@ import { makeQuota } from '../utils/quotaTestUtils'
import { visionQuotaLogic } from './visionQuotaLogic'
const quota = makeQuota({
- monthly_quota: 1000,
- usage_this_month: 100,
+ credit_limit: 1000,
+ credits_used: 100,
remaining: 900,
- projected_monthly_observations: 500,
+ projected_monthly_credits: 500,
})
describe('visionQuotaLogic', () => {
@@ -35,10 +35,10 @@ describe('visionQuotaLogic', () => {
await expectLogic(logic).toDispatchActions(['loadQuotaSuccess'])
logic.actions.adjustProjectedMonthly(250)
- expect(logic.values.quota?.projected_monthly_observations).toBe(750)
+ expect(logic.values.quota?.projected_monthly_credits).toBe(750)
logic.actions.adjustProjectedMonthly(-10_000)
- expect(logic.values.quota?.projected_monthly_observations).toBe(0)
+ expect(logic.values.quota?.projected_monthly_credits).toBe(0)
})
it('adjustProjectedMonthly is a no-op before the quota has loaded', () => {
@@ -52,6 +52,6 @@ describe('visionQuotaLogic', () => {
await expectLogic(logic, () => logic.actions.loadQuota()).toDispatchActions(['loadQuotaSuccess'])
- expect(logic.values.quota?.projected_monthly_observations).toBe(500)
+ expect(logic.values.quota?.projected_monthly_credits).toBe(500)
})
})
diff --git a/products/replay_vision/frontend/logics/visionQuotaLogic.ts b/products/replay_vision/frontend/logics/visionQuotaLogic.ts
index cd42e3f76ee7..d14df115f39f 100644
--- a/products/replay_vision/frontend/logics/visionQuotaLogic.ts
+++ b/products/replay_vision/frontend/logics/visionQuotaLogic.ts
@@ -45,7 +45,7 @@ export const visionQuotaLogic = kea<visionQuotaLogicType>([
state
? {
...state,
- projected_monthly_observations: Math.max(0, state.projected_monthly_observations + delta),
+ projected_monthly_credits: Math.max(0, state.projected_monthly_credits + delta),
}
: state,
},
diff --git a/products/replay_vision/frontend/replay_scanners/ReplayScanner.tsx b/products/replay_vision/frontend/replay_scanners/ReplayScanner.tsx
index fead90bd95fd..f8db0d2cee2f 100644
--- a/products/replay_vision/frontend/replay_scanners/ReplayScanner.tsx
+++ b/products/replay_vision/frontend/replay_scanners/ReplayScanner.tsx
@@ -19,6 +19,7 @@ import { AccessControlLevel, AccessControlResourceType } from '~/types'
import { ReplayVisionFeedbackButton } from '../components/ReplayVisionFeedbackButton'
import { visionQuotaLogic } from '../logics/visionQuotaLogic'
+import { formatCredits } from '../utils/credits'
import { quotaBannerState } from '../utils/quotaProjection'
import { ObservationSearchMaxChat } from './components/ObservationSearchMaxChat'
import { ScannerConfigReadonly } from './components/ScannerConfigReadonly'
@@ -161,8 +162,8 @@ function QuotaBanner(): JSX.Element | null {
return (
<LemonBanner type="warning">
{state.kind === 'exhausted'
- ? `Monthly observation quota reached (${state.quota.usage_this_month.toLocaleString()} / ${state.quota.monthly_quota.toLocaleString()}). New observations are paused until ${state.resetsOn}.`
- : `${state.quota.usage_this_month.toLocaleString()} of ${state.quota.monthly_quota.toLocaleString()} monthly observations used. New observations will pause once you hit the cap. Resets ${state.resetsOn}.`}
+ ? `Monthly spend limit reached (${formatCredits(state.quota.credits_used)} of ${formatCredits(state.quota.credit_limit ?? 0)}). New observations are paused until ${state.resetsOn}.`
+ : `${formatCredits(state.quota.credits_used)} of your ${formatCredits(state.quota.credit_limit ?? 0)} monthly spend limit used. New observations will pause once you hit the limit. Resets ${state.resetsOn}.`}
</LemonBanner>
)
}
diff --git a/products/replay_vision/frontend/replay_scanners/ReplayScannersScene.stories.tsx b/products/replay_vision/frontend/replay_scanners/ReplayScannersScene.stories.tsx
index 8af2c561be2b..2bbd0dce245f 100644
--- a/products/replay_vision/frontend/replay_scanners/ReplayScannersScene.stories.tsx
+++ b/products/replay_vision/frontend/replay_scanners/ReplayScannersScene.stories.tsx
@@ -88,11 +88,11 @@ const scanners = {
}
const quota: VisionQuotaApi = {
- monthly_quota: 10000,
- usage_this_month: 2400,
+ credit_limit: 10000,
+ credits_used: 2400,
remaining: 7600,
exhausted: false,
- projected_monthly_observations: 5200,
+ projected_monthly_credits: 5200,
period_start: '2026-05-01T00:00:00Z',
period_end: '2026-06-01T00:00:00Z',
}
diff --git a/products/replay_vision/frontend/replay_scanners/ScannerEditorScene.tsx b/products/replay_vision/frontend/replay_scanners/ScannerEditorScene.tsx
index d801927ee999..5e6831cc99d2 100644
--- a/products/replay_vision/frontend/replay_scanners/ScannerEditorScene.tsx
+++ b/products/replay_vision/frontend/replay_scanners/ScannerEditorScene.tsx
@@ -3,18 +3,10 @@ import { Form } from 'kea-forms'
import { router } from 'kea-router'
import * as construction2Png from '@posthog/brand/hoggies/png/construction-2'
+import * as imTheDriverPng from '@posthog/brand/hoggies/png/im-the-driver'
import * as magnifyingGlassPng from '@posthog/brand/hoggies/png/magnifying-glass'
import * as xRayPng from '@posthog/brand/hoggies/png/x-ray'
-import {
- LemonButton,
- LemonCollapse,
- LemonInput,
- LemonSelect,
- LemonSwitch,
- LemonTag,
- LemonTextArea,
- Link,
-} from '@posthog/lemon-ui'
+import { LemonButton, LemonInput, LemonSelect, LemonSwitch, LemonTag, LemonTextArea, Link } from '@posthog/lemon-ui'
import { pngHoggie } from 'lib/brand/hoggies'
import { NotFound } from 'lib/components/NotFound'
@@ -35,11 +27,17 @@ import { ScannerTemplatePicker } from './components/ScannerTemplatePicker'
import { ScannerTriggers } from './components/ScannerTriggers'
import { ScannerTypeConfigEditor } from './components/ScannerTypeConfigEditor'
import { replayScannerLogic } from './replayScannerLogic'
-import { SCANNER_EDITOR_STEP_ORDER, ScannerEditorStep, scannerEditorSceneLogic } from './scannerEditorSceneLogic'
-import { ScannerEditorStepper } from './ScannerEditorStepper'
+import {
+ SCANNER_EDITOR_STEP_ORDER,
+ ScannerEditorStep,
+ scannerEditorSceneLogic,
+ scannerStepUrl,
+} from './scannerEditorSceneLogic'
+import { ScannerEditorStepper, STEP_LABELS } from './ScannerEditorStepper'
import { MODEL_OPTIONS, SCANNER_TYPE_OPTIONS } from './types'
const HedgehogConstruction2 = pngHoggie(construction2Png)
+const HedgehogImTheDriver = pngHoggie(imTheDriverPng)
const HedgehogMagnifyingGlass = pngHoggie(magnifyingGlassPng)
const HedgehogXRay = pngHoggie(xRayPng)
@@ -49,6 +47,28 @@ export const scene: SceneExport = {
productKey: ProductKey.REPLAY_VISION,
}
+// Template renders its own header, so only the form steps need one here.
+const STEP_HEADERS: Record<
+ Exclude<ScannerEditorStep, 'template'>,
+ { hedgehog: JSX.Element; title: string; subtitle: string }
+> = {
+ configure: {
+ hedgehog: <HedgehogMagnifyingGlass className="h-24 w-auto shrink-0" />,
+ title: 'Configure your scanner',
+ subtitle: 'What it looks for and how it analyzes recordings.',
+ },
+ triggers: {
+ hedgehog: <HedgehogConstruction2 className="h-24 w-auto shrink-0" />,
+ title: 'Set up scan conditions',
+ subtitle: 'Pick which recordings to scan, and how often.',
+ },
+ self_driving: {
+ hedgehog: <HedgehogImTheDriver className="h-24 w-auto shrink-0" />,
+ title: 'Self-driving',
+ subtitle: 'Close the loop: from findings to shipped fixes.',
+ },
+}
+
export function ScannerEditorSceneComponent(): JSX.Element {
const { scannerId, step, isNew, visibleSteps } = useValues(scannerEditorSceneLogic)
@@ -74,13 +94,18 @@ export function ScannerEditorSceneComponent(): JSX.Element {
const title = isNew ? scanner?.name || 'New scanner' : scanner?.name || 'Scanner'
- const stepErrors = showScannerErrors
- ? {
- template: false,
- configure: !!(scannerValidationErrors?.name || scannerValidationErrors?.scanner_config),
- triggers: scannerValidationErrors?.sampling_rate != null,
- }
- : { template: false, configure: false, triggers: false }
+ const stepErrors: Record<ScannerEditorStep, boolean> = {
+ template: false,
+ self_driving: false,
+ configure: showScannerErrors && !!(scannerValidationErrors?.name || scannerValidationErrors?.scanner_config),
+ triggers: showScannerErrors && scannerValidationErrors?.sampling_rate != null,
+ }
+
+ // Validate the current step and move on: submit routes to the next visible step on success.
+ const advance = (): void => {
+ setSubmitIntent('advance')
+ submitScanner()
+ }
const goToStep = (next: ScannerEditorStep): void => {
if (isScannerSubmitting) {
@@ -91,19 +116,10 @@ export function ScannerEditorSceneComponent(): JSX.Element {
router.actions.push(urls.replayVisionScannerConfigure(scannerId))
return
}
- setSubmitIntent('advance')
- submitScanner()
+ advance()
return
}
- if (next === 'template') {
- router.actions.push(urls.replayVisionScannerTemplate(scannerId))
- return
- }
- router.actions.push(
- next === 'configure'
- ? urls.replayVisionScannerConfigure(scannerId)
- : urls.replayVisionScannerTriggers(scannerId)
- )
+ router.actions.push(scannerStepUrl(next, scannerId))
}
return (
@@ -145,32 +161,26 @@ export function ScannerEditorSceneComponent(): JSX.Element {
>
<div className="bg-bg-light border rounded-lg shadow-sm p-6 flex flex-col gap-6 [&_.Field--error_.input-like]:!border-danger">
<div className="flex items-center gap-3">
- {step === 'configure' ? (
- <HedgehogMagnifyingGlass className="h-24 w-auto shrink-0" />
- ) : (
- <HedgehogConstruction2 className="h-24 w-auto shrink-0" />
- )}
+ {STEP_HEADERS[step].hedgehog}
<div>
- <div className="text-base font-semibold">
- {step === 'configure' ? 'Configure your scanner' : 'Set up scan conditions'}
- </div>
- <div className="text-sm text-muted">
- {step === 'configure'
- ? 'What it looks for and how it analyzes recordings.'
- : 'Pick which recordings to scan, and how often.'}
- </div>
+ <div className="text-base font-semibold">{STEP_HEADERS[step].title}</div>
+ <div className="text-sm text-muted">{STEP_HEADERS[step].subtitle}</div>
</div>
</div>
- {step === 'configure' ? <ConfigureStep /> : <ScannerTriggers scannerId={scannerId} />}
+ {step === 'configure' ? (
+ <ConfigureStep />
+ ) : step === 'triggers' ? (
+ <ScannerTriggers scannerId={scannerId} />
+ ) : (
+ <SelfDrivingStep />
+ )}
<EditorFooter
step={step}
scannerId={scannerId}
+ visibleSteps={visibleSteps}
isNew={isNew}
isSubmitting={isScannerSubmitting}
- onAdvance={() => {
- setSubmitIntent('advance')
- submitScanner()
- }}
+ onAdvance={advance}
onSave={() => {
setSubmitIntent('save')
submitScanner()
@@ -262,37 +272,46 @@ function ConfigureStep(): JSX.Element {
</div>
)}
+ <div className="flex flex-col gap-1 items-start">
+ <LemonField name="model" label="Model" className="items-start">
+ <LemonSelect value={scanner.model} options={MODEL_OPTIONS} />
+ </LemonField>
+ <div className="text-xs text-muted">
+ Newer models tend to produce higher-quality observations, but cost more per observation.
+ </div>
+ </div>
+
<ScannerTypeConfigEditor scannerId={scannerId} />
+ </div>
+ )
+}
- <LemonCollapse
- panels={[
- {
- key: 'advanced',
- header: 'Advanced',
- content: (
- <div className="flex flex-col gap-4">
- <LemonField name="model" label="Model" className="items-start">
- <LemonSelect value={scanner.model} options={MODEL_OPTIONS} />
- </LemonField>
- <LemonField name="emits_signals">
- {({ value, onChange }) => (
- <div className="flex items-center gap-3">
- <LemonSwitch checked={!!value} onChange={onChange} />
- <div>
- <div className="text-sm font-medium">Hand off to Responder agents</div>
- <div className="text-xs text-muted">
- Adds a side mission to each scan: clear, actionable product issues
- are handled by PostHog Responder agents.
- </div>
- </div>
- </div>
- )}
- </LemonField>
+function SelfDrivingStep(): JSX.Element {
+ return (
+ <div className="flex flex-col gap-4">
+ <p className="text-sm text-muted m-0">
+ Don't just find problems, fix them. As this scanner reviews recordings, any issues it spots flow into
+ PostHog Signals, where agents dig into the root cause and draft a pull request. You stay in control of
+ what ships.{' '}
+ <Link to="https://posthog.com/self-driving" target="_blank">
+ Learn more about PostHog self-driving
+ </Link>
+ .
+ </p>
+ <LemonField name="emits_signals">
+ {({ value, onChange }) => (
+ <div className="flex items-center gap-3">
+ <LemonSwitch checked={!!value} onChange={onChange} />
+ <div>
+ <div className="text-sm font-medium">Emit findings as Signals</div>
+ <div className="text-xs text-muted">
+ Adds a side mission to each scan: clear, actionable product issues are emitted as
+ PostHog Signals to feed the self-driving loop.
</div>
- ),
- },
- ]}
- />
+ </div>
+ </div>
+ )}
+ </LemonField>
</div>
)
}
@@ -300,6 +319,7 @@ function ConfigureStep(): JSX.Element {
function EditorFooter({
step,
scannerId,
+ visibleSteps,
isNew,
isSubmitting,
onAdvance,
@@ -307,50 +327,51 @@ function EditorFooter({
}: {
step: ScannerEditorStep
scannerId: string
+ visibleSteps: readonly ScannerEditorStep[]
isNew: boolean
isSubmitting: boolean
onAdvance: () => void
onSave: () => void
}): JSX.Element {
const { scanner } = useValues(replayScannerLogic({ id: scannerId }))
+ const stepIndex = visibleSteps.indexOf(step)
+ const prevStep = stepIndex > 0 ? visibleSteps[stepIndex - 1] : null
+ const nextStep = stepIndex < visibleSteps.length - 1 ? visibleSteps[stepIndex + 1] : null
+
return (
<div className="flex items-center justify-between">
- {step === 'configure' ? (
- <>
- {isNew && (
- <LemonButton type="tertiary" to={urls.replayVisionTemplates()} data-attr="vision-editor-back">
- Back to templates
- </LemonButton>
- )}
- <LemonButton
- type="primary"
- loading={isSubmitting}
- onClick={onAdvance}
- className="ml-auto"
- data-attr="vision-editor-next"
- >
- Next: scan conditions
- </LemonButton>
- </>
+ {/* First form step of a new scanner goes back to the template picker; a mid-flow step goes to the
+ previous visible step; editing's first step (configure, no template) has no back. */}
+ {isNew && step === 'configure' ? (
+ <LemonButton type="tertiary" to={urls.replayVisionTemplates()} data-attr="vision-editor-back">
+ Back to templates
+ </LemonButton>
+ ) : prevStep ? (
+ <LemonButton type="tertiary" to={scannerStepUrl(prevStep, scannerId)} data-attr="vision-editor-back">
+ Back
+ </LemonButton>
+ ) : null}
+ {nextStep ? (
+ <LemonButton
+ type="primary"
+ loading={isSubmitting}
+ onClick={onAdvance}
+ className="ml-auto"
+ data-attr="vision-editor-next"
+ >
+ Next: {STEP_LABELS[nextStep]}
+ </LemonButton>
) : (
- <>
- <LemonButton
- type="tertiary"
- to={urls.replayVisionScannerConfigure(scannerId)}
- data-attr="vision-editor-back"
- >
- Back
- </LemonButton>
- <LemonButton
- type="primary"
- loading={isSubmitting}
- onClick={onSave}
- data-attr="vision-editor-save"
- data-ph-capture-attribute-scanner-type={scanner?.scanner_type}
- >
- {isNew ? 'Create scanner' : 'Save changes'}
- </LemonButton>
- </>
+ <LemonButton
+ type="primary"
+ loading={isSubmitting}
+ onClick={onSave}
+ className="ml-auto"
+ data-attr="vision-editor-save"
+ data-ph-capture-attribute-scanner-type={scanner?.scanner_type}
+ >
+ {isNew ? 'Create scanner' : 'Save changes'}
+ </LemonButton>
)}
</div>
)
diff --git a/products/replay_vision/frontend/replay_scanners/ScannerEditorStepper.tsx b/products/replay_vision/frontend/replay_scanners/ScannerEditorStepper.tsx
index 4bb8319acaa3..dafffc26a576 100644
--- a/products/replay_vision/frontend/replay_scanners/ScannerEditorStepper.tsx
+++ b/products/replay_vision/frontend/replay_scanners/ScannerEditorStepper.tsx
@@ -4,10 +4,11 @@ import { cn } from 'lib/utils/css-classes'
import { SCANNER_EDITOR_STEP_ORDER, ScannerEditorStep } from './scannerEditorSceneLogic'
-const STEP_LABELS: Record<ScannerEditorStep, string> = {
+export const STEP_LABELS: Record<ScannerEditorStep, string> = {
template: 'Template',
configure: 'Configure',
triggers: 'Scan conditions',
+ self_driving: 'Self-driving',
}
interface ScannerEditorStepperProps {
diff --git a/products/replay_vision/frontend/replay_scanners/components/QuotaStatusLine.tsx b/products/replay_vision/frontend/replay_scanners/components/QuotaStatusLine.tsx
index e00ab4eea87d..5b4564324646 100644
--- a/products/replay_vision/frontend/replay_scanners/components/QuotaStatusLine.tsx
+++ b/products/replay_vision/frontend/replay_scanners/components/QuotaStatusLine.tsx
@@ -1,18 +1,18 @@
import type { QuotaProjection } from '../../utils/quotaProjection'
-/** Red warning when the quota is exhausted or projected to overshoot; renders nothing otherwise. */
+/** Red warning when the spend limit is exhausted or projected to overshoot; renders nothing otherwise. */
export function QuotaStatusLine({ projection }: { projection: QuotaProjection }): JSX.Element | null {
if (projection.exhausted) {
- return <span className="text-danger">Quota exhausted</span>
+ return <span className="text-danger">Spend limit reached</span>
}
if (projection.status !== 'danger') {
return null
}
return projection.capReachDate ? (
<span className="text-danger">
- Quota projected to run out on <strong>{projection.capReachDate.format('MMMM D')}</strong>
+ Spend limit projected to be reached on <strong>{projection.capReachDate.format('MMMM D')}</strong>
</span>
) : (
- <span className="text-danger">Projected to exceed the monthly quota</span>
+ <span className="text-danger">Projected to exceed the monthly spend limit</span>
)
}
diff --git a/products/replay_vision/frontend/replay_scanners/components/ScannerConfigReadonly.tsx b/products/replay_vision/frontend/replay_scanners/components/ScannerConfigReadonly.tsx
index 0ee06d5ae19a..389e81a46bda 100644
--- a/products/replay_vision/frontend/replay_scanners/components/ScannerConfigReadonly.tsx
+++ b/products/replay_vision/frontend/replay_scanners/components/ScannerConfigReadonly.tsx
@@ -33,6 +33,7 @@ import { BooleanTag } from '../../components/BooleanTag'
import { CardHeader } from '../../components/CardHeader'
import { LabeledRow } from '../../components/LabeledRow'
import { ScannerTypeBadge } from '../../components/ScannerTypeBadge'
+import { formatCredits } from '../../utils/credits'
import { replayScannerLogic } from '../replayScannerLogic'
import { MODEL_OPTIONS, ReplayScanner, SAMPLING_MODE_OPTIONS, ScannerType } from '../types'
@@ -314,10 +315,13 @@ export function ScannerConfigReadonly({ scanner }: { scanner: ReplayScanner }):
<LemonCard className="p-4" hoverEffect={false}>
<CardHeader icon={<IconGraph />} title="Usage" />
<div className="flex flex-col gap-3">
- <LabeledRow label="Estimated monthly observations">
- {scanner.estimated_monthly_observations != null ? (
+ <LabeledRow label="Estimated monthly cost">
+ {scanner.estimated_monthly_credits != null ? (
<span className="tabular-nums">
- {scanner.estimated_monthly_observations.toLocaleString()}
+ {formatCredits(scanner.estimated_monthly_credits)}{' '}
+ <span className="text-muted">
+ ({(scanner.estimated_monthly_observations ?? 0).toLocaleString()} observations)
+ </span>
</span>
) : (
<span className="text-muted">—</span>
diff --git a/products/replay_vision/frontend/replay_scanners/components/ScannerQuotaForecast.tsx b/products/replay_vision/frontend/replay_scanners/components/ScannerQuotaForecast.tsx
index cdbc06717e8a..f21cbd2ec869 100644
--- a/products/replay_vision/frontend/replay_scanners/components/ScannerQuotaForecast.tsx
+++ b/products/replay_vision/frontend/replay_scanners/components/ScannerQuotaForecast.tsx
@@ -5,7 +5,14 @@ import { LemonCard, Spinner, Tooltip } from '@posthog/lemon-ui'
import { LemonLabel } from 'lib/lemon-ui/LemonLabel'
import { visionQuotaLogic } from '../../logics/visionQuotaLogic'
-import { QUOTA_STATUS_STYLES, type QuotaStatus, projectQuota, splitProjectedPct } from '../../utils/quotaProjection'
+import { formatCredits } from '../../utils/credits'
+import {
+ QUOTA_STATUS_STYLES,
+ type QuotaStatus,
+ hasCreditLimit,
+ projectQuota,
+ splitProjectedPct,
+} from '../../utils/quotaProjection'
import { replayScannerLogic } from '../replayScannerLogic'
import { QuotaMeterBar, QuotaMeterLegendItem } from './QuotaMeterBar'
import { QuotaStatusLine } from './QuotaStatusLine'
@@ -26,40 +33,43 @@ export function ScannerQuotaForecast({ scannerId }: Props): JSX.Element | null {
const samplingRatio = Math.max(0, Math.min(scanner.sampling_rate, 1))
// The estimate already applies the quality filter and sampling rate backend-side.
- const projected = scannerEstimate?.estimated_observations_per_month ?? null
- const hasCap = !!quota && quota.monthly_quota > 0
- const used = quota?.usage_this_month ?? 0
- const cap = quota?.monthly_quota ?? 0
+ const projectedObservations = scannerEstimate?.estimated_observations_per_month ?? null
+ const projectedCredits = scannerEstimate?.estimated_credits_per_month ?? null
+ const hasCap = hasCreditLimit(quota)
+ const used = quota?.credits_used ?? 0
+ const cap = quota?.credit_limit ?? 0
- // `other_enabled_scanners_monthly` comes from the same estimate response as `projected`, so the two are a
- // consistent snapshot. Subtracting this scanner's stored estimate from the live fleet sum instead would race the
- // estimate-refresh cadence and double-count the scanner right after creating it.
- const fleetMonthly = quota?.projected_monthly_observations ?? 0
- const othersMonthly = scannerEstimate?.other_enabled_scanners_monthly ?? 0
+ // `other_enabled_scanners_monthly_credits` comes from the same estimate response as `projectedCredits`, so the
+ // two are a consistent snapshot. Subtracting this scanner's stored estimate from the live fleet sum instead would
+ // race the estimate-refresh cadence and double-count the scanner right after creating it.
+ const fleetMonthly = quota?.projected_monthly_credits ?? 0
+ const othersMonthly = scannerEstimate?.other_enabled_scanners_monthly_credits ?? 0
// projectQuota wants a delta off the stored fleet total, so compute the new fleet total (others + this) and pass the difference.
- const newFleetMonthly = projected !== null ? othersMonthly + projected : fleetMonthly
+ const newFleetMonthly = projectedCredits !== null ? othersMonthly + projectedCredits : fleetMonthly
const projection = projectQuota(quota, newFleetMonthly - fleetMonthly)
const { status, percentLabel, resetsOn, usedPct, projectedPct } = projection
- const effectiveStatus: QuotaStatus = projected === null ? 'safe' : status
+ const effectiveStatus: QuotaStatus = projectedCredits === null ? 'safe' : status
const styles = QUOTA_STATUS_STYLES[effectiveStatus]
- const { thisScannerPct, othersPct } = splitProjectedPct(projectedPct, projected ?? 0, othersMonthly)
+ const { thisScannerPct, othersPct } = splitProjectedPct(projectedPct, projectedCredits ?? 0, othersMonthly)
const breakdown = (
<div className="text-xs space-y-0.5">
<div>
- Used this month: <strong>{used.toLocaleString()}</strong>
+ Spent this month: <strong>{formatCredits(used)}</strong>
</div>
<div>
- Projected from this scanner: <strong>~{(projected ?? 0).toLocaleString()}/month</strong>
+ Projected from this scanner: <strong>~{formatCredits(projectedCredits ?? 0)}/month</strong>
</div>
<div>
- Projected from other scanners: <strong>~{othersMonthly.toLocaleString()}/month</strong>
- </div>
- <div>
- Monthly quota: <strong>{cap.toLocaleString()}</strong>
+ Projected from other scanners: <strong>~{formatCredits(othersMonthly)}/month</strong>
</div>
+ {hasCap && (
+ <div>
+ Monthly limit: <strong>{formatCredits(cap)}</strong>
+ </div>
+ )}
{resetsOn && <div className="text-muted">Resets {resetsOn}</div>}
</div>
)
@@ -67,8 +77,8 @@ export function ScannerQuotaForecast({ scannerId }: Props): JSX.Element | null {
return (
<LemonCard hoverEffect={false} className="p-3 space-y-2">
<div className="flex items-baseline justify-between gap-3">
- <LemonLabel>Estimated impact</LemonLabel>
- {hasCap && projected !== null && (
+ <LemonLabel>Estimated cost</LemonLabel>
+ {hasCap && projectedCredits !== null && (
<Tooltip title={breakdown}>
<span className={`text-xs tabular-nums ${styles.text}`}>
{percentLabel}%{' '}
@@ -79,14 +89,18 @@ export function ScannerQuotaForecast({ scannerId }: Props): JSX.Element | null {
</div>
<div className="flex items-baseline justify-between gap-3">
- {projected !== null ? (
+ {projectedCredits !== null ? (
<div className="text-base font-semibold tabular-nums flex items-center gap-2">
<span>
- {projected.toLocaleString()}{' '}
- <span className="text-sm font-normal text-muted">observations/month</span>
+ ~{formatCredits(projectedCredits)}
+ <span className="text-sm font-normal text-muted">/month</span>{' '}
+ <span className="text-sm font-normal text-muted">
+ ({(projectedObservations ?? 0).toLocaleString()} observations at{' '}
+ {formatCredits(scannerEstimate?.credits_per_observation ?? 0)} each)
+ </span>
</span>
{scannerEstimateLoading && (
- <Tooltip title="Recomputing with the latest filters and sampling rate.">
+ <Tooltip title="Recomputing with the latest filters, sampling rate, and model.">
<Spinner className="text-muted text-sm" />
</Tooltip>
)}
@@ -101,7 +115,7 @@ export function ScannerQuotaForecast({ scannerId }: Props): JSX.Element | null {
)}
</div>
- {hasCap && projected !== null && (
+ {hasCap && projectedCredits !== null && (
<>
<Tooltip title={breakdown}>
<QuotaMeterBar
@@ -111,13 +125,13 @@ export function ScannerQuotaForecast({ scannerId }: Props): JSX.Element | null {
{ pct: thisScannerPct, barClass: styles.bar, striped: true },
]}
valueNow={percentLabel}
- label={`Projected ${percentLabel}% of monthly observation quota by ${
+ label={`Projected ${percentLabel}% of the monthly spend limit by ${
resetsOn ?? 'period end'
}`}
/>
</Tooltip>
<div className="flex items-center gap-3 text-xs text-muted">
- <QuotaMeterLegendItem>Used</QuotaMeterLegendItem>
+ <QuotaMeterLegendItem>Spent</QuotaMeterLegendItem>
<QuotaMeterLegendItem barClass="bg-accent">Projected (other scanners)</QuotaMeterLegendItem>
<QuotaMeterLegendItem barClass={styles.bar} striped>
Projected (this scanner)
@@ -140,7 +154,7 @@ export function ScannerQuotaForecast({ scannerId }: Props): JSX.Element | null {
recordings in the last {scannerEstimate.window_days} days.
</div>
) : scannerEstimateError ? (
- <div className="text-xs text-danger">Couldn't estimate impact: {scannerEstimateError}</div>
+ <div className="text-xs text-danger">Couldn't estimate cost: {scannerEstimateError}</div>
) : (
<div className="text-xs text-muted">Estimate unavailable. Try adjusting your filters.</div>
)}
diff --git a/products/replay_vision/frontend/replay_scanners/components/VisionMetrics.tsx b/products/replay_vision/frontend/replay_scanners/components/VisionMetrics.tsx
index b1e15794c6d4..74d043a9790c 100644
--- a/products/replay_vision/frontend/replay_scanners/components/VisionMetrics.tsx
+++ b/products/replay_vision/frontend/replay_scanners/components/VisionMetrics.tsx
@@ -10,7 +10,8 @@ import { BaseMathType, ChartDisplayType, InsightLogicProps } from '~/types'
import { ScannerTypeBadge } from '../../components/ScannerTypeBadge'
import { visionQuotaLogic } from '../../logics/visionQuotaLogic'
-import { QUOTA_STATUS_STYLES, projectQuota } from '../../utils/quotaProjection'
+import { formatCredits } from '../../utils/credits'
+import { QUOTA_STATUS_STYLES, hasCreditLimit, projectQuota } from '../../utils/quotaProjection'
import { replayScannersLogic } from '../replayScannersLogic'
import { SCANNER_TYPE_OPTIONS } from '../types'
import { QuotaMeterBar, QuotaMeterLegendItem } from './QuotaMeterBar'
@@ -27,7 +28,7 @@ export function VisionMetrics(): JSX.Element {
const projection = projectQuota(quota)
const { resetsOn, status, percentLabel, usedPct, projectedPct } = projection
- const hasCap = (quota?.monthly_quota ?? 0) > 0
+ const hasCap = hasCreditLimit(quota)
const styles = QUOTA_STATUS_STYLES[status]
// Memoized so a re-render (e.g. stats/quota arriving) can't churn the query and abort an in-flight load.
@@ -103,7 +104,7 @@ export function VisionMetrics(): JSX.Element {
</div>
<div className="flex-1 bg-bg-light border rounded p-4 flex flex-col">
<div className="flex items-baseline justify-between gap-3 mb-2">
- <div className="text-muted text-xs font-medium uppercase">Observations this month</div>
+ <div className="text-muted text-xs font-medium uppercase">Spend this month</div>
{hasCap && (
<span className={`text-xs tabular-nums ${styles.text}`}>
{percentLabel}%{' '}
@@ -114,48 +115,62 @@ export function VisionMetrics(): JSX.Element {
{quota ? (
<>
<div className="text-3xl font-semibold tabular-nums">
- {quota.usage_this_month.toLocaleString()}
- <span className="text-muted text-lg font-normal">
- {' / '}
- {quota.monthly_quota.toLocaleString()}
- </span>
+ {formatCredits(quota.credits_used)}
+ {hasCap && (
+ <span className="text-muted text-lg font-normal">
+ {' / '}
+ {formatCredits(quota.credit_limit ?? 0)}
+ </span>
+ )}
</div>
- <Tooltip
- title={
- <div className="text-xs space-y-0.5">
- <div>
- Used this month: <strong>{quota.usage_this_month.toLocaleString()}</strong>
- </div>
- <div>
- Projected from enabled scanners:{' '}
- <strong>
- ~{quota.projected_monthly_observations.toLocaleString()}/month
- </strong>
- </div>
- <div>
- Monthly quota: <strong>{quota.monthly_quota.toLocaleString()}</strong>
- </div>
- {resetsOn && <div className="text-muted">Resets {resetsOn}</div>}
+ {hasCap ? (
+ <>
+ <Tooltip
+ title={
+ <div className="text-xs space-y-0.5">
+ <div>
+ Spent this month:{' '}
+ <strong>{formatCredits(quota.credits_used)}</strong>
+ </div>
+ <div>
+ Projected from enabled scanners:{' '}
+ <strong>
+ ~{formatCredits(quota.projected_monthly_credits)}/month
+ </strong>
+ </div>
+ <div>
+ Monthly limit:{' '}
+ <strong>{formatCredits(quota.credit_limit ?? 0)}</strong>
+ </div>
+ {resetsOn && <div className="text-muted">Resets {resetsOn}</div>}
+ </div>
+ }
+ >
+ <QuotaMeterBar
+ className="mt-2"
+ usedPct={usedPct}
+ projected={[{ pct: projectedPct, barClass: styles.bar, striped: true }]}
+ valueNow={percentLabel}
+ label={`Projected ${percentLabel}% of the monthly spend limit`}
+ />
+ </Tooltip>
+ <div className="flex items-center gap-3 text-xs text-muted mt-1.5">
+ <QuotaMeterLegendItem>Spent</QuotaMeterLegendItem>
+ <QuotaMeterLegendItem barClass={styles.bar} striped>
+ Projected
+ </QuotaMeterLegendItem>
+ <span className="ml-auto">
+ <QuotaStatusLine projection={projection} />
+ </span>
</div>
- }
- >
- <QuotaMeterBar
- className="mt-2"
- usedPct={usedPct}
- projected={[{ pct: projectedPct, barClass: styles.bar, striped: true }]}
- valueNow={percentLabel}
- label={`Projected ${percentLabel}% of monthly observation quota`}
- />
- </Tooltip>
- <div className="flex items-center gap-3 text-xs text-muted mt-1.5">
- <QuotaMeterLegendItem>Used</QuotaMeterLegendItem>
- <QuotaMeterLegendItem barClass={styles.bar} striped>
- Projected
- </QuotaMeterLegendItem>
- <span className="ml-auto">
- <QuotaStatusLine projection={projection} />
- </span>
- </div>
+ </>
+ ) : (
+ <div className="text-xs text-muted mt-2">
+ No spend limit set: projected ~{formatCredits(quota.projected_monthly_credits)}
+ /month from enabled scanners. Set a billing limit in your billing settings to cap
+ spend.
+ </div>
+ )}
</>
) : quotaLoading ? (
<div className="flex items-center py-2">
diff --git a/products/replay_vision/frontend/replay_scanners/replayScannerLogic.ts b/products/replay_vision/frontend/replay_scanners/replayScannerLogic.ts
index f36ebbb491ec..196f671410a5 100644
--- a/products/replay_vision/frontend/replay_scanners/replayScannerLogic.ts
+++ b/products/replay_vision/frontend/replay_scanners/replayScannerLogic.ts
@@ -33,6 +33,7 @@ import { requestObservationRetry } from '../logics/observationRetry'
import { refreshVisionQuota } from '../logics/visionQuotaLogic'
import { type UrlSorting, parseCsvParam, parseSortParam, serializeSortParam } from '../utils/urlParams'
import type { replayScannerLogicType } from './replayScannerLogicType'
+import { SCANNER_EDITOR_STEPS, scannerEditorSceneLogic, scannerStepUrl } from './scannerEditorSceneLogic'
import { findScannerTemplate, newScanner } from './scannerTemplates'
import {
ScannerConfig,
@@ -280,13 +281,18 @@ export const replayScannerLogic = kea<replayScannerLogicType>([
}
},
submit: async (scanner: ReplayScanner) => {
- // Mid-wizard Enter (default 'save' intent) must advance, not create; pathname is project-prefixed, hence endsWith.
- const onConfigureStep = router.values.location.pathname.endsWith(
- urls.replayVisionScannerConfigure(props.id)
+ // Advance to the next visible step instead of persisting, when the footer asked to (intent
+ // 'advance') or a new scanner submitted mid-wizard via Enter on any non-final step. The step
+ // order and self-driving visibility live in the editor scene, so read visibleSteps from there;
+ // findMounted keeps this usable in isolation (tests), falling back to the full order.
+ const steps = scannerEditorSceneLogic.findMounted()?.values.visibleSteps ?? SCANNER_EDITOR_STEPS
+ const currentStep = steps.find((step) =>
+ router.values.location.pathname.endsWith(scannerStepUrl(step, props.id))
)
- if (values.submitIntent === 'advance' || (values.isNew && onConfigureStep)) {
+ const nextStep = currentStep ? steps[steps.indexOf(currentStep) + 1] : undefined
+ if (nextStep && (values.submitIntent === 'advance' || values.isNew)) {
actions.setSubmitIntent('save')
- router.actions.push(urls.replayVisionScannerTriggers(props.id))
+ router.actions.push(scannerStepUrl(nextStep, props.id))
return
}
const teamId = teamLogic.values.currentTeamId
@@ -795,6 +801,8 @@ export const replayScannerLogic = kea<replayScannerLogicType>([
const response = await visionScannersEstimateCreate(String(teamId), {
query: scanner.query ?? undefined,
sampling_rate: scanner.sampling_rate,
+ // The proposed model prices the credit estimate.
+ model: scanner.model,
sampling_mode: scanner.sampling_mode,
// Exclude the edited scanner from the others-sum so the forecast doesn't double-count it.
scanner_id: props.id !== 'new' ? props.id : null,
diff --git a/products/replay_vision/frontend/replay_scanners/replayScannersLogic.test.ts b/products/replay_vision/frontend/replay_scanners/replayScannersLogic.test.ts
index a856c8716412..a90e473b2beb 100644
--- a/products/replay_vision/frontend/replay_scanners/replayScannersLogic.test.ts
+++ b/products/replay_vision/frontend/replay_scanners/replayScannersLogic.test.ts
@@ -15,10 +15,10 @@ import {
import { ScannerConfig, ScannerType, ReplayScanner } from './types'
const quotaFixture = makeQuotaFixture({
- monthly_quota: 1000,
- usage_this_month: 100,
+ credit_limit: 1000,
+ credits_used: 100,
remaining: 900,
- projected_monthly_observations: 500,
+ projected_monthly_credits: 500,
})
function defaultConfigForType(scannerType: ScannerType): ScannerConfig {
@@ -322,13 +322,13 @@ describe('replayScannersLogic', () => {
quotaLogic.mount()
quotaLogic.actions.loadQuotaSuccess(quotaFixture)
logic.actions.loadScannersSuccess(
- [makeScanner({ id: 'a', enabled: true, estimated_monthly_observations: 200 })],
+ [makeScanner({ id: 'a', enabled: true, estimated_monthly_credits: 200 })],
1
)
logic.actions.toggleScannerEnabled('a') // disabling → subtract the stored estimate
- expect(quotaLogic.values.quota?.projected_monthly_observations).toBe(300)
+ expect(quotaLogic.values.quota?.projected_monthly_credits).toBe(300)
quotaLogic.unmount()
})
@@ -338,17 +338,17 @@ describe('replayScannersLogic', () => {
quotaLogic.actions.loadQuotaSuccess(quotaFixture)
logic.actions.loadScannersSuccess(
[
- makeScanner({ id: 'a', enabled: true, estimated_monthly_observations: 200 }),
- makeScanner({ id: 'b', name: 'other', enabled: false, estimated_monthly_observations: 999 }),
+ makeScanner({ id: 'a', enabled: true, estimated_monthly_credits: 200 }),
+ makeScanner({ id: 'b', name: 'other', enabled: false, estimated_monthly_credits: 999 }),
],
2
)
logic.actions.deleteScanner('b') // disabled — contributes nothing to the sum
- expect(quotaLogic.values.quota?.projected_monthly_observations).toBe(500)
+ expect(quotaLogic.values.quota?.projected_monthly_credits).toBe(500)
logic.actions.deleteScanner('a')
- expect(quotaLogic.values.quota?.projected_monthly_observations).toBe(300)
+ expect(quotaLogic.values.quota?.projected_monthly_credits).toBe(300)
quotaLogic.unmount()
})
@@ -362,13 +362,13 @@ describe('replayScannersLogic', () => {
quotaLogic.mount()
quotaLogic.actions.loadQuotaSuccess(quotaFixture)
logic.actions.loadScannersSuccess(
- [makeScanner({ id: 'a', enabled: true, estimated_monthly_observations: 200 })],
+ [makeScanner({ id: 'a', enabled: true, estimated_monthly_credits: 200 })],
1
)
await expectLogic(logic, () => logic.actions.deleteScanner('a')).toFinishAllListeners()
- expect(quotaLogic.values.quota?.projected_monthly_observations).toBe(500)
+ expect(quotaLogic.values.quota?.projected_monthly_credits).toBe(500)
quotaLogic.unmount()
})
})
diff --git a/products/replay_vision/frontend/replay_scanners/replayScannersLogic.ts b/products/replay_vision/frontend/replay_scanners/replayScannersLogic.ts
index 82fd8d5fc841..d9c59cf6a53f 100644
--- a/products/replay_vision/frontend/replay_scanners/replayScannersLogic.ts
+++ b/products/replay_vision/frontend/replay_scanners/replayScannersLogic.ts
@@ -309,7 +309,7 @@ export const replayScannersLogic = kea<replayScannersLogicType>([
actions.setScannerDeleting(id, true)
// Deleting an enabled scanner removes its known contribution from the fleet sum — exact, so apply it now.
const scanner = values.scanners.find((s) => s.id === id)
- const delta = scanner?.enabled ? -(scanner.estimated_monthly_observations ?? 0) : 0
+ const delta = scanner?.enabled ? -(scanner.estimated_monthly_credits ?? 0) : 0
visionQuotaLogic.findMounted()?.actions.adjustProjectedMonthly(delta)
try {
await visionScannersDestroy(String(teamId), id)
@@ -347,7 +347,7 @@ export const replayScannersLogic = kea<replayScannersLogicType>([
return
}
// The stored estimate is kept ≤24h fresh even while disabled, so the projection shift is known up front.
- const estimate = scanner.estimated_monthly_observations ?? 0
+ const estimate = scanner.estimated_monthly_credits ?? 0
const delta = scanner.enabled ? estimate : -estimate
visionQuotaLogic.findMounted()?.actions.adjustProjectedMonthly(delta)
try {
diff --git a/products/replay_vision/frontend/replay_scanners/scannerEditorSceneLogic.test.ts b/products/replay_vision/frontend/replay_scanners/scannerEditorSceneLogic.test.ts
index 150641ea6cfc..8877014f9e15 100644
--- a/products/replay_vision/frontend/replay_scanners/scannerEditorSceneLogic.test.ts
+++ b/products/replay_vision/frontend/replay_scanners/scannerEditorSceneLogic.test.ts
@@ -60,17 +60,17 @@ describe('scannerEditorSceneLogic', () => {
})
describe('visibleSteps', () => {
- it('shows all three steps for a new scanner', async () => {
+ it('shows all four steps for a new scanner', async () => {
router.actions.push(urls.replayVisionScannerConfigure('new'))
await expectLogic(logic).toMatchValues({
- visibleSteps: ['template', 'configure', 'triggers'],
+ visibleSteps: ['template', 'configure', 'triggers', 'self_driving'],
})
})
- it('hides the template step for an existing scanner', async () => {
+ it('hides only the template step for an existing scanner', async () => {
router.actions.push(urls.replayVisionScannerConfigure('abc-123'))
await expectLogic(logic).toMatchValues({
- visibleSteps: ['configure', 'triggers'],
+ visibleSteps: ['configure', 'triggers', 'self_driving'],
})
})
})
diff --git a/products/replay_vision/frontend/replay_scanners/scannerEditorSceneLogic.ts b/products/replay_vision/frontend/replay_scanners/scannerEditorSceneLogic.ts
index 6517f649eb6b..7ba46759b3c4 100644
--- a/products/replay_vision/frontend/replay_scanners/scannerEditorSceneLogic.ts
+++ b/products/replay_vision/frontend/replay_scanners/scannerEditorSceneLogic.ts
@@ -7,12 +7,26 @@ import { Breadcrumb } from '~/types'
import type { scannerEditorSceneLogicType } from './scannerEditorSceneLogicType'
-export type ScannerEditorStep = 'template' | 'configure' | 'triggers'
-export const SCANNER_EDITOR_STEPS: readonly ScannerEditorStep[] = ['template', 'configure', 'triggers']
+export type ScannerEditorStep = 'template' | 'configure' | 'triggers' | 'self_driving'
+export const SCANNER_EDITOR_STEPS: readonly ScannerEditorStep[] = ['template', 'configure', 'triggers', 'self_driving']
export const SCANNER_EDITOR_STEP_ORDER: Record<ScannerEditorStep, number> = {
template: 0,
configure: 1,
triggers: 2,
+ self_driving: 3,
+}
+
+export function scannerStepUrl(step: ScannerEditorStep, scannerId: string): string {
+ switch (step) {
+ case 'template':
+ return urls.replayVisionScannerTemplate(scannerId)
+ case 'configure':
+ return urls.replayVisionScannerConfigure(scannerId)
+ case 'triggers':
+ return urls.replayVisionScannerTriggers(scannerId)
+ case 'self_driving':
+ return urls.replayVisionScannerSelfDriving(scannerId)
+ }
}
export const scannerEditorSceneLogic = kea<scannerEditorSceneLogicType>([
@@ -43,7 +57,8 @@ export const scannerEditorSceneLogic = kea<scannerEditorSceneLogicType>([
visibleSteps: [
(s) => [s.isNew],
(isNew: boolean): readonly ScannerEditorStep[] =>
- isNew ? SCANNER_EDITOR_STEPS : SCANNER_EDITOR_STEPS.filter((s) => s !== 'template'),
+ // The template picker only exists for a new scanner; every other step, self-driving included, always shows.
+ SCANNER_EDITOR_STEPS.filter((step) => isNew || step !== 'template'),
],
breadcrumbs: [
(s) => [s.scannerId, s.isNew],
@@ -111,5 +126,14 @@ export const scannerEditorSceneLogic = kea<scannerEditorSceneLogicType>([
actions.setStep('triggers')
}
},
+ [urls.replayVisionScannerSelfDriving(':id')]: ({ id }) => {
+ const scannerId = id || 'new'
+ if (scannerId !== values.scannerId) {
+ actions.setScannerId(scannerId)
+ }
+ if (values.step !== 'self_driving') {
+ actions.setStep('self_driving')
+ }
+ },
})),
])
diff --git a/products/replay_vision/frontend/replay_scanners/scannerTemplates.ts b/products/replay_vision/frontend/replay_scanners/scannerTemplates.ts
index 669ef94bab1c..ce37c97242f1 100644
--- a/products/replay_vision/frontend/replay_scanners/scannerTemplates.ts
+++ b/products/replay_vision/frontend/replay_scanners/scannerTemplates.ts
@@ -9,7 +9,7 @@ import type {
ScorerScannerConfig,
SummarizerScannerConfig,
} from './types'
-import { DEFAULT_MODEL, DEFAULT_PROVIDER } from './types'
+import { DEFAULT_MODEL, DEFAULT_PROVIDER, OBSERVATION_CREDITS_BY_MODEL } from './types'
export type ScannerTemplateIcon = 'warning' | 'notebook' | 'target' | 'thumbs-down' | 'check'
@@ -136,6 +136,9 @@ export function newScanner(templateKey?: string | null): ReplayScanner {
updated_at: dayjs().toISOString(),
created_by: null,
estimated_monthly_observations: null,
+ estimated_monthly_credits: null,
+ // Seed price for the unsaved scanner; the server-computed value takes over after the first save.
+ credits_per_observation: OBSERVATION_CREDITS_BY_MODEL[DEFAULT_MODEL],
} as const
const template = findScannerTemplate(templateKey ?? undefined)
diff --git a/products/replay_vision/frontend/replay_scanners/types.ts b/products/replay_vision/frontend/replay_scanners/types.ts
index c7b3c5e578ae..91095ca471fe 100644
--- a/products/replay_vision/frontend/replay_scanners/types.ts
+++ b/products/replay_vision/frontend/replay_scanners/types.ts
@@ -9,6 +9,7 @@ import type {
ScannerTypeEnumApi,
UserBasicApi,
} from '../generated/api.schemas'
+import { formatCredits } from '../utils/credits'
export type ScannerType = ScannerTypeEnumApi
@@ -116,10 +117,26 @@ export const ENABLED_OPTIONS: { value: EnabledFilter; label: string }[] = [
{ value: 'disabled', label: 'Disabled' },
]
-export const MODEL_OPTIONS: { value: ScannerModelEnumApi; label: string }[] = [
- { value: ScannerModelEnumApi.Gemini3FlashPreview, label: 'Gemini 3 Flash' },
- { value: ScannerModelEnumApi.Gemini31FlashLitePreview, label: 'Gemini 3 Flash Lite' },
-]
+// Mirrors the backend `OBSERVATION_CREDITS_BY_MODEL` table (the scanner/estimate API responses are authoritative);
+// the picker needs a price per model before anything is saved, so it can't come from a per-instance response.
+export const OBSERVATION_CREDITS_BY_MODEL: Record<ScannerModelEnumApi, number> = {
+ [ScannerModelEnumApi.Gemini25Flash]: 2,
+ [ScannerModelEnumApi.Gemini3FlashPreview]: 5,
+ [ScannerModelEnumApi.Gemini35Flash]: 15,
+}
+
+const MODEL_NAMES: Record<ScannerModelEnumApi, string> = {
+ [ScannerModelEnumApi.Gemini25Flash]: 'Gemini 2.5 Flash',
+ [ScannerModelEnumApi.Gemini3FlashPreview]: 'Gemini 3 Flash',
+ [ScannerModelEnumApi.Gemini35Flash]: 'Gemini 3.5 Flash',
+}
+
+export const MODEL_OPTIONS: { value: ScannerModelEnumApi; label: string }[] = Object.values(ScannerModelEnumApi).map(
+ (value) => ({
+ value,
+ label: `${MODEL_NAMES[value]} (${formatCredits(OBSERVATION_CREDITS_BY_MODEL[value])}/observation)`,
+ })
+)
export function modelLabel(model: string | null | undefined): string {
if (!model) {
diff --git a/products/replay_vision/frontend/utils/credits.ts b/products/replay_vision/frontend/utils/credits.ts
new file mode 100644
index 000000000000..71597630667d
--- /dev/null
+++ b/products/replay_vision/frontend/utils/credits.ts
@@ -0,0 +1,8 @@
+import { humanFriendlyCurrency } from 'lib/utils/numbers'
+
+/** 1 credit = $0.01; all quota amounts arrive from the API as credits and render as dollars. */
+export const CREDITS_PER_DOLLAR = 100
+
+export function formatCredits(credits: number): string {
+ return humanFriendlyCurrency(credits / CREDITS_PER_DOLLAR)
+}
diff --git a/products/replay_vision/frontend/utils/quotaProjection.test.ts b/products/replay_vision/frontend/utils/quotaProjection.test.ts
index 026c9ae36d1d..e55439689d61 100644
--- a/products/replay_vision/frontend/utils/quotaProjection.test.ts
+++ b/products/replay_vision/frontend/utils/quotaProjection.test.ts
@@ -2,20 +2,30 @@ import { projectQuota, quotaUx, splitProjectedPct } from './quotaProjection'
import { makeQuota } from './quotaTestUtils'
describe('projectQuota', () => {
- it('returns the empty projection when quota is null or unbounded', () => {
+ it('returns the empty projection when quota is null or uncapped', () => {
expect(projectQuota(null)).toMatchObject({ status: 'safe', usedPct: 0, projectedPct: 0 })
- expect(projectQuota(makeQuota({ monthly_quota: 0 }))).toMatchObject({ status: 'safe', percentLabel: 0 })
+ expect(projectQuota(makeQuota({ credit_limit: null, remaining: null }))).toMatchObject({
+ status: 'safe',
+ percentLabel: 0,
+ })
+ })
+
+ it('treats a zero limit as fully blocking, not uncapped', () => {
+ const proj = projectQuota(makeQuota({ credit_limit: 0, remaining: 0, exhausted: true }))
+ expect(proj.status).toBe('danger')
+ expect(proj.percentLabel).toBe(100)
+ expect(proj.exhausted).toBe(true)
})
it('safe when the fleet rate projects well under the cap', () => {
// 3,000/month fleet → 100/day → ends at 3,000 of 10,000.
- const proj = projectQuota(makeQuota({ usage_this_month: 1_000, projected_monthly_observations: 3_000 }))
+ const proj = projectQuota(makeQuota({ credits_used: 1_000, projected_monthly_credits: 3_000 }))
expect(proj.status).toBe('safe')
expect(proj.percentLabel).toBe(30)
})
it('zero fleet rate projects flat usage to period end', () => {
- const proj = projectQuota(makeQuota({ usage_this_month: 4_000 }))
+ const proj = projectQuota(makeQuota({ credits_used: 4_000 }))
expect(proj.projectedPct).toBe(0)
expect(proj.percentLabel).toBe(40)
expect(proj.capReachDate).toBeNull()
@@ -23,45 +33,42 @@ describe('projectQuota', () => {
it('warning when the fleet projection crosses the warn threshold but stays under cap', () => {
// 3,000 used + 9,000/month fleet → 300/day × 20 days → ends at 9,000 (90% of cap).
- const proj = projectQuota(makeQuota({ usage_this_month: 3_000, projected_monthly_observations: 9_000 }))
+ const proj = projectQuota(makeQuota({ credits_used: 3_000, projected_monthly_credits: 9_000 }))
expect(proj.status).toBe('warning')
expect(proj.percentLabel).toBe(90)
})
it('danger when projected to exhaust before period end', () => {
// 9,000 used + 100/day → cap reached in 10 days, 20 days left in the period.
- const proj = projectQuota(makeQuota({ usage_this_month: 9_000, projected_monthly_observations: 3_000 }))
+ const proj = projectQuota(makeQuota({ credits_used: 9_000, projected_monthly_credits: 3_000 }))
expect(proj.status).toBe('danger')
expect(proj.capReachDate).not.toBeNull()
})
it('danger when explicitly exhausted regardless of the fleet rate', () => {
- const proj = projectQuota(makeQuota({ usage_this_month: 10_000, remaining: 0, exhausted: true }))
+ const proj = projectQuota(makeQuota({ credits_used: 10_000, remaining: 0, exhausted: true }))
expect(proj.status).toBe('danger')
expect(proj.exhausted).toBe(true)
})
it('a positive scanner delta raises the projection on top of the fleet sum', () => {
- const base = projectQuota(makeQuota({ usage_this_month: 1_000, projected_monthly_observations: 3_000 }))
- const withDelta = projectQuota(
- makeQuota({ usage_this_month: 1_000, projected_monthly_observations: 3_000 }),
- 6_000
- )
+ const base = projectQuota(makeQuota({ credits_used: 1_000, projected_monthly_credits: 3_000 }))
+ const withDelta = projectQuota(makeQuota({ credits_used: 1_000, projected_monthly_credits: 3_000 }), 6_000)
expect(withDelta.projectedPct).toBeGreaterThan(base.projectedPct)
expect(withDelta.percentLabel).toBeGreaterThan(base.percentLabel)
})
it('a negative scanner delta lowers the projection and clamps at zero', () => {
// 2,000/month over a 30-day period × 20 remaining days = ~1,333 of the 10,000 cap.
- const lowered = projectQuota(makeQuota({ projected_monthly_observations: 3_000 }), -1_000)
+ const lowered = projectQuota(makeQuota({ projected_monthly_credits: 3_000 }), -1_000)
expect(lowered.projectedPct).toBeCloseTo(13.33, 1)
- const clamped = projectQuota(makeQuota({ projected_monthly_observations: 3_000 }), -9_000)
+ const clamped = projectQuota(makeQuota({ projected_monthly_credits: 3_000 }), -9_000)
expect(clamped.projectedPct).toBe(0)
})
it('reports unclamped percentages on overshoot', () => {
// 8,000 used + 30,000/month × 20 days = 20,000 more → 280% of the 10,000 cap.
- const proj = projectQuota(makeQuota({ usage_this_month: 8_000, projected_monthly_observations: 30_000 }))
+ const proj = projectQuota(makeQuota({ credits_used: 8_000, projected_monthly_credits: 30_000 }))
expect(proj.percentLabel).toBe(280)
expect(proj.projectedPct).toBeCloseTo(200, 0)
})
@@ -82,24 +89,29 @@ describe('splitProjectedPct', () => {
})
describe('quotaUx', () => {
- it('returns nothing when no quota is configured', () => {
+ it('returns nothing when no limit is configured', () => {
expect(quotaUx(null)).toEqual({})
- expect(quotaUx(makeQuota({ monthly_quota: 0 }))).toEqual({})
+ // A zero limit with the backend reporting exhaustion must block, not read as uncapped.
+ expect(quotaUx(makeQuota({ credit_limit: 0, remaining: 0, exhausted: true })).disabledReason).toMatch(
+ /spend limit reached/i
+ )
+ // Uncapped orgs never block or warn.
+ expect(quotaUx(makeQuota({ credit_limit: null, credits_used: 999_999, remaining: null }))).toEqual({})
})
it('blocks with a disabledReason when exhausted', () => {
- const ux = quotaUx(makeQuota({ usage_this_month: 10_000, remaining: 0, exhausted: true }))
- expect(ux.disabledReason).toMatch(/quota reached/i)
+ const ux = quotaUx(makeQuota({ credits_used: 10_000, remaining: 0, exhausted: true }))
+ expect(ux.disabledReason).toMatch(/spend limit reached/i)
expect(ux.tooltip).toBeUndefined()
})
- it('shows a tooltip near the warn threshold but does not block', () => {
- const ux = quotaUx(makeQuota({ usage_this_month: 8_500, remaining: 1_500 }))
+ it('shows a dollar tooltip near the warn threshold but does not block', () => {
+ const ux = quotaUx(makeQuota({ credits_used: 8_500, remaining: 1_500 }))
expect(ux.disabledReason).toBeUndefined()
- expect(ux.tooltip).toContain('1,500')
+ expect(ux.tooltip).toContain('$15.00')
})
it('returns nothing while usage is well under the threshold', () => {
- expect(quotaUx(makeQuota({ usage_this_month: 1_000, remaining: 9_000 }))).toEqual({})
+ expect(quotaUx(makeQuota({ credits_used: 1_000, remaining: 9_000 }))).toEqual({})
})
})
diff --git a/products/replay_vision/frontend/utils/quotaProjection.ts b/products/replay_vision/frontend/utils/quotaProjection.ts
index a3362c660b44..89cbe08fb67c 100644
--- a/products/replay_vision/frontend/utils/quotaProjection.ts
+++ b/products/replay_vision/frontend/utils/quotaProjection.ts
@@ -1,6 +1,7 @@
import { dayjs } from 'lib/dayjs'
import type { VisionQuotaApi } from '../generated/api.schemas'
+import { formatCredits } from './credits'
export const QUOTA_WARN_THRESHOLD = 0.85
@@ -16,12 +17,12 @@ export interface QuotaProjection {
status: QuotaStatus
exhausted: boolean
capReachDate: dayjs.Dayjs | null
- /** Projected period-end usage as a rounded percentage of the cap; exceeds 100 on overshoot. */
+ /** Projected period-end spend as a rounded percentage of the limit; exceeds 100 on overshoot. */
percentLabel: number
resetsOn: string | null
- /** Actual usage as a percentage of the cap; `QuotaMeterBar` clamps for display. */
+ /** Actual spend as a percentage of the limit; `QuotaMeterBar` clamps for display. */
usedPct: number
- /** Projected additional usage as a percentage of the cap, unclamped. */
+ /** Projected additional spend as a percentage of the limit, unclamped. */
projectedPct: number
}
@@ -35,25 +36,45 @@ const EMPTY: QuotaProjection = {
projectedPct: 0,
}
+/** True when the org has a real spend limit to render a meter against; uncapped orgs get spend-only UI. */
+export function hasCreditLimit(quota: VisionQuotaApi | null): quota is VisionQuotaApi & { credit_limit: number } {
+ // 0 is a real (fully blocking) limit; only null means uncapped.
+ return !!quota && quota.credit_limit !== null
+}
+
/**
- * Project quota usage to period end from the enabled fleet's summed per-scanner estimates.
- * `scannerProjectedMonthlyDelta` adjusts the fleet sum for a scanner being edited:
- * its proposed monthly estimate minus the stored contribution already in the sum.
+ * Project credit spend to period end from the enabled fleet's summed per-scanner estimates.
+ * `scannerProjectedMonthlyCreditsDelta` adjusts the fleet sum for a scanner being edited:
+ * its proposed monthly credit estimate minus the stored contribution already in the sum.
*/
-export function projectQuota(quota: VisionQuotaApi | null, scannerProjectedMonthlyDelta: number = 0): QuotaProjection {
- if (!quota || quota.monthly_quota <= 0) {
+export function projectQuota(
+ quota: VisionQuotaApi | null,
+ scannerProjectedMonthlyCreditsDelta: number = 0
+): QuotaProjection {
+ if (!hasCreditLimit(quota)) {
return EMPTY
}
const now = dayjs()
- const used = quota.usage_this_month
- const cap = quota.monthly_quota
+ const used = quota.credits_used
+ const cap = quota.credit_limit
+ if (cap === 0) {
+ // A $0 spend limit blocks everything; there is no ratio to project against.
+ return {
+ ...EMPTY,
+ status: 'danger',
+ exhausted: quota.exhausted,
+ percentLabel: 100,
+ usedPct: 100,
+ resetsOn: quota.period_end ? dayjs(quota.period_end).format('MMMM D') : null,
+ }
+ }
const periodStart = quota.period_start ? dayjs(quota.period_start) : null
const periodEnd = quota.period_end ? dayjs(quota.period_end) : null
const periodLengthDays = periodStart && periodEnd ? Math.max(periodEnd.diff(periodStart, 'day', true), 1) : 30
const daysRemaining = periodEnd ? Math.max(periodEnd.diff(now, 'day', true), 0) : 0
const resetsOn = periodEnd ? periodEnd.format('MMMM D') : null
- const projectedMonthly = Math.max(quota.projected_monthly_observations + scannerProjectedMonthlyDelta, 0)
+ const projectedMonthly = Math.max(quota.projected_monthly_credits + scannerProjectedMonthlyCreditsDelta, 0)
const combinedDailyRate = projectedMonthly / periodLengthDays
const projectedAdditional = combinedDailyRate * daysRemaining
@@ -79,7 +100,7 @@ export function projectQuota(quota: VisionQuotaApi | null, scannerProjectedMonth
}
}
-/** Apportion a projected percentage between this scanner and the rest of the fleet by monthly volume. */
+/** Apportion a projected percentage between this scanner and the rest of the fleet by monthly credit volume. */
export function splitProjectedPct(
projectedPct: number,
thisScannerMonthly: number,
@@ -92,7 +113,7 @@ export function splitProjectedPct(
}
/**
- * Disabled-reason / tooltip for scan triggers based on the monthly observation quota.
+ * Disabled-reason / tooltip for scan triggers based on the monthly credit limit.
* Assumes block-only overage policy; revisit when `usage_based` lands so we don't disable on metered orgs.
*/
export function quotaUx(quota: VisionQuotaApi | null): { disabledReason?: string; tooltip?: string } {
@@ -101,10 +122,10 @@ export function quotaUx(quota: VisionQuotaApi | null): { disabledReason?: string
return {}
}
if (state.kind === 'exhausted') {
- return { disabledReason: `Monthly observation quota reached. Resets ${state.resetsOn}.` }
+ return { disabledReason: `Monthly Replay vision spend limit reached. Resets ${state.resetsOn}.` }
}
return {
- tooltip: `${state.quota.remaining.toLocaleString()} observations left this month (resets ${state.resetsOn})`,
+ tooltip: `${formatCredits(state.quota.remaining ?? 0)} left this month (resets ${state.resetsOn})`,
}
}
@@ -112,14 +133,14 @@ export function quotaUx(quota: VisionQuotaApi | null): { disabledReason?: string
export function quotaBannerState(
quota: VisionQuotaApi | null
): { kind: null } | { kind: 'exhausted' | 'warning'; resetsOn: string; quota: VisionQuotaApi } {
- if (!quota || quota.monthly_quota <= 0) {
+ if (!hasCreditLimit(quota)) {
return { kind: null }
}
const resetsOn = dayjs(quota.period_end).format('MMMM D')
if (quota.exhausted) {
return { kind: 'exhausted', resetsOn, quota }
}
- if (quota.usage_this_month / quota.monthly_quota >= QUOTA_WARN_THRESHOLD) {
+ if (quota.credits_used / quota.credit_limit >= QUOTA_WARN_THRESHOLD) {
return { kind: 'warning', resetsOn, quota }
}
return { kind: null }
diff --git a/products/replay_vision/frontend/utils/quotaTestUtils.ts b/products/replay_vision/frontend/utils/quotaTestUtils.ts
index 2123c443daae..ac043c918b0b 100644
--- a/products/replay_vision/frontend/utils/quotaTestUtils.ts
+++ b/products/replay_vision/frontend/utils/quotaTestUtils.ts
@@ -5,11 +5,11 @@ export function makeQuota(overrides: Partial<VisionQuotaApi> = {}): VisionQuotaA
const now = new Date()
const daysFromNow = (days: number): string => new Date(now.getTime() + days * 24 * 3600 * 1000).toISOString()
return {
- monthly_quota: 10_000,
- usage_this_month: 0,
+ credit_limit: 10_000,
+ credits_used: 0,
remaining: 10_000,
exhausted: false,
- projected_monthly_observations: 0,
+ projected_monthly_credits: 0,
period_start: daysFromNow(-10),
period_end: daysFromNow(20),
...overrides,
diff --git a/products/replay_vision/manifest.tsx b/products/replay_vision/manifest.tsx
index b2b428a6a6fb..eb28f2d72e9d 100644
--- a/products/replay_vision/manifest.tsx
+++ b/products/replay_vision/manifest.tsx
@@ -70,6 +70,7 @@ export const manifest: ProductManifest = {
'/replay-vision/:id/template': ['ReplayVisionScannerEditor', 'replayVisionScannerTemplate'],
'/replay-vision/:id/configure': ['ReplayVisionScannerEditor', 'replayVisionScannerConfigure'],
'/replay-vision/:id/triggers': ['ReplayVisionScannerEditor', 'replayVisionScannerTriggers'],
+ '/replay-vision/:id/self-driving': ['ReplayVisionScannerEditor', 'replayVisionScannerSelfDriving'],
'/replay-vision/:id': ['ReplayVisionScanner', 'replayVision'],
},
redirects: {
@@ -83,6 +84,7 @@ export const manifest: ProductManifest = {
replayVisionScannerTemplate: (id: string): string => `/replay-vision/${id}/template`,
replayVisionScannerConfigure: (id: string): string => `/replay-vision/${id}/configure`,
replayVisionScannerTriggers: (id: string): string => `/replay-vision/${id}/triggers`,
+ replayVisionScannerSelfDriving: (id: string): string => `/replay-vision/${id}/self-driving`,
replayVisionObservation: (observationId: string): string => `/replay-vision/observations/${observationId}`,
replayVisionAction: (actionId: string): string => `/replay-vision/actions/${actionId}`,
replayVisionActionRun: (actionId: string, runId: string): string =>
diff --git a/products/replay_vision/mcp/tools.yaml b/products/replay_vision/mcp/tools.yaml
index 322c45101f2c..384dabb7ccef 100644
--- a/products/replay_vision/mcp/tools.yaml
+++ b/products/replay_vision/mcp/tools.yaml
@@ -116,10 +116,11 @@ tools:
idempotent: true
title: Get replay vision quota
description: >
- Get the organization's monthly Replay Vision observation budget. Returns `monthly_quota`, `usage_this_month`
- (in-flight + succeeded observations counted against it), `remaining`, `exhausted`, and the
+ Get the organization's monthly Replay vision credit budget (1 credit = $0.01; observations cost credits by
+ model). Returns `credit_limit` (null when uncapped), `credits_used` (in-flight + succeeded observations
+ counted against it), `remaining`, `exhausted`, `projected_monthly_credits`, and the
`period_start`/`period_end` of the current calendar-month window. Check `remaining`/`exhausted` before
- creating a scanner or calling `vision-scanners-scan-session` — observations requested over quota are
+ creating a scanner or calling `vision-scanners-scan-session` — observations requested over budget are
silently skipped until the next period. Pair with `vision-scanners-estimate-create` to size a new scanner
against the remaining budget.
feature_flag: replay-vision
diff --git a/products/replay_vision/skills/creating-replay-vision-scanners/SKILL.md b/products/replay_vision/skills/creating-replay-vision-scanners/SKILL.md
index 4e25718ac7de..9d7d2aeebe04 100644
--- a/products/replay_vision/skills/creating-replay-vision-scanners/SKILL.md
+++ b/products/replay_vision/skills/creating-replay-vision-scanners/SKILL.md
@@ -58,7 +58,7 @@ Before creating, run both checks and reason about them together:
It returns `matched_sessions_in_window`, the `window_days` measured, and
`estimated_observations_per_month`.
2. **Check budget** — call `vision-quota-retrieve` for `remaining` and `exhausted` against the org's monthly
- `monthly_quota`.
+ `credit_limit` (credits, 1 credit = $0.01; `null` when uncapped).
Then decide:
diff --git a/services/mcp/schema/generated-tool-definitions.json b/services/mcp/schema/generated-tool-definitions.json
index a6d72063d54e..ec52dbb14278 100644
--- a/services/mcp/schema/generated-tool-definitions.json
+++ b/services/mcp/schema/generated-tool-definitions.json
@@ -8374,7 +8374,7 @@
"feature_flag": "replay-vision"
},
"vision-quota-retrieve": {
- "description": "Get the organization's monthly Replay Vision observation budget. Returns `monthly_quota`, `usage_this_month` (in-flight + succeeded observations counted against it), `remaining`, `exhausted`, and the `period_start`/`period_end` of the current calendar-month window. Check `remaining`/`exhausted` before creating a scanner or calling `vision-scanners-scan-session` — observations requested over quota are silently skipped until the next period. Pair with `vision-scanners-estimate-create` to size a new scanner against the remaining budget.",
+ "description": "Get the organization's monthly Replay vision credit budget (1 credit = $0.01; observations cost credits by model). Returns `credit_limit` (null when uncapped), `credits_used` (in-flight + succeeded observations counted against it), `remaining`, `exhausted`, `projected_monthly_credits`, and the `period_start`/`period_end` of the current calendar-month window. Check `remaining`/`exhausted` before creating a scanner or calling `vision-scanners-scan-session` — observations requested over budget are silently skipped until the next period. Pair with `vision-scanners-estimate-create` to size a new scanner against the remaining budget.",
"category": "Replay vision",
"feature": "replay_vision",
"summary": "Get replay vision quota",
diff --git a/services/mcp/schema/tool-definitions-all.json b/services/mcp/schema/tool-definitions-all.json
index c15e989e1b97..1bbe6f2f1234 100644
--- a/services/mcp/schema/tool-definitions-all.json
+++ b/services/mcp/schema/tool-definitions-all.json
@@ -8897,7 +8897,7 @@
"feature_flag": "replay-vision"
},
"vision-quota-retrieve": {
- "description": "Get the organization's monthly Replay Vision observation budget. Returns `monthly_quota`, `usage_this_month` (in-flight + succeeded observations counted against it), `remaining`, `exhausted`, and the `period_start`/`period_end` of the current calendar-month window. Check `remaining`/`exhausted` before creating a scanner or calling `vision-scanners-scan-session` — observations requested over quota are silently skipped until the next period. Pair with `vision-scanners-estimate-create` to size a new scanner against the remaining budget.",
+ "description": "Get the organization's monthly Replay vision credit budget (1 credit = $0.01; observations cost credits by model). Returns `credit_limit` (null when uncapped), `credits_used` (in-flight + succeeded observations counted against it), `remaining`, `exhausted`, `projected_monthly_credits`, and the `period_start`/`period_end` of the current calendar-month window. Check `remaining`/`exhausted` before creating a scanner or calling `vision-scanners-scan-session` — observations requested over budget are silently skipped until the next period. Pair with `vision-scanners-estimate-create` to size a new scanner against the remaining budget.",
"category": "Replay vision",
"feature": "replay_vision",
"summary": "Get replay vision quota",
diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.ts
index bb800dbc87b6..b3105b0d6d8a 100644
--- a/services/mcp/src/api/generated.ts
+++ b/services/mcp/src/api/generated.ts
@@ -21270,6 +21270,20 @@ export namespace Schemas {
Comprehensive: 'comprehensive',
} as const;
+ /**
+ * * `gemini-2.5-flash` - Gemini 2.5 Flash
+ * * `gemini-3-flash-preview` - Gemini 3 Flash
+ * * `gemini-3.5-flash` - Gemini 3.5 Flash
+ */
+ export type ScannerModelEnum = typeof ScannerModelEnum[keyof typeof ScannerModelEnum];
+
+
+ export const ScannerModelEnum = {
+ Gemini25Flash: 'gemini-2.5-flash',
+ Gemini3FlashPreview: 'gemini-3-flash-preview',
+ Gemini35Flash: 'gemini-3.5-flash',
+ } as const;
+
/**
* Body of POST /vision/scanners/estimate/ — a proposed, unsaved scanner config.
*/
@@ -21289,14 +21303,20 @@ export namespace Schemas {
* * `comprehensive` - Comprehensive */
sampling_mode?: SamplingModeEnum;
/**
- * The scanner being edited, excluded from `other_enabled_scanners_monthly` so its stored estimate isn't double-counted in the forecast. Omit (or null) when estimating a brand-new scanner.
+ * The scanner being edited, excluded from `other_enabled_scanners_monthly_credits` so its stored estimate isn't double-counted in the forecast. Omit (or null) when estimating a brand-new scanner.
* @nullable
*/
scanner_id?: string | null;
+ /** Proposed model; determines `credits_per_observation` in the response.
+ *
+ * * `gemini-2.5-flash` - Gemini 2.5 Flash
+ * * `gemini-3-flash-preview` - Gemini 3 Flash
+ * * `gemini-3.5-flash` - Gemini 3.5 Flash */
+ model?: ScannerModelEnum;
}
/**
- * Forward-looking observation-volume estimate for a proposed scanner. Pricing-agnostic.
+ * Forward-looking volume and credit-cost estimate for a proposed scanner.
*/
export interface EstimateResponse {
/** Distinct sessions matching the query within the 30-day lookback, after the sampling_mode quality filter but before random sampling. */
@@ -21305,8 +21325,12 @@ export namespace Schemas {
window_days: number;
/** Projected monthly observations: quality-filtered matched sessions scaled to 30 days, times sampling_rate. */
estimated_observations_per_month: number;
- /** Summed projected monthly observations of the org's other enabled scanners (excluding `scanner_id`), from their cached estimates. Read from the same snapshot as this estimate so the forecast can't double-count the edited scanner. */
- other_enabled_scanners_monthly: number;
+ /** Credits one observation costs at the proposed `model` (1 credit = $0.01). */
+ credits_per_observation: number;
+ /** `estimated_observations_per_month` priced at `credits_per_observation`. */
+ estimated_credits_per_month: number;
+ /** Credit-weighted projected monthly spend of the org's other enabled scanners (excluding `scanner_id`), from their cached estimates. Read from the same snapshot as this estimate so the forecast can't double-count the edited scanner. */
+ other_enabled_scanners_monthly_credits: number;
/** Sampling rate applied to the projection. Echoed from the request. */
sampling_rate: number;
}
@@ -34727,18 +34751,6 @@ export namespace Schemas {
Google: 'google',
} as const;
- /**
- * * `gemini-3-flash-preview` - Gemini 3 Flash
- * * `gemini-3.1-flash-lite-preview` - Gemini 3 Flash Lite
- */
- export type ScannerModelEnum = typeof ScannerModelEnum[keyof typeof ScannerModelEnum];
-
-
- export const ScannerModelEnum = {
- Gemini3FlashPreview: 'gemini-3-flash-preview',
- Gemini31FlashLitePreview: 'gemini-3.1-flash-lite-preview',
- } as const;
-
export interface ReplayScanner {
readonly id: string;
/**
@@ -34780,8 +34792,9 @@ export namespace Schemas {
provider?: ScannerProviderEnum;
/** Concrete model to use for this scanner.
*
+ * * `gemini-2.5-flash` - Gemini 2.5 Flash
* * `gemini-3-flash-preview` - Gemini 3 Flash
- * * `gemini-3.1-flash-lite-preview` - Gemini 3 Flash Lite */
+ * * `gemini-3.5-flash` - Gemini 3.5 Flash */
model: ScannerModelEnum;
/** When false, the reconciler removes the scanner's Temporal schedule. On-demand triggers still work. */
enabled?: boolean;
@@ -34794,6 +34807,13 @@ export namespace Schemas {
* @nullable
*/
readonly estimated_monthly_observations: number | null;
+ /** Credits one observation by this scanner costs (1 credit = $0.01), derived from `model`. */
+ readonly credits_per_observation: number;
+ /**
+ * `estimated_monthly_observations` priced at `credits_per_observation`. Null until the estimate is first computed.
+ * @nullable
+ */
+ readonly estimated_monthly_credits: number | null;
/** Watermark for the scanner's last scheduled fire. Mirrors Temporal schedule state for recovery. */
readonly last_swept_at: string;
readonly created_at: string;
@@ -42617,8 +42637,9 @@ export namespace Schemas {
provider?: ScannerProviderEnum;
/** Concrete model to use for this scanner.
*
+ * * `gemini-2.5-flash` - Gemini 2.5 Flash
* * `gemini-3-flash-preview` - Gemini 3 Flash
- * * `gemini-3.1-flash-lite-preview` - Gemini 3 Flash Lite */
+ * * `gemini-3.5-flash` - Gemini 3.5 Flash */
model?: ScannerModelEnum;
/** When false, the reconciler removes the scanner's Temporal schedule. On-demand triggers still work. */
enabled?: boolean;
@@ -42631,6 +42652,13 @@ export namespace Schemas {
* @nullable
*/
readonly estimated_monthly_observations?: number | null;
+ /** Credits one observation by this scanner costs (1 credit = $0.01), derived from `model`. */
+ readonly credits_per_observation?: number;
+ /**
+ * `estimated_monthly_observations` priced at `credits_per_observation`. Null until the estimate is first computed.
+ * @nullable
+ */
+ readonly estimated_monthly_credits?: number | null;
/** Watermark for the scanner's last scheduled fire. Mirrors Temporal schedule state for recovery. */
readonly last_swept_at?: string;
readonly created_at?: string;
@@ -56806,20 +56834,26 @@ export namespace Schemas {
}
export interface VisionQuota {
- /** Total observations the org may complete per calendar month. */
- readonly monthly_quota: number;
- /** Observations created this month that are in flight or have succeeded, counted against the quota. */
- readonly usage_this_month: number;
- /** `monthly_quota - usage_this_month`, floored at 0. */
- readonly remaining: number;
- /** True when `usage_this_month >= monthly_quota`; further observations are skipped until next period. */
+ /**
+ * Credits the org may spend per billing period (1 credit = $0.01). Null when billing has synced the product with no spend limit: uncapped.
+ * @nullable
+ */
+ readonly credit_limit: number | null;
+ /** Credits spent this period: succeeded observations from the receipt ledger plus reserved in-flight observations. */
+ readonly credits_used: number;
+ /**
+ * `credit_limit - credits_used`, floored at 0. Null when uncapped.
+ * @nullable
+ */
+ readonly remaining: number | null;
+ /** True when `credits_used >= credit_limit`; further observations are skipped until next period. Always false when uncapped. */
readonly exhausted: boolean;
/** First moment of the current quota period (UTC). */
readonly period_start: string;
/** First moment of the next quota period (UTC); the current period's exclusive upper bound. */
readonly period_end: string;
- /** Sum of enabled scanners' projected observations/month across the organization. Scanners without a computed estimate contribute 0. */
- readonly projected_monthly_observations: number;
+ /** Credit-weighted sum of enabled scanners' projected observations/month across the organization. Scanners without a computed estimate contribute 0. */
+ readonly projected_monthly_credits: number;
}
export interface WarehouseConnection {
diff --git a/services/mcp/src/generated/replay_vision/api.ts b/services/mcp/src/generated/replay_vision/api.ts
index 8105bffe06e7..7f1fad0656b2 100644
--- a/services/mcp/src/generated/replay_vision/api.ts
+++ b/services/mcp/src/generated/replay_vision/api.ts
@@ -195,12 +195,12 @@ export const VisionScannersCreateBody = /* @__PURE__ */ zod.object({
.optional()
.describe('LLM provider. v1 is Google-only.\n\n* `google` - Google'),
model: zod
- .enum(['gemini-3-flash-preview', 'gemini-3.1-flash-lite-preview'])
+ .enum(['gemini-2.5-flash', 'gemini-3-flash-preview', 'gemini-3.5-flash'])
.describe(
- '* `gemini-3-flash-preview` - Gemini 3 Flash\n* `gemini-3.1-flash-lite-preview` - Gemini 3 Flash Lite'
+ '* `gemini-2.5-flash` - Gemini 2.5 Flash\n* `gemini-3-flash-preview` - Gemini 3 Flash\n* `gemini-3.5-flash` - Gemini 3.5 Flash'
)
.describe(
- 'Concrete model to use for this scanner.\n\n* `gemini-3-flash-preview` - Gemini 3 Flash\n* `gemini-3.1-flash-lite-preview` - Gemini 3 Flash Lite'
+ 'Concrete model to use for this scanner.\n\n* `gemini-2.5-flash` - Gemini 2.5 Flash\n* `gemini-3-flash-preview` - Gemini 3 Flash\n* `gemini-3.5-flash` - Gemini 3.5 Flash'
),
enabled: zod
.boolean()
@@ -298,13 +298,13 @@ export const VisionScannersPartialUpdateBody = /* @__PURE__ */ zod.object({
.optional()
.describe('LLM provider. v1 is Google-only.\n\n* `google` - Google'),
model: zod
- .enum(['gemini-3-flash-preview', 'gemini-3.1-flash-lite-preview'])
+ .enum(['gemini-2.5-flash', 'gemini-3-flash-preview', 'gemini-3.5-flash'])
.describe(
- '* `gemini-3-flash-preview` - Gemini 3 Flash\n* `gemini-3.1-flash-lite-preview` - Gemini 3 Flash Lite'
+ '* `gemini-2.5-flash` - Gemini 2.5 Flash\n* `gemini-3-flash-preview` - Gemini 3 Flash\n* `gemini-3.5-flash` - Gemini 3.5 Flash'
)
.optional()
.describe(
- 'Concrete model to use for this scanner.\n\n* `gemini-3-flash-preview` - Gemini 3 Flash\n* `gemini-3.1-flash-lite-preview` - Gemini 3 Flash Lite'
+ 'Concrete model to use for this scanner.\n\n* `gemini-2.5-flash` - Gemini 2.5 Flash\n* `gemini-3-flash-preview` - Gemini 3 Flash\n* `gemini-3.5-flash` - Gemini 3.5 Flash'
),
enabled: zod
.boolean()
@@ -534,6 +534,7 @@ export const visionScannersEstimateCreateBodySamplingRateMin = 0
export const visionScannersEstimateCreateBodySamplingRateMax = 1
export const visionScannersEstimateCreateBodySamplingModeDefault = `comprehensive`
+export const visionScannersEstimateCreateBodyModelDefault = `gemini-3-flash-preview`
export const VisionScannersEstimateCreateBody = /* @__PURE__ */ zod
.object({
@@ -560,7 +561,16 @@ export const VisionScannersEstimateCreateBody = /* @__PURE__ */ zod
.string()
.nullish()
.describe(
- "The scanner being edited, excluded from `other_enabled_scanners_monthly` so its stored estimate isn't double-counted in the forecast. Omit (or null) when estimating a brand-new scanner."
+ "The scanner being edited, excluded from `other_enabled_scanners_monthly_credits` so its stored estimate isn't double-counted in the forecast. Omit (or null) when estimating a brand-new scanner."
+ ),
+ model: zod
+ .enum(['gemini-2.5-flash', 'gemini-3-flash-preview', 'gemini-3.5-flash'])
+ .describe(
+ '* `gemini-2.5-flash` - Gemini 2.5 Flash\n* `gemini-3-flash-preview` - Gemini 3 Flash\n* `gemini-3.5-flash` - Gemini 3.5 Flash'
+ )
+ .default(visionScannersEstimateCreateBodyModelDefault)
+ .describe(
+ 'Proposed model; determines `credits_per_observation` in the response.\n\n* `gemini-2.5-flash` - Gemini 2.5 Flash\n* `gemini-3-flash-preview` - Gemini 3 Flash\n* `gemini-3.5-flash` - Gemini 3.5 Flash'
),
})
.describe('Body of POST /vision/scanners/estimate/ — a proposed, unsaved scanner config.')
diff --git a/services/mcp/src/tools/generated/replay_vision.ts b/services/mcp/src/tools/generated/replay_vision.ts
index 4497340b79a9..294e8fae9b8a 100644
--- a/services/mcp/src/tools/generated/replay_vision.ts
+++ b/services/mcp/src/tools/generated/replay_vision.ts
@@ -219,6 +219,9 @@ const visionScannersEstimateCreate = (): ToolBase<
if (params.scanner_id !== undefined) {
body['scanner_id'] = params.scanner_id
}
+ if (params.model !== undefined) {
+ body['model'] = params.model
+ }
const result = await context.api.request<Schemas.EstimateResponse>({
method: 'POST',
path: `/api/projects/${encodeURIComponent(String(projectId))}/vision/scanners/estimate/`,