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.

fix(replay-vision): harden scanner sweep, estimator, and asset retries (#67002)

Tue Haulund0a2676d5b3d9
diff --git a/products/replay_vision/backend/api/scanners.py b/products/replay_vision/backend/api/scanners.py
index 346160db348b..471102a95f9e 100644
--- a/products/replay_vision/backend/api/scanners.py
+++ b/products/replay_vision/backend/api/scanners.py
@@ -56,7 +56,7 @@ from products.replay_vision.backend.queries import (
project_monthly_observations,
refresh_scanner_estimate,
)
-from products.replay_vision.backend.quota import compute_quota_snapshot
+from products.replay_vision.backend.quota import compute_quota_snapshot, sum_enabled_scanner_estimates
from products.replay_vision.backend.tag_suggestions import SuggestionError, suggest_classifier_tags
from products.replay_vision.backend.temporal.constants import (
APPLY_SCANNER_WORKFLOW_NAME,
@@ -274,6 +274,7 @@ class ReplayScannerSerializer(serializers.ModelSerializer):
team = self.context["get_team"]()
user = cast(User, self.context["request"].user)
try:
+ # last_swept_at is seeded a settle-interval back by the model default (initial_watermark) to avoid a cold start.
scanner = ReplayScanner.objects.create(team=team, created_by=user, **validated_data)
except IntegrityError as e:
self._reraise_unique_name_violation(e)
@@ -439,6 +440,14 @@ class EstimateRequestSerializer(serializers.Serializer):
max_value=1.0,
help_text="0..1 downsample applied to matched sessions. Defaults to 1.0 (no downsampling).",
)
+ scanner_id = serializers.UUIDField(
+ 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."
+ ),
+ )
def validate_query(self, value: dict[str, Any]) -> dict[str, Any]:
try:
@@ -500,6 +509,13 @@ class EstimateResponseSerializer(serializers.Serializer):
estimated_observations_per_month = serializers.IntegerField(
help_text="Projected monthly observations: matched sessions scaled to 30 days, times sampling_rate.",
)
+ other_enabled_scanners_monthly = 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."
+ ),
+ )
sampling_rate = serializers.FloatField(
help_text="Sampling rate applied to the projection. Echoed from the request.",
)
@@ -747,6 +763,11 @@ class ReplayScannerViewSet(TeamAndOrgViewSetMixin, viewsets.ModelViewSet):
body.is_valid(raise_exception=True)
sampling_rate: float = body.validated_data["sampling_rate"]
+ # Reject a scanner_id outside this project before doing any work, so it can't silently undercount the others-sum.
+ scanner_id = body.validated_data.get("scanner_id")
+ if scanner_id is not None and not ReplayScanner.objects.filter(team_id=self.team_id, pk=scanner_id).exists():
+ raise serializers.ValidationError({"scanner_id": "No scanner with this id exists in this project."})
+
# validate_query already validated this; the empty-dict default needs `kind` to parse.
query_dict: dict[str, Any] = dict(body.validated_data.get("query") or {})
query_dict.setdefault("kind", "RecordingsQuery")
@@ -755,12 +776,19 @@ class ReplayScannerViewSet(TeamAndOrgViewSetMixin, viewsets.ModelViewSet):
estimate = estimate_scanner_session_volume(team=self.team, query=recordings_query)
observations_per_month = project_monthly_observations(estimate, sampling_rate)
+ # 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(
+ self.team.organization_id, exclude_scanner_id=scanner_id
+ )
+
return Response(
EstimateResponseSerializer(
{
"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,
"sampling_rate": sampling_rate,
}
).data
diff --git a/products/replay_vision/backend/migrations/0022_alter_replayscanner_last_swept_at.py b/products/replay_vision/backend/migrations/0022_alter_replayscanner_last_swept_at.py
new file mode 100644
index 000000000000..0f91bfef8fc3
--- /dev/null
+++ b/products/replay_vision/backend/migrations/0022_alter_replayscanner_last_swept_at.py
@@ -0,0 +1,22 @@
+# Generated by Django 5.2.14 on 2026-06-30 12:12
+
+from django.db import migrations, models
+
+import products.replay_vision.backend.models.replay_scanner
+
+
+class Migration(migrations.Migration):
+ dependencies = [
+ ("replay_vision", "0021_replayobservation_scanner_created_idx"),
+ ]
+
+ operations = [
+ migrations.AlterField(
+ model_name="replayscanner",
+ name="last_swept_at",
+ field=models.DateTimeField(
+ default=products.replay_vision.backend.models.replay_scanner.initial_watermark,
+ help_text="Watermark for the scanner schedule's last fire; mirrors Temporal schedule state for recovery.",
+ ),
+ ),
+ ]
diff --git a/products/replay_vision/backend/migrations/max_migration.txt b/products/replay_vision/backend/migrations/max_migration.txt
index 90101ebbac90..8c6dfb94f372 100644
--- a/products/replay_vision/backend/migrations/max_migration.txt
+++ b/products/replay_vision/backend/migrations/max_migration.txt
@@ -1 +1 @@
-0021_replayobservation_scanner_created_idx
+0022_alter_replayscanner_last_swept_at
diff --git a/products/replay_vision/backend/models/replay_scanner.py b/products/replay_vision/backend/models/replay_scanner.py
index 51ce5360fe45..c9e63ca11b05 100644
--- a/products/replay_vision/backend/models/replay_scanner.py
+++ b/products/replay_vision/backend/models/replay_scanner.py
@@ -9,6 +9,8 @@ from posthog.models.utils import UUIDModel
# This model loads at django.setup() in every process; posthog.schema (the pydantic
# models) is runtime-imported in the accessor that materializes the typed query.
if TYPE_CHECKING:
+ from datetime import datetime
+
from posthog.schema import RecordingsQuery
@@ -28,6 +30,17 @@ class ScannerModel(models.TextChoices):
GEMINI_3_FLASH_LITE = "gemini-3.1-flash-lite-preview", "Gemini 3 Flash Lite"
+def initial_watermark() -> "datetime":
+ """A new scanner's sweep watermark, started one settle-interval back so its first sweep immediately picks up
+ recordings that have just cleared the settle window instead of a ~settle-interval cold start; it advances
+ forward normally from there, so there's no re-scan."""
+ from products.replay_vision.backend.queries.scanner_candidate_query import ( # noqa: PLC0415 — keep the heavy hogql query module off the model import path
+ SETTLE_INTERVAL,
+ )
+
+ return timezone.now() - SETTLE_INTERVAL
+
+
class ReplayScanner(UUIDModel):
"""A configured probe that gets applied to completed session recordings (see README)."""
@@ -65,7 +78,7 @@ class ReplayScanner(UUIDModel):
help_text="Increments on every config-changing save. Observations snapshot the version that produced them.",
)
last_swept_at = models.DateTimeField(
- default=timezone.now,
+ default=initial_watermark,
help_text="Watermark for the scanner schedule's last fire; mirrors Temporal schedule state for recovery.",
)
last_seen_session_id = models.CharField(
diff --git a/products/replay_vision/backend/queries/scanner_candidate_query.py b/products/replay_vision/backend/queries/scanner_candidate_query.py
index e4e9555a54f0..e8a2d8a96a9d 100644
--- a/products/replay_vision/backend/queries/scanner_candidate_query.py
+++ b/products/replay_vision/backend/queries/scanner_candidate_query.py
@@ -17,6 +17,12 @@ from posthog.clickhouse.query_tagging import Feature, Product, tags_context
from posthog.models import Team
from posthog.session_recordings.queries.session_recording_list_from_query import SessionRecordingListFromQuery
+from products.replay_vision.backend.temporal.constants import (
+ MAX_ACTIVE_SECONDS_FOR_VIDEO_SCANNER_S,
+ MIN_ACTIVE_SECONDS_FOR_VIDEO_SCANNER_S,
+ MIN_SESSION_DURATION_FOR_VIDEO_SCANNER_S,
+)
+
logger = structlog.get_logger(__name__)
tracer = trace.get_tracer(__name__)
@@ -34,6 +40,32 @@ DEFAULT_MAX_EXECUTION_SECONDS = 180
_MAX_SESSION_ID_LENGTH = 128
+def eligibility_predicates() -> list[ast.Expr]:
+ # Mirror the scan-time eligibility gate (fetch_session_events) on the same ClickHouse aggregates the scan reads, so
+ # too-short/idle/long recordings never become candidates and the volume estimate counts the same eligible set. The
+ # scan still re-checks these authoritatively; this only spares the wasted observation + metadata fetch each rejected
+ # recording would otherwise cost.
+ duration = ast.Field(chain=["duration"])
+ active_seconds = ast.Field(chain=["active_seconds"])
+ return [
+ ast.CompareOperation(
+ op=ast.CompareOperationOp.GtEq,
+ left=duration,
+ right=ast.Constant(value=MIN_SESSION_DURATION_FOR_VIDEO_SCANNER_S),
+ ),
+ ast.CompareOperation(
+ op=ast.CompareOperationOp.GtEq,
+ left=active_seconds,
+ right=ast.Constant(value=MIN_ACTIVE_SECONDS_FOR_VIDEO_SCANNER_S),
+ ),
+ ast.CompareOperation(
+ op=ast.CompareOperationOp.LtEq,
+ left=active_seconds,
+ right=ast.Constant(value=MAX_ACTIVE_SECONDS_FOR_VIDEO_SCANNER_S),
+ ),
+ ]
+
+
@dataclass(frozen=True)
class CandidateSession:
session_id: str
@@ -76,8 +108,9 @@ class ScannerCandidateQuery:
inner_query.offset = None
inner_query.after = None
- # Sampling in the inner HAVING drops un-sampled sessions before outer aggregation.
- extra_having: list[ast.Expr] = []
+ # Drop recordings the scan would reject anyway (too short / too idle / too long) before they become candidates,
+ # then sample the rest — all in the inner HAVING, before outer aggregation.
+ extra_having: list[ast.Expr] = eligibility_predicates()
if (sampling := self._sampling_predicate()) is not None:
extra_having.append(sampling)
diff --git a/products/replay_vision/backend/queries/scanner_volume_estimate.py b/products/replay_vision/backend/queries/scanner_volume_estimate.py
index 86f74fd64e9e..2dd3fbcba0c6 100644
--- a/products/replay_vision/backend/queries/scanner_volume_estimate.py
+++ b/products/replay_vision/backend/queries/scanner_volume_estimate.py
@@ -14,6 +14,7 @@ from posthog.models import Team
from posthog.session_recordings.queries.session_recording_list_from_query import SessionRecordingListFromQuery
from products.replay_vision.backend.models.replay_scanner import ReplayScanner
+from products.replay_vision.backend.queries.scanner_candidate_query import eligibility_predicates
# A pathological filter must not be able to hang the estimate request.
_ESTIMATE_MAX_EXECUTION_TIME_SECONDS = 30
@@ -49,7 +50,10 @@ def estimate_scanner_session_volume(
windowed.date_from = f"-{ESTIMATE_WINDOW_DAYS}d"
windowed.date_to = None
- inner = SessionRecordingListFromQuery(team=team, query=windowed).get_query()
+ # Count only sessions the sweep would actually observe, so the forecast matches the eligible set the candidate query selects.
+ inner = SessionRecordingListFromQuery(
+ team=team, query=windowed, extra_having_predicates=eligibility_predicates()
+ ).get_query()
# The inner query groups by session_id, so one row is one session; order is irrelevant to a count.
inner.order_by = None
diff --git a/products/replay_vision/backend/quota.py b/products/replay_vision/backend/quota.py
index fc42df484f3c..dc854e8d5368 100644
--- a/products/replay_vision/backend/quota.py
+++ b/products/replay_vision/backend/quota.py
@@ -48,6 +48,14 @@ 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."""
+ 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"]
+
+
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)
@@ -70,10 +78,7 @@ def compute_quota_snapshot(organization_id: UUID) -> QuotaSnapshot:
organization_id=organization_id,
expires_at__gt=now,
).aggregate(total=Coalesce(Sum("amount"), Value(0)))["total"]
- projected = ReplayScanner.objects.filter(
- team__organization_id=organization_id,
- enabled=True,
- ).aggregate(total=Coalesce(Sum("estimated_monthly_observations"), Value(0)))["total"]
+ projected = sum_enabled_scanner_estimates(organization_id)
return QuotaSnapshot(
monthly_quota=MONTHLY_OBSERVATION_QUOTA + bonus,
usage_this_month=usage,
diff --git a/products/replay_vision/backend/temporal/workflow.py b/products/replay_vision/backend/temporal/workflow.py
index cb998614d113..96ce8199d618 100644
--- a/products/replay_vision/backend/temporal/workflow.py
+++ b/products/replay_vision/backend/temporal/workflow.py
@@ -88,8 +88,12 @@ _FETCH_RETRY = common.RetryPolicy(
maximum_attempts=6,
)
-# Asset get-or-create has no transient failure modes worth retrying.
-_ENSURE_ASSET_RETRY = common.RetryPolicy(maximum_attempts=1)
+# A transient shared-DB slowdown can time this out; retry like the other state activities (the get-or-create makes sequential retries dedup-safe).
+_ENSURE_ASSET_RETRY = common.RetryPolicy(
+ initial_interval=dt.timedelta(seconds=1),
+ maximum_interval=dt.timedelta(seconds=10),
+ maximum_attempts=5,
+)
# Deterministic failures opt out via ScannerFailureError's non_retryable flag; only transient kinds re-run.
_UPLOAD_RETRY = common.RetryPolicy(
diff --git a/products/replay_vision/backend/tests/test_api.py b/products/replay_vision/backend/tests/test_api.py
index bcf0916954be..3e6a044500a8 100644
--- a/products/replay_vision/backend/tests/test_api.py
+++ b/products/replay_vision/backend/tests/test_api.py
@@ -25,6 +25,7 @@ from products.replay_vision.backend.models.replay_scanner import (
ScannerProvider,
ScannerType,
)
+from products.replay_vision.backend.queries.scanner_candidate_query import SETTLE_INTERVAL
from products.replay_vision.backend.temporal.constants import (
APPLY_SCANNER_WORKFLOW_NAME,
build_apply_scanner_workflow_id,
@@ -89,6 +90,22 @@ class TestReplayScannerViewSet(_VisionAPITestCase):
self.assertEqual(body["scanner_version"], 1)
self.assertEqual(body["created_by"]["id"], self.user.id)
+ def test_create_seeds_sweep_watermark_a_settle_interval_back(self) -> None:
+ # The watermark starts one settle-interval before creation so the first sweep isn't a ~settle-interval cold start.
+ resp = self.client.post(
+ self.scanners_url,
+ data={
+ "name": "watermark-seed",
+ "scanner_type": ScannerType.MONITOR,
+ "scanner_config": {"prompt": "did checkout complete?"},
+ "model": ScannerModel.GEMINI_3_FLASH,
+ },
+ format="json",
+ )
+ self.assertEqual(resp.status_code, 201, resp.json())
+ scanner = ReplayScanner.objects.get(pk=resp.json()["id"])
+ self.assertAlmostEqual(scanner.created_at - scanner.last_swept_at, SETTLE_INTERVAL, delta=timedelta(seconds=5))
+
@parameterized.expand(["name", "scanner_type", "scanner_config", "model"])
def test_create_validates_required_field(self, missing_field: str) -> None:
payload = {
@@ -1513,6 +1530,8 @@ class TestReplayScannerEstimateAction(ClickhouseTestMixin, _VisionAPITestCase):
distinct_id="estimate-distinct-id",
first_timestamp=first_timestamp,
last_timestamp=first_timestamp + timedelta(minutes=5),
+ # Clear the scanner eligibility bounds the estimate applies, so these sessions count.
+ active_milliseconds=30_000,
)
@parameterized.expand(
@@ -1552,3 +1571,45 @@ class TestReplayScannerEstimateAction(ClickhouseTestMixin, _VisionAPITestCase):
self.assertEqual(body["window_days"], 30)
self.assertEqual(body["sampling_rate"], 0.5)
self.assertEqual(body["estimated_observations_per_month"], 2)
+
+ def test_estimate_others_sum_is_enabled_only_and_excludes_the_edited_scanner(self) -> None:
+ self._ingest_session(days_ago=1)
+
+ def make(name: str, *, enabled: bool, estimate: int) -> ReplayScanner:
+ return ReplayScanner.objects.create(
+ team=self.team,
+ name=name,
+ scanner_type=ScannerType.MONITOR,
+ scanner_config={"prompt": "p"},
+ model=ScannerModel.GEMINI_3_FLASH,
+ enabled=enabled,
+ estimated_monthly_observations=estimate,
+ )
+
+ a = make("a", enabled=True, estimate=100)
+ 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_body = self.client.post(self.estimate_url, data={}, format="json").json()
+ self.assertEqual(new_body["other_enabled_scanners_monthly"], 350)
+
+ # 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)
+
+ 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.
+ other_team = Team.objects.create(organization=self.team.organization, name="sibling")
+ other_scanner = ReplayScanner.objects.create(
+ team=other_team,
+ name="theirs",
+ scanner_type=ScannerType.MONITOR,
+ scanner_config={"prompt": "p"},
+ model=ScannerModel.GEMINI_3_FLASH,
+ enabled=True,
+ estimated_monthly_observations=500,
+ )
+ resp = self.client.post(self.estimate_url, data={"scanner_id": str(other_scanner.id)}, format="json")
+ self.assertEqual(resp.status_code, 400, resp.json())
+ self.assertEqual(resp.json()["attr"], "scanner_id")
diff --git a/products/replay_vision/backend/tests/test_scanner_candidate_query.py b/products/replay_vision/backend/tests/test_scanner_candidate_query.py
index cd33e929b13c..f8548f1c0c0a 100644
--- a/products/replay_vision/backend/tests/test_scanner_candidate_query.py
+++ b/products/replay_vision/backend/tests/test_scanner_candidate_query.py
@@ -19,6 +19,7 @@ from products.replay_vision.backend.queries.scanner_candidate_query import (
SETTLE_INTERVAL,
ScannerCandidateQuery,
)
+from products.replay_vision.backend.queries.scanner_volume_estimate import estimate_scanner_session_volume
_NOW = dt.datetime(2026, 5, 1, 12, 0, 0, tzinfo=dt.UTC)
_FROZEN_TIME = _NOW.strftime("%Y-%m-%dT%H:%M:%SZ")
@@ -137,6 +138,9 @@ class TestScannerCandidateQueryAgainstClickHouse(ClickhouseTestMixin):
@staticmethod
def _produce(team_id: int, session_id: str, first: dt.datetime, last: dt.datetime, **kwargs) -> None:
+ # Default to an eligibility-passing recording (>= MIN_ACTIVE active seconds) so tests exercising the watermark /
+ # settle / sampling dimensions aren't incidentally dropped by the eligibility filter; override per-test as needed.
+ kwargs.setdefault("active_milliseconds", 30_000)
produce_replay_summary(
team_id=team_id,
session_id=session_id,
@@ -171,7 +175,8 @@ class TestScannerCandidateQueryAgainstClickHouse(ClickhouseTestMixin):
self._produce(
team.id,
"just-after-watermark",
- last_swept_at,
+ # >= 15s long so it clears the duration eligibility bound; session_end is still just past the watermark.
+ last_swept_at - dt.timedelta(seconds=14),
last_swept_at + dt.timedelta(seconds=1),
)
@@ -344,6 +349,37 @@ class TestScannerCandidateQueryAgainstClickHouse(ClickhouseTestMixin):
results = self._run(team=team, query=query, last_swept_at=_NOW - dt.timedelta(hours=2))
assert [r.session_id for r in results] == ["long"]
+ @pytest.mark.django_db
+ def test_excludes_recordings_the_scan_would_mark_ineligible(self, team) -> None:
+ # Recordings the scan rejects as too short / too idle / too long are dropped before becoming candidates (the
+ # scan re-checks them authoritatively). All four end before the settle bound, so settle isn't the reason.
+ sb = _NOW - SETTLE_INTERVAL
+
+ def produce(session_id: str, start: dt.datetime, duration_s: int, active_ms: int) -> None:
+ self._produce(
+ team.id, session_id, start, start + dt.timedelta(seconds=duration_s), active_milliseconds=active_ms
+ )
+
+ produce("too-short", sb - dt.timedelta(minutes=10), 10, 10_000) # 10s wall < 15s min duration
+ produce("too-idle", sb - dt.timedelta(minutes=12), 60, 5_000) # 5s active < 10s min active
+ produce("too-long", sb - dt.timedelta(minutes=80), 4200, 3_700_000) # 3700s active > 3600s max active
+ produce("eligible", sb - dt.timedelta(minutes=20), 60, 30_000) # 60s wall, 30s active
+
+ results = {r.session_id for r in self._run(team=team, last_swept_at=_NOW - dt.timedelta(hours=2))}
+ assert results == {"eligible"}
+
+ @pytest.mark.django_db
+ def test_volume_estimate_counts_only_eligible_recordings(self, team) -> None:
+ # The estimate shares eligibility_predicates() with the candidate query, so the forecast counts the same
+ # eligible set the sweep selects instead of over-counting recordings the scan would reject.
+ recent = _NOW - dt.timedelta(days=2)
+ self._produce(team.id, "too-short", recent, recent + dt.timedelta(seconds=10), active_milliseconds=10_000)
+ self._produce(team.id, "eligible", recent, recent + dt.timedelta(seconds=60), active_milliseconds=30_000)
+
+ estimate = estimate_scanner_session_volume(team=team, query=RecordingsQuery())
+
+ assert estimate.matched_sessions == 1
+
@pytest.mark.django_db
def test_filter_test_accounts_excludes_internal_users(self, team) -> None:
# test_account_filters are exclusion-style — the operator picks the accounts to drop.
diff --git a/products/replay_vision/frontend/generated/api.schemas.ts b/products/replay_vision/frontend/generated/api.schemas.ts
index 6d05fd6bd0d0..d4348bf5e9ac 100644
--- a/products/replay_vision/frontend/generated/api.schemas.ts
+++ b/products/replay_vision/frontend/generated/api.schemas.ts
@@ -757,6 +757,11 @@ export interface EstimateRequestApi {
* @maximum 1
*/
sampling_rate?: number
+ /**
+ * 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.
+ * @nullable
+ */
+ scanner_id?: string | null
}
/**
@@ -769,6 +774,8 @@ export interface EstimateResponseApi {
window_days: number
/** Projected monthly observations: 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
/** 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 b8c0a7222bfe..81c3b8c81d80 100644
--- a/products/replay_vision/frontend/generated/api.zod.ts
+++ b/products/replay_vision/frontend/generated/api.zod.ts
@@ -386,6 +386,12 @@ export const VisionScannersEstimateCreateBody = /* @__PURE__ */ zod
.max(visionScannersEstimateCreateBodySamplingRateMax)
.default(visionScannersEstimateCreateBodySamplingRateDefault)
.describe('0..1 downsample applied to matched sessions. Defaults to 1.0 (no downsampling).'),
+ scanner_id: 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."
+ ),
})
.describe('Body of POST \/vision\/scanners\/estimate\/ — a proposed, unsaved scanner config.')
diff --git a/products/replay_vision/frontend/replay_scanners/components/ScannerQuotaForecast.tsx b/products/replay_vision/frontend/replay_scanners/components/ScannerQuotaForecast.tsx
index a06cc9fd937b..ae899b905f66 100644
--- a/products/replay_vision/frontend/replay_scanners/components/ScannerQuotaForecast.tsx
+++ b/products/replay_vision/frontend/replay_scanners/components/ScannerQuotaForecast.tsx
@@ -30,13 +30,14 @@ export function ScannerQuotaForecast({ scannerId }: Props): JSX.Element | null {
const used = quota?.usage_this_month ?? 0
const cap = quota?.monthly_quota ?? 0
- // The fleet sum already contains this scanner's stored estimate when it's enabled. Deriving the
- // delta from the clamped `othersMonthly` keeps the projection and the bar split consistent even
- // when a stale stored estimate exceeds the reported fleet sum.
- const storedContribution = scanner.enabled ? (scanner.estimated_monthly_observations ?? 0) : 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 = Math.max(fleetMonthly - storedContribution, 0)
- const projection = projectQuota(quota, projected !== null ? othersMonthly + projected - fleetMonthly : 0)
+ const othersMonthly = scannerEstimate?.other_enabled_scanners_monthly ?? 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 projection = projectQuota(quota, newFleetMonthly - fleetMonthly)
const { status, percentLabel, resetsOn, usedPct, projectedPct } = projection
const effectiveStatus: QuotaStatus = projected === null ? 'safe' : status
diff --git a/products/replay_vision/frontend/replay_scanners/replayScannerLogic.ts b/products/replay_vision/frontend/replay_scanners/replayScannerLogic.ts
index ddab17e73c59..e40d149b9917 100644
--- a/products/replay_vision/frontend/replay_scanners/replayScannerLogic.ts
+++ b/products/replay_vision/frontend/replay_scanners/replayScannerLogic.ts
@@ -810,6 +810,8 @@ export const replayScannerLogic = kea<replayScannerLogicType>([
const response = await visionScannersEstimateCreate(String(teamId), {
query: scanner.query ?? undefined,
sampling_rate: scanner.sampling_rate,
+ // Exclude the edited scanner from the others-sum so the forecast doesn't double-count it.
+ scanner_id: props.id !== 'new' ? props.id : null,
})
breakpoint()
if (values.estimateRequestVersion !== version) {
diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.ts
index 3ecb311e2eca..c29669f9411d 100644
--- a/services/mcp/src/api/generated.ts
+++ b/services/mcp/src/api/generated.ts
@@ -20078,6 +20078,11 @@ export namespace Schemas {
* @maximum 1
*/
sampling_rate?: number;
+ /**
+ * 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.
+ * @nullable
+ */
+ scanner_id?: string | null;
}
/**
@@ -20090,6 +20095,8 @@ export namespace Schemas {
window_days: number;
/** Projected monthly observations: 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;
/** Sampling rate applied to the projection. Echoed from the request. */
sampling_rate: number;
}
diff --git a/services/mcp/src/generated/replay_vision/api.ts b/services/mcp/src/generated/replay_vision/api.ts
index 8244bbb6a79b..93756dd52c78 100644
--- a/services/mcp/src/generated/replay_vision/api.ts
+++ b/services/mcp/src/generated/replay_vision/api.ts
@@ -371,5 +371,11 @@ export const VisionScannersEstimateCreateBody = /* @__PURE__ */ zod
.max(visionScannersEstimateCreateBodySamplingRateMax)
.default(visionScannersEstimateCreateBodySamplingRateDefault)
.describe('0..1 downsample applied to matched sessions. Defaults to 1.0 (no downsampling).'),
+ scanner_id: 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."
+ ),
})
.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 0184c641af72..5661fe07a012 100644
--- a/services/mcp/src/tools/generated/replay_vision.ts
+++ b/services/mcp/src/tools/generated/replay_vision.ts
@@ -158,6 +158,9 @@ const visionScannersEstimateCreate = (): ToolBase<
if (params.sampling_rate !== undefined) {
body['sampling_rate'] = params.sampling_rate
}
+ if (params.scanner_id !== undefined) {
+ body['scanner_id'] = params.scanner_id
+ }
const result = await context.api.request<Schemas.EstimateResponse>({
method: 'POST',
path: `/api/projects/${encodeURIComponent(String(projectId))}/vision/scanners/estimate/`,