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): send scanner credit rate in the usage report (#125102)

Tue Haulundb2556dd88228
diff --git a/posthog/tasks/test/test_usage_report.py b/posthog/tasks/test/test_usage_report.py
index 1524ed8114a3..da2470dbf3b4 100644
--- a/posthog/tasks/test/test_usage_report.py
+++ b/posthog/tasks/test/test_usage_report.py
@@ -318,6 +318,7 @@ class TestUsageReport(APIBaseTest, ClickhouseTestMixin, ClickhouseDestroyTablesM
scanner_type=ScannerType.MONITOR,
model=ScannerModel.GEMINI_3_8_FLASH,
enabled=True,
+ estimated_monthly_observations=100,
)
ReplayScanner.objects.create(
team=self.org_1_team_1,
@@ -325,6 +326,7 @@ class TestUsageReport(APIBaseTest, ClickhouseTestMixin, ClickhouseDestroyTablesM
scanner_type=ScannerType.MONITOR,
model=ScannerModel.GEMINI_3_8_FLASH,
enabled=False,
+ estimated_monthly_observations=100,
)
ErrorTrackingIssue.objects.create(team=self.org_1_team_1)
@@ -762,6 +764,8 @@ class TestUsageReport(APIBaseTest, ClickhouseTestMixin, ClickhouseDestroyTablesM
"replay_vision_observation_count_in_period": 0,
"replay_vision_scanner_count": 2,
"replay_vision_scanner_active_count": 1,
+ "replay_vision_scanner_projected_credits": 1100,
+ "replay_vision_backfill_committed_credits": 0,
"group_types_total": 2,
"dashboard_count": 2,
"dashboard_template_count": 0,
@@ -863,6 +867,8 @@ class TestUsageReport(APIBaseTest, ClickhouseTestMixin, ClickhouseDestroyTablesM
"replay_vision_observation_count_in_period": 0,
"replay_vision_scanner_count": 2,
"replay_vision_scanner_active_count": 1,
+ "replay_vision_scanner_projected_credits": 1100,
+ "replay_vision_backfill_committed_credits": 0,
"group_types_total": 2,
"dashboard_count": 2,
"dashboard_template_count": 0,
@@ -958,6 +964,8 @@ class TestUsageReport(APIBaseTest, ClickhouseTestMixin, ClickhouseDestroyTablesM
"replay_vision_observation_count_in_period": 0,
"replay_vision_scanner_count": 0,
"replay_vision_scanner_active_count": 0,
+ "replay_vision_scanner_projected_credits": 0,
+ "replay_vision_backfill_committed_credits": 0,
"group_types_total": 0,
"dashboard_count": 0,
"dashboard_template_count": 0,
@@ -1076,6 +1084,8 @@ class TestUsageReport(APIBaseTest, ClickhouseTestMixin, ClickhouseDestroyTablesM
"replay_vision_observation_count_in_period": 0,
"replay_vision_scanner_count": 0,
"replay_vision_scanner_active_count": 0,
+ "replay_vision_scanner_projected_credits": 0,
+ "replay_vision_backfill_committed_credits": 0,
"group_types_total": 0,
"dashboard_count": 0,
"dashboard_template_count": 0,
@@ -1177,6 +1187,8 @@ class TestUsageReport(APIBaseTest, ClickhouseTestMixin, ClickhouseDestroyTablesM
"replay_vision_observation_count_in_period": 0,
"replay_vision_scanner_count": 0,
"replay_vision_scanner_active_count": 0,
+ "replay_vision_scanner_projected_credits": 0,
+ "replay_vision_backfill_committed_credits": 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 facbc2f97c91..0320f0c0ed8a 100644
--- a/posthog/tasks/usage_report.py
+++ b/posthog/tasks/usage_report.py
@@ -76,6 +76,7 @@ from products.replay_vision.backend.billing import (
get_replay_vision_observations_by_team,
)
from products.replay_vision.backend.models.replay_scanner import ReplayScanner
+from products.replay_vision.backend.quota import unreported_spend_by_org
from products.signals.backend.billing import credited_refund_credits_for_org, get_signals_billing_credits_by_team
from products.surveys.backend.models import Survey
from products.surveys.backend.util import (
@@ -166,6 +167,15 @@ QUERY_RETRY_BACKOFF = 2
# `(team_id, count)` rows, the shape `convert_team_usage_rows_to_dict` reads.
TeamUsageRows = list[tuple[int, int]]
+
+@frozen
+class ReplayVisionSpendProjection:
+ """Each org's Replay vision spend after the report cutoff, on one team so the org report sums to it."""
+
+ scanner_credits: TeamUsageRows
+ backfill_credits: TeamUsageRows
+
+
# Kafka's default `message.max.bytes` is ~1 MiB. For orgs with several hundred
# teams the per-team breakdown under `teams` makes the report payload exceed
# that limit, and the event is dropped at the broker — silently.
@@ -223,6 +233,9 @@ class UsageReportCounters:
replay_vision_observation_count_in_period: int
replay_vision_scanner_count: int
replay_vision_scanner_active_count: int
+ # Enabled scanners' 30-day credit rate. A snapshot, not usage: billing forecasts Replay Vision spend from it.
+ replay_vision_scanner_projected_credits: int
+ replay_vision_backfill_committed_credits: int
# Persons and Groups
group_types_total: int
@@ -1308,6 +1321,38 @@ def get_teams_with_replay_vision_observation_count_in_period(begin: datetime, en
return get_replay_vision_observations_by_team(begin, end)
+@timed_log()
+@retry(tries=QUERY_RETRIES, delay=QUERY_RETRY_DELAY, backoff=QUERY_RETRY_BACKOFF)
+def get_teams_with_replay_vision_spend_projection(begin: datetime, end: datetime) -> ReplayVisionSpendProjection:
+ spend_by_org = unreported_spend_by_org(report_cutoff=end)
+ scanners: TeamUsageRows = []
+ backfills: TeamUsageRows = []
+ if not spend_by_org:
+ return ReplayVisionSpendProjection(scanner_credits=scanners, backfill_credits=backfills)
+ # The projection is org-wide, so each org's value goes on its first billable team only.
+ reported_orgs: set[uuid.UUID] = set()
+ for team in iter_billable_teams(
+ team_fields=("id",), organization_fields=("id",), organization_ids=[str(org_id) for org_id in spend_by_org]
+ ):
+ if team.organization_id in reported_orgs:
+ continue
+ reported_orgs.add(team.organization_id)
+ spend = spend_by_org[team.organization_id]
+ if spend.scanner_credits:
+ scanners.append((team.id, spend.scanner_credits))
+ if spend.backfill_credits:
+ backfills.append((team.id, spend.backfill_credits))
+ return ReplayVisionSpendProjection(scanner_credits=scanners, backfill_credits=backfills)
+
+
+def _replay_vision_spend_projection_rows(begin: datetime, end: datetime) -> dict[str, TeamUsageRows]:
+ projection = get_teams_with_replay_vision_spend_projection(begin, end)
+ return {
+ "teams_with_replay_vision_scanner_projected_credits": projection.scanner_credits,
+ "teams_with_replay_vision_backfill_committed_credits": projection.backfill_credits,
+ }
+
+
@timed_log()
@retry(tries=QUERY_RETRIES, delay=QUERY_RETRY_DELAY, backoff=QUERY_RETRY_BACKOFF)
def get_teams_with_zero_duration_recording_count_in_period(begin: datetime, end: datetime) -> list[tuple[int, int]]:
@@ -3248,6 +3293,7 @@ def _get_all_usage_data(period_start: datetime, period_end: datetime) -> dict[st
"teams_with_replay_vision_scanner_active_count": list(
ReplayScanner.objects.filter(enabled=True).values("team_id").annotate(total=Count("id")).order_by("team_id")
),
+ **_replay_vision_spend_projection_rows(period_start, period_end),
"teams_with_issues_created_total": [
{"team_id": team_id, "total": total} for team_id, total in error_tracking_api.get_issue_counts_by_team()
],
@@ -3475,6 +3521,12 @@ def _get_team_report(all_data: dict[str, Any], team: Team) -> UsageReportCounter
),
replay_vision_scanner_count=all_data["teams_with_replay_vision_scanner_count"].get(team.id, 0),
replay_vision_scanner_active_count=all_data["teams_with_replay_vision_scanner_active_count"].get(team.id, 0),
+ replay_vision_scanner_projected_credits=all_data["teams_with_replay_vision_scanner_projected_credits"].get(
+ team.id, 0
+ ),
+ replay_vision_backfill_committed_credits=all_data["teams_with_replay_vision_backfill_committed_credits"].get(
+ team.id, 0
+ ),
group_types_total=all_data["teams_with_group_types_total"].get(team.id, 0),
decide_requests_count_in_period=decide_requests_count_in_period,
local_evaluation_requests_count_in_period=local_evaluation_requests_count_in_period,
diff --git a/posthog/temporal/tests/usage_report/test_aggregator.py b/posthog/temporal/tests/usage_report/test_aggregator.py
index bb578fb67cfe..ff3907ad9fbc 100644
--- a/posthog/temporal/tests/usage_report/test_aggregator.py
+++ b/posthog/temporal/tests/usage_report/test_aggregator.py
@@ -27,6 +27,7 @@ from posthog.temporal.tests.usage_report.test_aggregate_activity import _instanc
from posthog.temporal.usage_report.aggregator import (
add_pre_logs_distinct_patterns_patch_defaults,
add_pre_mcp_event_count_patch_defaults,
+ add_pre_replay_vision_spend_projection_patch_defaults,
add_pre_sandbox_compute_patch_defaults,
add_pre_transactional_emails_patch_defaults,
build_manifest,
@@ -190,6 +191,22 @@ def test_load_all_data_defaults_single_query_for_pre_patch_workflow_history(
assert patched_data == {query_name: {1: 2}}
+def test_load_all_data_defaults_replay_vision_spend_projection_for_pre_patch_workflow_history() -> None:
+ all_data: dict[str, dict[int, int]] = {}
+ add_pre_replay_vision_spend_projection_patch_defaults(all_data, [])
+
+ assert all_data == {
+ "teams_with_replay_vision_scanner_projected_credits": {},
+ "teams_with_replay_vision_backfill_committed_credits": {},
+ }
+
+ patched_data: dict[str, dict[int, int]] = {}
+ results = [RunQueryToS3Result(query_name="replay_vision_spend_projection", s3_key="unused", duration_ms=1)]
+ add_pre_replay_vision_spend_projection_patch_defaults(patched_data, results)
+
+ assert patched_data == {}
+
+
def test_load_all_data_does_not_default_compute_for_patched_workflow_history() -> None:
all_data: dict[str, dict[int, int]] = {}
results = [RunQueryToS3Result(query_name="sandbox_compute_usage", s3_key="unused", duration_ms=1)]
diff --git a/posthog/temporal/tests/usage_report/test_workflow.py b/posthog/temporal/tests/usage_report/test_workflow.py
index 8e6133e60b9b..94652baea726 100644
--- a/posthog/temporal/tests/usage_report/test_workflow.py
+++ b/posthog/temporal/tests/usage_report/test_workflow.py
@@ -51,12 +51,14 @@ from posthog.temporal.usage_report.workflow import (
MCP_EVENT_COUNT_QUERY_NAME,
PARALLEL_COUNTER_QUERIES_PATCH_ID,
QUERY_CONCURRENCY,
+ REPLAY_VISION_SPEND_PROJECTION_QUERY_NAME,
SANDBOX_COMPUTE_QUERY_NAME,
TRANSACTIONAL_EMAILS_QUERY_NAME,
USAGE_COUNTER_SERVICE_PATCH_ID,
RunUsageReportsWorkflow,
_queries_for_logs_distinct_patterns_patch,
_queries_for_mcp_event_count_patch,
+ _queries_for_replay_vision_spend_projection_patch,
_queries_for_sandbox_compute_patch,
_queries_for_transactional_emails_patch,
build_context,
@@ -80,6 +82,11 @@ def test_sandbox_compute_query_is_versioned_for_existing_histories() -> None:
("logs_distinct_patterns", _queries_for_logs_distinct_patterns_patch, LOGS_DISTINCT_PATTERNS_QUERY_NAME),
("transactional_emails", _queries_for_transactional_emails_patch, TRANSACTIONAL_EMAILS_QUERY_NAME),
("mcp_event_count", _queries_for_mcp_event_count_patch, MCP_EVENT_COUNT_QUERY_NAME),
+ (
+ "replay_vision_spend_projection",
+ _queries_for_replay_vision_spend_projection_patch,
+ REPLAY_VISION_SPEND_PROJECTION_QUERY_NAME,
+ ),
]
)
def test_single_query_is_versioned_for_existing_histories(
diff --git a/posthog/temporal/usage_report/activities.py b/posthog/temporal/usage_report/activities.py
index 09c73caa06bd..637f26cc898d 100644
--- a/posthog/temporal/usage_report/activities.py
+++ b/posthog/temporal/usage_report/activities.py
@@ -28,6 +28,7 @@ from posthog.temporal.common.metrics import ExecutionTimeRecorder
from posthog.temporal.usage_report.aggregator import (
add_pre_logs_distinct_patterns_patch_defaults,
add_pre_mcp_event_count_patch_defaults,
+ add_pre_replay_vision_spend_projection_patch_defaults,
add_pre_sandbox_compute_patch_defaults,
add_pre_transactional_emails_patch_defaults,
get_org_user_counts,
@@ -252,6 +253,7 @@ async def aggregate_and_chunk_org_reports(inputs: AggregateInputs) -> AggregateR
add_pre_logs_distinct_patterns_patch_defaults(all_data, inputs.query_results)
add_pre_transactional_emails_patch_defaults(all_data, inputs.query_results)
add_pre_mcp_event_count_patch_defaults(all_data, inputs.query_results)
+ add_pre_replay_vision_spend_projection_patch_defaults(all_data, inputs.query_results)
check_cancelled()
counter_report = load_usage_counter_report(inputs)
all_data.update({field: dict(rows) for field, rows in counter_report.counts.items()})
diff --git a/posthog/temporal/usage_report/aggregator.py b/posthog/temporal/usage_report/aggregator.py
index 3f934528f1f4..896de5da6741 100644
--- a/posthog/temporal/usage_report/aggregator.py
+++ b/posthog/temporal/usage_report/aggregator.py
@@ -61,6 +61,11 @@ _SANDBOX_COMPUTE_DESTINATION_KEYS = (
_LOGS_DISTINCT_PATTERNS_QUERY_NAME = "teams_with_logs_distinct_patterns_in_period"
_TRANSACTIONAL_EMAILS_QUERY_NAME = "teams_with_workflow_transactional_emails_sent_in_period"
_MCP_EVENT_COUNT_QUERY_NAME = "teams_with_mcp_event_count_in_period"
+_REPLAY_VISION_SPEND_PROJECTION_QUERY_NAME = "replay_vision_spend_projection"
+_REPLAY_VISION_SPEND_PROJECTION_DESTINATION_KEYS = (
+ "teams_with_replay_vision_scanner_projected_credits",
+ "teams_with_replay_vision_backfill_committed_credits",
+)
def load_usage_counter_report(inputs: AggregateInputs) -> UsageCounterReport:
@@ -121,6 +126,14 @@ def add_pre_mcp_event_count_patch_defaults(
all_data[_MCP_EVENT_COUNT_QUERY_NAME] = {}
+def add_pre_replay_vision_spend_projection_patch_defaults(
+ all_data: dict[str, dict[int, int]], query_results: list[RunQueryToS3Result]
+) -> None:
+ if not any(result.query_name == _REPLAY_VISION_SPEND_PROJECTION_QUERY_NAME for result in query_results):
+ for key in _REPLAY_VISION_SPEND_PROJECTION_DESTINATION_KEYS:
+ all_data[key] = {}
+
+
def iter_chunk_lines(
org_reports: Iterable[OrgReport],
instance_metadata: InstanceMetadata,
diff --git a/posthog/temporal/usage_report/queries.py b/posthog/temporal/usage_report/queries.py
index ec23f4428699..3c350342ff0d 100644
--- a/posthog/temporal/usage_report/queries.py
+++ b/posthog/temporal/usage_report/queries.py
@@ -47,6 +47,7 @@ from django.db.models import Count
from posthog.models.group_type_mapping import count_group_type_mappings_per_team
from posthog.tasks.usage_report import (
+ TeamUsageRows,
get_all_event_metrics_in_period,
get_teams_with_active_batch_exports_in_period,
get_teams_with_active_external_data_schemas_in_period,
@@ -82,6 +83,7 @@ from posthog.tasks.usage_report import (
get_teams_with_recording_count_in_period,
get_teams_with_replay_vision_credits_used_in_period,
get_teams_with_replay_vision_observation_count_in_period,
+ get_teams_with_replay_vision_spend_projection,
get_teams_with_rows_exported_in_period,
get_teams_with_rows_synced_in_period,
get_teams_with_sdk_logs_records_in_period,
@@ -229,6 +231,14 @@ def _task_sandbox_usage(begin: datetime, end: datetime) -> dict[str, list[tuple[
}
+def _replay_vision_spend_projection(begin: datetime, end: datetime) -> dict[str, TeamUsageRows]:
+ projection = get_teams_with_replay_vision_spend_projection(begin, end)
+ return {
+ "scanner_credits": projection.scanner_credits,
+ "backfill_credits": projection.backfill_credits,
+ }
+
+
def _sandbox_compute_usage(begin: datetime, end: datetime) -> dict[str, list[tuple[int, int]]]:
usage = get_teams_with_billable_sandbox_compute_usage_in_period(begin, end)
return {
@@ -732,6 +742,16 @@ QUERIES: list[QuerySpec] = [
timeout_minutes=5,
kind="snapshot",
),
+ QuerySpec(
+ name="replay_vision_spend_projection",
+ fn=_replay_vision_spend_projection,
+ timeout_minutes=5,
+ output="multi",
+ multi_keys_mapping={
+ "scanner_credits": "teams_with_replay_vision_scanner_projected_credits",
+ "backfill_credits": "teams_with_replay_vision_backfill_committed_credits",
+ },
+ ),
QuerySpec(
name="teams_with_issues_created_total",
fn=_issues_created_total,
diff --git a/posthog/temporal/usage_report/workflow.py b/posthog/temporal/usage_report/workflow.py
index 200c26a0efc0..1bbe1be09fe7 100644
--- a/posthog/temporal/usage_report/workflow.py
+++ b/posthog/temporal/usage_report/workflow.py
@@ -62,6 +62,8 @@ TRANSACTIONAL_EMAILS_QUERY_PATCH_ID = "usage-report-transactional-emails-query-2
TRANSACTIONAL_EMAILS_QUERY_NAME = "teams_with_workflow_transactional_emails_sent_in_period"
MCP_EVENT_COUNT_QUERY_PATCH_ID = "usage-report-mcp-event-count-query-2026-10"
MCP_EVENT_COUNT_QUERY_NAME = "teams_with_mcp_event_count_in_period"
+REPLAY_VISION_SPEND_PROJECTION_QUERY_PATCH_ID = "usage-report-replay-vision-spend-projection-query-2026-10"
+REPLAY_VISION_SPEND_PROJECTION_QUERY_NAME = "replay_vision_spend_projection"
def _queries_for_sandbox_compute_patch(patch_applied: bool) -> list[QuerySpec]:
@@ -88,6 +90,12 @@ def _queries_for_mcp_event_count_patch(queries: list[QuerySpec], patch_applied:
return [spec for spec in queries if spec.name != MCP_EVENT_COUNT_QUERY_NAME]
+def _queries_for_replay_vision_spend_projection_patch(queries: list[QuerySpec], patch_applied: bool) -> list[QuerySpec]:
+ if patch_applied:
+ return queries
+ return [spec for spec in queries if spec.name != REPLAY_VISION_SPEND_PROJECTION_QUERY_NAME]
+
+
def build_context(inputs: RunUsageReportsInputs, run_id: str, now: datetime) -> WorkflowContext:
"""Compute the period and S3 layout context. Pure function so it's safe
to call from the workflow body (no real-time access).
@@ -155,6 +163,9 @@ class RunUsageReportsWorkflow(PostHogWorkflow):
queries, workflow.patched(TRANSACTIONAL_EMAILS_QUERY_PATCH_ID)
)
queries = _queries_for_mcp_event_count_patch(queries, workflow.patched(MCP_EVENT_COUNT_QUERY_PATCH_ID))
+ queries = _queries_for_replay_vision_spend_projection_patch(
+ queries, workflow.patched(REPLAY_VISION_SPEND_PROJECTION_QUERY_PATCH_ID)
+ )
if workflow.patched(USAGE_COUNTER_SERVICE_PATCH_ID):
ctx.usage_counter_plan = await workflow.execute_activity(
plan_usage_counters,
diff --git a/products/replay_vision/backend/api/quota.py b/products/replay_vision/backend/api/quota.py
index 09d44e853d39..9e62151bb9e2 100644
--- a/products/replay_vision/backend/api/quota.py
+++ b/products/replay_vision/backend/api/quota.py
@@ -77,6 +77,13 @@ class VisionQuotaSerializer(serializers.Serializer):
"Scanners without a computed estimate contribute 0."
),
)
+ scanners_period_credits = serializers.IntegerField(
+ read_only=True,
+ help_text=(
+ "The part of `scanners_monthly_credits` that lands between now and `period_end`. "
+ "Use it for rest-of-period forecasts; billing forecasts from the same figure."
+ ),
+ )
backfills_committed_credits = serializers.IntegerField(
read_only=True,
help_text=(
diff --git a/products/replay_vision/backend/quota.py b/products/replay_vision/backend/quota.py
index 739b1a243872..683dc8d84e18 100644
--- a/products/replay_vision/backend/quota.py
+++ b/products/replay_vision/backend/quota.py
@@ -139,6 +139,9 @@ class SpendProjection:
scanners_monthly_credits: int
# Committed-but-unspent credits of active backfills. A one-off charge, not a rate.
backfills_committed_credits: int
+ # The scanners' share of that rate that lands before the period ends: the one rest-of-period figure
+ # the meters, the spend chart and billing's forecast all read.
+ scanners_period_credits: int = 0
# The monthly rate the free credits still cover after the other free-only scanners and backfills.
# Only the editor's forecast asks for it, so it is None unless requested.
free_only_monthly_credits_left: int | None = None
@@ -155,6 +158,7 @@ class QuotaSnapshot(QuotaState):
projected_monthly_credits: int = 0
scanners_monthly_credits: int = 0
backfills_committed_credits: int = 0
+ scanners_period_credits: int = 0
def next_month_start(now: datetime) -> datetime:
@@ -556,6 +560,12 @@ def _billing_synced_limit(organization: Organization | None) -> tuple[bool, int
return False, None
+def _monthly_rate_to_period_credits(monthly_credits: float, period_end: datetime, now: datetime) -> int:
+ """The part of a 30-day credit rate that lands between `now` and `period_end`."""
+ days_left = max((period_end - now).total_seconds() / 86400, 0)
+ return round(max(monthly_credits, 0) * days_left / ESTIMATE_MONTH_DAYS)
+
+
def spend_projection(
organization_id: UUID,
exclude_scanner_id: UUID | None = None,
@@ -594,13 +604,66 @@ def spend_projection(
pool_rate = _remaining_as_monthly_rate(pool, datetime.now(UTC))
# Past the period end there is no rate to share, and an unbounded rate leaves nothing to cap.
free_left = max(0, round(pool_rate - rates.free_only)) if math.isfinite(pool_rate) else 0
+ period_end = org_state.period_end if org_state else current_period_bounds(organization_id).end
return SpendProjection(
scanners_monthly_credits=rates.total,
backfills_committed_credits=backfills.paid + free_only_backfills,
+ scanners_period_credits=_monthly_rate_to_period_credits(rates.total, period_end, datetime.now(UTC)),
free_only_monthly_credits_left=free_left,
)
+@frozen
+class UnreportedSpend:
+ """An org's spend that a usage report has not counted yet, through to the period end."""
+
+ # Credits, not a rate, so billing needs no clock.
+ scanner_credits: int
+ backfill_credits: int
+
+
+def unreported_spend_by_org(report_cutoff: datetime) -> dict[UUID, UnreportedSpend]:
+ """Every org's spend after a usage report's cutoff, for billing's forecast.
+
+ The report counts receipts up to its cutoff, but the projection starts now. The spend in between,
+ receipts since the cutoff and in-flight reservations, goes onto the scanner figure.
+ """
+ receipts = ReplayObservationUsage.objects.filter(created_at__gte=report_cutoff)
+ # An org that switched its last scanner off after the cutoff still has that spend to report.
+ org_ids = (
+ set(ReplayScanner.objects.filter(enabled=True).values_list("team__organization_id", flat=True))
+ | set(
+ ReplayScannerBackfill.objects.unscoped()
+ .filter(status__in=ACTIVE_BACKFILL_STATUSES)
+ .values_list("team__organization_id", flat=True)
+ )
+ | set(
+ ReplayObservation.objects.filter(status__in=IN_FLIGHT_STATUSES).values_list(
+ "team__organization_id", flat=True
+ )
+ )
+ | set(receipts.values_list("organization_id", flat=True).distinct())
+ )
+ # Reservations read BEFORE receipts: an observation settling between the two is counted twice, never zero times.
+ states = {org_id: quota_state(org_id) for org_id in org_ids}
+ receipts_since_cutoff = dict(
+ receipts.filter(organization_id__in=org_ids)
+ .values("organization_id")
+ .annotate(total=Sum("credits"))
+ .values_list("organization_id", "total")
+ )
+ result: dict[UUID, UnreportedSpend] = {}
+ for org_id, state in states.items():
+ projection = spend_projection(org_id, org_state=state)
+ result[org_id] = UnreportedSpend(
+ scanner_credits=projection.scanners_period_credits
+ + (receipts_since_cutoff.get(org_id) or 0)
+ + state.credits_reserved,
+ backfill_credits=projection.backfills_committed_credits,
+ )
+ return result
+
+
@frozen
class OrgCreditCap:
"""The org's credit limit and the billing period it applies to, read without any spend aggregates."""
@@ -715,6 +778,7 @@ def compute_quota_snapshot(organization_id: UUID) -> QuotaSnapshot:
projected_monthly_credits=projection.total,
scanners_monthly_credits=projection.scanners_monthly_credits,
backfills_committed_credits=projection.backfills_committed_credits,
+ scanners_period_credits=projection.scanners_period_credits,
)
diff --git a/products/replay_vision/backend/tests/test_quota.py b/products/replay_vision/backend/tests/test_quota.py
index 149c3386be87..a42d4c8a9e40 100644
--- a/products/replay_vision/backend/tests/test_quota.py
+++ b/products/replay_vision/backend/tests/test_quota.py
@@ -841,6 +841,40 @@ class TestProjectedMonthlyObservations(_VisionQuotaTestCase):
snapshot = compute_quota_snapshot(organization_id=self.organization.id)
assert snapshot.projected_monthly_credits == 0
+ def test_unreported_spend_adds_spend_after_the_report_cutoff(self) -> None:
+ ReplayScanner.objects.filter(pk=self.scanner.pk).update(enabled=True)
+ self._make_scanner(team=self.team, name="paid", estimate=100) # 100 × 15 credits
+ quiet_org = Organization.objects.create(name="quiet-org")
+ quiet_team = Team.objects.create(organization=quiet_org, name="quiet-team")
+ self._make_scanner(team=quiet_team, name="off", enabled=False, estimate=999)
+ switched_off_org = Organization.objects.create(name="switched-off-org")
+ switched_off_team = Team.objects.create(organization=switched_off_org, name="switched-off-team")
+ switched_off = ReplayScanner.objects.create(
+ team=switched_off_team, name="was-on", scanner_type=ScannerType.MONITOR, scanner_config={"prompt": "p"}
+ )
+ with time_machine.travel("2026-09-15T12:00:00Z", tick=False):
+ self._make_observation(status=ObservationStatus.SUCCEEDED, completed_at=timezone.now())
+ with time_machine.travel("2026-09-16T03:00:00Z", tick=False):
+ self._make_observation(status=ObservationStatus.SUCCEEDED, completed_at=timezone.now())
+ self._make_observation(status=ObservationStatus.RUNNING)
+ seed_scanner_spend(switched_off, 30)
+ with patch.object(
+ quota,
+ "_sum_active_backfill_remaining_credits",
+ side_effect=lambda org_id: quota.BackfillCommitments(
+ paid=400 if org_id == self.organization.id else 0, free_only=0
+ ),
+ ):
+ spend = quota.unreported_spend_by_org(report_cutoff=datetime(2026, 9, 16, tzinfo=UTC))
+
+ # The 15-credit receipt and reservation after midnight count; the receipt before it is in the report.
+ assert spend == {
+ self.organization.id: quota.UnreportedSpend(
+ scanner_credits=round(1500 * (14 + 21 / 24) / 30) + 15 + 15, backfill_credits=400
+ ),
+ switched_off_org.id: quota.UnreportedSpend(scanner_credits=30, backfill_credits=0),
+ }
+
class TestVisionQuotaEndpoint(_VisionQuotaTestCase):
@property
diff --git a/products/replay_vision/frontend/components/PlayerSidebarObservationsTab.stories.tsx b/products/replay_vision/frontend/components/PlayerSidebarObservationsTab.stories.tsx
index 5c52786567b4..37fc739717fc 100644
--- a/products/replay_vision/frontend/components/PlayerSidebarObservationsTab.stories.tsx
+++ b/products/replay_vision/frontend/components/PlayerSidebarObservationsTab.stories.tsx
@@ -32,6 +32,7 @@ const quota = {
exhausted: false,
projected_monthly_credits: 5200,
scanners_monthly_credits: 5200,
+ scanners_period_credits: 5200,
backfills_committed_credits: 0,
free_monthly_credits: 2500,
credits_settled: 2400,
diff --git a/products/replay_vision/frontend/generated/api.schemas.ts b/products/replay_vision/frontend/generated/api.schemas.ts
index 467ce554cb06..3efb3b28feca 100644
--- a/products/replay_vision/frontend/generated/api.schemas.ts
+++ b/products/replay_vision/frontend/generated/api.schemas.ts
@@ -971,6 +971,8 @@ export interface VisionQuotaApi {
readonly projected_monthly_credits: number
/** Credit-weighted sum of enabled scanners' projected observations/month across the organization. A capped scanner contributes at most what its own credit limit has left this period, folded back into a 30-day rate. A monthly rate: only the part falling in the days left of the period lands this period. Scanners without a computed estimate contribute 0. */
readonly scanners_monthly_credits: number
+ /** The part of `scanners_monthly_credits` that lands between now and `period_end`. Use it for rest-of-period forecasts; billing forecasts from the same figure. */
+ readonly scanners_period_credits: number
/** Committed-but-unspent credits of the organization's active backfills. A one-off charge rather than a rate, so it lands in full regardless of how much of the period is left. */
readonly backfills_committed_credits: number
/** Credits per period included for free. Already counted inside `credit_limit`; only credits beyond this number are billed. */
diff --git a/products/replay_vision/frontend/logics/visionQuotaLogic.ts b/products/replay_vision/frontend/logics/visionQuotaLogic.ts
index 7797671f5349..7414dda85edd 100644
--- a/products/replay_vision/frontend/logics/visionQuotaLogic.ts
+++ b/products/replay_vision/frontend/logics/visionQuotaLogic.ts
@@ -9,7 +9,13 @@ import type { BillingType } from '~/types'
import { environmentVisionQuotaRetrieve } from '../generated/api'
import type { VisionQuotaApi } from '../generated/api.schemas'
import { billableCredits } from '../utils/credits'
-import { freeCreditsAllowance, freeCreditsLeft, hasBillableSpend, isFreeAllocationOnly } from '../utils/quotaProjection'
+import {
+ freeCreditsAllowance,
+ freeCreditsLeft,
+ hasBillableSpend,
+ isFreeAllocationOnly,
+ periodShareOfMonthlyRate,
+} from '../utils/quotaProjection'
import { applyStartupCap, startupCapCredits } from '../utils/startupCap'
// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
@@ -126,6 +132,10 @@ export const visionQuotaLogic = kea<visionQuotaLogicType>([
...state,
// Meters project from the scanner rate, so the headline total and the rate move together.
scanners_monthly_credits: Math.max(0, state.scanners_monthly_credits + delta),
+ scanners_period_credits: Math.max(
+ 0,
+ state.scanners_period_credits + periodShareOfMonthlyRate(state, delta)
+ ),
projected_monthly_credits: Math.max(0, state.projected_monthly_credits + delta),
}
: state,
diff --git a/products/replay_vision/frontend/replay_scanners/ReplayScannersScene.stories.tsx b/products/replay_vision/frontend/replay_scanners/ReplayScannersScene.stories.tsx
index 6808f1cb3d95..d0c4570e3998 100644
--- a/products/replay_vision/frontend/replay_scanners/ReplayScannersScene.stories.tsx
+++ b/products/replay_vision/frontend/replay_scanners/ReplayScannersScene.stories.tsx
@@ -173,6 +173,7 @@ const quota: VisionQuotaApi = {
exhausted: false,
projected_monthly_credits: 5200,
scanners_monthly_credits: 5200,
+ scanners_period_credits: 3467,
backfills_committed_credits: 0,
free_monthly_credits: 2500,
credits_settled: 2400,
diff --git a/products/replay_vision/frontend/replay_scanners/components/SpendTrajectoryChart.stories.tsx b/products/replay_vision/frontend/replay_scanners/components/SpendTrajectoryChart.stories.tsx
index 6abbd2b9061b..1fc4d2162e1f 100644
--- a/products/replay_vision/frontend/replay_scanners/components/SpendTrajectoryChart.stories.tsx
+++ b/products/replay_vision/frontend/replay_scanners/components/SpendTrajectoryChart.stories.tsx
@@ -35,6 +35,7 @@ const quota: VisionQuotaApi = {
exhausted: false,
projected_monthly_credits: 5_200,
scanners_monthly_credits: 5_200,
+ scanners_period_credits: 3_467,
backfills_committed_credits: 0,
free_monthly_credits: 2_500,
credits_settled: 2_400,
@@ -60,7 +61,12 @@ export const OnTrack: Story = {
export const HitsTheLimit: Story = {
args: {
- quota: { ...quota, scanners_monthly_credits: 16_000, projected_monthly_credits: 16_000 },
+ quota: {
+ ...quota,
+ scanners_monthly_credits: 16_000,
+ scanners_period_credits: 10_667,
+ projected_monthly_credits: 16_000,
+ },
dailyCredits,
projectedTotal: 10_000,
capReachDate: dayjs.utc('2026-05-26T12:00:00Z'),
diff --git a/products/replay_vision/frontend/utils/quotaContributions.test.ts b/products/replay_vision/frontend/utils/quotaContributions.test.ts
index e5f997c1ec13..8b5b17cb2424 100644
--- a/products/replay_vision/frontend/utils/quotaContributions.test.ts
+++ b/products/replay_vision/frontend/utils/quotaContributions.test.ts
@@ -1,5 +1,5 @@
import type { VisionQuotaApi } from '../generated/api.schemas'
-import { type QuotaContribution, buildQuotaMeter } from './quotaContributions'
+import { type QuotaContribution, buildQuotaMeter, fleetContributions } from './quotaContributions'
const HALF_PERIOD_QUOTA: VisionQuotaApi = {
credit_limit: 1000,
@@ -9,6 +9,7 @@ const HALF_PERIOD_QUOTA: VisionQuotaApi = {
free_monthly_credits: 0,
projected_monthly_credits: 400,
scanners_monthly_credits: 400,
+ scanners_period_credits: 200,
backfills_committed_credits: 0,
// 15 of 30 days are left, so a 30-day rate lands at half value and a one-off lands whole.
period_start: '2026-04-17T00:00:00Z',
@@ -63,6 +64,13 @@ describe('quotaContributions', () => {
expect(model.periodEndPct).toBe(Math.round(drawn))
})
+ it('uses the backend rest-of-period credits for the fleet, the figure billing forecasts from', () => {
+ // A capped scanner leaves less than the pro-rated rate, and only the backend knows that.
+ const quota = { ...HALF_PERIOD_QUOTA, scanners_period_credits: 50 }
+ const model = buildQuotaMeter(quota, fleetContributions(quota))
+ expect(model.periodEndCredits).toBe(100 + 50)
+ })
+
it('reports no cap and zero-width segments for an uncapped org', () => {
const model = buildQuotaMeter({ ...HALF_PERIOD_QUOTA, credit_limit: null } as VisionQuotaApi, [
contribution({ key: 'backfill', credits: 500, kind: 'one-off' }),
diff --git a/products/replay_vision/frontend/utils/quotaContributions.ts b/products/replay_vision/frontend/utils/quotaContributions.ts
index e8c0304d3393..1344aedb82b9 100644
--- a/products/replay_vision/frontend/utils/quotaContributions.ts
+++ b/products/replay_vision/frontend/utils/quotaContributions.ts
@@ -28,6 +28,8 @@ export interface QuotaContribution {
label: string
credits: number
kind: 'monthly-rate' | 'one-off'
+ /** For a monthly rate: the backend's share of it before the period ends, the figure billing also uses. */
+ periodCredits?: number
barClass: string
striped?: boolean
}
@@ -72,6 +74,7 @@ export function fleetContributions(quota: VisionQuotaApi | null): QuotaContribut
label: 'Projected (scanners)',
credits: quota?.scanners_monthly_credits ?? 0,
kind: 'monthly-rate',
+ periodCredits: quota?.scanners_period_credits ?? 0,
barClass: QUOTA_STATUS_CLASS,
striped: true,
},
@@ -90,8 +93,15 @@ export function buildQuotaMeter(quota: VisionQuotaApi | null, contributions: Quo
const cap = hasCap ? quota.credit_limit : 0
const rateTotal = contributions.reduce((sum, c) => (c.kind === 'monthly-rate' ? sum + c.credits : sum), 0)
const oneOffTotal = contributions.reduce((sum, c) => (c.kind === 'one-off' ? sum + c.credits : sum), 0)
+ const rates = contributions.filter((c) => c.kind === 'monthly-rate')
+ // Use the backend's rest-of-period figure whenever every rate carries one, so this matches billing.
+ const ratePeriodCredits =
+ rates.length > 0 && rates.every((c) => c.periodCredits !== undefined)
+ ? rates.reduce((sum, c) => sum + (c.periodCredits ?? 0), 0)
+ : undefined
+ const inputs = { monthlyRateCredits: rateTotal, oneOffCredits: oneOffTotal, ratePeriodCredits }
// The contributions are the whole projection, so the stored fleet rate is not consulted here.
- const projection = projectQuota(quota, { monthlyRateCredits: rateTotal, oneOffCredits: oneOffTotal })
+ const projection = projectQuota(quota, inputs)
const asPct = (credits: number): number => (hasCap && cap > 0 ? (credits / cap) * 100 : 0)
const segments = contributions.map((c) => ({
@@ -130,9 +140,7 @@ export function buildQuotaMeter(quota: VisionQuotaApi | null, contributions: Quo
: segment
),
periodEndPct,
- periodEndCredits: quota
- ? Math.round(projectDemandCredits(quota, { monthlyRateCredits: rateTotal, oneOffCredits: oneOffTotal }))
- : null,
+ periodEndCredits: quota ? Math.round(projectDemandCredits(quota, inputs)) : null,
rateTotal,
oneOffTotal,
hasCap,
diff --git a/products/replay_vision/frontend/utils/quotaProjection.ts b/products/replay_vision/frontend/utils/quotaProjection.ts
index 36751f02b4ac..5aa73d47f65e 100644
--- a/products/replay_vision/frontend/utils/quotaProjection.ts
+++ b/products/replay_vision/frontend/utils/quotaProjection.ts
@@ -97,15 +97,32 @@ export function isFreeAllocationOnly(quota: VisionQuotaApi | null): boolean {
export interface ProjectionInputs {
/** Fleet rate in credits per 30 days; defaults to the quota's stored `scanners_monthly_credits`. */
monthlyRateCredits?: number
+ /** `monthlyRateCredits` already pro-rated to the period end by the backend, which then wins. */
+ ratePeriodCredits?: number
/** Charged once (backfills), so they count toward the cap-reach date but not the rate. */
oneOffCredits?: number
}
-/** Credits the period ends on: spend so far, the rate pro-rated over the days left, and the one-offs. Unclamped. */
+/** Credits the period ends on: spend so far, the scanners' rest-of-period credits, and the one-offs. Unclamped. */
export function projectDemandCredits(quota: VisionQuotaApi, inputs: ProjectionInputs = {}): number {
+ return quota.credits_used + scannerPeriodCredits(quota, inputs) + Math.max(inputs.oneOffCredits ?? 0, 0)
+}
+
+/** The backend's rest-of-period figure, which billing also forecasts from; a what-if rate pro-rates locally. */
+function scannerPeriodCredits(quota: VisionQuotaApi, inputs: ProjectionInputs): number {
+ if (inputs.ratePeriodCredits !== undefined) {
+ return Math.max(inputs.ratePeriodCredits, 0)
+ }
+ if (inputs.monthlyRateCredits === undefined) {
+ return quota.scanners_period_credits
+ }
+ return periodShareOfMonthlyRate(quota, Math.max(inputs.monthlyRateCredits, 0))
+}
+
+/** The part of a 30-day rate that lands before the period ends, for rates the backend has not seen yet. */
+export function periodShareOfMonthlyRate(quota: VisionQuotaApi, monthlyCredits: number): number {
const daysRemaining = Math.max(dayjs.utc(quota.period_end).diff(dayjs(), 'day', true), 0)
- const rate = Math.max(inputs.monthlyRateCredits ?? quota.scanners_monthly_credits, 0) / ESTIMATE_MONTH_DAYS
- return quota.credits_used + rate * daysRemaining + Math.max(inputs.oneOffCredits ?? 0, 0)
+ return (monthlyCredits / ESTIMATE_MONTH_DAYS) * daysRemaining
}
/** Project credit spend to period end from a fleet rate and the one-offs already committed. */
diff --git a/products/replay_vision/frontend/utils/quotaTestUtils.ts b/products/replay_vision/frontend/utils/quotaTestUtils.ts
index 4996e31cbe00..d9f3f3509eca 100644
--- a/products/replay_vision/frontend/utils/quotaTestUtils.ts
+++ b/products/replay_vision/frontend/utils/quotaTestUtils.ts
@@ -4,7 +4,7 @@ import type { VisionQuotaApi } from '../generated/api.schemas'
export function makeQuota(overrides: Partial<VisionQuotaApi> = {}): VisionQuotaApi {
const now = new Date()
const daysFromNow = (days: number): string => new Date(now.getTime() + days * 24 * 3600 * 1000).toISOString()
- return {
+ const quota: VisionQuotaApi = {
credit_limit: 10_000,
credits_used: 0,
credits_settled: 0,
@@ -17,6 +17,11 @@ export function makeQuota(overrides: Partial<VisionQuotaApi> = {}): VisionQuotaA
free_monthly_credits: 2500,
period_start: daysFromNow(-10),
period_end: daysFromNow(20),
+ scanners_period_credits: 0,
...overrides,
}
+ // The backend pro-rates the rate to the 20 days left; keep the fixture consistent unless a test overrides it.
+ return 'scanners_period_credits' in overrides
+ ? quota
+ : { ...quota, scanners_period_credits: (quota.scanners_monthly_credits * 20) / 30 }
}
diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.ts
index 542525210de6..2101cca20e89 100644
--- a/services/mcp/src/api/generated.ts
+++ b/services/mcp/src/api/generated.ts
@@ -124144,6 +124144,8 @@ export namespace Schemas {
readonly projected_monthly_credits: number;
/** Credit-weighted sum of enabled scanners' projected observations/month across the organization. A capped scanner contributes at most what its own credit limit has left this period, folded back into a 30-day rate. A monthly rate: only the part falling in the days left of the period lands this period. Scanners without a computed estimate contribute 0. */
readonly scanners_monthly_credits: number;
+ /** The part of `scanners_monthly_credits` that lands between now and `period_end`. Use it for rest-of-period forecasts; billing forecasts from the same figure. */
+ readonly scanners_period_credits: number;
/** Committed-but-unspent credits of the organization's active backfills. A one-off charge rather than a rate, so it lands in full regardless of how much of the period is left. */
readonly backfills_committed_credits: number;
/** Credits per period included for free. Already counted inside `credit_limit`; only credits beyond this number are billed. */