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): per-scanner read budget throttle (#81727)

Tue Haulunda63ee20d97cd
diff --git a/posthog/clickhouse/query_tagging.py b/posthog/clickhouse/query_tagging.py
index b67ad4d3c6c9..3d358e862839 100644
--- a/posthog/clickhouse/query_tagging.py
+++ b/posthog/clickhouse/query_tagging.py
@@ -405,6 +405,7 @@ class QueryTags(BaseModel):
workload: Optional[str] = None # enum connection.Workload
dashboard_id: Optional[int] = None
insight_id: Optional[int] = None
+ scanner_id: Optional[str] = None # replay-vision scanner, for per-scanner read metering
exported_asset_id: Optional[int] = None
export_format: Optional[str] = None
chargeable: Optional[int] = None
diff --git a/posthog/temporal/schedule.py b/posthog/temporal/schedule.py
index 4d45ed0abd06..e9bd10df9da1 100644
--- a/posthog/temporal/schedule.py
+++ b/posthog/temporal/schedule.py
@@ -103,6 +103,7 @@ from products.replay_vision.backend.temporal.estimates import create_replay_visi
from products.replay_vision.backend.temporal.gemini_cleanup_sweep import (
create_replay_vision_gemini_cleanup_sweep_schedule,
)
+from products.replay_vision.backend.temporal.read_meter import create_replay_vision_read_meter_schedule
from products.replay_vision.backend.temporal.reconciler import create_replay_vision_reconciler_schedule
from products.review_hog.backend.temporal.outcomes_schedule import create_review_hog_finding_outcomes_schedule
from products.signals.backend.emission.conversations_schedule import create_conversations_signals_coordinator_schedule
@@ -880,6 +881,7 @@ schedules = [
create_calendar_sync_coordinator_schedule,
create_replay_vision_reconciler_schedule,
create_replay_vision_estimates_schedule,
+ create_replay_vision_read_meter_schedule,
create_github_job_logs_coordinator_schedule,
create_review_hog_finding_outcomes_schedule,
create_ci_signals_coordinator_schedule,
diff --git a/products/replay_vision/backend/api/backfills.py b/products/replay_vision/backend/api/backfills.py
index 57d5cf6f369d..692b304523df 100644
--- a/products/replay_vision/backend/api/backfills.py
+++ b/products/replay_vision/backend/api/backfills.py
@@ -222,6 +222,7 @@ class ReplayScannerBackfillViewSet(
window_end=window_end,
sampling_rate=snapshot.sampling_rate,
sampling_salt=str(scanner.id),
+ scanner_id=str(scanner.id),
sampling_mode=snapshot.sampling_mode,
exclude_observed_by_scanner=str(scanner.id) if exclude_observed else None,
max_execution_time_seconds=ENUMERATION_MAX_EXECUTION_SECONDS,
diff --git a/products/replay_vision/backend/migrations/0071_replayscanner_sweep_read_bytes_by_hour_and_more.py b/products/replay_vision/backend/migrations/0071_replayscanner_sweep_read_bytes_by_hour_and_more.py
new file mode 100644
index 000000000000..957ae96877ff
--- /dev/null
+++ b/products/replay_vision/backend/migrations/0071_replayscanner_sweep_read_bytes_by_hour_and_more.py
@@ -0,0 +1,28 @@
+# Generated by Django 5.2.17 on 2026-08-12 08:47
+
+from django.db import migrations, models
+
+
+class Migration(migrations.Migration):
+ dependencies = [("replay_vision", "0070_backfill_usage_scanner_id")]
+
+ operations = [
+ migrations.AddField(
+ model_name="replayscanner",
+ name="sweep_read_bytes_by_hour",
+ field=models.JSONField(
+ blank=True,
+ help_text="ClickHouse read bytes per hour bucket (ISO hour -> bytes), maintained by the read-metering workflow; drives the sweep throttle.",
+ null=True,
+ ),
+ ),
+ migrations.AddField(
+ model_name="replayscanner",
+ name="sweep_throttle_factor_override",
+ field=models.PositiveSmallIntegerField(
+ blank=True,
+ help_text="Manual cadence-stretch multiplier; overrides the computed read-budget throttle. 1 disables throttling; null means automatic.",
+ null=True,
+ ),
+ ),
+ ]
diff --git a/products/replay_vision/backend/migrations/max_migration.txt b/products/replay_vision/backend/migrations/max_migration.txt
index 9c0537ff6a88..617aa08a7419 100644
--- a/products/replay_vision/backend/migrations/max_migration.txt
+++ b/products/replay_vision/backend/migrations/max_migration.txt
@@ -1 +1 @@
-0070_backfill_usage_scanner_id
+0071_replayscanner_sweep_read_bytes_by_hour_and_more
diff --git a/products/replay_vision/backend/models/replay_scanner.py b/products/replay_vision/backend/models/replay_scanner.py
index be49af9f686a..1c1708092248 100644
--- a/products/replay_vision/backend/models/replay_scanner.py
+++ b/products/replay_vision/backend/models/replay_scanner.py
@@ -156,6 +156,16 @@ class ReplayScanner(UUIDModel):
blank=True,
help_text="Watermark for the periodic full-events-lookback catch-up sweep; null until the first regular sweep initializes it.",
)
+ sweep_read_bytes_by_hour = models.JSONField(
+ null=True,
+ blank=True,
+ help_text="ClickHouse read bytes per hour bucket (ISO hour -> bytes), maintained by the read-metering workflow; drives the sweep throttle.",
+ )
+ sweep_throttle_factor_override = models.PositiveSmallIntegerField(
+ null=True,
+ blank=True,
+ help_text="Manual cadence-stretch multiplier; overrides the computed read-budget throttle. 1 disables throttling; null means automatic.",
+ )
# Shape: ScannerExperimentTargetingSerializer. Stored because the compiled `query` speaks flag
# keys, so the experiment association isn't recoverable from it. Not version-tracked; scanning
diff --git a/products/replay_vision/backend/queries/scanner_candidate_query.py b/products/replay_vision/backend/queries/scanner_candidate_query.py
index 350c86b54987..77e48a5f4a73 100644
--- a/products/replay_vision/backend/queries/scanner_candidate_query.py
+++ b/products/replay_vision/backend/queries/scanner_candidate_query.py
@@ -105,13 +105,13 @@ def eligibility_predicates() -> list[ast.Expr]:
def _execute_candidate_query(
- query: ast.SelectQuery, *, team: Team, query_type: str, max_execution_time_seconds: int
+ query: ast.SelectQuery, *, team: Team, query_type: str, max_execution_time_seconds: int, scanner_id: str | None
) -> list[list]:
"""One home for the candidate queries' ClickHouse execution policy.
The dedicated user keeps sweep and backfill admission out of the contended shared `default` pool.
"""
- with tags_context(product=Product.REPLAY_VISION, feature=Feature.ENRICHMENT):
+ with tags_context(product=Product.REPLAY_VISION, feature=Feature.ENRICHMENT, scanner_id=scanner_id):
response = execute_hogql_query(
query=query,
team=team,
@@ -143,6 +143,8 @@ class ScannerCandidateQuery:
candidate_limit: int = DEFAULT_CANDIDATE_LIMIT,
max_execution_time_seconds: int = DEFAULT_MAX_EXECUTION_SECONDS,
events_lookback: dt.timedelta | None = None,
+ # Tags the ClickHouse query for per-scanner read metering; sweep callers should always pass it.
+ scanner_id: str | None = None,
) -> None:
if not isinstance(last_swept_at, dt.datetime):
raise TypeError(f"last_swept_at must be a datetime, got {type(last_swept_at).__name__}")
@@ -160,6 +162,7 @@ class ScannerCandidateQuery:
self._sampling_salt = sampling_salt
self._candidate_limit = candidate_limit
self._max_execution_time_seconds = max_execution_time_seconds
+ self._scanner_id = scanner_id
# Fixed at construction and exposed so callers can persist exactly the horizon the query filtered on.
self.settle_cutoff = dt.datetime.now(dt.UTC) - SETTLE_INTERVAL
@@ -199,6 +202,7 @@ class ScannerCandidateQuery:
team=self._team,
query_type="ReplayVisionScannerCandidateQuery",
max_execution_time_seconds=self._max_execution_time_seconds,
+ scanner_id=self._scanner_id,
)
return [CandidateSession(session_id=row[0], session_end=row[1]) for row in rows]
@@ -312,6 +316,7 @@ class BackfillCandidateQuery:
exclude_session_ids: list[str] | None = None,
candidate_limit: int = DEFAULT_CANDIDATE_LIMIT,
max_execution_time_seconds: int = DEFAULT_MAX_EXECUTION_SECONDS,
+ scanner_id: str | None = None,
) -> None:
for name, value in (("window_start", window_start), ("window_end", window_end)):
if not isinstance(value, dt.datetime):
@@ -332,6 +337,7 @@ class BackfillCandidateQuery:
self._exclude_session_ids = exclude_session_ids
self._candidate_limit = candidate_limit
self._max_execution_time_seconds = max_execution_time_seconds
+ self._scanner_id = scanner_id
# The backfill owns the time window; the frozen scanner query only contributes filters.
inner_query = query.model_copy(deep=True)
@@ -362,6 +368,7 @@ class BackfillCandidateQuery:
team=self._team,
query_type="ReplayVisionBackfillCandidateQuery",
max_execution_time_seconds=self._max_execution_time_seconds,
+ scanner_id=self._scanner_id,
)
return [CandidateSession(session_id=row[0], session_end=row[1]) for row in rows]
@@ -376,6 +383,7 @@ class BackfillCandidateQuery:
team=self._team,
query_type="ReplayVisionBackfillCountQuery",
max_execution_time_seconds=self._max_execution_time_seconds,
+ scanner_id=self._scanner_id,
)
return int(rows[0][0]) if rows else 0
diff --git a/products/replay_vision/backend/temporal/__init__.py b/products/replay_vision/backend/temporal/__init__.py
index b454511c1750..cae8ea86e12a 100644
--- a/products/replay_vision/backend/temporal/__init__.py
+++ b/products/replay_vision/backend/temporal/__init__.py
@@ -27,6 +27,7 @@ from products.replay_vision.backend.temporal.activities import (
mark_observation_ineligible_activity,
mark_observation_running_activity,
mark_observation_succeeded_activity,
+ meter_scanner_read_bytes_activity,
pause_backfill_schedule_activity,
prepare_backfill_tick_activity,
reap_backfill_schedules_activity,
@@ -47,6 +48,7 @@ from products.replay_vision.backend.temporal.gemini_cleanup_sweep import (
ReplayVisionGeminiCleanupSweepWorkflow,
sweep_gemini_files_activity,
)
+from products.replay_vision.backend.temporal.read_meter import MeterScannerReadsWorkflow
from products.replay_vision.backend.temporal.reconciler import ReconcileScannerSchedulesWorkflow
from products.replay_vision.backend.temporal.sweep_workflow import SweepScannerWorkflow
from products.replay_vision.backend.temporal.vision_actions import (
@@ -65,6 +67,7 @@ WORKFLOWS = [
ApplyScannerWorkflow,
BackfillScannerWorkflow,
EvaluatePromptSuggestionWorkflow,
+ MeterScannerReadsWorkflow,
ReconcileScannerSchedulesWorkflow,
RefreshScannerEstimatesWorkflow,
ReplayVisionGeminiCleanupSweepWorkflow,
@@ -106,6 +109,7 @@ ACTIVITIES: list[Callable[..., Any]] = [
delete_scanner_schedule_activity,
list_stale_scanner_estimates_activity,
refresh_scanner_estimate_activity,
+ meter_scanner_read_bytes_activity,
reap_childless_inline_scanners_activity,
reap_orphaned_observations_activity,
reap_stuck_vision_action_runs_activity,
@@ -125,6 +129,7 @@ __all__ = [
"ApplyScannerWorkflow",
"BackfillScannerWorkflow",
"EvaluatePromptSuggestionWorkflow",
+ "MeterScannerReadsWorkflow",
"ProcessVisionActionWorkflow",
"ReconcileScannerSchedulesWorkflow",
"RefreshScannerEstimatesWorkflow",
@@ -155,6 +160,7 @@ __all__ = [
"list_enabled_scanners_activity",
"list_scanner_schedules_activity",
"list_stale_scanner_estimates_activity",
+ "meter_scanner_read_bytes_activity",
"mark_observation_failed_activity",
"mark_observation_ineligible_activity",
"mark_observation_running_activity",
diff --git a/products/replay_vision/backend/temporal/activities/__init__.py b/products/replay_vision/backend/temporal/activities/__init__.py
index 620d131c237f..533b6cd747ff 100644
--- a/products/replay_vision/backend/temporal/activities/__init__.py
+++ b/products/replay_vision/backend/temporal/activities/__init__.py
@@ -31,6 +31,7 @@ from products.replay_vision.backend.temporal.activities.find_scanner_candidates
from products.replay_vision.backend.temporal.activities.list_stale_scanner_estimates import (
list_stale_scanner_estimates_activity,
)
+from products.replay_vision.backend.temporal.activities.meter_scanner_reads import meter_scanner_read_bytes_activity
from products.replay_vision.backend.temporal.activities.observation_state import (
mark_observation_failed_activity,
mark_observation_ineligible_activity,
@@ -86,6 +87,7 @@ __all__ = [
"list_enabled_scanners_activity",
"list_scanner_schedules_activity",
"list_stale_scanner_estimates_activity",
+ "meter_scanner_read_bytes_activity",
"mark_observation_failed_activity",
"mark_observation_ineligible_activity",
"mark_observation_running_activity",
diff --git a/products/replay_vision/backend/temporal/activities/backfill.py b/products/replay_vision/backend/temporal/activities/backfill.py
index 5d6dfc573e10..693f28e88c61 100644
--- a/products/replay_vision/backend/temporal/activities/backfill.py
+++ b/products/replay_vision/backend/temporal/activities/backfill.py
@@ -150,6 +150,7 @@ def find_backfill_candidates_activity(inputs: FindBackfillCandidatesInputs) -> F
sampling_rate=snapshot.sampling_rate,
# Same salt as the live sweep, so a sampled scanner backfills the same deterministic bucket it scans live.
sampling_salt=str(backfill.scanner_id),
+ scanner_id=str(backfill.scanner_id),
sampling_mode=snapshot.sampling_mode,
cursor_end_time=backfill.cursor_end_time,
cursor_session_id=backfill.cursor_session_id or None,
diff --git a/products/replay_vision/backend/temporal/activities/find_scanner_candidates.py b/products/replay_vision/backend/temporal/activities/find_scanner_candidates.py
index 58cb7fe89e1b..f219fd7eae1a 100644
--- a/products/replay_vision/backend/temporal/activities/find_scanner_candidates.py
+++ b/products/replay_vision/backend/temporal/activities/find_scanner_candidates.py
@@ -11,7 +11,7 @@ from posthog.schema import RecordingsQuery
from posthog.rbac.user_access_control import UserAccessControl
from products.replay_vision.backend.models.replay_observation import ReplayObservation
-from products.replay_vision.backend.models.replay_scanner import ReplayScanner
+from products.replay_vision.backend.models.replay_scanner import SETTLE_INTERVAL, ReplayScanner
from products.replay_vision.backend.queries.scanner_candidate_query import (
DEFAULT_CANDIDATE_LIMIT,
SWEEP_EVENTS_LOOKBACK,
@@ -19,9 +19,14 @@ from products.replay_vision.backend.queries.scanner_candidate_query import (
CandidateSession,
ScannerCandidateQuery,
)
-from products.replay_vision.backend.temporal.constants import DEEP_SWEEP_INTERVAL, DEEP_SWEEP_MAX_EXECUTION_SECONDS
+from products.replay_vision.backend.temporal.constants import (
+ DEEP_SWEEP_INTERVAL,
+ DEEP_SWEEP_MAX_EXECUTION_SECONDS,
+ SCANNER_SCHEDULE_INTERVAL,
+)
from products.replay_vision.backend.temporal.decorators import track_activity
from products.replay_vision.backend.temporal.metrics import record_sweep_outcome
+from products.replay_vision.backend.temporal.read_meter_types import sweep_spend_bytes_24h, sweep_throttle_factor
from products.replay_vision.backend.temporal.sweep_types import (
CandidateSessionPayload,
FindScannerCandidatesInputs,
@@ -54,6 +59,11 @@ def find_scanner_candidates_activity(inputs: FindScannerCandidatesInputs) -> Fin
f"ReplayScanner {inputs.scanner_id} has malformed query: {exc}", non_retryable=True
) from exc
+ if _throttled(scanner):
+ record_sweep_outcome("throttled")
+ # No watermark advance, so the next executed sweep covers the skipped range in one query.
+ return FindScannerCandidatesOutput(candidates=[], saturated=False)
+
limit = inputs.candidate_limit if inputs.candidate_limit is not None else DEFAULT_CANDIDATE_LIMIT
candidate_query = ScannerCandidateQuery(
team=scanner.team,
@@ -65,6 +75,7 @@ def find_scanner_candidates_activity(inputs: FindScannerCandidatesInputs) -> Fin
last_seen_session_id=scanner.last_seen_session_id or None,
candidate_limit=limit,
events_lookback=SWEEP_EVENTS_LOOKBACK,
+ scanner_id=str(scanner.id),
)
candidates = candidate_query.run()
# A full batch means there may be more past the keyset; the next sweep resumes from the last candidate.
@@ -103,6 +114,23 @@ def find_scanner_candidates_activity(inputs: FindScannerCandidatesInputs) -> Fin
_DEEP_SWEEP_MAX_EXCLUSIONS = 20_000
+def _throttled(scanner: ReplayScanner) -> bool:
+ """True when this tick should be skipped to keep the scanner inside its 24h read budget.
+
+ The factor stretches the effective cadence: factor N means one executed sweep per N schedule
+ intervals. Distance is measured watermark-to-settle-horizon, so a saturated keyset walk (watermark
+ lagging behind the horizon) is never throttled harder while it drains its backlog.
+ """
+ now = dt.datetime.now(dt.UTC)
+ factor = sweep_throttle_factor(
+ sweep_spend_bytes_24h(scanner.sweep_read_bytes_by_hour, now),
+ scanner.sweep_throttle_factor_override,
+ )
+ if factor <= 1:
+ return False
+ return (now - SETTLE_INTERVAL) - scanner.last_swept_at < SCANNER_SCHEDULE_INTERVAL * factor
+
+
def _deep_sweep(
scanner: ReplayScanner, query: RecordingsQuery, limit: int
) -> tuple[list[CandidateSession], dt.datetime | None]:
@@ -140,6 +168,7 @@ def _deep_sweep(
exclude_session_ids=observed_session_ids,
candidate_limit=limit,
max_execution_time_seconds=DEEP_SWEEP_MAX_EXECUTION_SECONDS,
+ scanner_id=str(scanner.id),
)
deep_candidates = deep_query.run()
if len(deep_candidates) == limit and len(observed_session_ids) < _DEEP_SWEEP_MAX_EXCLUSIONS:
diff --git a/products/replay_vision/backend/temporal/activities/meter_scanner_reads.py b/products/replay_vision/backend/temporal/activities/meter_scanner_reads.py
new file mode 100644
index 000000000000..df1128f7b006
--- /dev/null
+++ b/products/replay_vision/backend/temporal/activities/meter_scanner_reads.py
@@ -0,0 +1,92 @@
+import datetime as dt
+from uuid import UUID
+
+from temporalio import activity
+
+from posthog.clickhouse.client import sync_execute
+from posthog.clickhouse.workload import Workload
+
+from products.replay_vision.backend.models.replay_scanner import ReplayScanner
+from products.replay_vision.backend.temporal.decorators import track_activity
+from products.replay_vision.backend.temporal.read_meter_types import MeterScannerReadsResult
+
+# Re-scan the last two full hours plus the current partial one. Buckets overwrite per hour key, so
+# the overlap with the previous run never double-counts, and a late-flushing query_log entry still
+# lands in its (re-scanned, complete) hour bucket.
+_FULL_HOURS_RESCANNED = 2
+
+_READ_BYTES_BY_SCANNER_HOUR_SQL = """
+SELECT
+ JSONExtractString(log_comment, 'scanner_id') AS scanner_id,
+ toStartOfHour(toTimeZone(event_time, 'UTC')) AS hour,
+ sum(read_bytes) AS read_bytes
+FROM clusterAllReplicas(%(cluster)s, system.query_log)
+WHERE event_date >= today() - 1
+ AND event_time >= %(since)s
+ AND type > 1
+ AND is_initial_query
+ -- Substring match first so the JSON parsing only runs on this product's rows rather than on
+ -- every query the cluster logged.
+ AND log_comment LIKE '%%replay_vision%%'
+ AND JSONExtractString(log_comment, 'product') = 'replay_vision'
+ AND scanner_id != ''
+GROUP BY scanner_id, hour
+"""
+
+
+@track_activity()
+def meter_scanner_read_bytes_activity() -> MeterScannerReadsResult:
+ """Fold recent per-scanner ClickHouse read bytes from query_log into hour buckets on the scanner rows."""
+ from django.conf import settings # noqa: PLC0415 — Django settings are unavailable at sandbox import time
+
+ now = dt.datetime.now(dt.UTC)
+ # Hour-aligned so every scanned hour bucket is covered in full, making the overwrite monotone-correct.
+ since = now.replace(minute=0, second=0, microsecond=0) - dt.timedelta(hours=_FULL_HOURS_RESCANNED)
+ rows = sync_execute(
+ _READ_BYTES_BY_SCANNER_HOUR_SQL,
+ {"cluster": settings.CLICKHOUSE_CLUSTER, "since": since},
+ workload=Workload.OFFLINE,
+ settings={"max_execution_time": 120, "skip_unavailable_shards": 1},
+ )
+
+ by_scanner: dict[str, dict[str, int]] = {}
+ for scanner_id, hour, read_bytes in rows:
+ # The tag is a free-form string in the query log, so a junk value must not take the run down.
+ if not _is_uuid(scanner_id):
+ continue
+ by_scanner.setdefault(scanner_id, {})[hour.replace(tzinfo=dt.UTC).isoformat()] = int(read_bytes)
+
+ prune_cutoff = now - dt.timedelta(hours=25)
+ scanners = list(ReplayScanner.objects.filter(pk__in=by_scanner.keys()).only("id", "sweep_read_bytes_by_hour"))
+ for scanner in scanners:
+ buckets = dict(scanner.sweep_read_bytes_by_hour or {})
+ buckets.update(by_scanner[str(scanner.id)])
+ fresh = {}
+ for hour_iso, read_bytes in buckets.items():
+ hour = _parse_hour(hour_iso)
+ if hour is not None and hour >= prune_cutoff:
+ fresh[hour_iso] = read_bytes
+ scanner.sweep_read_bytes_by_hour = fresh
+ # One statement per batch rather than per scanner: this runs hourly over every active scanner.
+ ReplayScanner.objects.bulk_update(scanners, ["sweep_read_bytes_by_hour"], batch_size=500)
+
+ activity.logger.info("replay_vision.read_meter_updated", extra={"scanners": len(scanners)})
+ return MeterScannerReadsResult(scanners_updated=len(scanners))
+
+
+def _is_uuid(value: str) -> bool:
+ try:
+ UUID(value)
+ except ValueError:
+ return False
+ return True
+
+
+def _parse_hour(hour_iso: str) -> dt.datetime | None:
+ """Parse a bucket key, treating a naive value as UTC so comparisons cannot raise."""
+ try:
+ hour = dt.datetime.fromisoformat(hour_iso)
+ except (TypeError, ValueError):
+ return None
+ return hour if hour.tzinfo is not None else hour.replace(tzinfo=dt.UTC)
diff --git a/products/replay_vision/backend/temporal/constants.py b/products/replay_vision/backend/temporal/constants.py
index f8bf3dc274a9..e7fe1ff52ad8 100644
--- a/products/replay_vision/backend/temporal/constants.py
+++ b/products/replay_vision/backend/temporal/constants.py
@@ -56,6 +56,21 @@ DEEP_SWEEP_INTERVAL = dt.timedelta(hours=6)
# share: it is catch-up work, and a tick that overruns retries both queries.
DEEP_SWEEP_MAX_EXECUTION_SECONDS = 60
+# Rolling 24h ClickHouse read budget per scanner. Above it, sweeps stretch their effective cadence
+# proportionally (skipped ticks batch into the next executed one, so no sessions are missed).
+# Sized an order of magnitude above the healthy post-optimization p95 so only pathological
+# filter configurations are ever throttled.
+SWEEP_READ_BUDGET_BYTES_24H = 200 * 1024**3
+# Cadence stretch ceiling: worst case one sweep an hour, so a throttled scanner stays usable.
+SWEEP_THROTTLE_MAX_FACTOR = 12
+
+READ_METER_WORKFLOW_NAME = "replay-vision-meter-scanner-reads"
+READ_METER_WORKFLOW_ID = "replay-vision-scanner-read-meter"
+READ_METER_SCHEDULE_ID = "replay-vision-scanner-read-meter-schedule"
+READ_METER_INTERVAL = dt.timedelta(hours=1)
+READ_METER_EXECUTION_TIMEOUT = dt.timedelta(minutes=10)
+METER_SCANNER_READS_TIMEOUT = dt.timedelta(minutes=5)
+
# Children are ABANDONed and don't count against this budget, but activities do: this must cover the
# prompt-suggestion refresh worst case plus the candidate scan, or a slow refresh kills the whole sweep.
# Overlap SKIP means a slow run absorbs later ticks instead of stacking.
diff --git a/products/replay_vision/backend/temporal/read_meter.py b/products/replay_vision/backend/temporal/read_meter.py
new file mode 100644
index 000000000000..4a3648ee1784
--- /dev/null
+++ b/products/replay_vision/backend/temporal/read_meter.py
@@ -0,0 +1,60 @@
+"""Per-scanner ClickHouse read metering and the sweep throttle it drives.
+
+An hourly workflow aggregates `system.query_log` read bytes by the `scanner_id` query tag into
+hourly buckets on each scanner row. The sweep consults the trailing-24h sum before querying and
+stretches its effective cadence when a scanner exceeds its read budget (see `sweep_throttle_factor`).
+"""
+
+from typing import TYPE_CHECKING
+
+from temporalio import workflow
+from temporalio.common import RetryPolicy
+
+from posthog.temporal.common.base import PostHogWorkflow
+
+from products.replay_vision.backend.temporal.constants import (
+ METER_SCANNER_READS_TIMEOUT,
+ READ_METER_EXECUTION_TIMEOUT,
+ READ_METER_INTERVAL,
+ READ_METER_SCHEDULE_ID,
+ READ_METER_WORKFLOW_ID,
+ READ_METER_WORKFLOW_NAME,
+)
+from products.replay_vision.backend.temporal.read_meter_types import MeterScannerReadsInputs, MeterScannerReadsResult
+
+if TYPE_CHECKING:
+ from temporalio.client import Client
+
+with workflow.unsafe.imports_passed_through():
+ from products.replay_vision.backend.temporal.activities import meter_scanner_read_bytes_activity
+
+
[email protected](name=READ_METER_WORKFLOW_NAME)
+class MeterScannerReadsWorkflow(PostHogWorkflow):
+ inputs_cls = MeterScannerReadsInputs
+ inputs_optional = True
+
+ @workflow.run
+ async def run(self, inputs: MeterScannerReadsInputs) -> MeterScannerReadsResult:
+ return await workflow.execute_activity(
+ meter_scanner_read_bytes_activity,
+ start_to_close_timeout=METER_SCANNER_READS_TIMEOUT,
+ retry_policy=RetryPolicy(maximum_attempts=3),
+ )
+
+
+async def create_replay_vision_read_meter_schedule(client: "Client") -> None:
+ """Upsert the hourly read-meter schedule. Called on worker startup."""
+ # Function-local: with `@workflow.defn` above, the Temporal sandbox can't
+ # re-import the helper's Django/temporalio.client dependencies at workflow load.
+ from products.replay_vision.backend.temporal.schedule import upsert_interval_schedule # noqa: PLC0415
+
+ await upsert_interval_schedule(
+ client,
+ schedule_id=READ_METER_SCHEDULE_ID,
+ workflow_name=READ_METER_WORKFLOW_NAME,
+ workflow_id=READ_METER_WORKFLOW_ID,
+ inputs=MeterScannerReadsInputs(),
+ interval=READ_METER_INTERVAL,
+ execution_timeout=READ_METER_EXECUTION_TIMEOUT,
+ )
diff --git a/products/replay_vision/backend/temporal/read_meter_types.py b/products/replay_vision/backend/temporal/read_meter_types.py
new file mode 100644
index 000000000000..90a3198d24e0
--- /dev/null
+++ b/products/replay_vision/backend/temporal/read_meter_types.py
@@ -0,0 +1,46 @@
+"""Types and pure throttle math for the scanner read metering — a dependency leaf, so the
+sweep activity can use the throttle without importing the workflow module."""
+
+import datetime as dt
+
+from pydantic import BaseModel
+
+from products.replay_vision.backend.temporal.constants import SWEEP_READ_BUDGET_BYTES_24H, SWEEP_THROTTLE_MAX_FACTOR
+
+
+class MeterScannerReadsInputs(BaseModel, frozen=True):
+ pass
+
+
+class MeterScannerReadsResult(BaseModel, frozen=True):
+ scanners_updated: int = 0
+
+
+def sweep_spend_bytes_24h(read_bytes_by_hour: dict[str, int] | None, now: dt.datetime) -> int:
+ """Trailing-24h read spend from the metered hour buckets; tolerates stale, unpruned entries."""
+ if not read_bytes_by_hour:
+ return 0
+ cutoff = now - dt.timedelta(hours=24)
+ total = 0
+ for hour_iso, read_bytes in read_bytes_by_hour.items():
+ # A malformed bucket must not raise: this runs inside the sweep, so an exception here would
+ # stop the scanner entirely rather than just mis-reporting its spend.
+ try:
+ hour = dt.datetime.fromisoformat(hour_iso)
+ if hour.tzinfo is None:
+ hour = hour.replace(tzinfo=dt.UTC)
+ if hour >= cutoff:
+ total += int(read_bytes)
+ except (TypeError, ValueError):
+ continue
+ return total
+
+
+def sweep_throttle_factor(spend_bytes: int, override: int | None) -> int:
+ """Cadence-stretch multiplier: 1 means sweep normally, N means sweep every N schedule intervals."""
+ if override is not None:
+ return max(1, min(override, SWEEP_THROTTLE_MAX_FACTOR))
+ # Rounds up, so any spend past the budget stretches the cadence. Rounding to nearest would leave a
+ # scanner between one and one and a half budgets running at full rate despite being over.
+ factor = -(-spend_bytes // SWEEP_READ_BUDGET_BYTES_24H)
+ return max(1, min(factor, SWEEP_THROTTLE_MAX_FACTOR))
diff --git a/products/replay_vision/backend/tests/test_read_meter.py b/products/replay_vision/backend/tests/test_read_meter.py
new file mode 100644
index 000000000000..0bc1edfce31d
--- /dev/null
+++ b/products/replay_vision/backend/tests/test_read_meter.py
@@ -0,0 +1,104 @@
+import datetime as dt
+
+import pytest
+from unittest.mock import patch
+
+from parameterized import parameterized
+
+from products.replay_vision.backend.temporal.activities.meter_scanner_reads import meter_scanner_read_bytes_activity
+from products.replay_vision.backend.temporal.constants import SWEEP_READ_BUDGET_BYTES_24H
+from products.replay_vision.backend.temporal.read_meter_types import sweep_spend_bytes_24h, sweep_throttle_factor
+
+_NOW = dt.datetime(2026, 8, 12, 12, 0, 0, tzinfo=dt.UTC)
+
+
+def _hour(hours_ago: int) -> str:
+ return (_NOW - dt.timedelta(hours=hours_ago)).replace(minute=0, second=0, microsecond=0).isoformat()
+
+
+class TestThrottleMath:
+ @parameterized.expand(
+ [
+ ("under_budget", SWEEP_READ_BUDGET_BYTES_24H // 2, None, 1),
+ ("at_budget", SWEEP_READ_BUDGET_BYTES_24H, None, 1),
+ # Just over the budget still has to throttle; nearest-rounding used to let this run free.
+ ("just_over_budget", SWEEP_READ_BUDGET_BYTES_24H + 1, None, 2),
+ ("well_under_one_and_a_half", int(SWEEP_READ_BUDGET_BYTES_24H * 1.25), None, 2),
+ ("ten_times_budget", SWEEP_READ_BUDGET_BYTES_24H * 10, None, 10),
+ ("capped_at_max", SWEEP_READ_BUDGET_BYTES_24H * 100, None, 12),
+ ("override_wins_over_spend", SWEEP_READ_BUDGET_BYTES_24H * 100, 1, 1),
+ ("override_forces_throttle", 0, 6, 6),
+ ("override_capped", 0, 99, 12),
+ ]
+ )
+ def test_sweep_throttle_factor(self, _name: str, spend: int, override: int | None, expected: int) -> None:
+ assert sweep_throttle_factor(spend, override) == expected
+
+ def test_spend_sums_only_trailing_24h_and_tolerates_junk(self) -> None:
+ buckets = {
+ _hour(1): 100,
+ _hour(23): 200,
+ _hour(30): 4_000_000, # stale, unpruned — must not count
+ "not-a-timestamp": 5_000_000,
+ }
+ assert sweep_spend_bytes_24h(buckets, _NOW) == 300
+
+ def test_naive_bucket_key_is_treated_as_utc_not_raised(self) -> None:
+ # This runs inside the sweep, so raising here would stop the scanner rather than mis-report it.
+ naive = (_NOW - dt.timedelta(hours=1)).replace(tzinfo=None).isoformat()
+ assert sweep_spend_bytes_24h({naive: 7}, _NOW) == 7
+
+ def test_spend_of_empty_buckets_is_zero(self) -> None:
+ assert sweep_spend_bytes_24h(None, _NOW) == 0
+ assert sweep_spend_bytes_24h({}, _NOW) == 0
+
+
[email protected]_db(transaction=True)
+class TestMeterScannerReadsActivity:
+ def test_junk_scanner_tag_does_not_take_down_the_run(self) -> None:
+ # scanner_id is a free-form string in the query log, so a non-UUID must be skipped rather
+ # than blowing up the pk__in lookup for every other scanner in the batch.
+ from products.replay_vision.backend.tests.test_sweep import _make_scanner
+
+ scanner = _make_scanner()
+ hour = dt.datetime.now(dt.UTC).replace(minute=0, second=0, microsecond=0)
+ with patch(
+ "products.replay_vision.backend.temporal.activities.meter_scanner_reads.sync_execute",
+ return_value=[
+ ("not-a-uuid", hour.replace(tzinfo=None), 11),
+ (str(scanner.id), hour.replace(tzinfo=None), 22),
+ ],
+ ):
+ result = meter_scanner_read_bytes_activity()
+
+ assert result.scanners_updated == 1
+ scanner.refresh_from_db()
+ assert scanner.sweep_read_bytes_by_hour == {hour.isoformat(): 22}
+
+ def test_folds_query_log_rows_into_hour_buckets_and_prunes(self) -> None:
+ from products.replay_vision.backend.tests.test_sweep import _make_scanner
+
+ scanner = _make_scanner()
+ stale_hour = (dt.datetime.now(dt.UTC) - dt.timedelta(hours=30)).isoformat()
+ fresh_hour = (dt.datetime.now(dt.UTC) - dt.timedelta(hours=2)).replace(minute=0, second=0, microsecond=0)
+ scanner.sweep_read_bytes_by_hour = {stale_hour: 999, fresh_hour.isoformat(): 50}
+ scanner.save(update_fields=["sweep_read_bytes_by_hour"])
+
+ current_hour = dt.datetime.now(dt.UTC).replace(minute=0, second=0, microsecond=0)
+ with patch(
+ "products.replay_vision.backend.temporal.activities.meter_scanner_reads.sync_execute",
+ return_value=[
+ # Re-scanned bucket overwrites (never sums with) the stored value for the same hour.
+ (str(scanner.id), fresh_hour.replace(tzinfo=None), 70),
+ (str(scanner.id), current_hour.replace(tzinfo=None), 40),
+ ("00000000-0000-0000-0000-000000000000", current_hour.replace(tzinfo=None), 123),
+ ],
+ ):
+ result = meter_scanner_read_bytes_activity()
+
+ assert result.scanners_updated == 1
+ scanner.refresh_from_db()
+ assert scanner.sweep_read_bytes_by_hour == {
+ fresh_hour.isoformat(): 70,
+ current_hour.isoformat(): 40,
+ }
diff --git a/products/replay_vision/backend/tests/test_sweep.py b/products/replay_vision/backend/tests/test_sweep.py
index a073b2ab3f15..f5661b373cbc 100644
--- a/products/replay_vision/backend/tests/test_sweep.py
+++ b/products/replay_vision/backend/tests/test_sweep.py
@@ -36,6 +36,7 @@ from products.replay_vision.backend.temporal.activities.refresh_prompt_suggestio
from products.replay_vision.backend.temporal.constants import (
MAX_IN_FLIGHT_APPLIES_PER_SCANNER,
MAX_IN_FLIGHT_APPLIES_PER_TEAM,
+ SWEEP_READ_BUDGET_BYTES_24H,
build_process_vision_action_workflow_id,
)
from products.replay_vision.backend.temporal.sweep_types import (
@@ -378,6 +379,41 @@ class TestFindScannerCandidatesActivity:
# The walk is newest-first, so advancing on a truncated batch would drop the oldest for good.
assert result.deep_swept_through is None
+ @parameterized.expand(
+ [
+ # Default watermark sits one settle-interval back, i.e. the last sweep just ran.
+ ("over_budget_recent_sweep_skips", None, dt.timedelta(0), False),
+ # Enough watermark lag accumulated (>= 12 x 5 min at the factor cap): the sweep runs and batches it.
+ ("over_budget_stale_watermark_runs", None, dt.timedelta(minutes=61), True),
+ ("override_disables_throttle", 1, dt.timedelta(0), True),
+ ]
+ )
+ def test_read_budget_throttle(
+ self, _name: str, override: int | None, extra_watermark_lag: dt.timedelta, expect_query: bool
+ ) -> None:
+ hour = dt.datetime.now(dt.UTC).replace(minute=0, second=0, microsecond=0)
+ scanner = _make_scanner(
+ sweep_read_bytes_by_hour={hour.isoformat(): 100 * SWEEP_READ_BUDGET_BYTES_24H},
+ sweep_throttle_factor_override=override,
+ )
+ if extra_watermark_lag:
+ scanner.last_swept_at = scanner.last_swept_at - extra_watermark_lag
+ scanner.save(update_fields=["last_swept_at"])
+
+ with patch(
+ "products.replay_vision.backend.temporal.activities.find_scanner_candidates.ScannerCandidateQuery"
+ ) as MockQuery:
+ MockQuery.return_value.run.return_value = []
+ result = find_scanner_candidates_activity(
+ FindScannerCandidatesInputs(scanner_id=scanner.id, team_id=scanner.team_id)
+ )
+
+ assert MockQuery.called is expect_query
+ if not expect_query:
+ # No horizon means the workflow can't advance the watermark, so the skipped range stays covered.
+ assert result.swept_through is None
+ assert result.candidates == []
+
def test_raises_non_retryable_on_malformed_query(self) -> None:
scanner = _make_scanner()
scanner.query = {"kind": "TrendsQuery"}