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): auto-materialize hot scanner properties and slow the estimate clocks (#85523)

Tue Haulunde044e87bc29d
diff --git a/products/replay_vision/backend/queries/__init__.py b/products/replay_vision/backend/queries/__init__.py
index 89c1d0fa4c07..d4e417f9335b 100644
--- a/products/replay_vision/backend/queries/__init__.py
+++ b/products/replay_vision/backend/queries/__init__.py
@@ -8,6 +8,7 @@ from products.replay_vision.backend.queries.scanner_candidate_query import (
ScannerCandidateQuery,
)
from products.replay_vision.backend.queries.scanner_volume_estimate import (
+ DISABLED_ESTIMATE_STALE_AFTER,
ESTIMATE_STALE_AFTER,
PREVIEW_ESTIMATE_BUDGET,
SAVE_ESTIMATE_BUDGET,
@@ -22,6 +23,7 @@ __all__ = [
"DEFAULT_MAX_EXECUTION_SECONDS",
"PREVIEW_ESTIMATE_BUDGET",
"SAVE_ESTIMATE_BUDGET",
+ "DISABLED_ESTIMATE_STALE_AFTER",
"ESTIMATE_STALE_AFTER",
"MIN_SAMPLING_RATE",
"SAMPLE_RATE_PRECISION",
diff --git a/products/replay_vision/backend/queries/scanner_volume_estimate.py b/products/replay_vision/backend/queries/scanner_volume_estimate.py
index 1ccefa32e81d..b815b3fae327 100644
--- a/products/replay_vision/backend/queries/scanner_volume_estimate.py
+++ b/products/replay_vision/backend/queries/scanner_volume_estimate.py
@@ -10,7 +10,7 @@ from posthog.hogql.constants import HogQLGlobalSettings
from posthog.hogql.query import execute_hogql_query
from posthog.clickhouse.client.connection import ClickHouseUser
-from posthog.clickhouse.query_tagging import Feature, Product, tag_queries
+from posthog.clickhouse.query_tagging import Feature, Product, tag_queries, tags_context
from posthog.exceptions import (
ClickHouseEstimatedQueryExecutionTimeTooLong,
ClickHouseQueryMemoryLimitExceeded,
@@ -64,8 +64,13 @@ SAVE_ESTIMATE_BUDGET = EstimateBudget(max_execution_seconds=10, scan_window_days
# sampling is unavailable they take an order-of-magnitude answer from a shorter window.
PREVIEW_ESTIMATE_BUDGET = EstimateBudget(max_execution_seconds=10, scan_window_days=7, unsampled_scan_window_days=2)
-# Persisted per-scanner estimates older than this are recomputed by the sweep.
-ESTIMATE_STALE_AFTER = dt.timedelta(hours=24)
+# Persisted per-scanner estimates older than this are recomputed by the refresher. Estimates only
+# track data drift between edits (an edit nulls `estimated_at` and refreshes within one cycle), so a
+# slower clock trades projection freshness directly for ClickHouse reads.
+ESTIMATE_STALE_AFTER = dt.timedelta(hours=72)
+# Disabled scanners refresh on a slower clock still: fresh enough that re-enabling one puts a usable
+# number into the quota sum, without paying a full-price estimate for every parked scanner.
+DISABLED_ESTIMATE_STALE_AFTER = dt.timedelta(days=7)
@dataclass(frozen=True)
@@ -268,13 +273,16 @@ def refresh_scanner_estimate(
ch_user: ClickHouseUser = ClickHouseUser.APP,
) -> None:
"""Recompute and persist the scanner's projected monthly volume. Raises on failure; callers decide severity."""
- estimate = estimate_scanner_session_volume(
- team=scanner.team,
- query=scanner.recordings_query(),
- sampling_mode=scanner.sampling_mode,
- budget=budget,
- ch_user=ch_user,
- )
+ # Scoped, not tag_queries: a bare tag on the worker thread would leak onto later queries and
+ # charge other scanners' reads to this one in the meter. Previews stay untagged (no scanner yet).
+ with tags_context(scanner_id=str(scanner.pk)):
+ estimate = estimate_scanner_session_volume(
+ team=scanner.team,
+ query=scanner.recordings_query(),
+ sampling_mode=scanner.sampling_mode,
+ budget=budget,
+ ch_user=ch_user,
+ )
projection = project_monthly_observations(estimate, scanner.sampling_rate)
estimated_at = timezone.now()
# Filtered write so a config edit racing the (slow) estimate query can't get stamped fresh with stale numbers.
diff --git a/products/replay_vision/backend/temporal/__init__.py b/products/replay_vision/backend/temporal/__init__.py
index da51f3439016..eb15d4f7ce71 100644
--- a/products/replay_vision/backend/temporal/__init__.py
+++ b/products/replay_vision/backend/temporal/__init__.py
@@ -4,6 +4,7 @@ from typing import Any
from products.replay_vision.backend.temporal.activities import (
advance_backfill_cursor_activity,
advance_scanner_watermark_activity,
+ auto_materialize_scanner_properties_activity,
call_scanner_provider_activity,
check_scanner_budget_activity,
cleanup_gemini_file_activity,
@@ -76,6 +77,7 @@ WORKFLOWS = [
ProcessVisionActionWorkflow,
]
ACTIVITIES: list[Callable[..., Any]] = [
+ auto_materialize_scanner_properties_activity,
create_observation_activity,
mark_observation_running_activity,
mark_observation_failed_activity,
diff --git a/products/replay_vision/backend/temporal/activities/__init__.py b/products/replay_vision/backend/temporal/activities/__init__.py
index 8caa302ce7da..d9c572e8ade2 100644
--- a/products/replay_vision/backend/temporal/activities/__init__.py
+++ b/products/replay_vision/backend/temporal/activities/__init__.py
@@ -1,6 +1,9 @@
from products.replay_vision.backend.temporal.activities.advance_scanner_watermark import (
advance_scanner_watermark_activity,
)
+from products.replay_vision.backend.temporal.activities.auto_materialize import (
+ auto_materialize_scanner_properties_activity,
+)
from products.replay_vision.backend.temporal.activities.backfill import (
advance_backfill_cursor_activity,
delete_backfill_schedule_activity,
@@ -65,6 +68,7 @@ from products.replay_vision.backend.temporal.activities.upload_video_to_gemini i
__all__ = [
"advance_backfill_cursor_activity",
"advance_scanner_watermark_activity",
+ "auto_materialize_scanner_properties_activity",
"delete_backfill_schedule_activity",
"find_backfill_candidates_activity",
"pause_backfill_schedule_activity",
diff --git a/products/replay_vision/backend/temporal/activities/auto_materialize.py b/products/replay_vision/backend/temporal/activities/auto_materialize.py
new file mode 100644
index 000000000000..86924206feae
--- /dev/null
+++ b/products/replay_vision/backend/temporal/activities/auto_materialize.py
@@ -0,0 +1,160 @@
+"""Materialize event properties that budget-burning scanners filter on.
+
+A scanner filtering on an unmaterialized event property (most often a `$feature/...` key served
+from the property-groups Map column) can read hundreds of GB per query where a materialized column
+reads a fraction of one. The sweep throttle only stretches how often that happens; this closes the
+loop by feeding the specific keys to the same `materialize_properties_task` machinery the weekly
+analyzer cron runs, once a scanner's metered spend shows the cost is real and sustained.
+"""
+
+import re
+import datetime as dt
+
+from django.core.exceptions import ValidationError as DjangoValidationError
+
+from pydantic import ValidationError
+from temporalio import activity
+
+from posthog.schema import EventPropertyFilter, FeaturePropertyFilter
+
+from posthog.dataclasses import frozen
+from posthog.settings import EE_AVAILABLE
+from posthog.settings.utils import get_from_env, str_to_bool
+
+from products.replay_vision.backend.models.replay_scanner import ReplayScanner
+from products.replay_vision.backend.temporal.decorators import track_activity
+from products.replay_vision.backend.temporal.metrics import record_auto_materialize_outcome
+from products.replay_vision.backend.temporal.read_meter_types import AutoMaterializeResult, sweep_spend_bytes_24h
+
+if EE_AVAILABLE:
+ from ee.clickhouse.materialized_columns.analyze import materialize_properties_task
+ from ee.clickhouse.materialized_columns.columns import get_materialized_columns
+
+# Off by default: enabling column creation is a deliberate per-environment decision. While off, the
+# activity still logs and counts every candidate, which is the dry run to watch before flipping it.
+AUTO_MATERIALIZE_ENABLED = get_from_env("REPLAY_VISION_AUTO_MATERIALIZE_ENABLED", False, type_cast=str_to_bool)
+# Metered daily reads (sweep + deep passes; backfill excluded, so a one-day backfill spike cannot
+# qualify a scanner). Five times the sweep budget: only scanners the throttle cannot make cheap get here.
+AUTO_MATERIALIZE_MIN_DAILY_READ_BYTES = get_from_env(
+ "REPLAY_VISION_AUTO_MATERIALIZE_MIN_DAILY_READ_BYTES", 1024**4, type_cast=int
+)
+# Days of history to backfill into a new column; 0 relies on inserts, which covers the sweep's
+# short lookback within days. Matches the weekly analyzer cron's default.
+AUTO_MATERIALIZE_BACKFILL_DAYS = get_from_env("REPLAY_VISION_AUTO_MATERIALIZE_BACKFILL_DAYS", 0, type_cast=int)
+# Ceiling on new columns per acting run; with one acting run per day this caps cluster-wide growth.
+AUTO_MATERIALIZE_MAX_PER_RUN = 2
+# The read meter runs hourly; only this UTC hour's run may create columns, making the cap daily.
+_ACTING_HOUR_UTC = 3
+
+# Property filter types that read event properties; everything else (person, session, log_entry,
+# hogql, cohort) does not touch the events properties column and cannot be helped by this.
+_EVENT_SCOPED_FILTER_TYPES = ("event", "feature")
+
+# Mirrors the weekly analyzer's extraction charset. Materialized-column metadata round-trips the key
+# through a `::`-delimited column comment, so a key like `foo::bar` would poison every registry
+# lookup cluster-wide; scanner filters are user input, so only plainly safe keys become columns.
+_SAFE_PROPERTY_KEY = re.compile(r"^[a-zA-Z0-9_\-\.\$\/ ]{1,200}$")
+
+
+@frozen
+class _Candidate:
+ property_name: str
+ scanner_id: str
+ spend_bytes_24h: int
+
+
+@track_activity()
+def auto_materialize_scanner_properties_activity() -> AutoMaterializeResult:
+ now = dt.datetime.now(dt.UTC)
+ candidates = _candidate_properties(now)
+ for candidate in candidates:
+ activity.logger.info(
+ "replay_vision.auto_materialize_candidate",
+ extra={
+ "property_name": candidate.property_name,
+ "scanner_id": candidate.scanner_id,
+ "spend_bytes_24h": candidate.spend_bytes_24h,
+ },
+ )
+ if not candidates:
+ return AutoMaterializeResult()
+ if not AUTO_MATERIALIZE_ENABLED or not EE_AVAILABLE:
+ record_auto_materialize_outcome("candidate_logged", len(candidates))
+ return AutoMaterializeResult(candidates=len(candidates))
+ if now.hour != _ACTING_HOUR_UTC:
+ record_auto_materialize_outcome("deferred_to_acting_hour", len(candidates))
+ return AutoMaterializeResult(candidates=len(candidates))
+
+ acted = candidates[:AUTO_MATERIALIZE_MAX_PER_RUN]
+ materialize_properties_task(
+ properties_to_materialize=[("events", "properties", c.property_name) for c in acted],
+ maximum=AUTO_MATERIALIZE_MAX_PER_RUN,
+ backfill_period_days=AUTO_MATERIALIZE_BACKFILL_DAYS,
+ )
+ record_auto_materialize_outcome("materialized", len(acted))
+ activity.logger.info(
+ "replay_vision.auto_materialized_properties",
+ extra={"property_names": [c.property_name for c in acted]},
+ )
+ return AutoMaterializeResult(candidates=len(candidates), materialized=len(acted))
+
+
+def _candidate_properties(now: dt.datetime) -> list[_Candidate]:
+ """Unmaterialized event properties filtered on by scanners over the spend threshold, costliest first."""
+ scanners = ReplayScanner.objects.filter(enabled=True).only(
+ "id", "query", "fast_read_bytes_by_hour", "deep_read_bytes_by_hour"
+ )
+ qualifying = [
+ (scanner, spend)
+ for scanner in scanners
+ if (spend := _daily_read_bytes(scanner, now)) >= AUTO_MATERIALIZE_MIN_DAILY_READ_BYTES
+ ]
+ if not qualifying:
+ return []
+
+ already_materialized = _materialized_event_properties()
+ best_per_property: dict[str, _Candidate] = {}
+ for scanner, spend in sorted(qualifying, key=lambda pair: pair[1], reverse=True):
+ for key in sorted(_event_property_keys(scanner)):
+ if key in already_materialized or key in best_per_property:
+ continue
+ best_per_property[key] = _Candidate(property_name=key, scanner_id=str(scanner.id), spend_bytes_24h=spend)
+ # Name breaks spend ties, so which candidates fit under the per-run cap is deterministic.
+ return sorted(best_per_property.values(), key=lambda c: (-c.spend_bytes_24h, c.property_name))
+
+
+def _daily_read_bytes(scanner: ReplayScanner, now: dt.datetime) -> int:
+ """Trailing-24h reads from the scanner's own passes, so backfill spend cannot qualify it.
+
+ Rows the meter has not split yet read as zero rather than falling back to the total, which
+ carries backfill reads; missing a transitional hour of candidates costs nothing.
+ """
+ return sweep_spend_bytes_24h(scanner.fast_read_bytes_by_hour, now) + sweep_spend_bytes_24h(
+ scanner.deep_read_bytes_by_hour, now
+ )
+
+
+def _materialized_event_properties() -> set[str]:
+ if not EE_AVAILABLE:
+ return set()
+ return {prop for prop, table_column in get_materialized_columns("events") if table_column == "properties"}
+
+
+def _event_property_keys(scanner: ReplayScanner) -> set[str]:
+ try:
+ query = scanner.recordings_query()
+ except (ValidationError, DjangoValidationError):
+ return set()
+ keys = {
+ prop.key for prop in (query.properties or []) if isinstance(prop, EventPropertyFilter | FeaturePropertyFilter)
+ }
+ for entity in [*(query.events or []), *(query.actions or [])]:
+ for prop in entity.get("properties") or []:
+ if (
+ isinstance(prop, dict)
+ and prop.get("type") in _EVENT_SCOPED_FILTER_TYPES
+ and isinstance(prop.get("key"), str)
+ ):
+ keys.add(prop["key"])
+ return {key for key in keys if _SAFE_PROPERTY_KEY.match(key)}
diff --git a/products/replay_vision/backend/temporal/activities/list_stale_scanner_estimates.py b/products/replay_vision/backend/temporal/activities/list_stale_scanner_estimates.py
index 5bba37e1638c..b4359970e15e 100644
--- a/products/replay_vision/backend/temporal/activities/list_stale_scanner_estimates.py
+++ b/products/replay_vision/backend/temporal/activities/list_stale_scanner_estimates.py
@@ -4,7 +4,7 @@ from django.utils import timezone
from temporalio import activity
from products.replay_vision.backend.models.replay_scanner import ReplayScanner
-from products.replay_vision.backend.queries import ESTIMATE_STALE_AFTER
+from products.replay_vision.backend.queries import DISABLED_ESTIMATE_STALE_AFTER, ESTIMATE_STALE_AFTER
from products.replay_vision.backend.temporal.constants import ESTIMATES_MAX_PER_RUN
from products.replay_vision.backend.temporal.decorators import track_activity
from products.replay_vision.backend.temporal.estimates_types import RefreshScannerEstimateInputs
@@ -15,12 +15,18 @@ from products.replay_vision.backend.temporal.estimates_types import RefreshScann
def list_stale_scanner_estimates_activity() -> list[RefreshScannerEstimateInputs]:
"""Scanners whose persisted estimate is missing or past the staleness window.
- Disabled scanners are refreshed too so re-enabling one puts an accurate number straight into the
- quota sum. Enabled scanners come first so they can't starve behind a backlog of disabled ones.
+ Disabled scanners are refreshed too, on a slower clock, so re-enabling one still puts a usable
+ number into the quota sum. Enabled scanners come first so they can't starve behind a backlog of
+ disabled ones.
"""
- cutoff = timezone.now() - ESTIMATE_STALE_AFTER
+ now = timezone.now()
+ stale = (
+ Q(estimated_at__isnull=True)
+ | Q(enabled=True, estimated_at__lt=now - ESTIMATE_STALE_AFTER)
+ | Q(enabled=False, estimated_at__lt=now - DISABLED_ESTIMATE_STALE_AFTER)
+ )
rows = (
- ReplayScanner.objects.filter(Q(estimated_at__isnull=True) | Q(estimated_at__lt=cutoff))
+ ReplayScanner.objects.filter(stale)
.order_by("-enabled", F("estimated_at").asc(nulls_first=True))
.values_list("id", "team_id")[:ESTIMATES_MAX_PER_RUN]
)
diff --git a/products/replay_vision/backend/temporal/constants.py b/products/replay_vision/backend/temporal/constants.py
index a26dfce84c1e..941df1009b0f 100644
--- a/products/replay_vision/backend/temporal/constants.py
+++ b/products/replay_vision/backend/temporal/constants.py
@@ -84,8 +84,12 @@ READ_METER_WORKFLOW_NAME = "replay-vision-meter-scanner-reads"
READ_METER_WORKFLOW_ID = "replay-vision-scanner-read-meter"
READ_METER_SCHEDULE_ID = "replay-vision-scanner-read-meter-schedule"
READ_METER_INTERVAL = dt.timedelta(hours=1)
-READ_METER_EXECUTION_TIMEOUT = dt.timedelta(minutes=10)
+# Must cover the metering activity's retries plus the auto-materialize pass, or a slow metering run
+# eats the day's only acting window. Overlap policy is SKIP, so a long run absorbs the next tick.
+READ_METER_EXECUTION_TIMEOUT = dt.timedelta(minutes=20)
METER_SCANNER_READS_TIMEOUT = dt.timedelta(minutes=5)
+# Covers the ON CLUSTER ADD COLUMN round when the auto-materializer acts; candidate scans are seconds.
+AUTO_MATERIALIZE_TIMEOUT = dt.timedelta(minutes=4)
# Children are ABANDONed and don't count against this budget, but activities do: this must cover the
# prompt-suggestion refresh worst case plus the candidate scan, or a slow refresh kills the whole sweep.
diff --git a/products/replay_vision/backend/temporal/metrics.py b/products/replay_vision/backend/temporal/metrics.py
index 683758c37013..9585ff0e8475 100644
--- a/products/replay_vision/backend/temporal/metrics.py
+++ b/products/replay_vision/backend/temporal/metrics.py
@@ -102,6 +102,13 @@ REPLAY_VISION_DEEP_SWEEP_FAILURES = Counter(
"outcomes so a tick still counts exactly once there",
)
+REPLAY_VISION_AUTO_MATERIALIZE_OUTCOMES = Counter(
+ "replay_vision_auto_materialize_outcomes_total",
+ "Event properties the auto-materializer saw, by what happened to them: candidate_logged (flag "
+ "off), deferred_to_acting_hour, materialized, or failed (the whole pass errored)",
+ ["outcome"],
+)
+
REPLAY_VISION_SWEEP_CANDIDATES = Counter(
"replay_vision_sweep_candidates_total",
"Candidate sessions returned to sweeps for dispatch",
@@ -216,6 +223,11 @@ def record_sweep_outcome(outcome: str, candidates: int = 0) -> None:
_otel.record_counter_twin(REPLAY_VISION_SWEEP_CANDIDATES, candidates, {})
+def record_auto_materialize_outcome(outcome: str, count: int) -> None:
+ REPLAY_VISION_AUTO_MATERIALIZE_OUTCOMES.labels(outcome=outcome).inc(count)
+ _otel.record_counter_twin(REPLAY_VISION_AUTO_MATERIALIZE_OUTCOMES, count, {"outcome": outcome})
+
+
def record_deep_sweep_failure() -> None:
REPLAY_VISION_DEEP_SWEEP_FAILURES.inc()
_otel.record_counter_twin(REPLAY_VISION_DEEP_SWEEP_FAILURES, 1, {})
diff --git a/products/replay_vision/backend/temporal/read_meter.py b/products/replay_vision/backend/temporal/read_meter.py
index 4a3648ee1784..cc311d438cc5 100644
--- a/products/replay_vision/backend/temporal/read_meter.py
+++ b/products/replay_vision/backend/temporal/read_meter.py
@@ -13,6 +13,7 @@ from temporalio.common import RetryPolicy
from posthog.temporal.common.base import PostHogWorkflow
from products.replay_vision.backend.temporal.constants import (
+ AUTO_MATERIALIZE_TIMEOUT,
METER_SCANNER_READS_TIMEOUT,
READ_METER_EXECUTION_TIMEOUT,
READ_METER_INTERVAL,
@@ -26,7 +27,11 @@ if TYPE_CHECKING:
from temporalio.client import Client
with workflow.unsafe.imports_passed_through():
- from products.replay_vision.backend.temporal.activities import meter_scanner_read_bytes_activity
+ from products.replay_vision.backend.temporal.activities import (
+ auto_materialize_scanner_properties_activity,
+ meter_scanner_read_bytes_activity,
+ )
+ from products.replay_vision.backend.temporal.metrics import record_auto_materialize_outcome
@workflow.defn(name=READ_METER_WORKFLOW_NAME)
@@ -36,11 +41,25 @@ class MeterScannerReadsWorkflow(PostHogWorkflow):
@workflow.run
async def run(self, inputs: MeterScannerReadsInputs) -> MeterScannerReadsResult:
- return await workflow.execute_activity(
+ result = await workflow.execute_activity(
meter_scanner_read_bytes_activity,
start_to_close_timeout=METER_SCANNER_READS_TIMEOUT,
retry_policy=RetryPolicy(maximum_attempts=3),
)
+ if workflow.patched("replay-vision-auto-materialize"):
+ try:
+ await workflow.execute_activity(
+ auto_materialize_scanner_properties_activity,
+ start_to_close_timeout=AUTO_MATERIALIZE_TIMEOUT,
+ retry_policy=RetryPolicy(maximum_attempts=1),
+ )
+ except Exception:
+ # Best-effort: a failed materialization attempt must not fail the metering run,
+ # whose buckets every sweep throttle reads.
+ if not workflow.unsafe.is_replaying():
+ record_auto_materialize_outcome("failed", 1)
+ workflow.logger.warning("replay_vision.auto_materialize_failed")
+ return result
async def create_replay_vision_read_meter_schedule(client: "Client") -> None:
diff --git a/products/replay_vision/backend/temporal/read_meter_types.py b/products/replay_vision/backend/temporal/read_meter_types.py
index 4f994c6a80ff..e0717ad33fd9 100644
--- a/products/replay_vision/backend/temporal/read_meter_types.py
+++ b/products/replay_vision/backend/temporal/read_meter_types.py
@@ -22,6 +22,11 @@ class MeterScannerReadsResult(BaseModel, frozen=True):
scanners_updated: int = 0
+class AutoMaterializeResult(BaseModel, frozen=True):
+ candidates: int = 0
+ materialized: int = 0
+
+
def sweep_spend_bytes_24h(read_bytes_by_hour: dict[str, int] | None, now: dt.datetime) -> int:
"""Trailing-24h read spend from the metered hour buckets; tolerates stale, unpruned entries."""
return _spend_since(read_bytes_by_hour, now - dt.timedelta(hours=24))
diff --git a/products/replay_vision/backend/tests/test_api.py b/products/replay_vision/backend/tests/test_api.py
index 8ef3c47c81e9..622feba6c4d4 100644
--- a/products/replay_vision/backend/tests/test_api.py
+++ b/products/replay_vision/backend/tests/test_api.py
@@ -40,7 +40,7 @@ from products.replay_vision.backend.models.replay_scanner import (
)
from products.replay_vision.backend.models.replay_scanner_backfill import ReplayScannerBackfill
from products.replay_vision.backend.models.vision_action import VisionAction
-from products.replay_vision.backend.queries import SAVE_ESTIMATE_BUDGET
+from products.replay_vision.backend.queries import ESTIMATE_STALE_AFTER, SAVE_ESTIMATE_BUDGET
from products.replay_vision.backend.queries.scanner_candidate_query import SETTLE_INTERVAL
from products.replay_vision.backend.quota import BillingPeriod, _current_period_bounds
from products.replay_vision.backend.scanner_draft import DraftError, ScannerDraft
@@ -1175,8 +1175,8 @@ class TestScannerEstimatePersistence(_VisionAPITestCase):
@parameterized.expand(
[
- ("fresh_estimate_skips_inline_refresh", timedelta(hours=1), False),
- ("stale_estimate_refreshes_inline", timedelta(days=2), True),
+ ("fresh_estimate_skips_inline_refresh", ESTIMATE_STALE_AFTER - timedelta(hours=1), False),
+ ("stale_estimate_refreshes_inline", ESTIMATE_STALE_AFTER + timedelta(hours=1), True),
]
)
def test_reenabling_refreshes_inline_only_when_stale(
diff --git a/products/replay_vision/backend/tests/test_auto_materialize.py b/products/replay_vision/backend/tests/test_auto_materialize.py
new file mode 100644
index 000000000000..7384176db354
--- /dev/null
+++ b/products/replay_vision/backend/tests/test_auto_materialize.py
@@ -0,0 +1,153 @@
+import datetime as dt
+
+import pytest
+from unittest.mock import patch
+
+from products.replay_vision.backend.models.replay_scanner import ReplayScanner
+from products.replay_vision.backend.temporal.activities.auto_materialize import (
+ AUTO_MATERIALIZE_MIN_DAILY_READ_BYTES,
+ auto_materialize_scanner_properties_activity,
+)
+from products.replay_vision.backend.tests.test_sweep import _make_scanner
+
+_MOD = "products.replay_vision.backend.temporal.activities.auto_materialize"
+
+_QUERY_WITH_EVENT_FILTERS = {
+ "kind": "RecordingsQuery",
+ "properties": [
+ {"type": "feature", "key": "$feature/expensive-flag", "operator": "exact", "value": ["true"]},
+ {"type": "person", "key": "email", "operator": "icontains", "value": "@example.com"},
+ ],
+ "events": [
+ {
+ "id": "$pageview",
+ "type": "events",
+ "properties": [{"type": "event", "key": "plan_tier", "operator": "exact", "value": "enterprise"}],
+ }
+ ],
+ "actions": [
+ {
+ "id": 42,
+ "type": "actions",
+ "properties": [{"type": "event", "key": "checkout_step", "operator": "exact", "value": "3"}],
+ }
+ ],
+}
+
+
+def _spendy_scanner(spend_bytes: int, query: dict | None = None) -> ReplayScanner:
+ hour = dt.datetime.now(dt.UTC).replace(minute=0, second=0, microsecond=0).isoformat()
+ return _make_scanner(query=query or _QUERY_WITH_EVENT_FILTERS, fast_read_bytes_by_hour={hour: spend_bytes})
+
+
+def _run(*, enabled: bool = True, acting_hour: bool = True, already_materialized: frozenset[str] = frozenset()):
+ hour_now = dt.datetime.now(dt.UTC).hour
+ with (
+ patch(f"{_MOD}.AUTO_MATERIALIZE_ENABLED", enabled),
+ patch(f"{_MOD}._ACTING_HOUR_UTC", hour_now if acting_hour else (hour_now + 1) % 24),
+ patch(f"{_MOD}.materialize_properties_task") as task,
+ patch(
+ f"{_MOD}.get_materialized_columns",
+ return_value={(prop, "properties"): object() for prop in already_materialized},
+ ),
+ ):
+ result = auto_materialize_scanner_properties_activity()
+ return result, task
+
+
[email protected]_db(transaction=True)
+class TestAutoMaterializeScannerProperties:
+ def test_materializes_event_and_feature_filters_of_a_scanner_over_budget(self) -> None:
+ _spendy_scanner(AUTO_MATERIALIZE_MIN_DAILY_READ_BYTES * 2)
+
+ result, task = _run()
+
+ # Person-scoped filters never reach the events properties column, so they must not be proposed.
+ assert sorted(task.call_args.kwargs["properties_to_materialize"]) == [
+ ("events", "properties", "$feature/expensive-flag"),
+ ("events", "properties", "checkout_step"),
+ ]
+ assert result.candidates == 3
+ assert result.materialized == 2
+
+ def test_a_scanner_under_the_spend_threshold_is_never_a_candidate(self) -> None:
+ _spendy_scanner(AUTO_MATERIALIZE_MIN_DAILY_READ_BYTES // 2)
+
+ result, task = _run()
+
+ task.assert_not_called()
+ assert result.candidates == 0
+
+ def test_backfill_spend_alone_does_not_qualify_a_scanner(self) -> None:
+ # Backfill reads land only in the total bucket; a one-day backfill must not mint columns.
+ hour = dt.datetime.now(dt.UTC).replace(minute=0, second=0, microsecond=0).isoformat()
+ _make_scanner(
+ query=_QUERY_WITH_EVENT_FILTERS,
+ fast_read_bytes_by_hour={hour: AUTO_MATERIALIZE_MIN_DAILY_READ_BYTES // 10},
+ deep_read_bytes_by_hour={},
+ sweep_read_bytes_by_hour={hour: AUTO_MATERIALIZE_MIN_DAILY_READ_BYTES * 5},
+ )
+
+ result, task = _run()
+
+ task.assert_not_called()
+ assert result.candidates == 0
+
+ def test_a_pre_split_scanner_with_only_the_total_bucket_never_qualifies(self) -> None:
+ # A row the split meter has not written yet has both split buckets null; the total bucket
+ # folds in backfill reads, so it must not qualify on that alone.
+ hour = dt.datetime.now(dt.UTC).replace(minute=0, second=0, microsecond=0).isoformat()
+ _make_scanner(
+ query=_QUERY_WITH_EVENT_FILTERS,
+ sweep_read_bytes_by_hour={hour: AUTO_MATERIALIZE_MIN_DAILY_READ_BYTES * 5},
+ )
+
+ result, task = _run()
+
+ task.assert_not_called()
+ assert result.candidates == 0
+
+ def test_flag_off_logs_candidates_but_creates_nothing(self) -> None:
+ _spendy_scanner(AUTO_MATERIALIZE_MIN_DAILY_READ_BYTES * 2)
+
+ result, task = _run(enabled=False)
+
+ task.assert_not_called()
+ assert result.candidates == 3
+ assert result.materialized == 0
+
+ def test_a_property_key_unsafe_for_column_metadata_is_never_proposed(self) -> None:
+ # Materialized-column metadata round-trips the key through a `::`-delimited comment, so a
+ # hostile or accidental `::` key would poison every registry lookup cluster-wide.
+ _spendy_scanner(
+ AUTO_MATERIALIZE_MIN_DAILY_READ_BYTES * 2,
+ query={
+ "kind": "RecordingsQuery",
+ "properties": [{"type": "event", "key": "foo::bar", "operator": "exact", "value": "x"}],
+ },
+ )
+
+ result, task = _run()
+
+ task.assert_not_called()
+ assert result.candidates == 0
+
+ def test_outside_the_acting_hour_nothing_is_created(self) -> None:
+ # The meter runs hourly; acting once a day is what bounds cluster-wide column growth.
+ _spendy_scanner(AUTO_MATERIALIZE_MIN_DAILY_READ_BYTES * 2)
+
+ result, task = _run(acting_hour=False)
+
+ task.assert_not_called()
+ assert result.candidates == 3
+
+ def test_already_materialized_properties_are_not_proposed_again(self) -> None:
+ _spendy_scanner(AUTO_MATERIALIZE_MIN_DAILY_READ_BYTES * 2)
+
+ result, task = _run(already_materialized=frozenset({"$feature/expensive-flag"}))
+
+ assert sorted(task.call_args.kwargs["properties_to_materialize"]) == [
+ ("events", "properties", "checkout_step"),
+ ("events", "properties", "plan_tier"),
+ ]
+ assert result.materialized == 2
diff --git a/products/replay_vision/backend/tests/test_estimate_refresh.py b/products/replay_vision/backend/tests/test_estimate_refresh.py
index b64a508b62b1..3005bb49e013 100644
--- a/products/replay_vision/backend/tests/test_estimate_refresh.py
+++ b/products/replay_vision/backend/tests/test_estimate_refresh.py
@@ -21,6 +21,8 @@ from posthog.session_recordings.queries.session_recording_list_from_query import
from products.replay_vision.backend.models.replay_scanner import ReplayScanner, ScannerModel, ScannerType
from products.replay_vision.backend.queries import (
+ DISABLED_ESTIMATE_STALE_AFTER,
+ ESTIMATE_STALE_AFTER,
ScannerVolumeEstimate,
project_monthly_observations,
refresh_scanner_estimate,
@@ -46,6 +48,9 @@ from products.replay_vision.backend.temporal.estimates_types import (
RefreshScannerEstimatesResult,
)
+_STALE_HOURS = int(ESTIMATE_STALE_AFTER.total_seconds() // 3600) + 1
+_DISABLED_STALE_HOURS = int(DISABLED_ESTIMATE_STALE_AFTER.total_seconds() // 3600) + 1
+
_ACTIVITY_HELPER = (
"products.replay_vision.backend.temporal.activities.refresh_scanner_estimate.refresh_scanner_estimate"
)
@@ -289,9 +294,9 @@ class TestRefreshScannerEstimateActivity:
"enabled, estimated_hours_ago, expect_refresh",
[
(True, None, True), # never computed → refresh
- (True, 25, True), # stale → refresh
+ (True, _STALE_HOURS, True), # stale → refresh
(True, 1, False), # fresh → no-op
- (False, 25, True), # disabled scanners refresh too, so re-enabling uses an accurate number
+ (False, _STALE_HOURS, True), # disabled scanners refresh too, so re-enabling uses an accurate number
(False, 1, False), # fresh → no-op regardless of enabled
],
)
@@ -330,13 +335,16 @@ class TestListStaleScannerEstimatesActivity:
def test_returns_stale_scanners_enabled_first_then_oldest(self) -> None:
never = _make_scanner(name="never-estimated")
stale = _make_scanner(name="stale")
- _set_estimate(stale, 10, hours_ago=48)
+ _set_estimate(stale, 10, hours_ago=_STALE_HOURS)
very_stale = _make_scanner(name="very-stale")
- _set_estimate(very_stale, 10, hours_ago=72)
+ _set_estimate(very_stale, 10, hours_ago=_STALE_HOURS + 24)
fresh = _make_scanner(name="fresh")
_set_estimate(fresh, 10, hours_ago=1)
disabled = _make_scanner(name="disabled", enabled=False)
- _set_estimate(disabled, 10, hours_ago=96)
+ _set_estimate(disabled, 10, hours_ago=_DISABLED_STALE_HOURS)
+ # Disabled scanners run on the slower clock: stale for an enabled scanner, not for a disabled one.
+ disabled_recent = _make_scanner(name="disabled-recent", enabled=False)
+ _set_estimate(disabled_recent, 10, hours_ago=_STALE_HOURS + 24)
entries = list_stale_scanner_estimates_activity()