: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): apply the selection targeting predicate in synthesis (#69005)
Kim Svatos Duganc12989f0ebc8
diff --git a/products/replay_vision/backend/api/vision_actions.py b/products/replay_vision/backend/api/vision_actions.pyindex 1b877e6c4db2..e0e61f3d0396 100644--- a/products/replay_vision/backend/api/vision_actions.py+++ b/products/replay_vision/backend/api/vision_actions.py@@ -1,5 +1,5 @@import uuid-from typing import Any, NoReturn, cast+from typing import Any, NoReturn, cast, get_argsfrom django.db import IntegrityError, transactionfrom django.db.models import QuerySet@@ -33,6 +33,7 @@ from products.replay_vision.backend.models.vision_action import (VisionActionRunStatus,)from products.replay_vision.backend.rrule import validate_rrule, validate_timezone+from products.replay_vision.backend.temporal.scanners.monitor import MonitorVerdictlogger = structlog.get_logger(__name__)@@ -53,44 +54,40 @@ class TriggerConfigSerializer(serializers.Serializer):class SelectionSerializer(serializers.Serializer):- """Observation filter applied at synthesis time. All keys optional; this typed shape is the- allowlist, so unknown input keys are dropped rather than persisted."""+ """The action's targeting predicate ("run this on…") applied when gathering observations. All keys+ optional; this typed shape is the allowlist, so unknown input keys are dropped rather than persisted."""- scanner_type = serializers.CharField(- required=False,- help_text="Filter observations by scanner type (monitor/classifier/scorer/summarizer).",- )scanner_ids = serializers.ListField(child=serializers.CharField(),required=False,- help_text="Restrict to observations produced by these scanner IDs.",+ help_text="Restrict to observations produced by these scanner IDs. Defaults to the bound scanner.",)- verdict = serializers.CharField(+ verdict = serializers.ListField(+ child=serializers.ChoiceField(choices=[(v, v) for v in get_args(MonitorVerdict)]),required=False,- help_text="Filter to observations with this monitor verdict.",+ help_text="Only run on monitor observations with one of these verdicts (yes/no/inconclusive).",)tags = serializers.ListField(child=serializers.CharField(),required=False,- help_text="Filter to observations carrying any of these classifier tags.",+ help_text="Only run on classifier observations carrying any of these tags (fixed or freeform).",)min_score = serializers.FloatField(required=False,- help_text="Lower bound (inclusive) on scorer score.",+ help_text="Only run on scorer observations with a score at or above this value (inclusive).",)max_score = serializers.FloatField(required=False,- help_text="Upper bound (inclusive) on scorer score.",- )- status = serializers.CharField(- required=False,- help_text="Filter to observations with this processing status.",- )- window_days = serializers.IntegerField(- required=False,- help_text="Lookback window in days for the observations gathered at synthesis time.",+ help_text="Only run on scorer observations with a score at or below this value (inclusive).",)+ def validate(self, attrs: dict[str, Any]) -> dict[str, Any]:+ min_score = attrs.get("min_score")+ max_score = attrs.get("max_score")+ if min_score is not None and max_score is not None and min_score > max_score:+ raise serializers.ValidationError({"min_score": "min_score cannot exceed max_score."})+ return attrs+class SynthesisConfigSerializer(serializers.Serializer):"""Options for the group-summary synthesis step."""@@ -147,7 +144,7 @@ class VisionActionSerializer(serializers.ModelSerializer):)selection = SelectionSerializer(required=False,- help_text="Observation filter applied at synthesis time.",+ help_text="Targeting predicate: which of the scanner's observations this action runs on.",)synthesis_config = SynthesisConfigSerializer(required=False,diff --git a/products/replay_vision/backend/temporal/vision_actions/synthesis.py b/products/replay_vision/backend/temporal/vision_actions/synthesis.pyindex 0782939f5130..6f2608f04de6 100644--- a/products/replay_vision/backend/temporal/vision_actions/synthesis.py+++ b/products/replay_vision/backend/temporal/vision_actions/synthesis.py@@ -12,6 +12,7 @@ from typing import TYPE_CHECKING, Any, NamedTuplefrom zoneinfo import ZoneInfofrom django.conf import settings+from django.db.models import Q, QuerySetimport structlogimport posthoganalytics@@ -166,6 +167,43 @@ def _window_end(run: VisionActionRun) -> datetime:return run.scheduled_at or datetime.now(UTC)+def apply_observation_predicate(+ queryset: "QuerySet[ReplayObservation]", selection: dict[str, Any]+) -> "QuerySet[ReplayObservation]":+ """Narrow an observation queryset to the action's targeting predicate ("run this on…").++ Filters on the persisted `scanner_result["model_output"]` JSON: monitor verdicts, classifier tags+ (fixed or freeform, any-of), and scorer score bounds. Empty or absent keys are ignored, so a+ default `selection` matches everything. Verdict/score filters implicitly exclude observations of+ other scanner types (the JSON key is absent there), which is what targeting means.+ """+ verdicts = selection.get("verdict") or []+ if isinstance(verdicts, str): # tolerate a legacy single-string row+ verdicts = [verdicts]+ if verdicts:+ queryset = queryset.filter(scanner_result__model_output__verdict__in=verdicts)++ tags = selection.get("tags") or []+ if tags:+ # `__contains` on a JSONB array uses `@>`: matches when the stored array contains the element.+ tag_q = Q()+ for tag in tags:+ tag_q |= Q(scanner_result__model_output__tags__contains=[tag])+ tag_q |= Q(scanner_result__model_output__tags_freeform__contains=[tag])+ queryset = queryset.filter(tag_q)++ # jsonb comparison is numeric for JSON numbers, so these bounds work for int and float scores.+ # bool is rejected explicitly (it's an int subclass but a nonsensical bound).+ min_score = selection.get("min_score")+ if isinstance(min_score, int | float) and not isinstance(min_score, bool):+ queryset = queryset.filter(scanner_result__model_output__score__gte=min_score)+ max_score = selection.get("max_score")+ if isinstance(max_score, int | float) and not isinstance(max_score, bool):+ queryset = queryset.filter(scanner_result__model_output__score__lte=max_score)++ return queryset++class _ObservationBatch(NamedTuple):# Formatted summary lines fed to the LLM, and the ids of the observations they came from, in the# same order — so the run persists exactly which observations its summary included. window_start is@@ -241,6 +279,9 @@ def _fetch_observations(team: Team, action: VisionAction, run: VisionActionRun)created_at__gte=window_start,created_at__lt=_window_end(run),)+ # Targeting ("run this on…") narrows the window BEFORE the count/cap/sampling below, so the header's+ # totals and the sampled batch reflect only the observations the action targets.+ observations_qs = apply_observation_predicate(observations_qs, selection)# Count the whole window so the header can say when the summary is only a sample of it (see cap below).window_total = observations_qs.count()diff --git a/products/replay_vision/backend/tests/test_vision_action_synthesis.py b/products/replay_vision/backend/tests/test_vision_action_synthesis.pyindex e915a9d60f54..95f50cf033fb 100644--- a/products/replay_vision/backend/tests/test_vision_action_synthesis.py+++ b/products/replay_vision/backend/tests/test_vision_action_synthesis.py@@ -480,6 +480,65 @@ class TestVisionActionSynthesis(BaseTest):# block stays the last thing the model reads.self.assertLess(human.index("focus on rage clicks"), human.index("<observations>"))+ def _typed_observation(self, model_output: dict, session_id: str) -> ReplayObservation:+ return ReplayObservation.objects.create(+ scanner=self.scanner,+ session_id=session_id,+ scanner_snapshot=snapshot_for(self.scanner),+ triggered_by=ObservationTrigger.SCHEDULE,+ status=ObservationStatus.SUCCEEDED,+ completed_at=timezone.now(),+ scanner_result={"model_output": model_output},+ )++ def test_targeting_verdict_only_feeds_matching_observations(self) -> None:+ matching = self._typed_observation(+ {"scanner_type": "monitor", "verdict": "yes", "reasoning": "user rage clicked"}, session_id="s1"+ )+ self._typed_observation(+ {"scanner_type": "monitor", "verdict": "no", "reasoning": "calm session"}, session_id="s2"+ )+ action = self._action(selection={"verdict": ["yes"]})+ run = self._run_for(action)++ result = self._synthesize(action, run)++ self.assertEqual(result.observation_count, 1)+ run.refresh_from_db()+ self.assertEqual(run.observation_ids, [str(matching.id)])++ def test_targeting_score_bounds_compare_numerically(self) -> None:+ # score 10 must satisfy min_score 9 — catches the jsonb bound regressing to text+ # comparison, where "10" < "9" lexicographically.+ self._typed_observation({"scanner_type": "scorer", "score": 2, "reasoning": "meh"}, session_id="s1")+ high = self._typed_observation({"scanner_type": "scorer", "score": 10, "reasoning": "great"}, session_id="s2")+ action = self._action(selection={"min_score": 9})+ run = self._run_for(action)++ result = self._synthesize(action, run)++ self.assertEqual(result.observation_count, 1)+ run.refresh_from_db()+ self.assertEqual(run.observation_ids, [str(high.id)])++ def test_targeting_tags_match_fixed_or_freeform(self) -> None:+ fixed = self._typed_observation(+ {"scanner_type": "classifier", "tags": ["bug"], "reasoning": "hit a bug"}, session_id="s1"+ )+ freeform = self._typed_observation(+ {"scanner_type": "classifier", "tags": [], "tags_freeform": ["slow"], "reasoning": "felt slow"},+ session_id="s2",+ )+ self._typed_observation({"scanner_type": "classifier", "tags": ["ux"], "reasoning": "ux note"}, session_id="s3")+ action = self._action(selection={"tags": ["bug", "slow"]})+ run = self._run_for(action)++ result = self._synthesize(action, run)++ self.assertEqual(result.observation_count, 2)+ run.refresh_from_db()+ self.assertEqual(set(run.observation_ids), {str(fixed.id), str(freeform.id)})+class TestMarkdownToSlack(BaseTest):@parameterized.expand(diff --git a/products/replay_vision/backend/tests/test_vision_actions_api.py b/products/replay_vision/backend/tests/test_vision_actions_api.pyindex b9326446aaa3..a95c7da307ac 100644--- a/products/replay_vision/backend/tests/test_vision_actions_api.py+++ b/products/replay_vision/backend/tests/test_vision_actions_api.py@@ -67,7 +67,7 @@ class _VisionActionAPITestCase(APIBaseTest):"name": "daily-summary","scanner": str(self.scanner.id),"trigger_config": {"rrule": "FREQ=DAILY", "timezone": "UTC"},- "selection": {"scanner_type": "summarizer", "window_days": 1},+ "selection": {"verdict": ["yes"]},"synthesis_config": {"prompt_guide": "keep it short"},"delivery_config": [{"type": "slack", "integration_id": self.integration.id, "channel": "#general"},@@ -192,9 +192,7 @@ class TestVisionActionViewSet(_VisionActionAPITestCase):def test_selection_valid_accepted(self) -> None:resp = self.client.post(self.actions_url,- data=self._create_payload(- selection={"scanner_type": "scorer", "min_score": 0.5, "max_score": 1.0, "tags": ["a", "b"]}- ),+ data=self._create_payload(selection={"min_score": 0.5, "max_score": 1.0, "tags": ["a", "b"]}),format="json",)self.assertEqual(resp.status_code, 201, resp.content)@@ -202,15 +200,28 @@ class TestVisionActionViewSet(_VisionActionAPITestCase):self.assertEqual(action.selection["min_score"], 0.5)def test_selection_unknown_key_ignored(self) -> None:- # The typed SelectionSerializer is the allowlist; unknown keys are dropped, not persisted.+ # The typed SelectionSerializer is the allowlist; unknown keys (including the retired+ # scanner_type/status/window_days) are dropped, not persisted.resp = self.client.post(self.actions_url,- data=self._create_payload(selection={"scanner_type": "summarizer", "bogus_key": "x"}),+ data=self._create_payload(selection={"scanner_type": "summarizer", "window_days": 3, "bogus_key": "x"}),format="json",)self.assertEqual(resp.status_code, 201, resp.content)action = VisionAction.all_teams.get(id=resp.json()["id"])- self.assertNotIn("bogus_key", action.selection)+ for key in ("bogus_key", "scanner_type", "window_days"):+ self.assertNotIn(key, action.selection)++ @parameterized.expand(+ [+ ("min_above_max", {"min_score": 2.0, "max_score": 1.0}),+ ("unknown_verdict", {"verdict": ["maybe"]}),+ ("verdict_not_a_list", {"verdict": "yes"}),+ ]+ )+ def test_selection_invalid_rejected(self, _name: str, selection: dict[str, Any]) -> None:+ resp = self.client.post(self.actions_url, data=self._create_payload(selection=selection), format="json")+ self.assertEqual(resp.status_code, 400, resp.content)class TestVisionActionCrossTeamIDOR(_VisionActionAPITestCase):diff --git a/products/replay_vision/frontend/generated/api.schemas.ts b/products/replay_vision/frontend/generated/api.schemas.tsindex fd8a8b819787..4d6cea292e34 100644--- a/products/replay_vision/frontend/generated/api.schemas.ts+++ b/products/replay_vision/frontend/generated/api.schemas.ts@@ -40,26 +40,33 @@ export interface TriggerConfigApi {}/**- * Observation filter applied at synthesis time. All keys optional; this typed shape is the- * allowlist, so unknown input keys are dropped rather than persisted.+ * * `yes` - yes+ * * `no` - no+ * * `inconclusive` - inconclusive+ */+export type VerdictEnumApi = (typeof VerdictEnumApi)[keyof typeof VerdictEnumApi]++export const VerdictEnumApi = {+ Yes: 'yes',+ No: 'no',+ Inconclusive: 'inconclusive',+} as const++/**+ * The action's targeting predicate ("run this on…") applied when gathering observations. All keys+ * optional; this typed shape is the allowlist, so unknown input keys are dropped rather than persisted.*/export interface SelectionApi {- /** Filter observations by scanner type (monitor/classifier/scorer/summarizer). */- scanner_type?: string- /** Restrict to observations produced by these scanner IDs. */+ /** Restrict to observations produced by these scanner IDs. Defaults to the bound scanner. */scanner_ids?: string[]- /** Filter to observations with this monitor verdict. */- verdict?: string- /** Filter to observations carrying any of these classifier tags. */+ /** Only run on monitor observations with one of these verdicts (yes/no/inconclusive). */+ verdict?: VerdictEnumApi[]+ /** Only run on classifier observations carrying any of these tags (fixed or freeform). */tags?: string[]- /** Lower bound (inclusive) on scorer score. */+ /** Only run on scorer observations with a score at or above this value (inclusive). */min_score?: number- /** Upper bound (inclusive) on scorer score. */+ /** Only run on scorer observations with a score at or below this value (inclusive). */max_score?: number- /** Filter to observations with this processing status. */- status?: string- /** Lookback window in days for the observations gathered at synthesis time. */- window_days?: number}/**@@ -174,7 +181,7 @@ export interface VisionActionApi {mode?: VisionActionModeEnumApi/** Trigger parameters. For schedule triggers: {rrule, timezone}. */trigger_config?: TriggerConfigApi- /** Observation filter applied at synthesis time. */+ /** Targeting predicate: which of the scanner's observations this action runs on. */selection?: SelectionApi/** Synthesis options for the group summary, e.g. {prompt_guide}. */synthesis_config?: SynthesisConfigApi@@ -233,7 +240,7 @@ export interface PatchedVisionActionApi {mode?: VisionActionModeEnumApi/** Trigger parameters. For schedule triggers: {rrule, timezone}. */trigger_config?: TriggerConfigApi- /** Observation filter applied at synthesis time. */+ /** Targeting predicate: which of the scanner's observations this action runs on. */selection?: SelectionApi/** Synthesis options for the group summary, e.g. {prompt_guide}. */synthesis_config?: SynthesisConfigApidiff --git a/products/replay_vision/frontend/generated/api.zod.ts b/products/replay_vision/frontend/generated/api.zod.tsindex 78cbd5b76df9..6758ad61560f 100644--- a/products/replay_vision/frontend/generated/api.zod.ts+++ b/products/replay_vision/frontend/generated/api.zod.ts@@ -56,32 +56,36 @@ export const VisionActionsCreateBody = /* @__PURE__ */ zod.object({.describe('Trigger parameters. For schedule triggers: {rrule, timezone}.'),selection: zod.object({- scanner_type: zod- .string()- .optional()- .describe('Filter observations by scanner type (monitor\/classifier\/scorer\/summarizer).'),scanner_ids: zod.array(zod.string()).optional()- .describe('Restrict to observations produced by these scanner IDs.'),- verdict: zod.string().optional().describe('Filter to observations with this monitor verdict.'),+ .describe('Restrict to observations produced by these scanner IDs. Defaults to the bound scanner.'),+ verdict: zod+ .array(+ zod+ .enum(['yes', 'no', 'inconclusive'])+ .describe('\* `yes` - yes\n\* `no` - no\n\* `inconclusive` - inconclusive')+ )+ .optional()+ .describe('Only run on monitor observations with one of these verdicts (yes\/no\/inconclusive).'),tags: zod.array(zod.string()).optional()- .describe('Filter to observations carrying any of these classifier tags.'),- min_score: zod.number().optional().describe('Lower bound (inclusive) on scorer score.'),- max_score: zod.number().optional().describe('Upper bound (inclusive) on scorer score.'),- status: zod.string().optional().describe('Filter to observations with this processing status.'),- window_days: zod+ .describe('Only run on classifier observations carrying any of these tags (fixed or freeform).'),+ min_score: zod+ .number()+ .optional()+ .describe('Only run on scorer observations with a score at or above this value (inclusive).'),+ max_score: zod.number().optional()- .describe('Lookback window in days for the observations gathered at synthesis time.'),+ .describe('Only run on scorer observations with a score at or below this value (inclusive).'),}).describe(- 'Observation filter applied at synthesis time. All keys optional; this typed shape is the\nallowlist, so unknown input keys are dropped rather than persisted.'+ 'The action\'s targeting predicate (\"run this on…\") applied when gathering observations. All keys\noptional; this typed shape is the allowlist, so unknown input keys are dropped rather than persisted.').optional()- .describe('Observation filter applied at synthesis time.'),+ .describe("Targeting predicate: which of the scanner's observations this action runs on."),synthesis_config: zod.object({prompt_guide: zod@@ -163,32 +167,36 @@ export const VisionActionsPartialUpdateBody = /* @__PURE__ */ zod.object({.describe('Trigger parameters. For schedule triggers: {rrule, timezone}.'),selection: zod.object({- scanner_type: zod- .string()- .optional()- .describe('Filter observations by scanner type (monitor\/classifier\/scorer\/summarizer).'),scanner_ids: zod.array(zod.string()).optional()- .describe('Restrict to observations produced by these scanner IDs.'),- verdict: zod.string().optional().describe('Filter to observations with this monitor verdict.'),+ .describe('Restrict to observations produced by these scanner IDs. Defaults to the bound scanner.'),+ verdict: zod+ .array(+ zod+ .enum(['yes', 'no', 'inconclusive'])+ .describe('\* `yes` - yes\n\* `no` - no\n\* `inconclusive` - inconclusive')+ )+ .optional()+ .describe('Only run on monitor observations with one of these verdicts (yes\/no\/inconclusive).'),tags: zod.array(zod.string()).optional()- .describe('Filter to observations carrying any of these classifier tags.'),- min_score: zod.number().optional().describe('Lower bound (inclusive) on scorer score.'),- max_score: zod.number().optional().describe('Upper bound (inclusive) on scorer score.'),- status: zod.string().optional().describe('Filter to observations with this processing status.'),- window_days: zod+ .describe('Only run on classifier observations carrying any of these tags (fixed or freeform).'),+ min_score: zod+ .number()+ .optional()+ .describe('Only run on scorer observations with a score at or above this value (inclusive).'),+ max_score: zod.number().optional()- .describe('Lookback window in days for the observations gathered at synthesis time.'),+ .describe('Only run on scorer observations with a score at or below this value (inclusive).'),}).describe(- 'Observation filter applied at synthesis time. All keys optional; this typed shape is the\nallowlist, so unknown input keys are dropped rather than persisted.'+ 'The action\'s targeting predicate (\"run this on…\") applied when gathering observations. All keys\noptional; this typed shape is the allowlist, so unknown input keys are dropped rather than persisted.').optional()- .describe('Observation filter applied at synthesis time.'),+ .describe("Targeting predicate: which of the scanner's observations this action runs on."),synthesis_config: zod.object({prompt_guide: zoddiff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.tsindex f33c08065e1a..409415fc5fab 100644--- a/services/mcp/src/api/generated.ts+++ b/services/mcp/src/api/generated.ts@@ -37097,26 +37097,34 @@ export namespace Schemas {}/**- * Observation filter applied at synthesis time. All keys optional; this typed shape is the- * allowlist, so unknown input keys are dropped rather than persisted.+ * * `yes` - yes+ * * `no` - no+ * * `inconclusive` - inconclusive+ */+ export type VerdictEnum = typeof VerdictEnum[keyof typeof VerdictEnum];+++ export const VerdictEnum = {+ Yes: 'yes',+ No: 'no',+ Inconclusive: 'inconclusive',+ } as const;++ /**+ * The action's targeting predicate ("run this on…") applied when gathering observations. All keys+ * optional; this typed shape is the allowlist, so unknown input keys are dropped rather than persisted.*/export interface Selection {- /** Filter observations by scanner type (monitor/classifier/scorer/summarizer). */- scanner_type?: string;- /** Restrict to observations produced by these scanner IDs. */+ /** Restrict to observations produced by these scanner IDs. Defaults to the bound scanner. */scanner_ids?: string[];- /** Filter to observations with this monitor verdict. */- verdict?: string;- /** Filter to observations carrying any of these classifier tags. */+ /** Only run on monitor observations with one of these verdicts (yes/no/inconclusive). */+ verdict?: VerdictEnum[];+ /** Only run on classifier observations carrying any of these tags (fixed or freeform). */tags?: string[];- /** Lower bound (inclusive) on scorer score. */+ /** Only run on scorer observations with a score at or above this value (inclusive). */min_score?: number;- /** Upper bound (inclusive) on scorer score. */+ /** Only run on scorer observations with a score at or below this value (inclusive). */max_score?: number;- /** Filter to observations with this processing status. */- status?: string;- /** Lookback window in days for the observations gathered at synthesis time. */- window_days?: number;}/**@@ -37153,7 +37161,7 @@ export namespace Schemas {mode?: VisionActionModeEnum;/** Trigger parameters. For schedule triggers: {rrule, timezone}. */trigger_config?: TriggerConfig;- /** Observation filter applied at synthesis time. */+ /** Targeting predicate: which of the scanner's observations this action runs on. */selection?: Selection;/** Synthesis options for the group summary, e.g. {prompt_guide}. */synthesis_config?: SynthesisConfig;@@ -44289,7 +44297,7 @@ export namespace Schemas {mode?: VisionActionModeEnum;/** Trigger parameters. For schedule triggers: {rrule, timezone}. */trigger_config?: TriggerConfig;- /** Observation filter applied at synthesis time. */+ /** Targeting predicate: which of the scanner's observations this action runs on. */selection?: Selection;/** Synthesis options for the group summary, e.g. {prompt_guide}. */synthesis_config?: SynthesisConfig;