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): monthly observation quota (#60357)

Tue Haulundfc2985574ecf
diff --git a/posthog/api/__init__.py b/posthog/api/__init__.py
index 7885c2ae2e50..b69971dc1e98 100644
--- a/posthog/api/__init__.py
+++ b/posthog/api/__init__.py
@@ -121,6 +121,7 @@ from products.replay_vision.backend.api import (
ReplayObservationViewSet,
ReplayScannerViewSet,
SessionReplayObservationViewSet,
+ VisionQuotaViewSet,
)
from products.signals.backend.views import SignalViewSet
from products.tracing.backend.presentation.views import SpansViewSet as TracingSpansViewSet
@@ -1679,6 +1680,12 @@ environments_router.register(
"environment_vision_observations",
["team_id"],
)
+environments_router.register(
+ r"vision/quota",
+ VisionQuotaViewSet,
+ "environment_vision_quota",
+ ["team_id"],
+)
environments_router.register(
r"change_requests",
diff --git a/products/replay_vision/backend/api/__init__.py b/products/replay_vision/backend/api/__init__.py
index 74ec2da1fe1f..55979c5102fb 100644
--- a/products/replay_vision/backend/api/__init__.py
+++ b/products/replay_vision/backend/api/__init__.py
@@ -1,4 +1,10 @@
from products.replay_vision.backend.api.observations import ReplayObservationViewSet, SessionReplayObservationViewSet
+from products.replay_vision.backend.api.quota import VisionQuotaViewSet
from products.replay_vision.backend.api.scanners import ReplayScannerViewSet
-__all__ = ["ReplayScannerViewSet", "ReplayObservationViewSet", "SessionReplayObservationViewSet"]
+__all__ = [
+ "ReplayObservationViewSet",
+ "ReplayScannerViewSet",
+ "SessionReplayObservationViewSet",
+ "VisionQuotaViewSet",
+]
diff --git a/products/replay_vision/backend/api/quota.py b/products/replay_vision/backend/api/quota.py
new file mode 100644
index 000000000000..7fa0c90cbe07
--- /dev/null
+++ b/products/replay_vision/backend/api/quota.py
@@ -0,0 +1,55 @@
+from uuid import UUID
+
+from drf_spectacular.utils import extend_schema, extend_schema_serializer
+from rest_framework import serializers, viewsets
+from rest_framework.permissions import IsAuthenticated
+from rest_framework.request import Request
+from rest_framework.response import Response
+
+from posthog.api.routing import TeamAndOrgViewSetMixin
+
+from products.replay_vision.backend.api.constants import VISION_TAG
+from products.replay_vision.backend.feature_flag import ReplayVisionEnabledPermission
+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(
+ read_only=True,
+ help_text="Total observations the org may complete per calendar month.",
+ )
+ usage_this_month = serializers.IntegerField(
+ read_only=True,
+ help_text="Observations created this month that are in flight or have succeeded, counted against the quota.",
+ )
+ remaining = serializers.IntegerField(
+ read_only=True,
+ help_text="`monthly_quota - usage_this_month`, floored at 0.",
+ )
+ exhausted = serializers.BooleanField(
+ read_only=True,
+ help_text="True when `usage_this_month >= monthly_quota`; further observations are skipped until next period.",
+ )
+ period_start = serializers.DateTimeField(
+ read_only=True,
+ help_text="First moment of the current quota period (UTC).",
+ )
+ period_end = serializers.DateTimeField(
+ read_only=True,
+ help_text="First moment of the next quota period (UTC); the current period's exclusive upper bound.",
+ )
+
+
+@extend_schema(tags=[VISION_TAG])
+class VisionQuotaViewSet(TeamAndOrgViewSetMixin, viewsets.ViewSet):
+ scope_object = "replay_scanner"
+ # Custom viewsets must declare scopes or personal-API-key callers 403 silently.
+ scope_object_read_actions = ["list"]
+ permission_classes = [IsAuthenticated, ReplayVisionEnabledPermission]
+
+ @extend_schema(operation_id="environment_vision_quota_retrieve", responses={200: VisionQuotaSerializer})
+ def list(self, request: Request, *args, **kwargs) -> Response:
+ snapshot = compute_quota_snapshot(organization_id=UUID(self.organization_id))
+ return Response(VisionQuotaSerializer(instance=snapshot).data)
diff --git a/products/replay_vision/backend/api/scanners.py b/products/replay_vision/backend/api/scanners.py
index c88b4b21a5f7..fc266117fde6 100644
--- a/products/replay_vision/backend/api/scanners.py
+++ b/products/replay_vision/backend/api/scanners.py
@@ -22,6 +22,7 @@ from posthog.schema import RecordingsQuery
from posthog.api.routing import TeamAndOrgViewSetMixin
from posthog.api.shared import UserBasicSerializer
+from posthog.exceptions import QuotaLimitExceeded
from posthog.models.user import User
from posthog.temporal.common.client import sync_connect
@@ -35,6 +36,7 @@ from products.replay_vision.backend.models.replay_scanner import (
ScannerType,
)
from products.replay_vision.backend.queries import estimate_scanner_session_volume
+from products.replay_vision.backend.quota import compute_quota_snapshot
from products.replay_vision.backend.temporal.constants import (
APPLY_SCANNER_WORKFLOW_NAME,
MAX_SESSION_ID_LENGTH,
@@ -346,6 +348,15 @@ 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.")
+ snapshot = compute_quota_snapshot(organization_id=self.team.organization_id)
+ if snapshot.exhausted:
+ raise QuotaLimitExceeded(
+ detail=(
+ f"Monthly Replay Vision quota of {snapshot.monthly_quota} observations reached; "
+ f"resets at {snapshot.period_end.isoformat()}."
+ )
+ )
+
body = ObserveRequestSerializer(data=request.data)
body.is_valid(raise_exception=True)
session_id: str = body.validated_data["session_id"]
diff --git a/products/replay_vision/backend/quota.py b/products/replay_vision/backend/quota.py
new file mode 100644
index 000000000000..bbca59ea7465
--- /dev/null
+++ b/products/replay_vision/backend/quota.py
@@ -0,0 +1,51 @@
+from dataclasses import dataclass
+from datetime import UTC, datetime
+from uuid import UUID
+
+from dateutil.relativedelta import relativedelta
+
+from posthog.date_util import start_of_month
+
+from products.replay_vision.backend.models.replay_observation import ObservationStatus, ReplayObservation
+
+MONTHLY_OBSERVATION_QUOTA = 3000
+
+# In-flight rows count against the quota so concurrent on-demand triggers can't all race past the gate before any complete.
+_COUNTED_STATUSES = (ObservationStatus.SUCCEEDED, ObservationStatus.PENDING, ObservationStatus.RUNNING)
+
+
+@dataclass(frozen=True)
+class QuotaSnapshot:
+ monthly_quota: int
+ usage_this_month: int
+ period_start: datetime
+ period_end: datetime
+
+ @property
+ def remaining(self) -> int:
+ return max(0, self.monthly_quota - self.usage_this_month)
+
+ @property
+ def exhausted(self) -> bool:
+ return self.usage_this_month >= self.monthly_quota
+
+
+def _current_month_bounds() -> tuple[datetime, datetime]:
+ period_start = start_of_month(datetime.now(UTC))
+ return period_start, period_start + relativedelta(months=1)
+
+
+def compute_quota_snapshot(organization_id: UUID) -> QuotaSnapshot:
+ period_start, period_end = _current_month_bounds()
+ usage = ReplayObservation.objects.filter(
+ team__organization_id=organization_id,
+ status__in=_COUNTED_STATUSES,
+ created_at__gte=period_start,
+ created_at__lt=period_end,
+ ).count()
+ return QuotaSnapshot(
+ monthly_quota=MONTHLY_OBSERVATION_QUOTA,
+ usage_this_month=usage,
+ period_start=period_start,
+ period_end=period_end,
+ )
diff --git a/products/replay_vision/backend/temporal/activities/create_observation.py b/products/replay_vision/backend/temporal/activities/create_observation.py
index 6e18da65545d..35cf36dffd91 100644
--- a/products/replay_vision/backend/temporal/activities/create_observation.py
+++ b/products/replay_vision/backend/temporal/activities/create_observation.py
@@ -10,6 +10,7 @@ from posthog.models.organization import OrganizationMembership
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
from products.replay_vision.backend.temporal.decorators import track_activity
from products.replay_vision.backend.temporal.types import (
CreateObservationInputs,
@@ -49,6 +50,17 @@ 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:
+ 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},
+ )
+ return CreateObservationOutput(
+ observation_id=None,
+ was_created=False,
+ scanner_type=scanner.scanner_type,
+ )
+
try:
with transaction.atomic():
observation = ReplayObservation.objects.create(
diff --git a/products/replay_vision/backend/temporal/types.py b/products/replay_vision/backend/temporal/types.py
index 64b948537f37..7f844a587ddd 100644
--- a/products/replay_vision/backend/temporal/types.py
+++ b/products/replay_vision/backend/temporal/types.py
@@ -79,9 +79,8 @@ class CreateObservationInputs(BaseModel, frozen=True):
class CreateObservationOutput(BaseModel, frozen=True):
- """`was_created=False` means the row already existed; the caller should no-op."""
-
- observation_id: UUID
+ # `was_created=False` means no row was persisted (either the row already existed, or the org's monthly quota is exhausted); the caller should no-op.
+ observation_id: UUID | None
was_created: bool
scanner_type: ScannerType
diff --git a/products/replay_vision/backend/temporal/workflow.py b/products/replay_vision/backend/temporal/workflow.py
index daf96f519e0f..b99e5d34b8fc 100644
--- a/products/replay_vision/backend/temporal/workflow.py
+++ b/products/replay_vision/backend/temporal/workflow.py
@@ -153,8 +153,8 @@ class ApplyScannerWorkflow(PostHogWorkflow):
start_to_close_timeout=dt.timedelta(seconds=30),
retry_policy=_CREATE_OBSERVATION_RETRY,
)
- if not create_result.was_created:
- return # Existing observation owns this (scanner, session_id); its workflow drives it.
+ if not create_result.was_created or create_result.observation_id is None:
+ return # Either an existing observation owns this (scanner, session_id), or the org's monthly quota is exhausted.
observation_id = create_result.observation_id
scanner_type = create_result.scanner_type
diff --git a/products/replay_vision/backend/tests/test_quota.py b/products/replay_vision/backend/tests/test_quota.py
new file mode 100644
index 000000000000..2cd6e9e0e82e
--- /dev/null
+++ b/products/replay_vision/backend/tests/test_quota.py
@@ -0,0 +1,212 @@
+from datetime import UTC, datetime, timedelta
+
+from posthog.test.base import APIBaseTest
+from unittest.mock import MagicMock, patch
+
+from django.utils import timezone
+
+from parameterized import parameterized
+
+from posthog.models import Organization, Team
+
+from products.replay_vision.backend.models.replay_observation import (
+ ObservationStatus,
+ ObservationTrigger,
+ ReplayObservation,
+)
+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.tests.helpers import snapshot_for as _snapshot_for
+
+
+class _VisionQuotaTestCase(APIBaseTest):
+ def setUp(self) -> None:
+ super().setUp()
+ self.flag_patcher = patch(
+ "products.replay_vision.backend.feature_flag.posthoganalytics.feature_enabled",
+ return_value=True,
+ )
+ self.flag_patcher.start()
+ self.scanner = ReplayScanner.objects.create(
+ team=self.team,
+ name="quota-test-scanner",
+ scanner_type=ScannerType.MONITOR,
+ scanner_config={"prompt": "p"},
+ model=ScannerModel.GEMINI_3_FLASH,
+ )
+
+ def tearDown(self) -> None:
+ self.flag_patcher.stop()
+ super().tearDown()
+
+ def _make_observation(
+ self,
+ *,
+ status: ObservationStatus,
+ completed_at: datetime | None = None,
+ created_at: datetime | None = None,
+ ) -> ReplayObservation:
+ observation = ReplayObservation.objects.create(
+ scanner=self.scanner,
+ team=self.team,
+ session_id=f"sess-{ReplayObservation.objects.count()}",
+ status=status,
+ scanner_snapshot=_snapshot_for(self.scanner),
+ triggered_by=ObservationTrigger.ON_DEMAND,
+ completed_at=completed_at,
+ )
+ if created_at is not None:
+ ReplayObservation.objects.filter(pk=observation.pk).update(created_at=created_at)
+ observation.refresh_from_db()
+ return observation
+
+
+class TestComputeQuotaSnapshot(_VisionQuotaTestCase):
+ @parameterized.expand(
+ [
+ (ObservationStatus.SUCCEEDED, 1),
+ (ObservationStatus.PENDING, 1),
+ (ObservationStatus.RUNNING, 1),
+ (ObservationStatus.FAILED, 0),
+ (ObservationStatus.INELIGIBLE, 0),
+ ]
+ )
+ def test_counts_only_succeeded_and_in_flight_this_month(
+ self, status: ObservationStatus, expected_count: int
+ ) -> None:
+ 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
+
+ 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
+
+ def test_period_bounds_are_first_of_month_utc(self) -> None:
+ snapshot = compute_quota_snapshot(organization_id=self.organization.id)
+ assert snapshot.period_start.day == 1
+ assert snapshot.period_start.tzinfo == UTC
+ assert snapshot.period_end.day == 1
+ assert snapshot.period_end > snapshot.period_start
+
+ def test_december_rollover_advances_year(self) -> None:
+ with patch("products.replay_vision.backend.quota.datetime", wraps=datetime) as mock_datetime:
+ mock_datetime.now.return_value = datetime(2026, 12, 15, 10, tzinfo=UTC)
+ snapshot = compute_quota_snapshot(organization_id=self.organization.id)
+ assert snapshot.period_start == datetime(2026, 12, 1, tzinfo=UTC)
+ assert snapshot.period_end == datetime(2027, 1, 1, tzinfo=UTC)
+
+ def test_observations_at_period_boundaries(self) -> None:
+ snapshot = compute_quota_snapshot(organization_id=self.organization.id)
+ self._make_observation(
+ status=ObservationStatus.SUCCEEDED,
+ completed_at=timezone.now(),
+ created_at=snapshot.period_end - timedelta(microseconds=1),
+ )
+ 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
+
+ def test_other_orgs_observations_not_counted(self) -> None:
+ other_org = Organization.objects.create(name="other-org")
+ other_team = Team.objects.create(organization=other_org, name="other-team")
+ other_scanner = ReplayScanner.objects.create(
+ team=other_team,
+ name="other-scanner",
+ scanner_type=ScannerType.MONITOR,
+ scanner_config={"prompt": "p"},
+ model=ScannerModel.GEMINI_3_FLASH,
+ )
+ ReplayObservation.objects.create(
+ scanner=other_scanner,
+ team=other_team,
+ session_id="other-sess",
+ status=ObservationStatus.SUCCEEDED,
+ scanner_snapshot=_snapshot_for(other_scanner),
+ triggered_by=ObservationTrigger.ON_DEMAND,
+ completed_at=timezone.now(),
+ )
+
+ snapshot = compute_quota_snapshot(organization_id=self.organization.id)
+ assert snapshot.usage_this_month == 0
+
+ def test_exhausted_when_usage_meets_quota(self) -> None:
+ with patch("products.replay_vision.backend.quota.MONTHLY_OBSERVATION_QUOTA", 2):
+ 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.exhausted is True
+ assert snapshot.remaining == 0
+
+
+class TestVisionQuotaEndpoint(_VisionQuotaTestCase):
+ @property
+ def quota_url(self) -> str:
+ return f"/api/environments/{self.team.id}/vision/quota/"
+
+ def test_returns_static_quota_and_zero_usage_when_empty(self) -> None:
+ 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["exhausted"] is False
+ assert "period_start" in body
+ assert "period_end" in body
+
+ 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
+
+ def test_requires_feature_flag(self) -> None:
+ with patch(
+ "products.replay_vision.backend.feature_flag.posthoganalytics.feature_enabled",
+ return_value=False,
+ ):
+ resp = self.client.get(self.quota_url)
+ assert resp.status_code == 404
+
+
+@patch("products.replay_vision.backend.api.scanners.async_to_sync")
+@patch("products.replay_vision.backend.api.scanners.sync_connect")
+class TestObserveQuotaEnforcement(_VisionQuotaTestCase):
+ @property
+ def observe_url(self) -> str:
+ return f"/api/environments/{self.team.id}/vision/scanners/{self.scanner.id}/observe/"
+
+ 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):
+ self._make_observation(status=ObservationStatus.SUCCEEDED, completed_at=timezone.now())
+
+ resp = self.client.post(self.observe_url, data={"session_id": "sess-blocked"}, format="json")
+
+ 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"]
+ mock_sync_connect.assert_not_called()
+ mock_async_to_sync.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()
+ mock_sync_connect.assert_called_once()
diff --git a/products/replay_vision/backend/tests/test_temporal.py b/products/replay_vision/backend/tests/test_temporal.py
index a149df526821..f149a2590e7a 100644
--- a/products/replay_vision/backend/tests/test_temporal.py
+++ b/products/replay_vision/backend/tests/test_temporal.py
@@ -27,6 +27,7 @@ from products.replay_vision.backend.models.replay_observation import (
ReplayObservation,
)
from products.replay_vision.backend.models.replay_scanner import ReplayScanner, ScannerModel, ScannerType
+from products.replay_vision.backend.quota import QuotaSnapshot
from products.replay_vision.backend.temporal import ApplyScannerWorkflow
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
@@ -126,6 +127,7 @@ class TestCreateObservationActivity:
)
assert result.was_created is True
+ assert result.observation_id is not None
observation = ReplayObservation.objects.get(id=result.observation_id)
assert observation.status == ObservationStatus.PENDING
assert observation.workflow_id == "wf-xyz"
@@ -158,6 +160,7 @@ class TestCreateObservationActivity:
scanner.scanner_config = {"prompt": "completely different prompt"}
scanner.save()
+ assert result.observation_id is not None
observation = ReplayObservation.objects.get(id=result.observation_id)
assert observation.scanner_snapshot["scanner_config"] == original_config
@@ -261,6 +264,32 @@ class TestCreateObservationActivity:
)
assert result.was_created is True
+ def test_skips_insert_when_monthly_quota_exhausted(self) -> None:
+ scanner = _make_scanner()
+ with patch(
+ "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,
+ period_start=dt.datetime.now(dt.UTC),
+ period_end=dt.datetime.now(dt.UTC),
+ )
+ result = create_observation_activity(
+ CreateObservationInputs(
+ scanner_id=scanner.id,
+ team_id=scanner.team_id,
+ session_id="sess-quota",
+ triggered_by=ObservationTrigger.SCHEDULE,
+ triggered_by_user_id=None,
+ workflow_id="wf-quota",
+ )
+ )
+ assert result == CreateObservationOutput(
+ observation_id=None, was_created=False, scanner_type=scanner.scanner_type
+ )
+ assert not ReplayObservation.objects.filter(scanner=scanner, session_id="sess-quota").exists()
+
@pytest.mark.django_db(transaction=True)
class TestObservationStateActivities:
diff --git a/products/replay_vision/frontend/generated/api.schemas.ts b/products/replay_vision/frontend/generated/api.schemas.ts
index 6480cd77c785..bf332b9786b7 100644
--- a/products/replay_vision/frontend/generated/api.schemas.ts
+++ b/products/replay_vision/frontend/generated/api.schemas.ts
@@ -223,6 +223,21 @@ export interface PaginatedReplayObservationListApi {
results: ReplayObservationApi[]
}
+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. */
+ 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
+}
+
export interface ReplayScannerApi {
readonly id: string
/**
diff --git a/products/replay_vision/frontend/generated/api.ts b/products/replay_vision/frontend/generated/api.ts
index a204f0b7b0f0..f943ab4570b9 100644
--- a/products/replay_vision/frontend/generated/api.ts
+++ b/products/replay_vision/frontend/generated/api.ts
@@ -19,6 +19,7 @@ import type {
ReplayObservationApi,
ReplayScannerApi,
VisionObservationsListParams,
+ VisionQuotaApi,
VisionScannersListParams,
VisionScannersObservationsListParams,
} from './api.schemas'
@@ -88,6 +89,20 @@ export const visionObservationsRetrieve = async (
})
}
+export const getEnvironmentVisionQuotaRetrieveUrl = (projectId: string) => {
+ return `/api/environments/${projectId}/vision/quota/`
+}
+
+export const environmentVisionQuotaRetrieve = async (
+ projectId: string,
+ options?: RequestInit
+): Promise<VisionQuotaApi> => {
+ return apiMutator<VisionQuotaApi>(getEnvironmentVisionQuotaRetrieveUrl(projectId), {
+ ...options,
+ method: 'GET',
+ })
+}
+
export const getVisionScannersListUrl = (projectId: string, params?: VisionScannersListParams) => {
const normalizedParams = new URLSearchParams()
diff --git a/products/replay_vision/frontend/replay_scanners/components/VisionQuotaMeter.tsx b/products/replay_vision/frontend/replay_scanners/components/VisionQuotaMeter.tsx
index 1fd7dfbf381e..b426e6eba714 100644
--- a/products/replay_vision/frontend/replay_scanners/components/VisionQuotaMeter.tsx
+++ b/products/replay_vision/frontend/replay_scanners/components/VisionQuotaMeter.tsx
@@ -1,82 +1,40 @@
-import { useActions, useValues } from 'kea'
+import { useValues } from 'kea'
-import { LemonSegmentedButton, Tooltip } from '@posthog/lemon-ui'
+import { Tooltip } from '@posthog/lemon-ui'
-import { Sparkline } from 'lib/components/Sparkline'
import { LemonProgress } from 'lib/lemon-ui/LemonProgress'
import { replayScannersLogic } from '../replayScannersLogic'
-const RANGE_OPTIONS: { value: 7 | 30 | 90; label: string }[] = [
- { value: 7, label: '7 days' },
- { value: 30, label: '30 days' },
- { value: 90, label: '90 days' },
-]
-
export function VisionQuotaMeter(): JSX.Element | null {
- const { quota, usageRangeDays } = useValues(replayScannersLogic)
- const { setUsageRangeDays } = useActions(replayScannersLogic)
+ const { quota } = useValues(replayScannersLogic)
if (!quota) {
return null
}
- const ratio = quota.limit > 0 ? Math.min(quota.used / quota.limit, 1) : 0
+ const ratio = quota.monthly_quota > 0 ? Math.min(quota.usage_this_month / quota.monthly_quota, 1) : 0
const percent = Math.round(ratio * 100)
- const remaining = Math.max(quota.limit - quota.used, 0)
- const strokeColor = ratio >= 1 ? 'var(--danger)' : ratio >= 0.8 ? 'var(--warning)' : 'var(--success)'
-
- const policyCopy =
- quota.policy === 'block'
- ? 'Schedules pause when this quota is reached.'
- : 'Observations beyond the quota accrue against your usage-based meter.'
-
- const history = quota.usage_history ?? []
- const slice = history.slice(-usageRangeDays)
- const sparklineData = slice.map((p) => p.count)
- const sparklineLabels = slice.map((p) => p.date)
- const rangeTotal = slice.reduce((sum, p) => sum + p.count, 0)
+ const strokeColor = quota.exhausted ? 'var(--danger)' : ratio >= 0.8 ? 'var(--warning)' : 'var(--success)'
return (
- <div className="border rounded p-3 bg-bg-light space-y-3">
- <div className="space-y-1">
- <div className="flex items-center justify-between">
- <Tooltip title={policyCopy}>
- <span className="text-sm font-medium">Vision observations this month</span>
- </Tooltip>
- <span className="text-sm tabular-nums">
- {quota.used.toLocaleString()} / {quota.limit.toLocaleString()}
- </span>
- </div>
- <LemonProgress percent={percent} strokeColor={strokeColor} />
- <div className="text-xs text-muted">
- {ratio >= 1 ? (
- <span className="text-danger">Quota reached.</span>
- ) : (
- <>{remaining.toLocaleString()} remaining</>
- )}
- <span className="mx-1">·</span>
- <span>{quota.policy === 'block' ? 'Block on overage' : 'Usage-based overage'}</span>
- </div>
+ <div className="border rounded p-3 bg-bg-light space-y-2">
+ <div className="flex items-center justify-between">
+ <Tooltip title="Observations are paused once this quota is reached, until next month.">
+ <span className="text-sm font-medium">Vision observations this month</span>
+ </Tooltip>
+ <span className="text-sm tabular-nums">
+ {quota.usage_this_month.toLocaleString()} / {quota.monthly_quota.toLocaleString()}
+ </span>
+ </div>
+ <LemonProgress percent={percent} strokeColor={strokeColor} />
+ <div className="text-xs text-muted">
+ {quota.exhausted ? (
+ <span className="text-danger">Quota reached.</span>
+ ) : (
+ <>{quota.remaining.toLocaleString()} remaining</>
+ )}
</div>
- {sparklineData.length > 0 && (
- <div>
- <div className="flex items-center justify-between mb-1">
- <div className="text-xs text-muted">
- Observations per day
- <span className="mx-1">·</span>
- <span className="tabular-nums">{rangeTotal.toLocaleString()} in range</span>
- </div>
- <LemonSegmentedButton
- size="xsmall"
- value={usageRangeDays}
- onChange={(value) => setUsageRangeDays(value)}
- options={RANGE_OPTIONS}
- />
- </div>
- <Sparkline data={sparklineData} labels={sparklineLabels} type="bar" className="h-12 w-full" />
- </div>
- )}
</div>
)
}
diff --git a/products/replay_vision/frontend/replay_scanners/replayScannersLogic.ts b/products/replay_vision/frontend/replay_scanners/replayScannersLogic.ts
index b755365730b3..47e2877f5e2e 100644
--- a/products/replay_vision/frontend/replay_scanners/replayScannersLogic.ts
+++ b/products/replay_vision/frontend/replay_scanners/replayScannersLogic.ts
@@ -1,7 +1,6 @@
import { actions, afterMount, kea, listeners, path, props, reducers, selectors } from 'kea'
import { router } from 'kea-router'
-import api from 'lib/api'
import { lemonToast } from 'lib/lemon-ui/LemonToast'
import { tabAwareActionToUrl } from 'lib/logic/scenes/tabAwareActionToUrl'
import { tabAwareScene } from 'lib/logic/scenes/tabAwareScene'
@@ -10,6 +9,7 @@ import { teamLogic } from 'scenes/teamLogic'
import { urls } from 'scenes/urls'
import {
+ environmentVisionQuotaRetrieve,
visionScannersCreate,
visionScannersDestroy,
visionScannersList,
@@ -66,7 +66,6 @@ export const replayScannersLogic = kea<replayScannersLogicType>([
setSearch: (search: string) => ({ search }),
setEnabledFilter: (values: EnabledFilter[]) => ({ values }),
setScannerTypeFilter: (scannerTypes: ScannerType[]) => ({ scannerTypes }),
- setUsageRangeDays: (days: 7 | 30 | 90) => ({ days }),
clearFilters: true,
}),
@@ -116,12 +115,6 @@ export const replayScannersLogic = kea<replayScannersLogicType>([
clearFilters: () => [],
},
],
- usageRangeDays: [
- 30 as 7 | 30 | 90,
- {
- setUsageRangeDays: (_, { days }) => days,
- },
- ],
}),
listeners(({ actions, values }) => ({
@@ -145,8 +138,7 @@ export const replayScannersLogic = kea<replayScannersLogicType>([
return
}
try {
- // nosemgrep: prefer-codegen-api
- const response = await api.get(`/api/environments/${teamId}/vision/quota/`)
+ const response = await environmentVisionQuotaRetrieve(String(teamId))
actions.loadQuotaSuccess(response)
} catch {
actions.loadQuotaSuccess(null)
diff --git a/products/replay_vision/frontend/replay_scanners/types.ts b/products/replay_vision/frontend/replay_scanners/types.ts
index f800f80db2ca..57524b8a158f 100644
--- a/products/replay_vision/frontend/replay_scanners/types.ts
+++ b/products/replay_vision/frontend/replay_scanners/types.ts
@@ -214,20 +214,7 @@ export interface IndexerScanner extends BaseReplayScanner {
export type ReplayScanner = MonitorScanner | SummarizerScanner | ClassifierScanner | ScorerScanner | IndexerScanner
-export interface VisionUsagePoint {
- date: string
- count: number
-}
-
-export interface VisionQuota {
- used: number
- limit: number
- policy: 'block' | 'usage_based'
- period_start: string
- period_end: string
- /** Daily observation counts across the current period. Optional until the backend exposes it. */
- usage_history?: VisionUsagePoint[]
-}
+export type { VisionQuotaApi as VisionQuota } from '../generated/api.schemas'
// The API exposes scanner_config and query as `unknown`. The client narrows them via
// the scanner_type discriminator, so conversion is contained to this single boundary.
diff --git a/products/replay_vision/mcp/tools.yaml b/products/replay_vision/mcp/tools.yaml
index 1f5c62a2d346..b2d2166f21ec 100644
--- a/products/replay_vision/mcp/tools.yaml
+++ b/products/replay_vision/mcp/tools.yaml
@@ -15,6 +15,9 @@ tools:
vision-observations-retrieve:
operation: vision_observations_retrieve
enabled: false
+ vision-quota-retrieve:
+ operation: environment_vision_quota_retrieve
+ enabled: false
vision-scanners-create:
operation: vision_scanners_create
enabled: true
diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.ts
index 085beb6edc40..c24feaae5398 100644
--- a/services/mcp/src/api/generated.ts
+++ b/services/mcp/src/api/generated.ts
@@ -38088,6 +38088,21 @@ export namespace Schemas {
source_table_key: string;
}
+ 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. */
+ 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;
+ }
+
/**
* * `pending` - pending
* `provisioning` - provisioning