: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): report the ranker experiment variant on feed views (#114129)
Kim Svatos Dugan66a17ac22e98
diff --git a/products/replay_vision/backend/api/scanners.py b/products/replay_vision/backend/api/scanners.pyindex b5f2e1a9f9f9..3890a113818a 100644--- a/products/replay_vision/backend/api/scanners.py+++ b/products/replay_vision/backend/api/scanners.py@@ -100,7 +100,8 @@ from products.replay_vision.backend.jev_watch_feed import (JevWatchReason,load_watch_ranks,rank_watch_feed_by_jev,- watch_feed_ranker,+ ranker_mode,+ watch_feed_ranker_variant,)from products.replay_vision.backend.models.replay_observation import (ObservationStatus,@@ -1786,6 +1787,15 @@ class WatchFeedResponseSerializer(serializers.Serializer):"clients read it from here rather than evaluating the flag themselves."),)+ ranker_variant = serializers.CharField(+ allow_null=True,+ help_text=(+ "The team's variant of the `vision-watch-feed-ranker` experiment flag (`control`, `jev-shadow`, "+ "`jev`), or null when the team takes no part. Unlike `ranker`, it tells the shadow arm from "+ "control. Clients report it on the feed-viewed event as `$feature/vision-watch-feed-ranker`, "+ "which is the exposure the experiment counts."+ ),+ )class ScannerCreatorsResponseSerializer(serializers.Serializer):@@ -2486,8 +2496,10 @@ class ReplayScannerViewSet(TeamAndOrgViewSetMixin, AccessControlViewSetMixin, vi# The flag selects one of two independent rankers; nothing is blended between them. Shadow# teams rank on the weighted score too, because only the `jev` arm reads the probabilities# the hourly sweep cached. Neither arm makes a model call here. The response names the- # ranker that ordered it, so the shadow arm reads as weighted-score to the client.- ranker = "jev" if watch_feed_ranker(self.team_id) == "jev" else "weighted-score"+ # ranker that ordered it, so the shadow arm reads as weighted-score to the client, and the+ # flag variant separately, which the client reports as the experiment's exposure.+ variant = watch_feed_ranker_variant(self.team_id, self.team.uuid)+ ranker = "jev" if ranker_mode(variant) == "jev" else "weighted-score"if ranker == "jev":ranks = load_watch_ranks(self.team_id, allowed_ids)probabilities = ranks.probabilities@@ -2545,7 +2557,7 @@ class ReplayScannerViewSet(TeamAndOrgViewSetMixin, AccessControlViewSetMixin, vifor entry in rankedif entry.observation_id in rows]- return Response({"results": results, "ranker": ranker})+ return Response({"results": results, "ranker": ranker, "ranker_variant": variant})@extend_schema(request=ObserveRequestSerializer,diff --git a/products/replay_vision/backend/jev_watch_feed.py b/products/replay_vision/backend/jev_watch_feed.pyindex e2d07c7cf06c..cbc10764161c 100644--- a/products/replay_vision/backend/jev_watch_feed.py+++ b/products/replay_vision/backend/jev_watch_feed.py@@ -206,23 +206,41 @@ _ESTIMATED_COST = Counter()-def watch_feed_ranker(team_id: int) -> RankerMode:- """The team's arm of the watch feed ranker experiment. Any flag failure reads as the default- arm, so the sweep and the feed never fail on flag evaluation."""+def watch_feed_ranker_variant(team_id: int, team_uuid: UUID | str) -> str | None:+ """The team's variant of the ranker flag, or None when the team takes no part in the experiment.++ Keyed on the project's uuid: both regions evaluate this one flag, and team ids repeat between+ them. A region without the decision service has no sweep to fill the cache, so its teams take+ no part rather than land on an empty `jev` feed. Any flag failure also reads as None."""+ if not decision_api.decisions_available_here():+ return Nonevalue = get_feature_flag_or_none(WATCH_FEED_RANKER_FLAG,+ # Only a person-property condition reads the distinct id; a project-aggregated flag buckets+ # and matches on the group below.f"team-{team_id}",- groups={"project": str(team_id)},- group_properties={"project": {"id": team_id}},+ groups={"project": str(team_uuid)},+ group_properties={"project": {"id": team_id, "uuid": str(team_uuid)}},send_feature_flag_events=False,)- if value == "jev-shadow":+ return value if isinstance(value, str) else None+++def ranker_mode(variant: str | None) -> RankerMode:+ """The ranker a flag variant selects. Any variant but the two Jev arms is the default arm."""+ if variant == "jev-shadow":return "jev-shadow"- if value == "jev":+ if variant == "jev":return "jev"return "weighted-score"+def watch_feed_ranker(team_id: int, team_uuid: UUID | str) -> RankerMode:+ """The team's arm of the watch feed ranker experiment. Any flag failure reads as the default+ arm, so the sweep and the feed never fail on flag evaluation."""+ return ranker_mode(watch_feed_ranker_variant(team_id, team_uuid))++@frozenclass WindowJudgment:"""Jev's judgment of one batch of observations: a probability per observation id (as a string)."""diff --git a/products/replay_vision/backend/temporal/jev_watch_rank/activities.py b/products/replay_vision/backend/temporal/jev_watch_rank/activities.pyindex 8f8651772de4..9e4779ce15a7 100644--- a/products/replay_vision/backend/temporal/jev_watch_rank/activities.py+++ b/products/replay_vision/backend/temporal/jev_watch_rank/activities.py@@ -26,6 +26,7 @@ import posthoganalyticsfrom asgiref.sync import sync_to_asyncfrom temporalio import activity+from posthog.models.team import Teamfrom posthog.temporal.common.heartbeat import Heartbeaterfrom products.ml_inference.backend.facade import api as decision_api@@ -84,6 +85,12 @@ def _teams_with_scanners() -> list[int]:return [*PINNED_TEAM_IDS, *[team_id for team_id in team_ids if team_id not in PINNED_TEAM_IDS]]+def _team_uuids(team_ids: list[int]) -> dict[int, UUID]:+ """The flag keys on the project's uuid, so the sweep looks them up in one query per run."""+ with bounded_queries(_QUERY_BUDGET, from_attempt_start=False):+ return dict(Team.objects.filter(id__in=team_ids).values_list("id", "uuid"))++def _team_scanner_ids(team_id: int, window_start: datetime) -> list[UUID]:with bounded_queries(_QUERY_BUDGET, from_attempt_start=False):return list(@@ -134,6 +141,7 @@ async def _judge_watch_ranks(inputs: JevWatchRankSweepInputs) -> JevWatchRankSwedeadline = monotonic() + SWEEP_TIME_BUDGET.total_seconds()window_start = datetime.now(UTC) - WATCH_RANK_WINDOWteam_ids = await sync_to_async(_teams_with_scanners)()+ team_uuids = await sync_to_async(_team_uuids)(team_ids[:MAX_TEAMS_PER_SWEEP])teams_enrolled = 0teams_without_consent = 0@@ -152,7 +160,10 @@ async def _judge_watch_ranks(inputs: JevWatchRankSweepInputs) -> JevWatchRankSweif monotonic() > deadline:hit_time_budget = Truebreak- mode = await asyncio.to_thread(watch_feed_ranker, team_id)+ team_uuid = team_uuids.get(team_id)+ if team_uuid is None:+ continue+ mode = await asyncio.to_thread(watch_feed_ranker, team_id, team_uuid)if mode == "weighted-score":continue# The scan prose the sweep sends to the model derives from recordings, so a revoked consentdiff --git a/products/replay_vision/backend/temporal/jev_watch_rank/constants.py b/products/replay_vision/backend/temporal/jev_watch_rank/constants.pyindex a2510cd2a941..28f0d718fb0b 100644--- a/products/replay_vision/backend/temporal/jev_watch_rank/constants.py+++ b/products/replay_vision/backend/temporal/jev_watch_rank/constants.py@@ -25,9 +25,7 @@ MAX_JUDGED_PER_SCANNER = 100MAX_JUDGE_ATTEMPTS = 3# TODO: Team 2 is PostHog's own team, pinned first while the jev ranker runs as an internal shadow# test, so it can never fall past the team cap. When the experiment opens to other teams: remove the-# pin, give the caps fair rotation, and make watch_feed_ranker return the default arm where-# decisions_available_here() is false, so a region without the decision service can never land on-# the jev arm. Enrollment is team-targeted and US-only until then.+# pin and give the caps fair rotation. Enrollment is team-targeted until then.PINNED_TEAM_IDS = (2,)# Bound one sweep. The flag gates per team, so at experiment scale these caps are slack; they exist# so a misconfigured flag rollout cannot turn the sweep into an unbounded flag-check or Jev fan-out.diff --git a/products/replay_vision/backend/tests/test_api.py b/products/replay_vision/backend/tests/test_api.pyindex 751269fcdc89..f17be8dc1fdd 100644--- a/products/replay_vision/backend/tests/test_api.py+++ b/products/replay_vision/backend/tests/test_api.py@@ -5061,13 +5061,15 @@ class TestWatchFeedAPI(_VisionAPITestCase):self.team.id, scanner.id, {str(jev_high.id), str(jev_low.id)}, {str(jev_high.id): 0.95}, {}, "jevk5-fp8-0.2")- ranker = "products.replay_vision.backend.api.scanners.watch_feed_ranker"- for mode in ("weighted-score", "jev-shadow"):+ ranker = "products.replay_vision.backend.api.scanners.watch_feed_ranker_variant"+ for mode in ("control", "jev-shadow", None):with patch(ranker, return_value=mode):resp = self.client.get(self.feed_url)items = resp.json()["results"]- # The shadow arm ranks on the weighted score, so the response names that ranker too.+ # The shadow arm ranks on the weighted score, so the response names that ranker too, but+ # it still reports its own variant, which the client records as the experiment exposure.self.assertEqual(resp.json()["ranker"], "weighted-score", mode)+ self.assertEqual(resp.json()["ranker_variant"], mode)# The signal and the verdict hit lead as today; the cached 0.95 moves nothing.self.assertEqual([item["observation"]["session_id"] for item in items],@@ -5112,8 +5114,8 @@ class TestWatchFeedAPI(_VisionAPITestCase):{str(old_interesting.id): "visible_error"},)- ranker = "products.replay_vision.backend.api.scanners.watch_feed_ranker"- with patch(ranker, return_value="weighted-score"):+ ranker = "products.replay_vision.backend.api.scanners.watch_feed_ranker_variant"+ with patch(ranker, return_value="control"):resp = self.client.get(self.feed_url)self.assertNotIn("old-interesting", [item["observation"]["session_id"] for item in resp.json()["results"]])@@ -5152,7 +5154,7 @@ class TestWatchFeedAPI(_VisionAPITestCase):watchable[str(old_interesting.id)] = 0.6store_watch_ranks(self.team.id, scanner.id, set(watchable), watchable, {}, "jevk5-fp8-0.2")- ranker = "products.replay_vision.backend.api.scanners.watch_feed_ranker"+ ranker = "products.replay_vision.backend.api.scanners.watch_feed_ranker_variant"with patch(ranker, return_value="jev"):resp = self.client.get(f"{self.feed_url}?search=needle")items = resp.json()["results"]diff --git a/products/replay_vision/backend/tests/test_jev_watch_feed.py b/products/replay_vision/backend/tests/test_jev_watch_feed.pyindex 8d762262af01..adad5aefd005 100644--- a/products/replay_vision/backend/tests/test_jev_watch_feed.py+++ b/products/replay_vision/backend/tests/test_jev_watch_feed.py@@ -32,6 +32,7 @@ from products.replay_vision.backend.jev_watch_feed import (rank_watch_feed_by_jev,store_watch_ranks,watch_feed_ranker,+ watch_feed_ranker_variant,)from products.replay_vision.backend.models.replay_observation import (ObservationStatus,@@ -46,6 +47,7 @@ from products.replay_vision.backend.tests.helpers import snapshot_for as _snapsh_FLAG = "products.replay_vision.backend.jev_watch_feed.get_feature_flag_or_none"_API = "products.replay_vision.backend.jev_watch_feed.decision_api"+_REGION = f"{_API}.decisions_available_here"def _answer_every_question(probability: float, reason: str = "visible_error"):@@ -90,8 +92,19 @@ class TestWatchFeedRankerFlag(SimpleTestCase):])def test_only_known_variants_leave_the_default_arm(self, _name: str, flag_value: object, expected: str) -> None:- with patch(_FLAG, return_value=flag_value):- assert watch_feed_ranker(1) == expected+ with patch(_FLAG, return_value=flag_value), patch(_REGION, return_value=True):+ assert watch_feed_ranker(1, "project-uuid") == expected++ def test_the_flag_keys_on_the_project_uuid_and_skips_regions_without_jev(self) -> None:+ # Both regions evaluate this one flag and team ids repeat between them, so only the uuid is unique.+ with patch(_FLAG, return_value="jev") as flag, patch(_REGION, return_value=True):+ assert watch_feed_ranker_variant(2, "project-uuid") == "jev"+ assert flag.call_args.kwargs["groups"] == {"project": "project-uuid"}+ # A region with no sweep to fill the cache must not land a team on an empty jev feed.+ with patch(_FLAG, return_value="jev") as flag, patch(_REGION, return_value=False):+ assert watch_feed_ranker_variant(2, "project-uuid") is None+ assert watch_feed_ranker(2, "project-uuid") == "weighted-score"+ flag.assert_not_called()class TestJudgeScannerWindow(SimpleTestCase):@@ -575,7 +588,7 @@ class TestJevWatchRankSweep(BaseTest):def _flag_arm(self, arm: str):"""The experiment arm for self.team only, so the pinned team 2 stays on the default arm."""- return lambda team_id: arm if team_id == self.team.id else "weighted-score"+ return lambda team_id, _team_uuid: arm if team_id == self.team.id else "weighted-score"def test_posthogs_own_team_is_always_swept_first(self) -> None:# While the experiment is internal-only, team 2 must never fall past the team cap,diff --git a/products/replay_vision/frontend/generated/api.schemas.ts b/products/replay_vision/frontend/generated/api.schemas.tsindex e8a7b53f67be..17b72388ef5e 100644--- a/products/replay_vision/frontend/generated/api.schemas.ts+++ b/products/replay_vision/frontend/generated/api.schemas.ts@@ -2821,6 +2821,11 @@ export interface WatchFeedResponseApi {* * `weighted-score` - weighted-score* * `jev` - jev */ranker: RankerEnumApi+ /**+ * The team's variant of the `vision-watch-feed-ranker` experiment flag (`control`, `jev-shadow`, `jev`), or null when the team takes no part. Unlike `ranker`, it tells the shadow arm from control. Clients report it on the feed-viewed event as `$feature/vision-watch-feed-ranker`, which is the exposure the experiment counts.+ * @nullable+ */+ ranker_variant: string | null}export type VisionAlertsListParams = {diff --git a/products/replay_vision/frontend/replay_scanners/watchFeedLogic.test.ts b/products/replay_vision/frontend/replay_scanners/watchFeedLogic.test.tsindex 265478ae3f82..59ba0bf6c47b 100644--- a/products/replay_vision/frontend/replay_scanners/watchFeedLogic.test.ts+++ b/products/replay_vision/frontend/replay_scanners/watchFeedLogic.test.ts@@ -1,5 +1,6 @@import { router } from 'kea-router'import { expectLogic } from 'kea-test-utils'+import posthog from 'posthog-js'import { useMocks } from '~/mocks/jest'import { initKeaTests } from '~/test/init'@@ -37,14 +38,21 @@ describe('watchFeedLogic', () => {})it('loads on mount and reloads with params when filters change', async () => {+ const captureSpy = jest.spyOn(posthog, 'capture').mockImplementation()+ const lastFeedViewed = (): Record<string, any> | null | undefined =>+ captureSpy.mock.calls.filter(([name]) => name === 'replay_vision_watch_feed_viewed').at(-1)?.[1]logic.mount()await expectLogic(logic).toDispatchActions(['loadFeed', 'loadFeedSuccess']).toFinishAllListeners()expect(logic.values.feedItems).toHaveLength(2)expect(new URL(feedSpy.mock.calls[0][0].request.url).searchParams.get('date_from')).toBe('-7d')- // A response without a ranker (an older API) reads as the default arm.+ // A response without a ranker (an older API) reads as the default arm, outside the experiment.expect(logic.values.feedRanker).toBe('weighted-score')+ expect(lastFeedViewed()).not.toHaveProperty('$feature/vision-watch-feed-ranker')- feedSpy.mockImplementation(() => [200, { results: [item('o1', 'jev_watchable')], ranker: 'jev' }])+ feedSpy.mockImplementation(() => [+ 200,+ { results: [item('o1', 'jev_watchable')], ranker: 'jev', ranker_variant: 'jev' },+ ])await expectLogic(logic, () => {logic.actions.setScannerTypeFilter('monitor')})@@ -52,8 +60,10 @@ describe('watchFeedLogic', () => {.toFinishAllListeners()const lastUrl = new URL(feedSpy.mock.calls.at(-1)[0].request.url)expect(lastUrl.searchParams.get('scanner_type')).toBe('monitor')- // The response names the ranker that ordered the feed.+ // The response names the ranker that ordered the feed, and the feed-viewed event reports the+ // project's variant, which is the exposure the experiment counts.expect(logic.values.feedRanker).toBe('jev')+ expect(lastFeedViewed()).toMatchObject({ ranker: 'jev', '$feature/vision-watch-feed-ranker': 'jev' })await expectLogic(logic, () => {logic.actions.setDateRange('-30d', null)diff --git a/products/replay_vision/frontend/replay_scanners/watchFeedLogic.ts b/products/replay_vision/frontend/replay_scanners/watchFeedLogic.tsindex a54ca59d5236..6cd34bc61afd 100644--- a/products/replay_vision/frontend/replay_scanners/watchFeedLogic.ts+++ b/products/replay_vision/frontend/replay_scanners/watchFeedLogic.ts@@ -36,6 +36,7 @@ export interface watchFeedLogicValues {feedItems: WatchFeedItemApi[] | nullfeedItemsLoading: booleanfeedRanker: WatchFeedRanker+ feedRankerVariant: string | nullhasFeedFilters: booleanscannerIdsFilter: string[]scannerTypeFilter: ScannerType | null@@ -92,8 +93,12 @@ export interface watchFeedLogicActions {dateFrom: string | nulldateTo: string | null}- setFeedRanker: (ranker: WatchFeedRanker) => {+ setFeedRanker: (+ ranker: WatchFeedRanker,+ variant: string | null+ ) => {ranker: RankerEnumApi+ variant: string | null}setScannerIdsFilter: (scannerIds: string[]) => {scannerIds: string[]@@ -148,6 +153,10 @@ export const DEFAULT_FEED_DATE_FROM: string = '-7d'* team, not the viewer), so the client reads it from the response instead of checking the flag. */export type WatchFeedRanker = WatchFeedResponseApi['ranker']+/** The ranker experiment's flag. The server decides its variant per project, so the client can't+ * evaluate it and reports the variant the response carries instead. */+const WATCH_FEED_RANKER_FLAG = 'vision-watch-feed-ranker'+function reportFiltered(values: watchFeedLogicValues): void {posthog.capture('replay_vision_watch_feed_filtered', {date_from: values.dateFrom,@@ -188,7 +197,7 @@ export const watchFeedLogic = kea<watchFeedLogicType>([restoreFeedFilters: (search: string, scannerIds: string[], tags: string[]) => ({ search, scannerIds, tags }),clearFeedFilters: true,loadFeed: true,- setFeedRanker: (ranker: WatchFeedRanker) => ({ ranker }),+ setFeedRanker: (ranker: WatchFeedRanker, variant: string | null) => ({ ranker, variant }),}),loaders(({ values, actions }) => ({@@ -222,7 +231,7 @@ export const watchFeedLogic = kea<watchFeedLogicType>([const response = await visionScannersWatchFeedRetrieve(String(teamId), params)// Drop out-of-order responses — the most recent filter change owns the feed.breakpoint()- actions.setFeedRanker(response.ranker ?? 'weighted-score')+ actions.setFeedRanker(response.ranker ?? 'weighted-score', response.ranker_variant ?? null)return response.results},},@@ -293,6 +302,12 @@ export const watchFeedLogic = kea<watchFeedLogicType>([setFeedRanker: (_, { ranker }) => ranker,},],+ feedRankerVariant: [+ null as string | null,+ {+ setFeedRanker: (_, { variant }) => variant,+ },+ ],}),listeners(({ actions, values }) => ({@@ -339,6 +354,10 @@ export const watchFeedLogic = kea<watchFeedLogicType>([scanner_count: new Set(items.map((item) => item.observation.scanner_id)).size,reason_kind_counts: countByReasonKind,ranker: values.feedRanker,+ // The ranker experiment counts this event as its exposure, so it carries the project's variant.+ ...(values.feedRankerVariant+ ? { [`$feature/${WATCH_FEED_RANKER_FLAG}`]: values.feedRankerVariant }+ : {}),signal_share: items.length > 0 ? (countByReasonKind.signal_emitted ?? 0) / items.length : 0,// Which dead end the reader hit, so the empty screens can be counted and ranked// against each other instead of only showing up as a clip count of zero.diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.tsindex eb6a701458a8..533d2fa2252a 100644--- a/services/mcp/src/api/generated.ts+++ b/services/mcp/src/api/generated.ts@@ -110092,6 +110092,11 @@ export namespace Schemas {* * `weighted-score` - weighted-score* * `jev` - jev */ranker: RankerEnum;+ /**+ * The team's variant of the `vision-watch-feed-ranker` experiment flag (`control`, `jev-shadow`, `jev`), or null when the team takes no part. Unlike `ranker`, it tells the shadow arm from control. Clients report it on the feed-viewed event as `$feature/vision-watch-feed-ranker`, which is the exposure the experiment counts.+ * @nullable+ */+ ranker_variant: string | null;}export interface WebAnalyticsBotCondition {