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.

chore(replay_vision): remove the scanner auto-materializer (#87705)

Tue Haulund71739d7c8dd8
diff --git a/products/replay_vision/backend/temporal/__init__.py b/products/replay_vision/backend/temporal/__init__.py
index eb15d4f7ce71..da51f3439016 100644
--- a/products/replay_vision/backend/temporal/__init__.py
+++ b/products/replay_vision/backend/temporal/__init__.py
@@ -4,7 +4,6 @@ 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,
@@ -77,7 +76,6 @@ 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 d9c572e8ade2..8caa302ce7da 100644
--- a/products/replay_vision/backend/temporal/activities/__init__.py
+++ b/products/replay_vision/backend/temporal/activities/__init__.py
@@ -1,9 +1,6 @@
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,
@@ -68,7 +65,6 @@ 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
deleted file mode 100644
index 86924206feae..000000000000
--- a/products/replay_vision/backend/temporal/activities/auto_materialize.py
+++ /dev/null
@@ -1,160 +0,0 @@
-"""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/constants.py b/products/replay_vision/backend/temporal/constants.py
index 6ddeb4a1fc17..38d5be87f429 100644
--- a/products/replay_vision/backend/temporal/constants.py
+++ b/products/replay_vision/backend/temporal/constants.py
@@ -102,12 +102,9 @@ 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)
-# 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.
+# Must cover the metering activity's retries. 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 d41a765d638d..980479f82a41 100644
--- a/products/replay_vision/backend/temporal/metrics.py
+++ b/products/replay_vision/backend/temporal/metrics.py
@@ -102,13 +102,6 @@ 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_DEEP_CANDIDATES = Counter(
"replay_vision_deep_candidates_total",
"Sessions the catch-up pass found that the frequent sweep had missed. This is the pass's whole "
@@ -235,11 +228,6 @@ 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_candidates(count: int) -> None:
REPLAY_VISION_DEEP_CANDIDATES.inc(count)
_otel.record_counter_twin(REPLAY_VISION_DEEP_CANDIDATES, count, {})
diff --git a/products/replay_vision/backend/temporal/read_meter.py b/products/replay_vision/backend/temporal/read_meter.py
index cc311d438cc5..4a3648ee1784 100644
--- a/products/replay_vision/backend/temporal/read_meter.py
+++ b/products/replay_vision/backend/temporal/read_meter.py
@@ -13,7 +13,6 @@ 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,
@@ -27,11 +26,7 @@ if TYPE_CHECKING:
from temporalio.client import Client
with workflow.unsafe.imports_passed_through():
- 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
+ from products.replay_vision.backend.temporal.activities import meter_scanner_read_bytes_activity
@workflow.defn(name=READ_METER_WORKFLOW_NAME)
@@ -41,25 +36,11 @@ class MeterScannerReadsWorkflow(PostHogWorkflow):
@workflow.run
async def run(self, inputs: MeterScannerReadsInputs) -> MeterScannerReadsResult:
- result = await workflow.execute_activity(
+ return 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 e0717ad33fd9..4f994c6a80ff 100644
--- a/products/replay_vision/backend/temporal/read_meter_types.py
+++ b/products/replay_vision/backend/temporal/read_meter_types.py
@@ -22,11 +22,6 @@ 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_auto_materialize.py b/products/replay_vision/backend/tests/test_auto_materialize.py
deleted file mode 100644
index 7384176db354..000000000000
--- a/products/replay_vision/backend/tests/test_auto_materialize.py
+++ /dev/null
@@ -1,153 +0,0 @@
-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