: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.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
feat(replay-vision): sample observations across the window, configurable cap (#67493)
Kim Svatos Duganfcef94525aa4
diff --git a/products/replay_vision/backend/admin.py b/products/replay_vision/backend/admin.pyindex 71180bfbaf1e..bf237068907f 100644--- a/products/replay_vision/backend/admin.py+++ b/products/replay_vision/backend/admin.py@@ -69,7 +69,17 @@ class ReplayQuotaGrantAdmin(admin.ModelAdmin):@admin.register(VisionAction)class VisionActionAdmin(admin.ModelAdmin):- list_display = ("name", "team", "scanner", "trigger_type", "mode", "enabled", "next_run_at", "created_at")+ list_display = (+ "name",+ "team",+ "scanner",+ "trigger_type",+ "mode",+ "enabled",+ "max_observations",+ "next_run_at",+ "created_at",+ )list_filter = ("trigger_type", "mode", "enabled")search_fields = ("name",)raw_id_fields = ("team", "scanner", "hog_flow", "created_by")diff --git a/products/replay_vision/backend/migrations/0024_visionaction_max_observations.py b/products/replay_vision/backend/migrations/0024_visionaction_max_observations.pynew file mode 100644index 000000000000..edd64cbda3a4--- /dev/null+++ b/products/replay_vision/backend/migrations/0024_visionaction_max_observations.py@@ -0,0 +1,22 @@+# Generated by Django 5.2.14 on 2026-07-01 18:18++import django.core.validators+from django.db import migrations, models+++class Migration(migrations.Migration):+ dependencies = [+ ("replay_vision", "0023_visionactionrun_observation_ids"),+ ]++ operations = [+ migrations.AddField(+ model_name="visionaction",+ name="max_observations",+ field=models.PositiveIntegerField(+ default=100,+ validators=[django.core.validators.MinValueValidator(1)],+ help_text="Max observations included in one group summary; sampled across the window when exceeded.",+ ),+ ),+ ]diff --git a/products/replay_vision/backend/migrations/max_migration.txt b/products/replay_vision/backend/migrations/max_migration.txtindex e881f3627d2f..e176a6e78da7 100644--- a/products/replay_vision/backend/migrations/max_migration.txt+++ b/products/replay_vision/backend/migrations/max_migration.txt@@ -1 +1 @@-0023_visionactionrun_observation_ids+0024_visionaction_max_observationsdiff --git a/products/replay_vision/backend/models/vision_action.py b/products/replay_vision/backend/models/vision_action.pyindex c584af80e689..9161bb0b1c62 100644--- a/products/replay_vision/backend/models/vision_action.py+++ b/products/replay_vision/backend/models/vision_action.py@@ -1,5 +1,6 @@from typing import Any+from django.core.validators import MinValueValidatorfrom django.db import modelsfrom django.utils import timezone@@ -76,6 +77,13 @@ class VisionAction(TeamScopedRootMixin, UUIDModel):),)synthesis_config = models.JSONField(default=dict, help_text="Synthesis options, e.g. {prompt_guide}.")+ # How many observations may feed one group summary. When the window holds more, they're sampled+ # evenly across it (not just the newest). Not exposed in the API/UI yet — tune via Django admin.+ max_observations = models.PositiveIntegerField(+ default=100,+ validators=[MinValueValidator(1)],+ help_text="Max observations included in one group summary; sampled across the window when exceeded.",+ )delivery_config = models.JSONField(default=list,help_text="List of destination targets, e.g. [{type: 'slack', integration_id, channel}].",diff --git a/products/replay_vision/backend/temporal/vision_actions/synthesis.py b/products/replay_vision/backend/temporal/vision_actions/synthesis.pyindex a9c07be519ed..fd50be7ba4c7 100644--- a/products/replay_vision/backend/temporal/vision_actions/synthesis.py+++ b/products/replay_vision/backend/temporal/vision_actions/synthesis.py@@ -42,6 +42,10 @@ logger = structlog.get_logger(__name__)SYNTHESIS_MODEL = ScannerModel.GEMINI_3_FLASH.value# Cap how many observations feed one group summary — bounds context size and cost.MAX_OBSERVATIONS = 100+# Upper bound on how many ids the sampling path pulls into memory. A very busy window (the case the+# cap guards against) samples across its newest SAMPLE_SCAN_LIMIT observations rather than every row,+# so this activity can't materialize an unbounded id list.+SAMPLE_SCAN_LIMIT = 10_000# Stay comfortably under Slack's ~40k message-text limit; truncate the tail if a report runs long.SLACK_TEXT_MAX = 38_000@@ -180,7 +184,28 @@ def _fetch_observations(team: Team, action: VisionAction, run: VisionActionRun)created_at__lt=_window_end(run),)- rows = observations_qs.order_by("-created_at").values_list("id", "scanner_result", "created_at")[:MAX_OBSERVATIONS]+ # Cap how many observations feed the summary (bounds context size + LLM cost). Per-action, tunable+ # via Django admin; falls back to the module default. Fast path: one query fetches the newest `cap`+ # rows. If it returns exactly `cap`, the window may hold more — only then scan ids and sample evenly+ # across them by recency rank, so a busy window reflects the period rather than just its newest slice.+ # Under the cap (the common case) this stays a single query. `-id` breaks created_at ties (observations+ # are often bulk-created with identical timestamps, which Postgres would otherwise order arbitrarily)+ # so the slice, the sample, and the persisted observation_ids are stable run-to-run.+ cap = action.max_observations or MAX_OBSERVATIONS+ ordered = observations_qs.order_by("-created_at", "-id")+ rows = list(ordered.values_list("id", "scanner_result", "created_at")[:cap])+ if len(rows) == cap:+ # Bound the scan so the guarded-against busy window can't pull an unbounded id list into memory;+ # a window larger than SAMPLE_SCAN_LIMIT samples across its newest slice.+ ids = list(ordered.values_list("id", flat=True)[:SAMPLE_SCAN_LIMIT])+ if len(ids) > cap:+ step = len(ids) / cap+ selected = {ids[int(i * step)] for i in range(cap)}+ rows = list(+ observations_qs.filter(id__in=selected)+ .order_by("-created_at", "-id")+ .values_list("id", "scanner_result", "created_at")+ )lines: list[str] = []observation_ids: list[str] = []diff --git a/products/replay_vision/backend/tests/test_vision_action_synthesis.py b/products/replay_vision/backend/tests/test_vision_action_synthesis.pyindex 507c7bdbd016..d2fbb1eee591 100644--- a/products/replay_vision/backend/tests/test_vision_action_synthesis.py+++ b/products/replay_vision/backend/tests/test_vision_action_synthesis.py@@ -157,6 +157,47 @@ class TestVisionActionSynthesis(BaseTest):run.refresh_from_db()self.assertEqual(run.observation_ids, [str(included.id)])+ def test_samples_across_window_when_over_cap(self) -> None:+ # Over the action's cap, observations are sampled evenly across the window by recency rank —+ # not just the newest N — so a busy window still reflects the whole period. With 9 in-window+ # observations and a cap of 3, the stride (9/3=3) picks recency ranks 0, 3, 6.+ obs = []+ for i in range(1, 10):+ o = self._observation(f"obs {i}", session_id=f"s{i}")+ ReplayObservation.objects.filter(pk=o.pk).update(created_at=datetime.now(UTC) - timedelta(hours=i))+ obs.append(o) # obs[0] is newest (1h ago) … obs[8] is oldest (9h ago)+ action = self._action(max_observations=3)+ run = self._run_for(action)++ result = self._synthesize(action, run)++ self.assertEqual(result.observation_count, 3)+ run.refresh_from_db()+ self.assertEqual(run.observation_ids, [str(obs[0].id), str(obs[3].id), str(obs[6].id)])++ def test_sample_is_deterministic_when_timestamps_tie(self) -> None:+ # Observations are often bulk-created with identical created_at; without an `-id` tiebreaker+ # Postgres orders ties arbitrarily and the sampled set (and persisted observation_ids) can drift+ # run-to-run. With the tiebreak, the window is ordered by (-created_at, -id), so the sample is+ # stable and predictable. Random UUIDs mean id-desc order differs from insertion order — asserting+ # the id-desc picks fails if the tiebreak is dropped.+ tied_at = datetime.now(UTC) - timedelta(hours=1)+ obs = []+ for i in range(6):+ o = self._observation(f"obs {i}", session_id=f"s{i}")+ ReplayObservation.objects.filter(pk=o.pk).update(created_at=tied_at)+ obs.append(o)+ action = self._action(max_observations=3)+ run = self._run_for(action)++ result = self._synthesize(action, run)++ self.assertEqual(result.observation_count, 3)+ # Ordered by -id (created_at all equal); stride 6/3=2 picks ranks 0, 2, 4 of that order.+ by_id_desc = sorted((str(o.id) for o in obs), reverse=True)+ run.refresh_from_db()+ self.assertEqual(run.observation_ids, [by_id_desc[0], by_id_desc[2], by_id_desc[4]])+def test_empty_model_output_skips_without_persisting(self) -> None:# An empty generation must not persist synthesized_markdown="" — that would read as "not done"# to the idempotency guard and re-bill the LLM on every retry.