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): throttle the deep sweep on its own read spend (#84098)

Tue Haulundeb5f91c99ec9
diff --git a/products/replay_vision/backend/api/backfills.py b/products/replay_vision/backend/api/backfills.py
index 7a335449442a..2f06bff2241d 100644
--- a/products/replay_vision/backend/api/backfills.py
+++ b/products/replay_vision/backend/api/backfills.py
@@ -30,7 +30,11 @@ from products.replay_vision.backend.models.replay_scanner_backfill import (
BackfillStatus,
ReplayScannerBackfill,
)
-from products.replay_vision.backend.queries.scanner_candidate_query import WindowedCandidateQuery
+from products.replay_vision.backend.queries.scanner_candidate_query import (
+ BACKFILL_CANDIDATE_QUERY_TYPE,
+ BACKFILL_COUNT_QUERY_TYPE,
+ WindowedCandidateQuery,
+)
from products.replay_vision.backend.quota import quota_state
from products.replay_vision.backend.temporal.snapshots import BackfillScannerSnapshot
@@ -220,14 +224,14 @@ class ReplayScannerBackfillViewSet(
query=scanner.recordings_query(),
window_start=window_start,
window_end=window_end,
- query_type="ReplayVisionBackfillCandidateQuery",
+ query_type=BACKFILL_CANDIDATE_QUERY_TYPE,
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,
- ).count(query_type="ReplayVisionBackfillCountQuery")
+ ).count(query_type=BACKFILL_COUNT_QUERY_TYPE)
def _unobserved_count(self, scanner: ReplayScanner, window_start: datetime, window_end: datetime) -> int:
"""Upper bound on what a backfill over this window would scan, rejecting when it is zero.
diff --git a/products/replay_vision/backend/migrations/0077_replayscanner_deep_sweep_fields.py b/products/replay_vision/backend/migrations/0077_replayscanner_deep_sweep_fields.py
new file mode 100644
index 000000000000..70de350789c1
--- /dev/null
+++ b/products/replay_vision/backend/migrations/0077_replayscanner_deep_sweep_fields.py
@@ -0,0 +1,77 @@
+# Generated by Django 5.2.17 on 2026-08-19 09:30
+
+from django.db import migrations, models
+
+
+class Migration(migrations.Migration):
+ dependencies = [
+ ("replay_vision", "0076_remap_scanner_models_gemini_3_7"),
+ ]
+
+ operations = [
+ migrations.AddField(
+ model_name="replayscanner",
+ name="deep_attempted_at",
+ field=models.DateTimeField(
+ blank=True,
+ help_text="When the deep pass last started; its cadence gates on this rather than on progress, so a cut-short pass still waits out its interval.",
+ null=True,
+ ),
+ ),
+ migrations.AddField(
+ model_name="replayscanner",
+ name="deep_read_bytes_by_hour",
+ field=models.JSONField(
+ blank=True,
+ help_text="ClickHouse read bytes per hour bucket for the deep catch-up pass only; drives its own cadence stretch independently of the frequent sweep.",
+ null=True,
+ ),
+ ),
+ migrations.AddField(
+ model_name="replayscanner",
+ name="deep_seen_session_id",
+ field=models.CharField(
+ blank=True,
+ db_default="",
+ default="",
+ help_text="Keyset tiebreaker paired with deep_swept_through, because a watermark moved without its tiebreaker skips every session tied at that timestamp.",
+ max_length=200,
+ ),
+ ),
+ migrations.AddField(
+ model_name="replayscanner",
+ name="deep_swept_through",
+ field=models.DateTimeField(
+ blank=True,
+ help_text="Watermark for the full-events-lookback catch-up pass; null until the first regular sweep seeds it.",
+ null=True,
+ ),
+ ),
+ migrations.AddField(
+ model_name="replayscanner",
+ name="fast_read_bytes_by_hour",
+ field=models.JSONField(
+ blank=True,
+ help_text="ClickHouse read bytes per hour bucket for the frequent sweep's own queries; drives its throttle, so backfill and catch-up reads do not stretch the cadence users see.",
+ null=True,
+ ),
+ ),
+ migrations.AlterField(
+ model_name="replayscanner",
+ name="sweep_read_bytes_by_hour",
+ field=models.JSONField(
+ blank=True,
+ help_text="Total ClickHouse read bytes per hour bucket (ISO hour -> bytes) across every pass, maintained by the read-metering workflow. Reporting only: each pass throttles on its own bucket.",
+ null=True,
+ ),
+ ),
+ migrations.AlterField(
+ model_name="replayscanner",
+ name="sweep_throttle_factor_override",
+ field=models.PositiveSmallIntegerField(
+ blank=True,
+ help_text="Manual cadence-stretch multiplier for the frequent sweep; overrides its computed read-budget throttle. 1 disables throttling; null means automatic. Does not affect the deep catch-up pass, which stretches on its own spend.",
+ null=True,
+ ),
+ ),
+ ]
diff --git a/products/replay_vision/backend/migrations/0078_migrate_deep_sweep_watermark.py b/products/replay_vision/backend/migrations/0078_migrate_deep_sweep_watermark.py
new file mode 100644
index 000000000000..2a60e8523951
--- /dev/null
+++ b/products/replay_vision/backend/migrations/0078_migrate_deep_sweep_watermark.py
@@ -0,0 +1,38 @@
+from django.db import migrations
+from django.db.models import F
+
+
+def copy_watermark_into_deep_fields(apps, schema_editor):
+ """Seed the new columns so no scanner reads as never deep-swept.
+
+ `deep_attempted_at` is seeded too: the settled-since-last-edit check compares `updated_at` against
+ it, and leaving it null would send every no-event-filter scanner through one full-width deep query
+ it used to skip.
+ """
+ ReplayScanner = apps.get_model("replay_vision", "ReplayScanner")
+ ReplayScanner.objects.exclude(last_deep_swept_at=None).update(
+ deep_swept_through=F("last_deep_swept_at"),
+ deep_attempted_at=F("last_deep_swept_at"),
+ )
+
+
+def copy_watermark_back(apps, schema_editor):
+ """Put the position back where reverted code reads it, covering scanners created after this migration."""
+ ReplayScanner = apps.get_model("replay_vision", "ReplayScanner")
+ ReplayScanner.objects.exclude(deep_swept_through=None).update(last_deep_swept_at=F("deep_swept_through"))
+
+
+class Migration(migrations.Migration):
+ dependencies = [
+ ("replay_vision", "0077_replayscanner_deep_sweep_fields"),
+ ]
+
+ operations = [
+ migrations.RunPython(copy_watermark_into_deep_fields, copy_watermark_back),
+ # State only: the column stays so the currently deployed workers, which still select it, keep
+ # working through the rollout. Dropping it is a separate change after a full deploy cycle.
+ migrations.SeparateDatabaseAndState(
+ state_operations=[migrations.RemoveField(model_name="replayscanner", name="last_deep_swept_at")],
+ database_operations=[],
+ ),
+ ]
diff --git a/products/replay_vision/backend/migrations/max_migration.txt b/products/replay_vision/backend/migrations/max_migration.txt
index 58f8f8bcc8e5..5c78554476f0 100644
--- a/products/replay_vision/backend/migrations/max_migration.txt
+++ b/products/replay_vision/backend/migrations/max_migration.txt
@@ -1 +1 @@
-0076_remap_scanner_models_gemini_3_7
+0078_migrate_deep_sweep_watermark
diff --git a/products/replay_vision/backend/models/replay_scanner.py b/products/replay_vision/backend/models/replay_scanner.py
index 7657a1b3c70c..5a016f357b2d 100644
--- a/products/replay_vision/backend/models/replay_scanner.py
+++ b/products/replay_vision/backend/models/replay_scanner.py
@@ -151,20 +151,42 @@ class ReplayScanner(UUIDModel):
db_default="",
help_text="Keyset tiebreaker; set when the last batch saturated so the next sweep resumes past session_end ties.",
)
- last_deep_swept_at = models.DateTimeField(
+ deep_swept_through = models.DateTimeField(
null=True,
blank=True,
- help_text="Watermark for the periodic full-events-lookback catch-up sweep; null until the first regular sweep initializes it.",
+ help_text="Watermark for the full-events-lookback catch-up pass; null until the first regular sweep seeds it.",
+ )
+ deep_seen_session_id = models.CharField(
+ max_length=200,
+ blank=True,
+ default="",
+ db_default="",
+ help_text="Keyset tiebreaker paired with deep_swept_through, because a watermark moved without its tiebreaker skips every session tied at that timestamp.",
+ )
+ deep_attempted_at = models.DateTimeField(
+ null=True,
+ blank=True,
+ help_text="When the deep pass last started; its cadence gates on this rather than on progress, so a cut-short pass still waits out its interval.",
)
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.",
+ help_text="Total ClickHouse read bytes per hour bucket (ISO hour -> bytes) across every pass, maintained by the read-metering workflow. Reporting only: each pass throttles on its own bucket.",
+ )
+ fast_read_bytes_by_hour = models.JSONField(
+ null=True,
+ blank=True,
+ help_text="ClickHouse read bytes per hour bucket for the frequent sweep's own queries; drives its throttle, so backfill and catch-up reads do not stretch the cadence users see.",
+ )
+ deep_read_bytes_by_hour = models.JSONField(
+ null=True,
+ blank=True,
+ help_text="ClickHouse read bytes per hour bucket for the deep catch-up pass only; drives its own cadence stretch independently of the frequent sweep.",
)
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.",
+ help_text="Manual cadence-stretch multiplier for the frequent sweep; overrides its computed read-budget throttle. 1 disables throttling; null means automatic. Does not affect the deep catch-up pass, which stretches on its own spend.",
)
# Shape: ScannerExperimentTargetingSerializer. Stored because the compiled `query` speaks flag
@@ -274,6 +296,19 @@ class ReplayScanner(UUIDModel):
# Fields the persisted volume estimate is computed from; changing them marks the estimate stale.
_ESTIMATE_FIELDS = frozenset({"query", "sampling_rate", "sampling_mode"})
+ # Written by sweeps and the read meter through queryset updates; a stale full save must not clobber them.
+ _MACHINE_OWNED_FIELDS = (
+ "last_swept_at",
+ "last_seen_session_id",
+ "deep_swept_through",
+ "deep_seen_session_id",
+ "deep_attempted_at",
+ "sweep_read_bytes_by_hour",
+ "fast_read_bytes_by_hour",
+ "deep_read_bytes_by_hour",
+ "limit_notified_period_start",
+ )
+
def save(self, *args, **kwargs) -> None:
update_fields = kwargs.get("update_fields")
if update_fields is not None:
@@ -291,23 +326,13 @@ class ReplayScanner(UUIDModel):
type(self)
.all_origins.select_for_update()
.filter(pk=self.pk)
- .only(
- "scanner_version",
- "enabled",
- "last_swept_at",
- "last_seen_session_id",
- "limit_notified_period_start",
- *relevant,
- )
+ .only("scanner_version", "enabled", *self._MACHINE_OWNED_FIELDS, *relevant)
.first()
)
if old is not None:
if update_fields is None:
- # The sweep writes these via targeted updates; a stale full save must not
- # clobber a concurrent sweep's watermark or notification stamp.
- self.last_swept_at = old.last_swept_at
- self.last_seen_session_id = old.last_seen_session_id
- self.limit_notified_period_start = old.limit_notified_period_start
+ for field in self._MACHINE_OWNED_FIELDS:
+ setattr(self, field, getattr(old, field))
changed = {f for f in relevant if getattr(old, f) != getattr(self, f)}
extra_fields = []
if changed:
@@ -322,8 +347,11 @@ class ReplayScanner(UUIDModel):
self.last_seen_session_id = ""
# The deep pass sweeps from this watermark up to the fast one, so leaving it
# behind would make its first window span the whole disabled gap.
- self.last_deep_swept_at = self.last_swept_at
- extra_fields.extend(["last_swept_at", "last_seen_session_id", "last_deep_swept_at"])
+ self.deep_swept_through = self.last_swept_at
+ self.deep_seen_session_id = ""
+ extra_fields.extend(
+ ["last_swept_at", "last_seen_session_id", "deep_swept_through", "deep_seen_session_id"]
+ )
if update_fields is not None and extra_fields:
kwargs["update_fields"] = [*update_fields, *extra_fields]
super().save(*args, **kwargs)
diff --git a/products/replay_vision/backend/queries/excluded_sessions.py b/products/replay_vision/backend/queries/excluded_sessions.py
index 6e473294ffc9..8c8c2a0488c4 100644
--- a/products/replay_vision/backend/queries/excluded_sessions.py
+++ b/products/replay_vision/backend/queries/excluded_sessions.py
@@ -56,6 +56,9 @@ def excluded_session_ids(
team: Team,
candidate_query: CandidateQuery,
candidates: list[CandidateSession],
+ # Tags these reads in `system.query_log`. Required, because the sweep and a backfill both exclude
+ # against the same scanner id, and the read meter throttles each path on what it is charged.
+ query_type: str,
scanner_id: str | None = None,
seconds_remaining: float | None = None,
) -> set[str]:
@@ -82,7 +85,7 @@ def excluded_session_ids(
rows = execute_candidate_query(
exclusion,
team=team,
- query_type="ReplayVisionExcludedSessionsQuery",
+ query_type=query_type,
max_execution_time_seconds=max(1, int(deadline - time.monotonic())),
# Metered against the scanner's read budget like its candidate query.
scanner_id=scanner_id,
diff --git a/products/replay_vision/backend/queries/scanner_candidate_query.py b/products/replay_vision/backend/queries/scanner_candidate_query.py
index 1e73b2a21dee..f25a0a379f48 100644
--- a/products/replay_vision/backend/queries/scanner_candidate_query.py
+++ b/products/replay_vision/backend/queries/scanner_candidate_query.py
@@ -2,7 +2,7 @@
import datetime as dt
from dataclasses import dataclass
-from typing import cast
+from typing import Literal, cast
import structlog
from opentelemetry import trace
@@ -40,6 +40,15 @@ _PARTITION_LOOKBACK = dt.timedelta(hours=26)
# deep sweep instead (see `find_scanner_candidates_activity`), which scans the full lookback.
SWEEP_EVENTS_LOOKBACK = dt.timedelta(hours=4)
+# ClickHouse query-log tags. The read meter matches on these to attribute spend per pass, so a tag
+# that drifts from its caller silently stops that pass being throttled.
+BACKFILL_CANDIDATE_QUERY_TYPE = "ReplayVisionBackfillCandidateQuery"
+BACKFILL_COUNT_QUERY_TYPE = "ReplayVisionBackfillCountQuery"
+DEEP_SWEEP_CANDIDATE_QUERY_TYPE = "ReplayVisionDeepSweepCandidateQuery"
+SWEEP_CANDIDATE_QUERY_TYPE = "ReplayVisionScannerCandidateQuery"
+EXCLUDED_SESSIONS_QUERY_TYPE = "ReplayVisionExcludedSessionsQuery"
+BACKFILL_EXCLUDED_SESSIONS_QUERY_TYPE = "ReplayVisionBackfillExcludedSessionsQuery"
+
SAMPLE_RATE_PRECISION = 10_000
# Smallest non-zero rate the modulo bucketing can express (one bucket); the API rejects non-zero rates below it.
MIN_SAMPLING_RATE = 1 / SAMPLE_RATE_PRECISION
@@ -212,7 +221,7 @@ class ScannerCandidateQuery:
rows = execute_candidate_query(
self.get_query(),
team=self._team,
- query_type="ReplayVisionScannerCandidateQuery",
+ query_type=SWEEP_CANDIDATE_QUERY_TYPE,
max_execution_time_seconds=self._max_execution_time_seconds,
scanner_id=self._scanner_id,
)
@@ -245,30 +254,43 @@ class ScannerCandidateQuery:
],
select_from=ast.JoinExpr(table=cast(ast.SelectQuery, inner), alias="sessions"),
where=ast.And(exprs=where_exprs),
- order_by=[
- ast.OrderExpr(expr=ast.Field(chain=["session_end"]), order="ASC"),
- ast.OrderExpr(expr=ast.Field(chain=["sessions", "session_id"]), order="ASC"),
- ],
+ order_by=keyset_order_by(ascending=True),
limit=ast.Constant(value=self._candidate_limit),
)
def _watermark_predicate(self) -> ast.Expr:
- end_time = ast.Field(chain=["sessions", "end_time"])
- watermark = ast.Constant(value=self._last_swept_at)
- strict = ast.CompareOperation(op=ast.CompareOperationOp.Gt, left=end_time, right=watermark)
- if self._last_seen_session_id is None:
- return strict
- # Lexicographic tuple comparison gives keyset semantics for resuming past saturated batches.
- return ast.CompareOperation(
- op=ast.CompareOperationOp.Gt,
- left=ast.Tuple(exprs=[end_time, ast.Field(chain=["sessions", "session_id"])]),
- right=ast.Tuple(exprs=[watermark, ast.Constant(value=self._last_seen_session_id)]),
- )
+ return keyset_predicate(self._last_swept_at, self._last_seen_session_id, ascending=True)
def _sampling_predicate(self) -> ast.Expr | None:
return sampling_predicate(self._sampling_rate, self._sampling_salt)
+def keyset_order_by(ascending: bool) -> list[ast.OrderExpr]:
+ """Ordering the keyset predicate below assumes; the two have to move together."""
+ direction: Literal["ASC", "DESC"] = "ASC" if ascending else "DESC"
+ return [
+ ast.OrderExpr(expr=ast.Field(chain=["session_end"]), order=direction),
+ ast.OrderExpr(expr=ast.Field(chain=["sessions", "session_id"]), order=direction),
+ ]
+
+
+def keyset_predicate(end_time: dt.datetime, session_id: str | None, ascending: bool) -> ast.Expr:
+ """Resume strictly past `(end_time, session_id)`, in whichever direction the query is ordered.
+
+ Falls back to comparing the timestamp alone when there is no tiebreaker, which is the first pass
+ over a window. Shared because a walk ordered one way and resumed the other silently skips rows.
+ """
+ field = ast.Field(chain=["sessions", "end_time"])
+ op = ast.CompareOperationOp.Gt if ascending else ast.CompareOperationOp.Lt
+ if not session_id:
+ return ast.CompareOperation(op=op, left=field, right=ast.Constant(value=end_time))
+ return ast.CompareOperation(
+ op=op,
+ left=ast.Tuple(exprs=[field, ast.Field(chain=["sessions", "session_id"])]),
+ right=ast.Tuple(exprs=[ast.Constant(value=end_time), ast.Constant(value=session_id)]),
+ )
+
+
def sampling_predicate(sampling_rate: float, sampling_salt: str) -> ast.Expr | None:
"""Deterministic salted-hash downsample on the inner query's session rows; None means keep everything."""
if sampling_rate >= 1.0:
@@ -327,6 +349,9 @@ class WindowedCandidateQuery:
sampling_mode: SamplingMode | str = SamplingMode.COMPREHENSIVE,
cursor_end_time: dt.datetime | None = None,
cursor_session_id: str | None = None,
+ # Oldest-first. The catch-up pass walks this way so a batch that fills up can advance its
+ # watermark to the last row instead of holding it: nothing older is left behind.
+ ascending: bool = False,
exclude_observed_by_scanner: str | None = None,
# Session ids to drop inside the query. Unlike `exclude_observed_by_scanner` this comes from
# the caller rather than from the `$recording_observed` event, so it can carry observations in
@@ -353,6 +378,7 @@ class WindowedCandidateQuery:
self._window_start = window_start
self._window_end = window_end
self._query_type = query_type
+ self._ascending = ascending
self._cursor_end_time = cursor_end_time
self._cursor_session_id = cursor_session_id
self._exclude_observed_by_scanner = exclude_observed_by_scanner
@@ -419,10 +445,7 @@ class WindowedCandidateQuery:
if (cursor := self._cursor_predicate()) is not None:
assert isinstance(query.where, ast.And)
query.where.exprs.append(cursor)
- query.order_by = [
- ast.OrderExpr(expr=ast.Field(chain=["session_end"]), order="DESC"),
- ast.OrderExpr(expr=ast.Field(chain=["sessions", "session_id"]), order="DESC"),
- ]
+ query.order_by = keyset_order_by(self._ascending)
query.limit = ast.Constant(value=self._candidate_limit)
return query
@@ -501,16 +524,4 @@ class WindowedCandidateQuery:
def _cursor_predicate(self) -> ast.Expr | None:
if self._cursor_end_time is None:
return None
- end_time = ast.Field(chain=["sessions", "end_time"])
- if not self._cursor_session_id:
- return ast.CompareOperation(
- op=ast.CompareOperationOp.Lt, left=end_time, right=ast.Constant(value=self._cursor_end_time)
- )
- # Mirror of the sweep's ascending keyset: lexicographic tuple comparison, walked downward.
- return ast.CompareOperation(
- op=ast.CompareOperationOp.Lt,
- left=ast.Tuple(exprs=[end_time, ast.Field(chain=["sessions", "session_id"])]),
- right=ast.Tuple(
- exprs=[ast.Constant(value=self._cursor_end_time), ast.Constant(value=self._cursor_session_id)]
- ),
- )
+ return keyset_predicate(self._cursor_end_time, self._cursor_session_id, ascending=self._ascending)
diff --git a/products/replay_vision/backend/temporal/activities/advance_scanner_watermark.py b/products/replay_vision/backend/temporal/activities/advance_scanner_watermark.py
index a13bd99ee545..bd965fdf083f 100644
--- a/products/replay_vision/backend/temporal/activities/advance_scanner_watermark.py
+++ b/products/replay_vision/backend/temporal/activities/advance_scanner_watermark.py
@@ -13,7 +13,8 @@ def advance_scanner_watermark_activity(inputs: AdvanceScannerWatermarkInputs) ->
"last_seen_session_id": inputs.new_last_seen_session_id,
}
if inputs.new_last_deep_swept_at is not None:
- updates["last_deep_swept_at"] = inputs.new_last_deep_swept_at
+ updates["deep_swept_through"] = inputs.new_last_deep_swept_at
+ updates["deep_seen_session_id"] = inputs.new_last_deep_seen_session_id
updated = ReplayScanner.objects.filter(pk=inputs.scanner_id).update(**updates)
if updated == 0:
activity.logger.info(
diff --git a/products/replay_vision/backend/temporal/activities/backfill.py b/products/replay_vision/backend/temporal/activities/backfill.py
index e8b7a39768cb..f9200464c956 100644
--- a/products/replay_vision/backend/temporal/activities/backfill.py
+++ b/products/replay_vision/backend/temporal/activities/backfill.py
@@ -27,7 +27,11 @@ from products.replay_vision.backend.models.replay_scanner_backfill import (
ReplayScannerBackfill,
)
from products.replay_vision.backend.queries import excluded_sessions
-from products.replay_vision.backend.queries.scanner_candidate_query import WindowedCandidateQuery
+from products.replay_vision.backend.queries.scanner_candidate_query import (
+ BACKFILL_CANDIDATE_QUERY_TYPE,
+ BACKFILL_EXCLUDED_SESSIONS_QUERY_TYPE,
+ WindowedCandidateQuery,
+)
from products.replay_vision.backend.quota import compute_scanner_budget, quota_state
from products.replay_vision.backend.temporal.activities.count_in_flight_applies import (
count_in_flight,
@@ -163,7 +167,7 @@ def find_backfill_candidates_activity(inputs: FindBackfillCandidatesInputs) -> F
query=query,
window_start=backfill.window_start,
window_end=backfill.window_end,
- query_type="ReplayVisionBackfillCandidateQuery",
+ query_type=BACKFILL_CANDIDATE_QUERY_TYPE,
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),
@@ -194,6 +198,7 @@ def find_backfill_candidates_activity(inputs: FindBackfillCandidatesInputs) -> F
team=backfill.team,
candidate_query=candidate_query,
candidates=unobserved,
+ query_type=BACKFILL_EXCLUDED_SESSIONS_QUERY_TYPE,
scanner_id=str(backfill.scanner_id),
seconds_remaining=FIND_BACKFILL_CANDIDATES_TIMEOUT.total_seconds() - (time.monotonic() - started_at),
)
diff --git a/products/replay_vision/backend/temporal/activities/check_scanner_budget.py b/products/replay_vision/backend/temporal/activities/check_scanner_budget.py
index 48fda5e03847..6b47248b2a81 100644
--- a/products/replay_vision/backend/temporal/activities/check_scanner_budget.py
+++ b/products/replay_vision/backend/temporal/activities/check_scanner_budget.py
@@ -129,23 +129,23 @@ def check_scanner_budget_activity(inputs: CheckScannerBudgetInputs) -> CheckScan
# The WHERE claims the notification stamp: of two racing ticks exactly one wins the send, and a
# crash before the send below can only skip a notification, never send an unrecorded one.
watermark = initial_watermark()
+ # The deep pass walks from its own watermark up to the fast one, so leaving it behind would hand
+ # the first uncapped deep sweep exactly the window this reset skips. The cursor is cleared with
+ # it: it points partway into ground nobody swept.
+ reset = {
+ "last_swept_at": watermark,
+ "last_seen_session_id": "",
+ "deep_swept_through": watermark,
+ "deep_seen_session_id": "",
+ }
stamped = (
ReplayScanner.objects.filter(pk=scanner.pk)
.exclude(limit_notified_period_start=period.start)
- .update(
- last_swept_at=watermark,
- last_seen_session_id="",
- # The deep pass walks from its own watermark up to the fast one, so leaving it behind would
- # hand the first uncapped deep sweep exactly the window this reset skips.
- last_deep_swept_at=watermark,
- limit_notified_period_start=period.start,
- )
+ .update(**reset, limit_notified_period_start=period.start)
)
if not stamped:
# Already notified this period; still advance the watermark past the skipped window.
- ReplayScanner.objects.filter(pk=scanner.pk).update(
- last_swept_at=watermark, last_seen_session_id="", last_deep_swept_at=watermark
- )
+ ReplayScanner.objects.filter(pk=scanner.pk).update(**reset)
activity.logger.info(
"Sweep skipped: scanner credit limit reached",
extra={
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 c7f4b42690b1..8b6e00dccb1c 100644
--- a/products/replay_vision/backend/temporal/activities/find_scanner_candidates.py
+++ b/products/replay_vision/backend/temporal/activities/find_scanner_candidates.py
@@ -9,6 +9,7 @@ from temporalio.exceptions import ApplicationError
from posthog.schema import RecordingsQuery
+from posthog.dataclasses import frozen
from posthog.rbac.user_access_control import UserAccessControl
from posthog.temporal.session_replay.rasterize_recording.activities.stuck_counter import read_stuck_session_ids
@@ -16,7 +17,9 @@ from products.replay_vision.backend.models.replay_observation import ReplayObser
from products.replay_vision.backend.models.replay_scanner import SETTLE_INTERVAL, ReplayScanner
from products.replay_vision.backend.queries import excluded_sessions
from products.replay_vision.backend.queries.scanner_candidate_query import (
+ DEEP_SWEEP_CANDIDATE_QUERY_TYPE,
DEFAULT_CANDIDATE_LIMIT,
+ EXCLUDED_SESSIONS_QUERY_TYPE,
SWEEP_EVENTS_LOOKBACK,
CandidateSession,
ScannerCandidateQuery,
@@ -25,12 +28,18 @@ from products.replay_vision.backend.queries.scanner_candidate_query import (
from products.replay_vision.backend.temporal.constants import (
DEEP_SWEEP_INTERVAL,
DEEP_SWEEP_MAX_EXECUTION_SECONDS,
+ DEEP_SWEEP_MAX_WINDOW,
FIND_SCANNER_CANDIDATES_TIMEOUT,
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.metrics import record_deep_sweep_failure, record_sweep_outcome
+from products.replay_vision.backend.temporal.read_meter_types import (
+ deep_spend_bytes_per_day,
+ deep_sweep_throttle_factor,
+ sweep_spend_bytes_24h,
+ sweep_throttle_factor,
+)
from products.replay_vision.backend.temporal.sweep_types import (
CandidateSessionPayload,
FindScannerCandidatesInputs,
@@ -38,6 +47,19 @@ from products.replay_vision.backend.temporal.sweep_types import (
)
+@frozen
+class _DeepProgress:
+ """How far the deep pass got; the two fields are one keyset, moved together or not at all."""
+
+ swept_through: dt.datetime
+ seen_session_id: str = ""
+
+
+def _seconds_left(started_at: float) -> float:
+ """What the activity has left of its own timeout, which both ClickHouse budgets are carved from."""
+ return FIND_SCANNER_CANDIDATES_TIMEOUT.total_seconds() - (time.monotonic() - started_at)
+
+
@activity.defn
@track_activity()
def find_scanner_candidates_activity(inputs: FindScannerCandidatesInputs) -> FindScannerCandidatesOutput:
@@ -92,11 +114,12 @@ def find_scanner_candidates_activity(inputs: FindScannerCandidatesInputs) -> Fin
# Deliberately not wrapped: the in-query blocklists are off, so a swallowed failure here would
# dispatch the batch unfiltered. Returns empty when the scanner excludes nothing.
excluded = excluded_sessions.excluded_session_ids(
+ query_type=EXCLUDED_SESSIONS_QUERY_TYPE,
team=scanner.team,
candidate_query=candidate_query,
candidates=fetched,
scanner_id=str(scanner.id),
- seconds_remaining=FIND_SCANNER_CANDIDATES_TIMEOUT.total_seconds() - (time.monotonic() - started_at),
+ seconds_remaining=_seconds_left(started_at),
)
candidates = [c for c in fetched if c.session_id not in excluded]
@@ -104,15 +127,27 @@ def find_scanner_candidates_activity(inputs: FindScannerCandidatesInputs) -> Fin
# pass gets whatever headroom the fast pass left. At zero there is nothing left to dispatch, which
# also covers the case where the fast batch used the budget on its own.
deep_candidates: list[CandidateSession] = []
- deep_swept_through: dt.datetime | None = None
+ deep_progress: _DeepProgress | None = None
deep_limit = limit - len(candidates)
- if scanner.last_deep_swept_at is None:
+ if scanner.deep_swept_through is None:
# Seed the deep clock at the fast watermark; everything before this deploy was swept
# full-width. This happens whatever the headroom, because the fast watermark advances on every
# tick: seeding only once headroom frees up would leave the range in between with no deep pass.
- deep_swept_through = scanner.last_swept_at
+ deep_progress = _DeepProgress(swept_through=scanner.last_swept_at)
elif deep_limit > 0:
- deep_candidates, deep_swept_through = _deep_sweep(scanner, query, candidate_query, deep_limit)
+ try:
+ deep_candidates, deep_progress = _deep_sweep(
+ scanner,
+ query,
+ candidate_query,
+ deep_limit,
+ seconds_remaining=_seconds_left(started_at),
+ )
+ except Exception:
+ # Best-effort catch-up must never fail the tick: the fast pass has already found and
+ # filtered its candidates, and losing them to a retry costs their reads again.
+ activity.logger.exception("replay_vision.deep_sweep_failed", extra={"scanner_id": str(scanner.id)})
+ record_deep_sweep_failure()
# Sessions that repeatedly exhausted the rasterizer's whole retry envelope (the Class B
# compositor wedge) get quarantined for the counter's TTL window; each dispatch would otherwise
@@ -138,11 +173,13 @@ def find_scanner_candidates_activity(inputs: FindScannerCandidatesInputs) -> Fin
deep_candidates=[
CandidateSessionPayload(session_id=c.session_id, session_end=c.session_end) for c in deep_candidates
],
- deep_swept_through=deep_swept_through,
+ deep_swept_through=deep_progress.swept_through if deep_progress else None,
+ deep_keyset_session_id=deep_progress.seen_session_id if deep_progress else "",
)
-# Past this the exclusion list stops being complete, so holding the watermark could stall the walk.
+# Ceiling on the ids inlined into the deep query; past it the walk re-fetches observed sessions,
+# which the post-query filter below then drops.
_DEEP_SWEEP_MAX_EXCLUSIONS = 20_000
@@ -155,7 +192,7 @@ def _throttled(scanner: ReplayScanner) -> bool:
"""
now = dt.datetime.now(dt.UTC)
factor = sweep_throttle_factor(
- sweep_spend_bytes_24h(scanner.sweep_read_bytes_by_hour, now),
+ sweep_spend_bytes_24h(_buckets_or_pre_split(scanner.fast_read_bytes_by_hour, scanner), now),
scanner.sweep_throttle_factor_override,
)
if factor <= 1:
@@ -163,9 +200,37 @@ def _throttled(scanner: ReplayScanner) -> bool:
return (now - SETTLE_INTERVAL) - scanner.last_swept_at < SCANNER_SCHEDULE_INTERVAL * factor
+def _buckets_or_pre_split(buckets: dict[str, int] | None, scanner: ReplayScanner) -> dict[str, int] | None:
+ """`is None`, not truthiness: only a column the meter has never written falls back to the
+ pre-split total bucket, which keeps throttled scanners throttled across the deploy."""
+ return scanner.sweep_read_bytes_by_hour if buckets is None else buckets
+
+
+# Kept back for the activity's own wrap-up (exclusion filtering, result serialization).
+_DEEP_QUERY_RESERVE_SECONDS = 60
+# Below this a deep query over a padded events window has no realistic chance of finishing.
+_DEEP_QUERY_MIN_SECONDS = 60
+
+
+def _deep_execution_budget(seconds_remaining: float) -> int:
+ """ClickHouse budget for one deep query, or 0 when too little of the activity is left to try.
+
+ Zero rather than a sliver, because a doomed query still costs a cadence stamp.
+ """
+ affordable = int(seconds_remaining) - _DEEP_QUERY_RESERVE_SECONDS
+ if affordable < _DEEP_QUERY_MIN_SECONDS:
+ return 0
+ return min(DEEP_SWEEP_MAX_EXECUTION_SECONDS, affordable)
+
+
def _deep_sweep(
- scanner: ReplayScanner, query: RecordingsQuery, fast_query: ScannerCandidateQuery, limit: int
-) -> tuple[list[CandidateSession], dt.datetime | None]:
+ scanner: ReplayScanner,
+ query: RecordingsQuery,
+ fast_query: ScannerCandidateQuery,
+ limit: int,
+ *,
+ seconds_remaining: float,
+) -> tuple[list[CandidateSession], _DeepProgress | None]:
"""Catch-up pass behind the fast watermark with the full events lookback.
The fast sweep's narrow events window can miss a session whose only matching event happened hours
@@ -173,57 +238,89 @@ def _deep_sweep(
`DEEP_SWEEP_INTERVAL`, excluding sessions the scanner already observed. Bounded above by
`last_swept_at` so it never overlaps the fast keyset's territory.
"""
- assert scanner.last_deep_swept_at is not None # seeded by the caller before the first pass runs
+ assert scanner.deep_swept_through is not None # seeded by the caller before the first pass runs
+ swept_through = scanner.deep_swept_through
now = timezone.now()
- if now - scanner.last_deep_swept_at < DEEP_SWEEP_INTERVAL or scanner.last_deep_swept_at >= scanner.last_swept_at:
+ if swept_through >= scanner.last_swept_at:
+ return [], None
+ # Cadence runs off the last attempt, not the progress watermark: the watermark deliberately stays
+ # put when a pass is cut short, and gating on it would let every such pass re-run on the next tick.
+ last_attempt = scanner.deep_attempted_at or swept_through
+ # The factor is >= 1, so the unstretched interval is a sound pre-filter that skips pricing the
+ # spend buckets on the ~143 of 144 ticks where the pass is not remotely due.
+ if now - last_attempt < DEEP_SWEEP_INTERVAL:
+ return [], None
+ factor = deep_sweep_throttle_factor(
+ deep_spend_bytes_per_day(_buckets_or_pre_split(scanner.deep_read_bytes_by_hour, scanner), now)
+ )
+ if now - last_attempt < DEEP_SWEEP_INTERVAL * factor:
return [], None
# Only the fast pass's events window can cost it candidates, so with nothing matching on events
- # this pass would re-find what the fast pass already dispatched. Advancing rather than parking the
- # watermark keeps the window this pass would open bounded if the query later gains an event filter.
- # The range behind the watermark has to have been swept under the current query though: an edit
- # that drops the last event filter leaves stragglers back there that only this pass ever revisits.
- # `updated_at` is safe to read as "query may have changed" because watermarks advance through
- # queryset updates, which do not touch it.
- settled_since_last_edit = scanner.updated_at <= scanner.last_deep_swept_at
+ # this pass would only re-find what the fast pass already dispatched — advance and skip the query.
+ # `updated_at` is compared against the attempt stamp (both wall-clock) and is safe to read as
+ # "query may have changed" because watermarks advance through queryset updates, which skip it.
+ settled_since_last_edit = scanner.deep_attempted_at is not None and scanner.updated_at <= scanner.deep_attempted_at
if settled_since_last_edit and not fast_query.matches_on_events():
- return [], scanner.last_swept_at
+ return [], _DeepProgress(swept_through=scanner.last_swept_at)
+ # An edit invalidates the cursor: it points partway into a window the new filters have never walked.
+ cursor_session_id = (scanner.deep_seen_session_id if settled_since_last_edit else None) or None
+
+ window_end = min(scanner.last_swept_at, swept_through + DEEP_SWEEP_MAX_WINDOW)
- # Exclude on observation rows rather than on the `$recording_observed` event. That event only
- # lands on the success path, so failed and ineligible sessions would keep matching and the walk
- # would never move past them. It is also an ingested event, so it is not ours to trust.
+ budget = _deep_execution_budget(seconds_remaining)
+ if budget == 0:
+ return [], None
+
+ # Excluded on observation rows rather than the `$recording_observed` event: that event only lands
+ # on the success path, so failed and ineligible sessions would keep matching forever, and it is
+ # ingested, so it is not ours to trust.
observed_session_ids = list(
ReplayObservation.objects.filter(
team_id=scanner.team_id,
scanner_id=scanner.id,
- created_at__gte=scanner.last_deep_swept_at,
+ created_at__gte=swept_through,
).values_list("session_id", flat=True)[:_DEEP_SWEEP_MAX_EXCLUSIONS]
)
deep_query = WindowedCandidateQuery(
team=scanner.team,
query=query,
- window_start=scanner.last_deep_swept_at,
- window_end=scanner.last_swept_at,
- query_type="ReplayVisionDeepSweepCandidateQuery",
+ window_start=swept_through,
+ window_end=window_end,
+ ascending=True,
+ cursor_end_time=swept_through if cursor_session_id else None,
+ cursor_session_id=cursor_session_id,
+ query_type=DEEP_SWEEP_CANDIDATE_QUERY_TYPE,
sampling_rate=scanner.sampling_rate,
sampling_salt=str(scanner.id),
sampling_mode=scanner.sampling_mode,
exclude_session_ids=observed_session_ids,
candidate_limit=limit,
- max_execution_time_seconds=DEEP_SWEEP_MAX_EXECUTION_SECONDS,
+ max_execution_time_seconds=budget,
scanner_id=str(scanner.id),
)
- # Deliberately still on the in-query blocklist. This pass holds its watermark when a batch
- # saturates, which assumes a full batch spent the headroom; scoped exclusion breaks that, since a
- # fully excluded batch dispatches nothing and the same rows return forever. It has no keyset to
- # resume from, so it cannot advance instead.
+ # Stamped before the query, so a pass that times out still counts against the cadence. Queryset
+ # update rather than save(): `updated_at` means "the scanner was edited", which the skip above reads.
+ ReplayScanner.objects.filter(pk=scanner.id).update(deep_attempted_at=now)
deep_candidates = deep_query.run()
- if len(deep_candidates) == limit and len(observed_session_ids) < _DEEP_SWEEP_MAX_EXCLUSIONS:
- # Truncated by the dispatch headroom rather than by the window running out, so hold the
- # watermark and cover the rest next time. The walk is newest-first, so advancing here would
- # drop the oldest stragglers, which are exactly the ones this pass exists to catch. Re-running
- # is self-limiting: a truncated batch means the headroom is spent, and the next tick
- # short-circuits on the in-flight cap before it queries anything.
- return deep_candidates, None
- return deep_candidates, scanner.last_swept_at
+
+ if len(deep_candidates) == limit:
+ # Filled up, so resume from the last row rather than re-walking. Oldest-first means everything
+ # below it is covered, which is what lets the watermark move at all here.
+ last = deep_candidates[-1]
+ progress = _DeepProgress(swept_through=last.session_end, seen_session_id=last.session_id)
+ else:
+ progress = _DeepProgress(swept_through=window_end)
+ if deep_candidates:
+ # The in-query exclusion is a bounded cost optimization; this filter is what guarantees an
+ # already-observed session never burns dispatch headroom, however far past the cap the backlog is.
+ already_observed = set(
+ ReplayObservation.objects.filter(
+ team_id=scanner.team_id,
+ scanner_id=scanner.id,
+ session_id__in=[c.session_id for c in deep_candidates],
+ ).values_list("session_id", flat=True)
+ )
+ deep_candidates = [c for c in deep_candidates if c.session_id not in already_observed]
+ return deep_candidates, progress
diff --git a/products/replay_vision/backend/temporal/activities/meter_scanner_reads.py b/products/replay_vision/backend/temporal/activities/meter_scanner_reads.py
index df1128f7b006..d04846d86328 100644
--- a/products/replay_vision/backend/temporal/activities/meter_scanner_reads.py
+++ b/products/replay_vision/backend/temporal/activities/meter_scanner_reads.py
@@ -7,19 +7,31 @@ 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.queries.scanner_candidate_query import (
+ DEEP_SWEEP_CANDIDATE_QUERY_TYPE,
+ EXCLUDED_SESSIONS_QUERY_TYPE,
+ SWEEP_CANDIDATE_QUERY_TYPE,
+)
+from products.replay_vision.backend.temporal.constants import DEEP_SPEND_WINDOW_DAYS
from products.replay_vision.backend.temporal.decorators import track_activity
-from products.replay_vision.backend.temporal.read_meter_types import MeterScannerReadsResult
+from products.replay_vision.backend.temporal.read_meter_types import MeterScannerReadsResult, parse_bucket_hour
# 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
+# Metered positively rather than by subtraction: a backfill runs under the same scanner id, so
+# anything not named here is not charged to the frequent sweep's cadence.
+_FAST_QUERY_TYPES = [SWEEP_CANDIDATE_QUERY_TYPE, EXCLUDED_SESSIONS_QUERY_TYPE]
+
_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
+ sum(read_bytes) AS read_bytes,
+ sumIf(read_bytes, JSONExtractString(log_comment, 'query_type') = %(deep_query_type)s) AS deep_read_bytes,
+ sumIf(read_bytes, JSONExtractString(log_comment, 'query_type') IN %(fast_query_types)s) AS fast_read_bytes
FROM clusterAllReplicas(%(cluster)s, system.query_log)
WHERE event_date >= today() - 1
AND event_time >= %(since)s
@@ -45,48 +57,75 @@ def meter_scanner_read_bytes_activity() -> MeterScannerReadsResult:
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},
+ {
+ "cluster": settings.CLICKHOUSE_CLUSTER,
+ "since": since,
+ "deep_query_type": DEEP_SWEEP_CANDIDATE_QUERY_TYPE,
+ "fast_query_types": _FAST_QUERY_TYPES,
+ },
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:
+ by_scanner: dict[str, dict[str, tuple[int, int, int]]] = {}
+ for scanner_id, hour, read_bytes, deep_read_bytes, fast_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)
+ hour_iso = hour.replace(tzinfo=dt.UTC).isoformat()
+ by_scanner.setdefault(scanner_id, {})[hour_iso] = (int(read_bytes), int(deep_read_bytes), int(fast_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"))
+ # Wider than the sweep's: the deep pass is priced on its average over this window, so a bucket
+ # pruned at 25h would let a stretched pass age out of its own measurement.
+ deep_prune_cutoff = now - dt.timedelta(days=DEEP_SPEND_WINDOW_DAYS)
+ scanners = list(
+ ReplayScanner.objects.filter(pk__in=by_scanner.keys()).only(
+ "id", "sweep_read_bytes_by_hour", "deep_read_bytes_by_hour", "fast_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
+ metered = by_scanner[str(scanner.id)]
+ scanner.sweep_read_bytes_by_hour = _merged_buckets(
+ scanner.sweep_read_bytes_by_hour, {h: total for h, (total, _, _) in metered.items()}, prune_cutoff
+ )
+ # Zeros are omitted: a missing bucket already reads as no spend, and most scanners never run a
+ # deep pass in a given hour, so storing them would double this table's hourly write volume.
+ scanner.deep_read_bytes_by_hour = _merged_buckets(
+ scanner.deep_read_bytes_by_hour,
+ {h: deep for h, (_, deep, _) in metered.items() if deep},
+ deep_prune_cutoff,
+ )
+ scanner.fast_read_bytes_by_hour = _merged_buckets(
+ scanner.fast_read_bytes_by_hour, {h: fast for h, (_, _, fast) in metered.items()}, prune_cutoff
+ )
# 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)
+ ReplayScanner.objects.bulk_update(
+ scanners,
+ ["sweep_read_bytes_by_hour", "deep_read_bytes_by_hour", "fast_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 _merged_buckets(
+ existing: dict[str, int] | None, fresh: dict[str, int], prune_cutoff: dt.datetime
+) -> dict[str, int]:
+ """The callers pass different cutoffs deliberately: the deep bucket must outlive its pricing window."""
+ buckets = dict(existing or {})
+ buckets.update(fresh)
+ return {
+ hour_iso: read_bytes
+ for hour_iso, read_bytes in buckets.items()
+ if (hour := parse_bucket_hour(hour_iso)) is not None and hour >= prune_cutoff
+ }
+
+
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 5b810d463ebf..a26dfce84c1e 100644
--- a/products/replay_vision/backend/temporal/constants.py
+++ b/products/replay_vision/backend/temporal/constants.py
@@ -51,10 +51,26 @@ SCANNER_SCHEDULE_INTERVAL = dt.timedelta(minutes=5)
# pass that picks up sessions whose matching events were older than the fast pass's narrow window.
# Paired with SWEEP_EVENTS_LOOKBACK: that sets what the fast pass can miss, this sets how long a miss
# waits, so tuning either one moves the same cost-against-latency tradeoff.
-DEEP_SWEEP_INTERVAL = dt.timedelta(hours=6)
-# The deep pass shares the sweep activity's time budget with the fast query, so it gets the smaller
-# share: it is catch-up work, and a tick that overruns retries both queries.
-DEEP_SWEEP_MAX_EXECUTION_SECONDS = 60
+DEEP_SWEEP_INTERVAL = dt.timedelta(hours=12)
+# ClickHouse budget for one deep query; the pass shares the sweep activity's ~200s timeout with the
+# fast query, so it only gets this when enough of the activity is left to spend it.
+DEEP_SWEEP_MAX_EXECUTION_SECONDS = 120
+
+# Most ground one deep pass covers. The events scan pads ~50h around whatever window it is given, so
+# an unbounded window is both slow and unbounded in cost; a scanner further behind takes more passes
+# rather than one huge one. Sized against the longest interval below, not the floor: the padding
+# dominates a single pass, so widening the window is much cheaper than shortening the gap.
+DEEP_SWEEP_MAX_WINDOW = dt.timedelta(hours=54)
+# Ceiling on the deep pass's cadence stretch. Must stay below DEEP_SWEEP_MAX_WINDOW / DEEP_SWEEP_INTERVAL
+# with margin: a pass covering less ground than the gap before it falls behind for good.
+DEEP_SWEEP_MAX_FACTOR = 3
+# The deep pass is priced on its average daily reads over this window, which has to outlast the
+# longest interval above or a stretched pass ages out of its own measurement and resets to the floor.
+DEEP_SPEND_WINDOW_DAYS = 8
+# Daily ClickHouse read budget for the deep pass alone; above it the pass stretches its interval.
+# Half the frequent sweep's budget: it is background catch-up, and giving each pass the full budget
+# would double the per-scanner ceiling this throttling exists to hold.
+DEEP_SWEEP_READ_BUDGET_BYTES_PER_DAY = 100 * 1024**3
# 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).
diff --git a/products/replay_vision/backend/temporal/metrics.py b/products/replay_vision/backend/temporal/metrics.py
index 818b5847126a..683758c37013 100644
--- a/products/replay_vision/backend/temporal/metrics.py
+++ b/products/replay_vision/backend/temporal/metrics.py
@@ -96,6 +96,12 @@ REPLAY_VISION_SCANNER_LIMIT_REACHED = Counter(
["surface"],
)
+REPLAY_VISION_DEEP_SWEEP_FAILURES = Counter(
+ "replay_vision_deep_sweep_failures_total",
+ "Deep catch-up passes that failed inside an otherwise successful sweep tick; separate from sweep "
+ "outcomes so a tick still counts exactly once there",
+)
+
REPLAY_VISION_SWEEP_CANDIDATES = Counter(
"replay_vision_sweep_candidates_total",
"Candidate sessions returned to sweeps for dispatch",
@@ -210,6 +216,11 @@ def record_sweep_outcome(outcome: str, candidates: int = 0) -> None:
_otel.record_counter_twin(REPLAY_VISION_SWEEP_CANDIDATES, candidates, {})
+def record_deep_sweep_failure() -> None:
+ REPLAY_VISION_DEEP_SWEEP_FAILURES.inc()
+ _otel.record_counter_twin(REPLAY_VISION_DEEP_SWEEP_FAILURES, 1, {})
+
+
def record_backfill_tick_outcome(outcome: str) -> None:
REPLAY_VISION_BACKFILL_TICK_OUTCOMES.labels(outcome=outcome).inc()
_otel.record_counter_twin(REPLAY_VISION_BACKFILL_TICK_OUTCOMES, 1, {"outcome": outcome})
diff --git a/products/replay_vision/backend/temporal/read_meter_types.py b/products/replay_vision/backend/temporal/read_meter_types.py
index 90a3198d24e0..4f994c6a80ff 100644
--- a/products/replay_vision/backend/temporal/read_meter_types.py
+++ b/products/replay_vision/backend/temporal/read_meter_types.py
@@ -5,7 +5,13 @@ 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
+from products.replay_vision.backend.temporal.constants import (
+ DEEP_SPEND_WINDOW_DAYS,
+ DEEP_SWEEP_MAX_FACTOR,
+ DEEP_SWEEP_READ_BUDGET_BYTES_PER_DAY,
+ SWEEP_READ_BUDGET_BYTES_24H,
+ SWEEP_THROTTLE_MAX_FACTOR,
+)
class MeterScannerReadsInputs(BaseModel, frozen=True):
@@ -18,21 +24,50 @@ class MeterScannerReadsResult(BaseModel, frozen=True):
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 _spend_since(read_bytes_by_hour, now - dt.timedelta(hours=24))
+
+
+def deep_spend_bytes_per_day(deep_by_hour: dict[str, int] | None, now: dt.datetime) -> int:
+ """The deep pass's daily read rate, averaged over a window wider than its longest interval.
+
+ A trailing 24h sum cannot price a pass that runs less than daily: the pass writes one bucket, that
+ bucket ages out, spend reads zero, and the interval collapses back to the floor. Averaging over
+ `DEEP_SPEND_WINDOW_DAYS` keeps a stretched pass priced by what it actually costs per day.
+ """
+ window = dt.timedelta(days=DEEP_SPEND_WINDOW_DAYS)
+ return _spend_since(deep_by_hour, now - window) // DEEP_SPEND_WINDOW_DAYS
+
+
+def parse_bucket_hour(hour_iso: str) -> dt.datetime | None:
+ """Parse an ISO timestamp, treating a naive value as UTC. None when it cannot be read.
+
+ Shared because the meter writes the keys and the throttles read them: parsing them on two
+ different clocks would price spend against hours it was not recorded in.
+ """
+ try:
+ hour = dt.datetime.fromisoformat(hour_iso)
+ except (TypeError, ValueError):
+ return None
+ return hour if hour.tzinfo else hour.replace(tzinfo=dt.UTC)
+
+
+def _spend_since(by_hour: dict[str, int] | None, cutoff: dt.datetime) -> int:
+ """Total of the buckets at or past the cutoff; unreadable keys are skipped rather than raised.
+
+ Tolerant because this runs inside the sweep: raising here would stop the scanner, not just
+ mis-report its spend.
+ """
+ if not 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.
+ for hour_iso, read_bytes in by_hour.items():
+ hour = parse_bucket_hour(hour_iso)
+ if hour is None or hour < cutoff:
+ continue
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)
+ total += int(read_bytes)
except (TypeError, ValueError):
- continue
+ pass
return total
@@ -40,7 +75,20 @@ 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))
+ return _throttle_factor(spend_bytes, SWEEP_READ_BUDGET_BYTES_24H, SWEEP_THROTTLE_MAX_FACTOR)
+
+
+def deep_sweep_throttle_factor(spend_bytes_per_day: int) -> int:
+ """Interval-stretch multiplier for the deep pass: N means it runs every N x DEEP_SWEEP_INTERVAL.
+
+ Takes no override: the one on the scanner steers the frequent sweep, and a single knob that moved
+ both would undo the independence this split exists for.
+ """
+ return _throttle_factor(spend_bytes_per_day, DEEP_SWEEP_READ_BUDGET_BYTES_PER_DAY, DEEP_SWEEP_MAX_FACTOR)
+
+
+def _throttle_factor(spend_bytes: int, budget_bytes: int, max_factor: int) -> int:
+ # Rounds up, so any spend past the budget stretches. 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 // budget_bytes)
+ return max(1, min(factor, max_factor))
diff --git a/products/replay_vision/backend/temporal/sweep_types.py b/products/replay_vision/backend/temporal/sweep_types.py
index 1f23eb8e41d2..44e005858354 100644
--- a/products/replay_vision/backend/temporal/sweep_types.py
+++ b/products/replay_vision/backend/temporal/sweep_types.py
@@ -44,7 +44,9 @@ class FindScannerCandidatesOutput(BaseModel, frozen=True):
# Stragglers from the periodic full-events-lookback catch-up pass; dispatch-only, never drive
# the fast watermark. Defaults keep pre-deploy histories replaying deterministically.
deep_candidates: list[CandidateSessionPayload] = Field(default_factory=list)
- # Horizon the deep pass covered; None when it didn't run or its batch saturated.
+ # Keyset tiebreaker the deep pass stopped on; empty when it finished its window.
+ deep_keyset_session_id: str = ""
+ # Horizon the deep pass covered; None when it didn't run.
deep_swept_through: dt.datetime | None = None
# Last row of the fetched batch, before negative-filter exclusion dropped any of it. Dropping rows
# must not regress or stall the keyset. None on pre-deploy histories and on empty batches, where
@@ -75,3 +77,5 @@ class AdvanceScannerWatermarkInputs(BaseModel, frozen=True):
new_last_seen_session_id: str = Field(max_length=MAX_SESSION_ID_LENGTH)
# None leaves the deep-sweep watermark untouched.
new_last_deep_swept_at: dt.datetime | None = None
+ # Only read when the deep watermark moves; empty clears the deep keyset tiebreaker.
+ new_last_deep_seen_session_id: str = ""
diff --git a/products/replay_vision/backend/temporal/sweep_workflow.py b/products/replay_vision/backend/temporal/sweep_workflow.py
index 4ce9f25749d9..39a9a84cd1ad 100644
--- a/products/replay_vision/backend/temporal/sweep_workflow.py
+++ b/products/replay_vision/backend/temporal/sweep_workflow.py
@@ -189,7 +189,11 @@ class SweepScannerWorkflow(PostHogWorkflow):
return
await self._advance_watermark(
- inputs.scanner_id, swept_at, last_seen_session_id, deep_swept_through=find_result.deep_swept_through
+ inputs.scanner_id,
+ swept_at,
+ last_seen_session_id,
+ deep_swept_through=find_result.deep_swept_through,
+ deep_keyset_session_id=find_result.deep_keyset_session_id,
)
async def _advance_watermark(
@@ -198,6 +202,7 @@ class SweepScannerWorkflow(PostHogWorkflow):
swept_at: dt.datetime,
last_seen_session_id: str = "",
deep_swept_through: dt.datetime | None = None,
+ deep_keyset_session_id: str = "",
) -> None:
await wf.execute_activity(
advance_scanner_watermark_activity,
@@ -206,6 +211,7 @@ class SweepScannerWorkflow(PostHogWorkflow):
new_last_swept_at=swept_at,
new_last_seen_session_id=last_seen_session_id,
new_last_deep_swept_at=deep_swept_through,
+ new_last_deep_seen_session_id=deep_keyset_session_id,
),
start_to_close_timeout=dt.timedelta(seconds=30),
retry_policy=common.RetryPolicy(maximum_attempts=3),
diff --git a/products/replay_vision/backend/tests/test_excluded_sessions.py b/products/replay_vision/backend/tests/test_excluded_sessions.py
index 2d47fcf17371..1b3330623082 100644
--- a/products/replay_vision/backend/tests/test_excluded_sessions.py
+++ b/products/replay_vision/backend/tests/test_excluded_sessions.py
@@ -8,7 +8,11 @@ from posthog.schema import EventPropertyFilter, FilterLogicalOperator, PropertyO
from products.replay_vision.backend.models.replay_scanner import SamplingMode
from products.replay_vision.backend.queries.excluded_sessions import excluded_session_ids
-from products.replay_vision.backend.queries.scanner_candidate_query import CandidateSession, ScannerCandidateQuery
+from products.replay_vision.backend.queries.scanner_candidate_query import (
+ EXCLUDED_SESSIONS_QUERY_TYPE,
+ CandidateSession,
+ ScannerCandidateQuery,
+)
_NOW = dt.datetime(2026, 5, 1, 12, 0, 0, tzinfo=dt.UTC)
_FROZEN_TIME = _NOW.strftime("%Y-%m-%dT%H:%M:%SZ")
@@ -55,7 +59,10 @@ class TestExcludedSessions(ClickhouseTestMixin):
_event(team, "elsewhere", _NOW - dt.timedelta(hours=2), **{"$host": "internal.example.com"})
excluded = excluded_session_ids(
- team=team, candidate_query=_query_for(team, _not_host()), candidates=_candidates("dirty", "clean")
+ query_type=EXCLUDED_SESSIONS_QUERY_TYPE,
+ team=team,
+ candidate_query=_query_for(team, _not_host()),
+ candidates=_candidates("dirty", "clean"),
)
assert excluded == {"dirty"}
@@ -68,6 +75,7 @@ class TestExcludedSessions(ClickhouseTestMixin):
_event(team, "old-dirty", lagged - dt.timedelta(hours=1), **{"$host": "internal.example.com"})
excluded = excluded_session_ids(
+ query_type=EXCLUDED_SESSIONS_QUERY_TYPE,
team=team,
candidate_query=_query_for(team, _not_host(), last_swept_at=lagged),
candidates=_candidates("old-dirty"),
@@ -85,7 +93,10 @@ class TestExcludedSessions(ClickhouseTestMixin):
_event(team, "web-session", _NOW - dt.timedelta(hours=2), **{"$lib": "web"})
excluded = excluded_session_ids(
- team=team, candidate_query=_query_for(team, query), candidates=_candidates("web-session")
+ query_type=EXCLUDED_SESSIONS_QUERY_TYPE,
+ team=team,
+ candidate_query=_query_for(team, query),
+ candidates=_candidates("web-session"),
)
assert excluded == set()
@@ -96,7 +107,10 @@ class TestExcludedSessions(ClickhouseTestMixin):
_event(team, "future", _NOW + dt.timedelta(hours=2), **{"$host": "internal.example.com"})
assert excluded_session_ids(
- team=team, candidate_query=_query_for(team, _not_host()), candidates=_candidates("future")
+ query_type=EXCLUDED_SESSIONS_QUERY_TYPE,
+ team=team,
+ candidate_query=_query_for(team, _not_host()),
+ candidates=_candidates("future"),
) == {"future"}
@pytest.mark.django_db
@@ -113,7 +127,10 @@ class TestExcludedSessions(ClickhouseTestMixin):
_event(team, "clean", _NOW - dt.timedelta(hours=2), **{"$host": "app.example.com"})
excluded = excluded_session_ids(
- team=team, candidate_query=_query_for(team, query), candidates=_candidates("staging", "clean")
+ query_type=EXCLUDED_SESSIONS_QUERY_TYPE,
+ team=team,
+ candidate_query=_query_for(team, query),
+ candidates=_candidates("staging", "clean"),
)
assert excluded == {"staging"}
@@ -143,4 +160,12 @@ class TestExcludedSessions(ClickhouseTestMixin):
@pytest.mark.django_db
def test_no_candidates_asks_nothing(self, team) -> None:
# Where the saving comes from: most ticks have no candidates and must issue no query.
- assert excluded_session_ids(team=team, candidate_query=_query_for(team, _not_host()), candidates=[]) == set()
+ assert (
+ excluded_session_ids(
+ query_type=EXCLUDED_SESSIONS_QUERY_TYPE,
+ team=team,
+ candidate_query=_query_for(team, _not_host()),
+ candidates=[],
+ )
+ == set()
+ )
diff --git a/products/replay_vision/backend/tests/test_models.py b/products/replay_vision/backend/tests/test_models.py
index a4112913a5b9..2fd08384609f 100644
--- a/products/replay_vision/backend/tests/test_models.py
+++ b/products/replay_vision/backend/tests/test_models.py
@@ -138,7 +138,10 @@ class TestReplayScanner(BaseTest):
# Without the reset, a re-enabled scanner backfills every session since it was disabled.
stale = timezone.now() - timedelta(days=21)
scanner = self._create_scanner(
- enabled=False, last_swept_at=stale, last_seen_session_id="sess-tie", last_deep_swept_at=stale
+ enabled=False,
+ last_swept_at=stale,
+ last_seen_session_id="sess-tie",
+ deep_swept_through=stale,
)
scanner.enabled = True
scanner.save(update_fields=update_fields)
@@ -146,7 +149,7 @@ class TestReplayScanner(BaseTest):
self.assertGreater(scanner.last_swept_at, timezone.now() - timedelta(hours=1))
self.assertEqual(scanner.last_seen_session_id, "")
# The deep pass sweeps from here to last_swept_at, so a stale value would cover the whole gap.
- self.assertEqual(scanner.last_deep_swept_at, scanner.last_swept_at)
+ self.assertEqual(scanner.deep_swept_through, scanner.last_swept_at)
@parameterized.expand(
[
@@ -162,7 +165,7 @@ class TestReplayScanner(BaseTest):
enabled=enabled_before,
last_swept_at=stale,
last_seen_session_id="sess-tie",
- last_deep_swept_at=stale,
+ deep_swept_through=stale,
)
scanner.enabled = enabled_after
scanner.description = "touched"
@@ -170,7 +173,7 @@ class TestReplayScanner(BaseTest):
scanner.refresh_from_db()
self.assertEqual(scanner.last_swept_at, stale)
self.assertEqual(scanner.last_seen_session_id, "sess-tie")
- self.assertEqual(scanner.last_deep_swept_at, stale)
+ self.assertEqual(scanner.deep_swept_through, stale)
def test_full_save_does_not_clobber_sweep_owned_columns(self) -> None:
# A concurrent sweep stamps these via targeted updates; a full save from a stale
diff --git a/products/replay_vision/backend/tests/test_read_meter.py b/products/replay_vision/backend/tests/test_read_meter.py
index 0bc1edfce31d..96bbc607b0d0 100644
--- a/products/replay_vision/backend/tests/test_read_meter.py
+++ b/products/replay_vision/backend/tests/test_read_meter.py
@@ -6,8 +6,20 @@ 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
+from products.replay_vision.backend.temporal.constants import (
+ DEEP_SPEND_WINDOW_DAYS,
+ DEEP_SWEEP_INTERVAL,
+ DEEP_SWEEP_MAX_FACTOR,
+ DEEP_SWEEP_MAX_WINDOW,
+ DEEP_SWEEP_READ_BUDGET_BYTES_PER_DAY,
+ SWEEP_READ_BUDGET_BYTES_24H,
+)
+from products.replay_vision.backend.temporal.read_meter_types import (
+ deep_spend_bytes_per_day,
+ deep_sweep_throttle_factor,
+ sweep_spend_bytes_24h,
+ sweep_throttle_factor,
+)
_NOW = dt.datetime(2026, 8, 12, 12, 0, 0, tzinfo=dt.UTC)
@@ -16,6 +28,15 @@ def _hour(hours_ago: int) -> str:
return (_NOW - dt.timedelta(hours=hours_ago)).replace(minute=0, second=0, microsecond=0).isoformat()
+class TestDeepSweepCadenceInvariant:
+ def test_a_pass_covers_more_ground_than_the_gap_before_it(self) -> None:
+ # The one invariant tying the two constants together. Stretch the cadence past the ground one
+ # pass covers and the watermark loses the difference every time, permanently, until it is far
+ # enough behind that the recordings it reaches have aged out and the pass finds nothing.
+ longest_gap = DEEP_SWEEP_INTERVAL * DEEP_SWEEP_MAX_FACTOR
+ assert DEEP_SWEEP_MAX_WINDOW > longest_gap
+
+
class TestThrottleMath:
@parameterized.expand(
[
@@ -34,6 +55,35 @@ class TestThrottleMath:
def test_sweep_throttle_factor(self, _name: str, spend: int, override: int | None, expected: int) -> None:
assert sweep_throttle_factor(spend, override) == expected
+ @parameterized.expand(
+ [
+ ("under_budget", DEEP_SWEEP_READ_BUDGET_BYTES_PER_DAY // 2, 1),
+ ("just_over_budget", DEEP_SWEEP_READ_BUDGET_BYTES_PER_DAY + 1, 2),
+ # Capped lower than the frequent sweep's ceiling, deliberately: the deep pass cannot be
+ # stretched past the ground one pass covers without falling behind for good.
+ ("over_budget_hits_the_deep_cap", DEEP_SWEEP_READ_BUDGET_BYTES_PER_DAY * 10, DEEP_SWEEP_MAX_FACTOR),
+ ("far_over_budget_stays_capped", DEEP_SWEEP_READ_BUDGET_BYTES_PER_DAY * 500, DEEP_SWEEP_MAX_FACTOR),
+ ]
+ )
+ def test_deep_sweep_throttle_factor(self, _name: str, spend: int, expected: int) -> None:
+ assert deep_sweep_throttle_factor(spend) == expected
+
+ def test_deep_spend_survives_longer_than_the_interval_it_sets(self) -> None:
+ # A pass stretched past a day writes one bucket and then has to stay priced by it. Measuring
+ # over 24h instead would let that bucket age out, collapse the factor to 1, and cap the real
+ # cadence near a day however high the ceiling is set.
+ # Sized like the scanners this exists for: one pass costing ~150x the daily budget.
+ one_pass = {_hour(72): SWEEP_READ_BUDGET_BYTES_24H * 150}
+
+ assert sweep_spend_bytes_24h(one_pass, _NOW) == 0
+ rate = deep_spend_bytes_per_day(one_pass, _NOW)
+ assert rate == SWEEP_READ_BUDGET_BYTES_24H * 150 // DEEP_SPEND_WINDOW_DAYS
+ assert deep_sweep_throttle_factor(rate) == DEEP_SWEEP_MAX_FACTOR
+
+ def test_deep_spend_drops_out_past_the_pricing_window(self) -> None:
+ # Otherwise a scanner stays throttled on spend it no longer incurs.
+ assert deep_spend_bytes_per_day({_hour(24 * DEEP_SPEND_WINDOW_DAYS + 1): 10**12}, _NOW) == 0
+
def test_spend_sums_only_trailing_24h_and_tolerates_junk(self) -> None:
buckets = {
_hour(1): 100,
@@ -65,8 +115,8 @@ class TestMeterScannerReadsActivity:
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),
+ ("not-a-uuid", hour.replace(tzinfo=None), 11, 0, 0),
+ (str(scanner.id), hour.replace(tzinfo=None), 22, 7, 15),
],
):
result = meter_scanner_read_bytes_activity()
@@ -74,6 +124,11 @@ class TestMeterScannerReadsActivity:
assert result.scanners_updated == 1
scanner.refresh_from_db()
assert scanner.sweep_read_bytes_by_hour == {hour.isoformat(): 22}
+ # Deep spend is metered separately so it can stretch the deep interval without
+ # dragging the frequent sweep's cadence down with it.
+ assert scanner.deep_read_bytes_by_hour == {hour.isoformat(): 7}
+ # Metered, not derived: the 22 total includes backfill reads that must not reach this bucket.
+ assert scanner.fast_read_bytes_by_hour == {hour.isoformat(): 15}
def test_folds_query_log_rows_into_hour_buckets_and_prunes(self) -> None:
from products.replay_vision.backend.tests.test_sweep import _make_scanner
@@ -89,15 +144,18 @@ class TestMeterScannerReadsActivity:
"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),
+ (str(scanner.id), fresh_hour.replace(tzinfo=None), 70, 0, 70),
+ (str(scanner.id), current_hour.replace(tzinfo=None), 40, 0, 40),
+ ("00000000-0000-0000-0000-000000000000", current_hour.replace(tzinfo=None), 123, 0, 123),
],
):
result = meter_scanner_read_bytes_activity()
assert result.scanners_updated == 1
scanner.refresh_from_db()
+ # Every mocked row here has zero deep spend, and zeros are not stored: keeping them would
+ # double this table's hourly write volume for the scanners that never run a deep pass.
+ assert scanner.deep_read_bytes_by_hour == {}
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 e03dcc3201a7..705b50066ff5 100644
--- a/products/replay_vision/backend/tests/test_sweep.py
+++ b/products/replay_vision/backend/tests/test_sweep.py
@@ -1,5 +1,7 @@
import uuid
import datetime as dt
+from collections.abc import Iterator
+from contextlib import contextmanager
from typing import Any
import pytest
@@ -44,6 +46,10 @@ from products.replay_vision.backend.temporal.activities.refresh_prompt_suggestio
refresh_prompt_suggestion_activity,
)
from products.replay_vision.backend.temporal.constants import (
+ DEEP_SPEND_WINDOW_DAYS,
+ DEEP_SWEEP_INTERVAL,
+ DEEP_SWEEP_MAX_WINDOW,
+ DEEP_SWEEP_READ_BUDGET_BYTES_PER_DAY,
MAX_IN_FLIGHT_APPLIES_PER_SCANNER,
MAX_IN_FLIGHT_APPLIES_PER_TEAM,
SWEEP_READ_BUDGET_BYTES_24H,
@@ -68,6 +74,26 @@ from products.replay_vision.backend.tests.helpers import seed_scanner_spend, sna
_OBSERVATION_CREDITS = observation_credits_for_model(ScannerModel.GEMINI_3_7_FLASH)
+_ACTIVITY = "products.replay_vision.backend.temporal.activities.find_scanner_candidates"
+
+
+@contextmanager
+def _patched_queries() -> Iterator[tuple[MagicMock, MagicMock]]:
+ """Patch both candidate queries at the activity's import site, with an empty fast batch by default."""
+ with (
+ patch(f"{_ACTIVITY}.ScannerCandidateQuery") as MockQuery,
+ patch(f"{_ACTIVITY}.WindowedCandidateQuery") as MockDeep,
+ ):
+ MockQuery.return_value.run.return_value = []
+ MockQuery.return_value.matches_on_events.return_value = True
+ MockDeep.return_value.run.return_value = []
+ yield MockQuery, MockDeep
+
+
+_PAST_DEEP_INTERVAL = DEEP_SWEEP_INTERVAL + dt.timedelta(hours=1)
+_WITHIN_DEEP_INTERVAL = DEEP_SWEEP_INTERVAL - dt.timedelta(hours=1)
+
+
def _make_scanner(**overrides) -> ReplayScanner:
org = Organization.objects.create(name="vision-sweep-test-org")
team = Team.objects.create(organization=org, name="vision-sweep-test-team")
@@ -83,13 +109,20 @@ def _make_scanner(**overrides) -> ReplayScanner:
def _settle_edit_clock(scanner: ReplayScanner) -> None:
- # Backdates `updated_at` past the deep watermark so the scanner reads as unedited since its last
- # deep pass. Queryset update, because `auto_now` would stamp it back to now on save().
- if scanner.last_deep_swept_at is None:
+ """Make the scanner read as unedited since its last deep pass.
+
+ Records an attempt one interval ago and backdates `updated_at` behind it, because the edit check
+ compares those two. Queryset update, since `auto_now` would stamp `updated_at` back to now.
+ """
+ if scanner.deep_swept_through is None:
return
- settled = scanner.last_deep_swept_at - dt.timedelta(minutes=1)
- ReplayScanner.objects.filter(pk=scanner.pk).update(updated_at=settled)
- scanner.updated_at = settled
+ # The last pass ran when it last made progress, so a scanner far behind is still due at any factor.
+ attempted = scanner.deep_swept_through
+ ReplayScanner.objects.filter(pk=scanner.pk).update(
+ deep_attempted_at=attempted,
+ updated_at=attempted - dt.timedelta(minutes=1),
+ )
+ scanner.refresh_from_db()
def _seed_in_flight_observations(scanner: ReplayScanner, *, count: int) -> None:
@@ -251,26 +284,18 @@ class TestFindScannerCandidatesActivity:
# Nothing swept yet, so there is no range behind the watermark to catch up on.
("first_sweep", None, True),
# Nothing the narrow events window could have cost this scanner, so nothing to catch up on.
- ("no_events_filters", dt.timedelta(hours=7), False),
+ ("no_events_filters", _PAST_DEEP_INTERVAL, False),
]
)
def test_deep_pass_skipped_but_watermark_still_advances(
self, _name: str, deep_watermark_age: dt.timedelta | None, matches_on_events: bool
) -> None:
scanner = _make_scanner(
- last_deep_swept_at=None if deep_watermark_age is None else dt.datetime.now(dt.UTC) - deep_watermark_age
+ deep_swept_through=None if deep_watermark_age is None else dt.datetime.now(dt.UTC) - deep_watermark_age
)
_settle_edit_clock(scanner)
- with (
- patch(
- "products.replay_vision.backend.temporal.activities.find_scanner_candidates.ScannerCandidateQuery"
- ) as MockQuery,
- patch(
- "products.replay_vision.backend.temporal.activities.find_scanner_candidates.WindowedCandidateQuery"
- ) as MockDeep,
- ):
- MockQuery.return_value.run.return_value = []
+ with _patched_queries() as (MockQuery, MockDeep):
MockQuery.return_value.matches_on_events.return_value = matches_on_events
result = find_scanner_candidates_activity(
FindScannerCandidatesInputs(scanner_id=scanner.id, team_id=scanner.team_id)
@@ -281,24 +306,222 @@ class TestFindScannerCandidatesActivity:
# Parking the watermark instead would hand a later tick an arbitrarily wide catch-up window.
assert result.deep_swept_through == scanner.last_swept_at
+ @parameterized.expand(
+ [
+ # Spend on the deep pass stretches its interval, so 7h since the last pass is not yet due.
+ ("deep_spend_stretches_interval", True, False),
+ # The same spend attributed to the frequent sweep must not: reading the wrong bucket here
+ # would throttle the deep pass on the fast pass's bill, and vice versa.
+ ("fast_spend_does_not", False, True),
+ ]
+ )
+ def test_deep_interval_stretches_on_deep_spend_only(
+ self, _name: str, spend_is_deep: bool, expect_run: bool
+ ) -> None:
+ # Deep spend is priced as a daily rate over DEEP_SPEND_WINDOW_DAYS, so one bucket carries the
+ # whole window: 32 budgets here is 4 budgets a day, capped to DEEP_SWEEP_MAX_FACTOR.
+ hour = dt.datetime.now(dt.UTC).replace(minute=0, second=0, microsecond=0).isoformat()
+ spend = {hour: DEEP_SWEEP_READ_BUDGET_BYTES_PER_DAY * 4 * DEEP_SPEND_WINDOW_DAYS}
+ scanner = _make_scanner(
+ deep_swept_through=dt.datetime.now(dt.UTC) - _PAST_DEEP_INTERVAL,
+ deep_read_bytes_by_hour=spend if spend_is_deep else None,
+ fast_read_bytes_by_hour=None if spend_is_deep else spend,
+ )
+ _settle_edit_clock(scanner)
+
+ with (
+ _patched_queries() as (MockQuery, MockDeep),
+ # The frequent sweep's own throttle would otherwise skip the tick before the deep pass runs.
+ patch(f"{_ACTIVITY}._throttled", return_value=False),
+ ):
+ find_scanner_candidates_activity(
+ FindScannerCandidatesInputs(scanner_id=scanner.id, team_id=scanner.team_id)
+ )
+
+ assert MockDeep.called is expect_run
+
+ @parameterized.expand(
+ [
+ # Neither path finishes its window. Cadence used to be measured from the progress
+ # watermark, so a pass that ended early cleared the gate again on the next tick with
+ # headroom and skipped the stretch entirely, for exactly the scanners it exists to slow.
+ ("saturated_batch", "saturate"),
+ ("failed_query", "raise"),
+ ]
+ )
+ def test_a_cut_short_pass_still_waits_out_the_interval(self, _name: str, mode: str) -> None:
+ hour = dt.datetime.now(dt.UTC).replace(minute=0, second=0, microsecond=0).isoformat()
+ # Spend stretches the interval to its cap, and the watermark starts further back than that so the
+ # first tick is genuinely due.
+ scanner = _make_scanner(
+ deep_swept_through=dt.datetime.now(dt.UTC) - dt.timedelta(hours=72),
+ deep_read_bytes_by_hour={hour: DEEP_SWEEP_READ_BUDGET_BYTES_PER_DAY * 4 * DEEP_SPEND_WINDOW_DAYS},
+ )
+ _settle_edit_clock(scanner)
+
+ def run_tick() -> bool:
+ with (
+ _patched_queries() as (MockQuery, MockDeep),
+ patch(f"{_ACTIVITY}._throttled", return_value=False),
+ ):
+ if mode == "raise":
+ MockDeep.return_value.run.side_effect = Exception("clickhouse timeout")
+ else:
+ MockDeep.return_value.run.return_value = [
+ CandidateSession(session_id=f"deep-{i}", session_end=dt.datetime(2026, 5, 1, tzinfo=dt.UTC))
+ for i in range(DEFAULT_CANDIDATE_LIMIT)
+ ]
+ find_scanner_candidates_activity(
+ FindScannerCandidatesInputs(scanner_id=scanner.id, team_id=scanner.team_id)
+ )
+ return bool(MockDeep.called)
+
+ assert run_tick() is True
+ scanner.refresh_from_db()
+ # Stamped even when the query never returned, or a failing pass would retry every tick.
+ assert scanner.deep_attempted_at is not None
+ assert run_tick() is False
+
+ def test_a_full_batch_resumes_instead_of_rewalking(self) -> None:
+ # The walk is oldest-first, so everything below the last row is covered and the watermark can
+ # move there. Re-walking from the window start instead would spend the whole next pass
+ # re-finding rows it already dispatched, and a scanner that always fills up would never finish.
+ scanner = _make_scanner(deep_swept_through=dt.datetime.now(dt.UTC) - _PAST_DEEP_INTERVAL)
+ _settle_edit_clock(scanner)
+ stopped_at = dt.datetime(2026, 5, 1, 6, 0, tzinfo=dt.UTC)
+ batch = [
+ CandidateSession(session_id=f"deep-{i}", session_end=stopped_at) for i in range(DEFAULT_CANDIDATE_LIMIT)
+ ]
+
+ with _patched_queries() as (MockQuery, MockDeep):
+ MockDeep.return_value.run.return_value = batch
+ result = find_scanner_candidates_activity(
+ FindScannerCandidatesInputs(scanner_id=scanner.id, team_id=scanner.team_id)
+ )
+
+ assert result.deep_swept_through == stopped_at
+ assert result.deep_keyset_session_id == batch[-1].session_id
+
+ def test_one_pass_covers_at_most_the_window_cap(self) -> None:
+ # A scanner far behind would otherwise open a window as wide as its backlog, which is both
+ # slow and unbounded in cost, and a pass that cannot finish advances nothing at all.
+ scanner = _make_scanner(deep_swept_through=dt.datetime.now(dt.UTC) - dt.timedelta(days=30))
+ _settle_edit_clock(scanner)
+
+ with _patched_queries() as (MockQuery, MockDeep):
+ result = find_scanner_candidates_activity(
+ FindScannerCandidatesInputs(scanner_id=scanner.id, team_id=scanner.team_id)
+ )
+
+ kwargs = MockDeep.call_args.kwargs
+ assert kwargs["window_end"] == kwargs["window_start"] + DEEP_SWEEP_MAX_WINDOW
+ assert kwargs["window_end"] < scanner.last_swept_at
+ # Advanced by one cap, so the backlog drains over successive passes rather than in one query.
+ assert result.deep_swept_through == kwargs["window_end"]
+
+ def test_throttle_falls_back_to_the_total_bucket_before_the_meter_splits_it(self) -> None:
+ # Every existing scanner has no fast bucket until the meter first runs. Reading only the new
+ # field would show zero spend on deploy and un-throttle every throttled scanner for an hour.
+ 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},
+ fast_read_bytes_by_hour=None,
+ )
+
+ with patch(
+ "products.replay_vision.backend.temporal.activities.find_scanner_candidates.ScannerCandidateQuery"
+ ) as MockQuery:
+ find_scanner_candidates_activity(
+ FindScannerCandidatesInputs(scanner_id=scanner.id, team_id=scanner.team_id)
+ )
+
+ MockQuery.return_value.run.assert_not_called()
+
+ def test_editing_the_scanner_drops_the_deep_cursor(self) -> None:
+ # A cursor points partway into a window walked under the old filters. Reusing it after an edit
+ # leaves everything below it in that window unvisited by the new ones.
+ scanner = _make_scanner(
+ deep_swept_through=dt.datetime.now(dt.UTC) - _PAST_DEEP_INTERVAL,
+ deep_seen_session_id="stopped-here",
+ deep_attempted_at=dt.datetime.now(dt.UTC) - _PAST_DEEP_INTERVAL,
+ )
+ assert scanner.deep_attempted_at is not None and scanner.updated_at > scanner.deep_attempted_at
+
+ with _patched_queries() as (MockQuery, MockDeep):
+ find_scanner_candidates_activity(
+ FindScannerCandidatesInputs(scanner_id=scanner.id, team_id=scanner.team_id)
+ )
+
+ assert MockDeep.call_args.kwargs["cursor_session_id"] is None
+ assert MockDeep.call_args.kwargs["cursor_end_time"] is None
+
+ def test_no_deep_query_when_the_activity_has_no_time_left(self) -> None:
+ # A sliver of budget buys a query certain to time out, and the cadence stamp goes with it,
+ # which at a stretched factor costs a week of catch-up for nothing.
+ scanner = _make_scanner(deep_swept_through=dt.datetime.now(dt.UTC) - _PAST_DEEP_INTERVAL)
+ _settle_edit_clock(scanner)
+ before = scanner.deep_attempted_at
+
+ with (
+ _patched_queries() as (MockQuery, MockDeep),
+ patch(f"{_ACTIVITY}._seconds_left", return_value=60.0),
+ ):
+ find_scanner_candidates_activity(
+ FindScannerCandidatesInputs(scanner_id=scanner.id, team_id=scanner.team_id)
+ )
+
+ MockDeep.assert_not_called()
+ scanner.refresh_from_db()
+ # Unmoved: a skipped pass must not spend the cadence, which at a stretched factor is a week.
+ assert scanner.deep_attempted_at == before
+
+ def test_an_unedited_scanner_keeps_its_cursor(self) -> None:
+ # The mirror of dropping it. Comparing the edit time against the swept position instead of the
+ # attempt time drops the cursor on every scanner whose watermark lags, which is all of them.
+ # Past the interval, so the pass is actually due, with the edit older still.
+ attempted = dt.datetime.now(dt.UTC) - _PAST_DEEP_INTERVAL
+ scanner = _make_scanner(
+ deep_swept_through=dt.datetime.now(dt.UTC) - dt.timedelta(days=20),
+ deep_seen_session_id="stopped-here",
+ deep_attempted_at=attempted,
+ )
+ ReplayScanner.objects.filter(pk=scanner.pk).update(updated_at=attempted - dt.timedelta(hours=1))
+
+ with _patched_queries() as (MockQuery, MockDeep):
+ find_scanner_candidates_activity(
+ FindScannerCandidatesInputs(scanner_id=scanner.id, team_id=scanner.team_id)
+ )
+
+ assert MockDeep.call_args.kwargs["cursor_session_id"] == "stopped-here"
+
+ def test_deep_pass_failure_does_not_discard_the_fast_batch(self) -> None:
+ # The fast pass has already paid for its reads by this point. Letting a catch-up failure fail
+ # the activity throws those candidates away and Temporal re-runs the whole tick, reads included.
+ scanner = _make_scanner(deep_swept_through=dt.datetime.now(dt.UTC) - _PAST_DEEP_INTERVAL)
+ _settle_edit_clock(scanner)
+ fast = [CandidateSession(session_id="fast-1", session_end=dt.datetime(2026, 5, 1, 6, 0, tzinfo=dt.UTC))]
+
+ with _patched_queries() as (MockQuery, MockDeep):
+ MockQuery.return_value.run.return_value = fast
+ MockDeep.return_value.run.side_effect = Exception("clickhouse timeout")
+ result = find_scanner_candidates_activity(
+ FindScannerCandidatesInputs(scanner_id=scanner.id, team_id=scanner.team_id)
+ )
+
+ assert [c.session_id for c in result.candidates] == ["fast-1"]
+ assert result.deep_candidates == []
+ # Not advanced: the range behind the watermark still has not been walked.
+ assert result.deep_swept_through is None
+
def test_deep_pass_runs_once_more_after_the_query_loses_its_event_filters(self) -> None:
# The range behind the watermark was swept under the old filters, with the fast pass's narrow
# events window costing it candidates. Skipping on the new filters would strand them there:
# the fast pass never looks back, so this is the only pass that revisits that range.
- scanner = _make_scanner(last_deep_swept_at=dt.datetime.now(dt.UTC) - dt.timedelta(hours=7))
- assert scanner.last_deep_swept_at is not None and scanner.updated_at > scanner.last_deep_swept_at
+ scanner = _make_scanner(deep_swept_through=dt.datetime.now(dt.UTC) - _PAST_DEEP_INTERVAL)
+ assert scanner.deep_swept_through is not None
- with (
- patch(
- "products.replay_vision.backend.temporal.activities.find_scanner_candidates.ScannerCandidateQuery"
- ) as MockQuery,
- patch(
- "products.replay_vision.backend.temporal.activities.find_scanner_candidates.WindowedCandidateQuery"
- ) as MockDeep,
- ):
- MockQuery.return_value.run.return_value = []
+ with _patched_queries() as (MockQuery, MockDeep):
MockQuery.return_value.matches_on_events.return_value = False
- MockDeep.return_value.run.return_value = []
find_scanner_candidates_activity(
FindScannerCandidatesInputs(scanner_id=scanner.id, team_id=scanner.team_id)
)
@@ -306,22 +529,13 @@ class TestFindScannerCandidatesActivity:
MockDeep.assert_called_once()
def test_stale_deep_watermark_runs_full_width_catchup(self) -> None:
- deep_watermark = dt.datetime.now(dt.UTC) - dt.timedelta(hours=7)
- scanner = _make_scanner(last_deep_swept_at=deep_watermark)
+ deep_watermark = dt.datetime.now(dt.UTC) - _PAST_DEEP_INTERVAL
+ scanner = _make_scanner(deep_swept_through=deep_watermark)
straggler = CandidateSession(
session_id="deep-sess", session_end=dt.datetime(2026, 5, 1, 6, 0, 0, tzinfo=dt.UTC)
)
- with (
- patch(
- "products.replay_vision.backend.temporal.activities.find_scanner_candidates.ScannerCandidateQuery"
- ) as MockQuery,
- patch(
- "products.replay_vision.backend.temporal.activities.find_scanner_candidates.WindowedCandidateQuery"
- ) as MockDeep,
- ):
- MockQuery.return_value.run.return_value = []
- MockQuery.return_value.matches_on_events.return_value = True
+ with _patched_queries() as (MockQuery, MockDeep):
MockDeep.return_value.run.return_value = [straggler]
result = find_scanner_candidates_activity(
FindScannerCandidatesInputs(scanner_id=scanner.id, team_id=scanner.team_id)
@@ -336,24 +550,15 @@ class TestFindScannerCandidatesActivity:
@parameterized.expand(
[
- ("fresh_watermark_skips", dt.timedelta(hours=1), False),
- ("stale_watermark_runs", dt.timedelta(hours=7), True),
+ ("fresh_watermark_skips", _WITHIN_DEEP_INTERVAL, False),
+ ("stale_watermark_runs", _PAST_DEEP_INTERVAL, True),
]
)
def test_deep_pass_gated_on_watermark_age(self, _name: str, watermark_age: dt.timedelta, expect_run: bool) -> None:
- scanner = _make_scanner(last_deep_swept_at=dt.datetime.now(dt.UTC) - watermark_age)
+ scanner = _make_scanner(deep_swept_through=dt.datetime.now(dt.UTC) - watermark_age)
straggler = CandidateSession(session_id="deep-a", session_end=dt.datetime(2026, 5, 1, 6, 0, tzinfo=dt.UTC))
- with (
- patch(
- "products.replay_vision.backend.temporal.activities.find_scanner_candidates.ScannerCandidateQuery"
- ) as MockQuery,
- patch(
- "products.replay_vision.backend.temporal.activities.find_scanner_candidates.WindowedCandidateQuery"
- ) as MockDeep,
- ):
- MockQuery.return_value.run.return_value = []
- MockQuery.return_value.matches_on_events.return_value = True
+ with _patched_queries() as (MockQuery, MockDeep):
MockDeep.return_value.run.return_value = [straggler]
result = find_scanner_candidates_activity(
FindScannerCandidatesInputs(scanner_id=scanner.id, team_id=scanner.team_id, candidate_limit=5)
@@ -369,20 +574,13 @@ class TestFindScannerCandidatesActivity:
def test_deep_watermark_seeds_even_when_fast_batch_takes_all_headroom(self) -> None:
scanner = _make_scanner()
- assert scanner.last_deep_swept_at is None
+ assert scanner.deep_swept_through is None
fast = [
CandidateSession(session_id=f"sess-{i}", session_end=dt.datetime(2026, 5, 1, 10, 0, i, tzinfo=dt.UTC))
for i in range(2)
]
- with (
- patch(
- "products.replay_vision.backend.temporal.activities.find_scanner_candidates.ScannerCandidateQuery"
- ) as MockQuery,
- patch(
- "products.replay_vision.backend.temporal.activities.find_scanner_candidates.WindowedCandidateQuery"
- ) as MockDeep,
- ):
+ with _patched_queries() as (MockQuery, MockDeep):
MockQuery.return_value.run.return_value = fast
result = find_scanner_candidates_activity(
FindScannerCandidatesInputs(scanner_id=scanner.id, team_id=scanner.team_id, candidate_limit=2)
@@ -402,22 +600,14 @@ class TestFindScannerCandidatesActivity:
def test_deep_pass_limited_to_headroom_left_by_fast_pass(
self, _name: str, fast_count: int, limit: int, expected_deep_limit: int | None
) -> None:
- scanner = _make_scanner(last_deep_swept_at=dt.datetime.now(dt.UTC) - dt.timedelta(hours=7))
+ scanner = _make_scanner(deep_swept_through=dt.datetime.now(dt.UTC) - _PAST_DEEP_INTERVAL)
fast = [
CandidateSession(session_id=f"sess-{i}", session_end=dt.datetime(2026, 5, 1, 10, 0, i, tzinfo=dt.UTC))
for i in range(fast_count)
]
- with (
- patch(
- "products.replay_vision.backend.temporal.activities.find_scanner_candidates.ScannerCandidateQuery"
- ) as MockQuery,
- patch(
- "products.replay_vision.backend.temporal.activities.find_scanner_candidates.WindowedCandidateQuery"
- ) as MockDeep,
- ):
+ with _patched_queries() as (MockQuery, MockDeep):
MockQuery.return_value.run.return_value = fast
- MockDeep.return_value.run.return_value = []
find_scanner_candidates_activity(
FindScannerCandidatesInputs(scanner_id=scanner.id, team_id=scanner.team_id, candidate_limit=limit)
)
@@ -431,7 +621,7 @@ class TestFindScannerCandidatesActivity:
def test_deep_pass_excludes_sessions_with_terminal_observations(self) -> None:
# The $recording_observed event only lands on success, so excluding on it would hand these
# sessions back on every tick and the walk would never move past them.
- scanner = _make_scanner(last_deep_swept_at=dt.datetime.now(dt.UTC) - dt.timedelta(hours=7))
+ scanner = _make_scanner(deep_swept_through=dt.datetime.now(dt.UTC) - _PAST_DEEP_INTERVAL)
for session_id, status in (("failed-sess", ObservationStatus.FAILED), ("ok-sess", ObservationStatus.SUCCEEDED)):
ReplayObservation.objects.create(
scanner=scanner,
@@ -443,17 +633,7 @@ class TestFindScannerCandidatesActivity:
completed_at=dt.datetime.now(dt.UTC),
)
- with (
- patch(
- "products.replay_vision.backend.temporal.activities.find_scanner_candidates.ScannerCandidateQuery"
- ) as MockQuery,
- patch(
- "products.replay_vision.backend.temporal.activities.find_scanner_candidates.WindowedCandidateQuery"
- ) as MockDeep,
- ):
- MockQuery.return_value.run.return_value = []
- MockQuery.return_value.matches_on_events.return_value = True
- MockDeep.return_value.run.return_value = []
+ with _patched_queries() as (MockQuery, MockDeep):
find_scanner_candidates_activity(
FindScannerCandidatesInputs(scanner_id=scanner.id, team_id=scanner.team_id, candidate_limit=5)
)
@@ -463,31 +643,36 @@ class TestFindScannerCandidatesActivity:
# The ingested event is no longer consulted, so it cannot suppress a candidate either.
assert "exclude_observed_by_scanner" not in MockDeep.call_args.kwargs
- def test_truncated_deep_batch_holds_watermark(self) -> None:
- scanner = _make_scanner(last_deep_swept_at=dt.datetime.now(dt.UTC) - dt.timedelta(hours=7))
- stragglers = [
- CandidateSession(session_id=f"deep-{i}", session_end=dt.datetime(2026, 5, 1, 6, 0, i, tzinfo=dt.UTC))
- for i in range(3)
+ def test_truncated_exclusions_do_not_redispatch_observed_sessions(self) -> None:
+ # Past the exclusion cap the in-query blocklist is incomplete, so observed sessions come back
+ # from the walk; dispatching them again would burn shared headroom on rows the unique
+ # constraint then rejects.
+ scanner = _make_scanner(deep_swept_through=dt.datetime.now(dt.UTC) - _PAST_DEEP_INTERVAL)
+ _settle_edit_clock(scanner)
+ for session_id in ("seen-1", "seen-2"):
+ ReplayObservation.objects.create(
+ scanner=scanner,
+ team=scanner.team,
+ session_id=session_id,
+ status=ObservationStatus.SUCCEEDED,
+ scanner_snapshot={"model": scanner.model},
+ triggered_by=ObservationTrigger.SCHEDULE,
+ completed_at=dt.datetime.now(dt.UTC),
+ )
+ batch = [
+ CandidateSession(session_id="seen-2", session_end=dt.datetime(2026, 5, 1, 6, 0, tzinfo=dt.UTC)),
+ CandidateSession(session_id="fresh", session_end=dt.datetime(2026, 5, 1, 7, 0, tzinfo=dt.UTC)),
]
- with (
- patch(
- "products.replay_vision.backend.temporal.activities.find_scanner_candidates.ScannerCandidateQuery"
- ) as MockQuery,
- patch(
- "products.replay_vision.backend.temporal.activities.find_scanner_candidates.WindowedCandidateQuery"
- ) as MockDeep,
- ):
- MockQuery.return_value.run.return_value = []
- MockQuery.return_value.matches_on_events.return_value = True
- MockDeep.return_value.run.return_value = stragglers
+ with _patched_queries() as (MockQuery, MockDeep):
+ MockDeep.return_value.run.return_value = batch
result = find_scanner_candidates_activity(
- FindScannerCandidatesInputs(scanner_id=scanner.id, team_id=scanner.team_id, candidate_limit=3)
+ FindScannerCandidatesInputs(scanner_id=scanner.id, team_id=scanner.team_id)
)
- assert [c.session_id for c in result.deep_candidates] == ["deep-0", "deep-1", "deep-2"]
- # The walk is newest-first, so advancing on a truncated batch would drop the oldest for good.
- assert result.deep_swept_through is None
+ assert [c.session_id for c in result.deep_candidates] == ["fresh"]
+ # The filtered rows still count as covered ground, so the walk moves past them.
+ assert result.deep_swept_through is not None
@parameterized.expand(
[
@@ -503,7 +688,7 @@ class TestFindScannerCandidatesActivity:
) -> 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},
+ fast_read_bytes_by_hour={hour.isoformat(): 100 * SWEEP_READ_BUDGET_BYTES_24H},
sweep_throttle_factor_override=override,
)
if extra_watermark_lag:
@@ -536,9 +721,7 @@ class TestFindScannerCandidatesActivity:
fetched = [CandidateSession(session_id="blocked", session_end=dt.datetime(2026, 5, 1, 10, 0, tzinfo=dt.UTC))]
with (
- patch(
- "products.replay_vision.backend.temporal.activities.find_scanner_candidates.ScannerCandidateQuery"
- ) as MockQuery,
+ patch(f"{_ACTIVITY}.ScannerCandidateQuery") as MockQuery,
patch.object(excluded_sessions, "excluded_session_ids", return_value={"blocked"}),
):
MockQuery.return_value.run.return_value = fetched
@@ -556,9 +739,7 @@ class TestFindScannerCandidatesActivity:
scanner = _make_scanner(query=self._NEGATIVE_QUERY)
with (
- patch(
- "products.replay_vision.backend.temporal.activities.find_scanner_candidates.ScannerCandidateQuery"
- ) as MockQuery,
+ patch(f"{_ACTIVITY}.ScannerCandidateQuery") as MockQuery,
patch.object(excluded_sessions, "excluded_session_ids", side_effect=RuntimeError("clickhouse down")),
):
MockQuery.return_value.run.return_value = [
@@ -602,6 +783,51 @@ class TestAdvanceScannerWatermarkActivity:
assert scanner.last_swept_at == new_watermark
assert scanner.last_seen_session_id == "last-id"
+ def test_a_full_save_does_not_clobber_metered_spend(self) -> None:
+ # The API saves the whole row on edit. A PATCH landing while the meter writes would restore
+ # stale buckets, and the scanner would run its expensive queries at a lower throttle factor.
+ hour = dt.datetime.now(dt.UTC).replace(minute=0, second=0, microsecond=0).isoformat()
+ scanner = _make_scanner()
+ metered = {hour: SWEEP_READ_BUDGET_BYTES_24H * 9}
+ ReplayScanner.objects.filter(pk=scanner.pk).update(
+ fast_read_bytes_by_hour=metered, deep_read_bytes_by_hour=metered, sweep_read_bytes_by_hour=metered
+ )
+
+ stale = ReplayScanner.objects.get(pk=scanner.pk)
+ stale.fast_read_bytes_by_hour = None
+ stale.deep_read_bytes_by_hour = None
+ stale.sweep_read_bytes_by_hour = None
+ stale.name = "renamed"
+ stale.save()
+
+ reloaded = ReplayScanner.objects.get(pk=scanner.pk)
+ assert reloaded.fast_read_bytes_by_hour == metered
+ assert reloaded.deep_read_bytes_by_hour == metered
+ assert reloaded.sweep_read_bytes_by_hour == metered
+
+ def test_progress_write_keeps_the_attempt_stamp(self) -> None:
+ # The stamp and the progress are written at different points in one tick. A whole-object write
+ # by the second drops the first, and cadence goes back to being measured from progress.
+ now = dt.datetime(2026, 5, 1, 12, 0, 0, tzinfo=dt.UTC)
+ stamped = now - dt.timedelta(minutes=3)
+ scanner = _make_scanner(deep_swept_through=now - dt.timedelta(days=1))
+ ReplayScanner.objects.filter(pk=scanner.pk).update(deep_attempted_at=stamped)
+
+ advance_scanner_watermark_activity(
+ AdvanceScannerWatermarkInputs(
+ scanner_id=scanner.id,
+ new_last_swept_at=now,
+ new_last_seen_session_id="",
+ new_last_deep_swept_at=now,
+ new_last_deep_seen_session_id="resume-here",
+ )
+ )
+
+ scanner.refresh_from_db()
+ assert scanner.deep_swept_through == now
+ assert scanner.deep_seen_session_id == "resume-here"
+ assert scanner.deep_attempted_at == stamped
+
def test_clears_last_seen_with_empty_string(self) -> None:
scanner = _make_scanner(last_seen_session_id="stale-id")
new_watermark = dt.datetime(2026, 5, 1, 12, 0, 0, tzinfo=dt.UTC)
@@ -619,7 +845,7 @@ class TestAdvanceScannerWatermarkActivity:
def test_advances_deep_watermark_only_when_provided(self) -> None:
existing_deep = dt.datetime(2026, 5, 1, 6, 0, 0, tzinfo=dt.UTC)
- scanner = _make_scanner(last_deep_swept_at=existing_deep)
+ scanner = _make_scanner(deep_swept_through=existing_deep)
new_deep = dt.datetime(2026, 5, 1, 11, 0, 0, tzinfo=dt.UTC)
advance_scanner_watermark_activity(
@@ -630,7 +856,7 @@ class TestAdvanceScannerWatermarkActivity:
)
)
scanner.refresh_from_db()
- assert scanner.last_deep_swept_at == existing_deep
+ assert scanner.deep_swept_through == existing_deep
advance_scanner_watermark_activity(
AdvanceScannerWatermarkInputs(
@@ -641,7 +867,7 @@ class TestAdvanceScannerWatermarkActivity:
)
)
scanner.refresh_from_db()
- assert scanner.last_deep_swept_at == new_deep
+ assert scanner.deep_swept_through == new_deep
def test_no_op_when_scanner_deleted(self) -> None:
advance_scanner_watermark_activity(
@@ -693,7 +919,9 @@ def test_check_scanner_budget_activity_caps_and_advances_the_watermark(
scanner = _make_scanner(credit_limit=limit)
stale = dt.datetime(2026, 1, 1, tzinfo=dt.UTC)
ReplayScanner.objects.filter(pk=scanner.pk).update(
- last_swept_at=stale, last_seen_session_id="sess-old", last_deep_swept_at=stale
+ last_swept_at=stale,
+ last_seen_session_id="sess-old",
+ deep_swept_through=stale,
)
seed_scanner_spend(scanner, _OBSERVATION_CREDITS, observations=spent_observations)
@@ -705,13 +933,13 @@ def test_check_scanner_budget_activity_caps_and_advances_the_watermark(
# Skip the capped window rather than backfilling (and billing) it when the limit frees up.
assert scanner.last_swept_at > stale
assert scanner.last_seen_session_id == ""
- # The deep pass walks [last_deep_swept_at, last_swept_at), so a stale value would hand the
+ # The deep pass walks from its own watermark up to the fast one, so a stale value would hand the
# first uncapped deep sweep exactly the window this reset skips.
- assert scanner.last_deep_swept_at == scanner.last_swept_at
+ assert scanner.deep_swept_through == scanner.last_swept_at
else:
assert scanner.last_swept_at == stale
assert scanner.last_seen_session_id == "sess-old"
- assert scanner.last_deep_swept_at == stale
+ assert scanner.deep_swept_through == stale
@pytest.mark.django_db(transaction=True)
@@ -722,7 +950,9 @@ def test_check_scanner_budget_activity_capped_by_in_flight_alone_does_not_advanc
scanner = _make_scanner(credit_limit=limit)
stale = dt.datetime(2026, 1, 1, tzinfo=dt.UTC)
ReplayScanner.objects.filter(pk=scanner.pk).update(
- last_swept_at=stale, last_seen_session_id="sess-old", last_deep_swept_at=stale
+ last_swept_at=stale,
+ last_seen_session_id="sess-old",
+ deep_swept_through=stale,
)
seed_scanner_spend(scanner, _OBSERVATION_CREDITS, observations=10)
_seed_in_flight_observations(scanner, count=10)
@@ -733,7 +963,7 @@ def test_check_scanner_budget_activity_capped_by_in_flight_alone_does_not_advanc
assert output.capped is True
assert scanner.last_swept_at == stale
assert scanner.last_seen_session_id == "sess-old"
- assert scanner.last_deep_swept_at == stale
+ assert scanner.deep_swept_through == stale
@pytest.mark.django_db(transaction=True)