: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
fix(experiments): give wizard scanners the same population as the recordings tab (#94499)
Marcel Poelker942a02e2f9b9
diff --git a/frontend/src/scenes/experiments/ExperimentForm/createExperimentLogic.test.ts b/frontend/src/scenes/experiments/ExperimentForm/createExperimentLogic.test.tsindex 697cadc895c0..4bdf6990506f 100644--- a/frontend/src/scenes/experiments/ExperimentForm/createExperimentLogic.test.ts+++ b/frontend/src/scenes/experiments/ExperimentForm/createExperimentLogic.test.ts@@ -8,12 +8,7 @@ import { lemonToast } from 'lib/lemon-ui/LemonToast/LemonToast'import { refreshTreeItem } from '~/layout/panel-layout/ProjectTree/projectTreeLogic'import { useMocks } from '~/mocks/jest'-import {- type ExperimentExposureCriteria,- NodeKind,- ProductIntentContext,- ProductKey,-} from '~/queries/schema/schema-general'+import { ProductIntentContext, ProductKey } from '~/queries/schema/schema-general'import { initKeaTests } from '~/test/init'import type { Experiment } from '~/types'@@ -39,7 +34,6 @@ describe('createExperimentLogic', () => {let scannerCreateSpy: jest.Mocklet scannerRequestBody: Record<string, unknown> | nulllet productIntentBodies: Record<string, unknown>[]- let exposureEventSeenWithSessionId: booleanbeforeEach(() => {// Clear persisted state to prevent it from affecting tests@@ -47,7 +41,6 @@ describe('createExperimentLogic', () => {sessionStorage.clear()scannerRequestBody = nullproductIntentBodies = []- exposureEventSeenWithSessionId = truescannerCreateSpy = jest.fn(async ({ request }: { request: Request }) => {scannerRequestBody = (await request.json()) as Record<string, unknown>return [200, { id: 'scanner-123' }]@@ -58,10 +51,6 @@ describe('createExperimentLogic', () => {// saveExperiment verifies flag-key availability before building the payload'/api/projects/:team_id/feature_flags/': () => [200, { results: [], count: 0 }],'/api/projects/:team_id/experiments': () => [200, { results: [], count: 0 }],- '/api/projects/:team_id/property_definitions/seen_together': ({ request }) => {- const eventNames = new URL(request.url).searchParams.getAll('event_names')- return [200, Object.fromEntries(eventNames.map((name) => [name, exposureEventSeenWithSessionId]))]- },},post: {[`/api/projects/${MOCK_TEAM_ID}/experiments`]: async ({ request }) => {@@ -195,25 +184,13 @@ describe('createExperimentLogic', () => {// `model` is required by the create serializer — omitting it 400s every createprovider: DEFAULT_PROVIDER,model: DEFAULT_MODEL,- query: {- filter_test_accounts: true,- events: [- {- id: '$feature_flag_called',- properties: expect.arrayContaining([- expect.objectContaining({- key: '$feature_flag_response',- value: ['control', 'new-checkout'],- }),- expect.objectContaining({- key: '$feature_flag',- value: ['checkout-flow'],- }),- ]),- },- ],- },+ experiment_targeting: { experiment_id: 123, variant: null },+ query: { kind: 'RecordingsQuery', filter_test_accounts: true },})+ // The API derives the exposure filter from the targeting and rejects one set in the+ // query, so a hand-built population here is the regression to catch+ expect(scannerRequestBody?.query).not.toHaveProperty('events')+ expect(scannerRequestBody?.query).not.toHaveProperty('experiment_exposure')// A plain product intent is indistinguishable from someone reaching Replay Vision on their// own, so the cross-sell metadata is the only thing that attributes the scanner to experimentsexpect(productIntentBodies).toContainEqual(@@ -235,53 +212,6 @@ describe('createExperimentLogic', () => {)})- it.each([- {- name: 'falls back to the flag-value filter for a default exposure event',- exposure_criteria: undefined,- expectedQuery: {- properties: [expect.objectContaining({ key: '$feature/server-side-exposure', type: 'event' })],- },- },- {- name: 'keeps the custom exposure filter, never an unfiltered query',- exposure_criteria: {- exposure_config: {- kind: NodeKind.ExperimentEventExposureConfig,- event: 'backend_assigned',- properties: [],- },- } satisfies ExperimentExposureCriteria as ExperimentExposureCriteria,- expectedQuery: {- events: [expect.objectContaining({ id: 'backend_assigned' })],- },- },- ])(- // The check reports "never seen with a session ID", which for a minutes-old flag is- // mostly "never seen at all" — so it must never refuse, and must never leave the query- // empty, which would scan every recording in the project.- 'creates a scoped scanner anyway when the exposure event looks unlinkable: $name',- async ({ exposure_criteria, expectedQuery }) => {- exposureEventSeenWithSessionId = false- await expectLogic(logic, () => {- logic.actions.setCreateReplayVisionScanner(true)- logic.actions.setExperiment({- ...NEW_EXPERIMENT,- name: 'Server-side exposure',- description: 'Test hypothesis',- feature_flag_key: 'server-side-exposure',- ...(exposure_criteria ? { exposure_criteria } : {}),- })- logic.actions.saveExperiment()- })- .toDispatchActions(['saveExperiment', 'createExperimentSuccess', 'saveExperimentSuccess'])- .toFinishAllListeners()-- expect(scannerCreateSpy).toHaveBeenCalledTimes(1)- expect(scannerRequestBody).toMatchObject({ query: expect.objectContaining(expectedQuery) })- }- )-it.each([{name: 'a generic failure is reported to error tracking',diff --git a/frontend/src/scenes/experiments/ExperimentForm/createExperimentLogic.ts b/frontend/src/scenes/experiments/ExperimentForm/createExperimentLogic.tsindex 0e774ce6017c..807d70e324df 100644--- a/frontend/src/scenes/experiments/ExperimentForm/createExperimentLogic.ts+++ b/frontend/src/scenes/experiments/ExperimentForm/createExperimentLogic.ts@@ -36,14 +36,13 @@ import type { ExperimentMetricUnion } from '../../../queries/schema/schema-generimport type { FeatureFlagType } from '../../../types'import { FORM_MODES, experimentLogic } from '../experimentLogic'import { experimentSceneLogic } from '../experimentSceneLogic'-import { experimentScannerBody, experimentScannerFilters } from '../replayVisionScanner'+import { experimentScannerBody } from '../replayVisionScanner'import {type ExperimentWritePayload,getExperimentVariants,toExperimentWritePayload,toFlagVariantsInput,} from '../utils'-import { loadUnlinkableEventNames } from '../viewRecordingsLinkabilityLogic'import { validateExperimentSubmission } from './experimentSubmissionValidation'import type { FeatureFlagKeyValidation } from './variantsPanelLogic'import { variantsPanelLogic } from './variantsPanelLogic'@@ -527,14 +526,10 @@ export const createExperimentLogic = kea<createExperimentLogicType>([let replayScannerId: string | null = nulllet replayScannerCreationFailed = falseif (values.createReplayVisionScanner) {- const { filters, usedExposureFallback } = experimentScannerFilters(- response,- await loadUnlinkableEventNames(response)- )try {const replayScanner = await visionScannersCreate(String(values.currentProjectId),- experimentScannerBody(response, filters, usedExposureFallback)+ experimentScannerBody(response))replayScannerId = replayScanner.idactions.addProductIntentForCrossSell({diff --git a/frontend/src/scenes/experiments/replayVisionScanner.test.ts b/frontend/src/scenes/experiments/replayVisionScanner.test.tsindex 5570463183d6..ff7c695c9b34 100644--- a/frontend/src/scenes/experiments/replayVisionScanner.test.ts+++ b/frontend/src/scenes/experiments/replayVisionScanner.test.ts@@ -1,28 +1,96 @@+import { type ExperimentExposureCriteria, NodeKind } from '~/queries/schema/schema-general'import type { Experiment } from '~/types'import { NEW_EXPERIMENT } from 'products/experiments/frontend/constants'+import { prefillScannerForExperiment } from 'products/replay_vision/frontend/replay_scanners/experimentTargeting'+import type { ReplayScanner } from 'products/replay_vision/frontend/replay_scanners/types'-import { experimentScannerPrompt } from './replayVisionScanner'--describe('experimentScannerPrompt', () => {- it.each([- {- name: 'uses the hypothesis as the changed-surface grounding',- description: 'New one-page checkout',- expected: 'What the experiment changes: New one-page checkout',- },- {- name: 'falls back to the experiment name when the hypothesis is blank',- description: '',- expected: 'Its name is "Checkout redesign"',- },- {- name: 'treats a whitespace-only hypothesis as blank',- description: ' ',- expected: 'Its name is "Checkout redesign"',- },- ])('$name', ({ description, expected }) => {- const experiment: Experiment = { ...NEW_EXPERIMENT, name: 'Checkout redesign', description }- expect(experimentScannerPrompt(experiment)).toContain(expected)+import { experimentScannerBody, experimentScannerPrompt } from './replayVisionScanner'++describe('replayVisionScanner', () => {+ describe('experimentScannerPrompt', () => {+ it.each([+ {+ name: 'uses the hypothesis as the changed-surface grounding',+ description: 'New one-page checkout',+ expected: 'What the experiment changes: New one-page checkout',+ },+ {+ name: 'falls back to the experiment name when the hypothesis is blank',+ description: '',+ expected: 'Its name is "Checkout redesign"',+ },+ {+ name: 'treats a whitespace-only hypothesis as blank',+ description: ' ',+ expected: 'Its name is "Checkout redesign"',+ },+ ])('$name', ({ description, expected }) => {+ const experiment: Experiment = { ...NEW_EXPERIMENT, name: 'Checkout redesign', description }+ expect(experimentScannerPrompt(experiment)).toContain(expected)+ })+ })++ describe('experimentScannerBody', () => {+ // Every experiment shape must produce the same population, because the API resolves the+ // exposed sessions from the targeting. A query that carries an exposure filter is the old+ // client-built shape, and the API rejects it.+ it.each([+ {+ name: 'a default exposure event',+ exposure_criteria: undefined,+ expectedFilterTestAccounts: false,+ },+ {+ name: 'a custom exposure event',+ exposure_criteria: {+ exposure_config: {+ kind: NodeKind.ExperimentEventExposureConfig,+ event: 'backend_assigned',+ properties: [],+ },+ } satisfies ExperimentExposureCriteria as ExperimentExposureCriteria,+ expectedFilterTestAccounts: false,+ },+ {+ name: 'an experiment that filters test accounts',+ exposure_criteria: { filterTestAccounts: true } satisfies ExperimentExposureCriteria,+ expectedFilterTestAccounts: true,+ },+ ])(+ 'targets all variants of the experiment and keeps the query free of filters: $name',+ ({ exposure_criteria, expectedFilterTestAccounts }) => {+ const experiment: Experiment = {+ ...NEW_EXPERIMENT,+ id: 123,+ name: 'Checkout redesign',+ exposure_criteria,+ }++ const body = experimentScannerBody(experiment)++ expect(body.experiment_targeting).toEqual({ experiment_id: 123, variant: null })+ expect(body.query).toEqual({+ kind: NodeKind.RecordingsQuery,+ filter_test_accounts: expectedFilterTestAccounts,+ })+ }+ )++ // The two entry points build different scanners on purpose: this one is a fixed classifier,+ // and the Recordings tab hands the person the scanner wizard. The population is the part+ // that must stay identical, because both feed the same server-derived exposure filter.+ it('builds the same population as the scanner wizard prefill', () => {+ const experiment: Experiment = { ...NEW_EXPERIMENT, id: 123, name: 'Checkout redesign' }+ const prefilled = prefillScannerForExperiment({ name: 'Frustration score' } as ReplayScanner, {+ experiment,+ variantKey: null,+ })++ const body = experimentScannerBody(experiment)++ expect(body.experiment_targeting).toEqual(prefilled.experiment_targeting)+ expect(body.query).toEqual(prefilled.query)+ })})})diff --git a/frontend/src/scenes/experiments/replayVisionScanner.ts b/frontend/src/scenes/experiments/replayVisionScanner.tsindex ff5c3d10099d..e2c78145b2fa 100644--- a/frontend/src/scenes/experiments/replayVisionScanner.ts+++ b/frontend/src/scenes/experiments/replayVisionScanner.ts@@ -1,21 +1,16 @@-import { convertUniversalFiltersToRecordingsQuery } from 'scenes/session-recordings/filters/recordingsQueryConversions'--import {- FilterLogicalOperator,- type Experiment,- type RecordingUniversalFilters,- type UniversalFiltersGroupValue,-} from '~/types'+import type { Experiment } from '~/types'import type { ReplayScannerApi } from 'products/replay_vision/frontend/generated/api.schemas'+import {+ buildExperimentTargeting,+ experimentScannerQuery,+} from 'products/replay_vision/frontend/replay_scanners/experimentTargeting'import {DEFAULT_MODEL,DEFAULT_PROVIDER,scannerToApiBody,} from 'products/replay_vision/frontend/replay_scanners/types'-import { applySessionLinkability, getExposureFallbackFilter, getViewRecordingFiltersForVariant } from './utils'-const SCANNER_NAME_MAX_LENGTH = 255/**@@ -57,50 +52,19 @@ export function experimentScannerPrompt(experiment: Experiment): string {}/**- * The scanner's population: the experiment's exposed sessions, with the same session-linkability- * handling the recordings surfaces use. A server-side exposure event carries no `$session_id`, so- * without this the query matches zero sessions forever while the scanner looks healthy.- *- * Advisory only here, unlike on the recordings surfaces: the check reports "never seen with a- * session id", which at creation time is mostly "never seen at all" — the flag is minutes old. So- * an unlinkable exposure downgrades to the fallback filter where one exists, and otherwise keeps- * the exposure filter. It must never fall through to the empty filter list `applySessionLinkability`- * returns for that case, which would scan every recording in the project.+ * The scanner's population lives in `experiment_targeting`, never in `query`: the API derives the+ * person-scoped exposure filter from it at scan time, and rejects an exposure filter set in the+ * query directly. That keeps the scanner on the same sessions the experiment's Recordings tab+ * lists, including an exposure event that fires server-side or in an earlier session. `query`+ * carries only the experiment's test-account setting.*/-export function experimentScannerFilters(- experiment: Experiment,- unlinkableEventNames: Set<string>-): { filters: UniversalFiltersGroupValue[]; usedExposureFallback: boolean } {- const exposureFilters = getViewRecordingFiltersForVariant(experiment)- const { filters, usedExposureFallback, exposureUnlinkable } = applySessionLinkability(- exposureFilters,- unlinkableEventNames,- getExposureFallbackFilter(experiment)- )- return { filters: exposureUnlinkable ? exposureFilters : filters, usedExposureFallback }-}--export function experimentScannerBody(- experiment: Experiment,- filters: UniversalFiltersGroupValue[],- usedExposureFallback: boolean-): ReplayScannerApi {+export function experimentScannerBody(experiment: Experiment): ReplayScannerApi {const nameSuffix = ` (#${experiment.id})`const name = `${experiment.name.slice(0, SCANNER_NAME_MAX_LENGTH - nameSuffix.length)}${nameSuffix}`- const universalFilters: RecordingUniversalFilters = {- filter_test_accounts: experiment.exposure_criteria?.filterTestAccounts ?? false,- duration: [],- filter_group: {- type: FilterLogicalOperator.And,- values: [{ type: FilterLogicalOperator.And, values: filters }],- },- }return scannerToApiBody({name,- description: usedExposureFallback- ? "Classifies what participants do in sessions where this experiment's feature flag was active."- : 'Classifies what participants do after they are exposed to this experiment.',+ description: 'Classifies what participants do after they are exposed to this experiment.',scanner_type: 'classifier',scanner_config: {prompt: experimentScannerPrompt(experiment),@@ -110,7 +74,9 @@ export function experimentScannerBody(// `model` is required by the create serializer; the rest of the product picks the same defaults.provider: DEFAULT_PROVIDER,model: DEFAULT_MODEL,- query: convertUniversalFiltersToRecordingsQuery(universalFilters),+ // A null variant watches every variant of the experiment.+ experiment_targeting: buildExperimentTargeting({ experiment, variantKey: null }),+ query: experimentScannerQuery(experiment),// Enabling starts real credit spend, so that stays a human decision on the scanner itself.enabled: false,})diff --git a/frontend/src/scenes/experiments/viewRecordingsLinkabilityLogic.ts b/frontend/src/scenes/experiments/viewRecordingsLinkabilityLogic.tsindex 33589dd54622..5e1f3b9b4d76 100644--- a/frontend/src/scenes/experiments/viewRecordingsLinkabilityLogic.ts+++ b/frontend/src/scenes/experiments/viewRecordingsLinkabilityLogic.ts@@ -1,6 +1,5 @@import { MakeLogicType, afterMount, kea, key, path, props, propsChanged, selectors } from 'kea'import { loaders } from 'kea-loaders'-import posthog from 'posthog-js'import api from 'lib/api'import { objectsEqual } from 'lib/utils/objects'@@ -37,27 +36,6 @@ export function unlinkableEventNamesFromSeenTogether()}-/**- * One-shot version of the check below, for surfaces that need the answer once rather than as- * mounted state. Fails open on error, the same way the logic's selector does, but captures the- * error first: callers bake the result into objects they create, so a systemic failure here is- * otherwise indistinguishable from "no unlinkable events".- */-export async function loadUnlinkableEventNames(experiment: Experiment): Promise<Set<string>> {- const eventNames = getSessionLinkabilityEventNames(experiment)- if (eventNames.length === 0) {- return new Set()- }- try {- return unlinkableEventNamesFromSeenTogether(- await api.propertyDefinitions.seenTogether({ eventNames, propertyDefinitionName: '$session_id' })- )- } catch (error) {- posthog.captureException(error)- return new Set()- }-}-// Generated by kea-typegen. Update if you're an agent, ignore if you're human.export interface viewRecordingsLinkabilityLogicValues {linkabilityLoaded: booleandiff --git a/products/experiments/skills/scanning-experiments-with-replay-vision/SKILL.md b/products/experiments/skills/scanning-experiments-with-replay-vision/SKILL.mdindex bc7119aff5ea..29d8c2dddb37 100644--- a/products/experiments/skills/scanning-experiments-with-replay-vision/SKILL.md+++ b/products/experiments/skills/scanning-experiments-with-replay-vision/SKILL.md@@ -62,7 +62,7 @@ Template hygiene, learned the hard way: name the changed surface concretely (notEvery prompt needs the **post-exposure framing** sentence: tell the model to focus on behavior after the point where the experiment's change would first be visible and ignore earlier activity. Be honest with the user that this is a request to the model, not an enforced window — scanners view the whole recording (see Limits).-**The experiment creation wizard offers the same scanner from a checkbox.** Its prompt and tag set are the post-exposure friction template below, canonical in `experimentScannerPrompt` and `EXPERIMENT_SCANNER_TAGS` (`frontend/src/scenes/experiments/replayVisionScanner.ts`) — change them and this section together, and prefer matching them over inventing a new prompt when a user already has a wizard-created scanner. For the population, use `experiment_targeting` as in Step 2, not that module's own filter builder.+**The experiment creation wizard offers the same scanner from a checkbox.** Its prompt and tag set are the post-exposure friction template below, canonical in `experimentScannerPrompt` and `EXPERIMENT_SCANNER_TAGS` (`frontend/src/scenes/experiments/replayVisionScanner.ts`) — change them and this section together, and prefer matching them over inventing a new prompt when a user already has a wizard-created scanner. The wizard sets the population with `experiment_targeting`, the same as Step 2.Starter templates:diff --git a/products/replay_vision/README.md b/products/replay_vision/README.mdindex 81132b8b1b4e..9f421612202f 100644--- a/products/replay_vision/README.md+++ b/products/replay_vision/README.md@@ -57,7 +57,7 @@ Outside these scenes, the product also renders inside the session replay player:## Experiment-created scanners-The experiment creation wizard offers an opt-in Replay Vision scanner when the `replay-vision` feature flag is enabled. The scanner is a **disabled** classifier — enabling it, and the credit spend that follows, stays a human decision on the scanner itself. Its `RecordingsQuery` uses the experiment's exposure event, enrolled variant filters, custom exposure properties, and test-account setting, with the session-linkability check the experiment recordings surfaces use, applied as advice rather than a veto: an exposure event never seen with a `$session_id` falls back to the `$feature/<key>` property where one applies, and otherwise keeps the exposure filter. The check can't distinguish "captured server-side" from "not emitted yet", which at creation time is the common case, so it must never refuse and never widen the query. Scanner creation runs after the experiment has been persisted and cannot roll back a successfully created experiment.+The experiment creation wizard offers an opt-in Replay Vision scanner when the `replay-vision` feature flag is enabled. The scanner is a **disabled** classifier — enabling it, and the credit spend that follows, stays a human decision on the scanner itself. Its population lives in `experiment_targeting`, never in its `RecordingsQuery`: the API derives the person-scoped exposure filter from that field at scan time, the same resolution the experiment's Recordings tab uses, so the scanner watches the sessions that tab lists, including an exposure event that fires server-side or in an earlier session. The `RecordingsQuery` carries only the experiment's test-account setting, and the API rejects an `experiment_exposure` set there directly. Scanners the wizard created before that field existed keep their original exposure-event filters; recreating one from the experiment's Recordings tab is the fix for a scanner watching nothing. Scanner creation runs after the experiment has been persisted and cannot roll back a successfully created experiment.The template lives in `frontend/src/scenes/experiments/replayVisionScanner.ts` and mirrors the one in the `scanning-experiments-with-replay-vision` skill: a fixed tag set (so variants stay comparable), an escape tag for sessions that never reached the changed surface, and no variant names in the prompt.diff --git a/products/replay_vision/backend/api/scanners.py b/products/replay_vision/backend/api/scanners.pyindex e23d800f4c31..63423a856909 100644--- a/products/replay_vision/backend/api/scanners.py+++ b/products/replay_vision/backend/api/scanners.py@@ -94,6 +94,7 @@ from products.replay_vision.backend.queries import (PREVIEW_ESTIMATE_BUDGET,SAVE_ESTIMATE_BUDGET,estimate_scanner_session_volume,+ is_experiment_linkage_unresolved,project_monthly_observations,refresh_scanner_estimate,)@@ -122,7 +123,7 @@ from products.replay_vision.backend.scanning import (from products.replay_vision.backend.session_limits import MAX_SESSION_ID_LENGTHfrom products.replay_vision.backend.tag_suggestions import SuggestionError, suggest_classifier_tagsfrom products.replay_vision.backend.temporal.constants import VISION_SIGNALS_SOURCE_PRODUCT, VISION_SIGNALS_SOURCE_TYPE-from products.replay_vision.backend.temporal.metrics import record_scanner_limit_reached+from products.replay_vision.backend.temporal.metrics import record_estimate_outcome, record_scanner_limit_reachedfrom products.signals.backend.facade.api import get_outcomes_for_signal_source_slice# Date is set by the schedule at trigger time, not by the user — strip on save.@@ -246,7 +247,10 @@ def _scanner_lifecycle_properties(scanner: ReplayScanner) -> dict[str, Any]:"sampling_rate": scanner.sampling_rate,"sampling_mode": scanner.sampling_mode,"enabled": scanner.enabled,- "has_filters": any(query.get(key) for key in _QUERY_FILTER_KEYS),+ # experiment_targeting narrows the population server-side, so it counts as filtered; the+ # separate flag keeps experiment-scoped scanners countable apart from hand-filtered ones.+ "has_filters": any(query.get(key) for key in _QUERY_FILTER_KEYS) or bool(scanner.experiment_targeting),+ "has_experiment_targeting": bool(scanner.experiment_targeting),"estimated_monthly_observations": estimate,"estimated_monthly_credits": (estimate * observation_credits_for_model(scanner.model) if estimate is not None else None@@ -260,8 +264,26 @@ def _refresh_estimate_fail_soft(scanner: ReplayScanner) -> None:# The estimate is advisory — never fail a scanner save over it, and keep the save's latency tail short.try:refresh_scanner_estimate(scanner, budget=SAVE_ESTIMATE_BUDGET)+ except (ValidationError, PermissionDenied) as error:+ if is_experiment_linkage_unresolved(scanner, error):+ # The experiment targeting cannot resolve an exposed population, most often the draft+ # a wizard creates next to the scanner. The hourly refresher retries, and the outcome+ # counter keeps the skip visible from the first save. `reason` takes `detail` because+ # a DRF ValidationError stringifies as an ErrorDetail list.+ record_estimate_outcome("experiment_linkage_unresolved")+ logger.info(+ "replay_vision.estimate_linkage_unresolved",+ scanner_id=str(scanner.id),+ reason=error.detail,+ )+ else:+ # The scanner's own query no longer builds, for example a deleted action or a bad+ # cohort reference. No launch heals that, so keep it in error tracking.+ logger.exception("replay_vision.estimate_refresh_failed", scanner_id=str(scanner.id))except Exception:logger.exception("replay_vision.estimate_refresh_failed", scanner_id=str(scanner.id))+ else:+ record_estimate_outcome("refreshed")def _scanner_copy_name(team_id: int, source_name: str) -> str:diff --git a/products/replay_vision/backend/queries/__init__.py b/products/replay_vision/backend/queries/__init__.pyindex e485e5d1dfb1..103c2691450a 100644--- a/products/replay_vision/backend/queries/__init__.py+++ b/products/replay_vision/backend/queries/__init__.py@@ -15,6 +15,7 @@ from products.replay_vision.backend.queries.scanner_volume_estimate import (SAVE_ESTIMATE_BUDGET,ScannerVolumeEstimate,estimate_scanner_session_volume,+ is_experiment_linkage_unresolved,project_monthly_observations,refresh_scanner_estimate,)@@ -37,6 +38,7 @@ __all__ = ["VisitedPath","estimate_scanner_session_volume","fetch_visited_paths",+ "is_experiment_linkage_unresolved","project_monthly_observations","refresh_scanner_estimate",]diff --git a/products/replay_vision/backend/queries/scanner_volume_estimate.py b/products/replay_vision/backend/queries/scanner_volume_estimate.pyindex 17fe96b7917a..e47ed403d928 100644--- a/products/replay_vision/backend/queries/scanner_volume_estimate.py+++ b/products/replay_vision/backend/queries/scanner_volume_estimate.py@@ -3,6 +3,8 @@ from dataclasses import dataclassfrom django.utils import timezone+from rest_framework.exceptions import PermissionDenied, ValidationError+from posthog.schema import FilterLogicalOperator, RecordingsQueryfrom posthog.hogql import ast@@ -336,6 +338,35 @@ def refresh_scanner_estimate(scanner.estimated_at = estimated_at+def is_experiment_linkage_unresolved(scanner: ReplayScanner, error: Exception) -> bool:+ """True when an estimate failure means the scanner's experiment targeting cannot resolve an+ exposed population: a draft that has not launched, a deleted or group-aggregated experiment,+ no variants, a renamed variant, exposures still computing, or lost creator access. False when+ the scanner's own query is what fails to build, for example a deleted action or a bad cohort+ reference; no launch heals that, so callers keep it on their error path. Both groups raise+ the same DRF ValidationError type inside the recordings query, so this re-resolves the+ linkage to tell them apart. The extra resolution runs on the failure path only."""+ targeting = scanner.experiment_targeting if isinstance(scanner.experiment_targeting, dict) else {}+ experiment_id = targeting.get("experiment_id")+ if experiment_id is None:+ return False+ if isinstance(error, PermissionDenied):+ # Only the exposure access check raises PermissionDenied inside the recordings query.+ return True+ # Deferred: the experiments facade imports posthog.api on init, which circles back into the+ # recordings query modules this package loads.+ from products.experiments.backend.facade.replay import resolve_exposure_linkage # noqa: PLC0415++ try:+ resolve_exposure_linkage(scanner.team, experiment_id=experiment_id, variant=targeting.get("variant"))+ except ValidationError:+ return True+ except Exception:+ # The re-resolution failed on infrastructure. Callers treat that as the loud path.+ return False+ return False++def _clamp_window_days(earliest: object, scan_window_days: int) -> int:"""Clamp the divisor to the team's actual data span so a new team isn't under-estimated."""if not isinstance(earliest, dt.datetime):diff --git a/products/replay_vision/backend/temporal/activities/refresh_scanner_estimate.py b/products/replay_vision/backend/temporal/activities/refresh_scanner_estimate.pyindex 65da733bb181..90a495c114a1 100644--- a/products/replay_vision/backend/temporal/activities/refresh_scanner_estimate.py+++ b/products/replay_vision/backend/temporal/activities/refresh_scanner_estimate.py@@ -1,13 +1,22 @@from django.utils import timezone+from rest_framework.exceptions import (+ PermissionDenied,+ ValidationError as DRFValidationError,+)from temporalio import activityfrom posthog.clickhouse.client.connection import ClickHouseUserfrom products.replay_vision.backend.models.replay_scanner import ReplayScanner-from products.replay_vision.backend.queries import ESTIMATE_STALE_AFTER, refresh_scanner_estimate+from products.replay_vision.backend.queries import (+ ESTIMATE_STALE_AFTER,+ is_experiment_linkage_unresolved,+ refresh_scanner_estimate,+)from products.replay_vision.backend.temporal.decorators import track_activityfrom products.replay_vision.backend.temporal.estimates_types import RefreshScannerEstimateInputs+from products.replay_vision.backend.temporal.metrics import record_estimate_outcome@activity.defn@@ -19,5 +28,23 @@ def refresh_scanner_estimate_activity(inputs: RefreshScannerEstimateInputs) -> breturn Falseif scanner.estimated_at is not None and timezone.now() - scanner.estimated_at < ESTIMATE_STALE_AFTER:return False- refresh_scanner_estimate(scanner, ch_user=ClickHouseUser.REPLAY_VISION)+ try:+ refresh_scanner_estimate(scanner, ch_user=ClickHouseUser.REPLAY_VISION)+ except (DRFValidationError, PermissionDenied) as error:+ if not is_experiment_linkage_unresolved(scanner, error):+ # The scanner's own query no longer builds, for example a deleted action or a bad+ # cohort reference. No launch heals that, so let the activity fail: the failure+ # metric and the workflow's partial-failure warning keep it alertable.+ raise+ # The experiment targeting cannot resolve an exposed population. A draft heals itself at+ # launch; the other states need a person. The sweep skips its tick on the same set.+ # `refresh_scanner_estimate` stamps `estimate_attempted_at` before it queries, so the+ # one-hour backoff still applies.+ record_estimate_outcome("experiment_linkage_unresolved")+ activity.logger.warning(+ "replay_vision.estimate_linkage_unresolved",+ extra={"scanner_id": str(scanner.id), "reason": error.detail},+ )+ return False+ record_estimate_outcome("refreshed")return Truediff --git a/products/replay_vision/backend/temporal/metrics.py b/products/replay_vision/backend/temporal/metrics.pyindex b1e97a9c117b..d07edd4f4e78 100644--- a/products/replay_vision/backend/temporal/metrics.py+++ b/products/replay_vision/backend/temporal/metrics.py@@ -148,6 +148,15 @@ REPLAY_VISION_ENQUEUE_CLAIM_FAILURES = Counter(["operation"],)+REPLAY_VISION_ESTIMATE_OUTCOMES = Counter(+ "replay_vision_estimate_outcomes_total",+ "Estimate outcomes, recorded by scanner saves and the hourly refresher: refreshed, or skipped "+ "because the scanner's experiment targeting can't resolve an exposed population. Most skips "+ "are drafts that heal at launch; a rising unresolved count means scanners are stuck with no "+ "estimate. Failures of the scanner's own query stay on the error path and are not counted",+ ["outcome"],+)+REPLAY_VISION_GEMINI_CLEANUP_BACKLOG = Gauge("replay_vision_gemini_cleanup_backlog","Tracked Gemini files awaiting cleanup (a growing backlog means the sweep is losing)",@@ -219,6 +228,11 @@ def record_sweep_outcome(outcome: str, candidates: int = 0) -> None:_otel.record_counter_twin(REPLAY_VISION_SWEEP_CANDIDATES, candidates, {})+def record_estimate_outcome(outcome: str) -> None:+ REPLAY_VISION_ESTIMATE_OUTCOMES.labels(outcome=outcome).inc()+ _otel.record_counter_twin(REPLAY_VISION_ESTIMATE_OUTCOMES, 1, {"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/tests/test_api.py b/products/replay_vision/backend/tests/test_api.pyindex cc5e99814c8f..af147310483b 100644--- a/products/replay_vision/backend/tests/test_api.py+++ b/products/replay_vision/backend/tests/test_api.py@@ -12,6 +12,8 @@ from django.utils import timezoneimport requestsfrom parameterized import parameterized+from prometheus_client import REGISTRY+from rest_framework.exceptions import ValidationError as DRFValidationErrorfrom temporalio.exceptions import WorkflowAlreadyStartedErrorfrom posthog.api.tagged_item import set_tags_on_object@@ -921,6 +923,43 @@ class TestScannerExperimentTargeting(_VisionAPITestCase):self.assertEqual(resp.status_code, 200, resp.json())self.assertIsNone(resp.json()["experiment_targeting"])+ def test_draft_experiment_targeting_saves_without_an_estimate_error(self) -> None:+ # The create wizard makes a scanner next to a fresh draft, so the exposed population cannot+ # resolve yet. The real estimate call runs here, because that is what must stay quiet.+ labels = {"outcome": "experiment_linkage_unresolved"}+ before = REGISTRY.get_sample_value("replay_vision_estimate_outcomes_total", labels) or 0.0+ self.refresh_estimate_patcher.stop()+ try:+ with patch("products.replay_vision.backend.api.scanners.logger") as mock_logger:+ resp = self.client.post(+ self.scanners_url,+ data=self._create_payload("draft-target", experiment_targeting=self.targeting),+ format="json",+ )+ finally:+ self.mock_refresh_estimate = self.refresh_estimate_patcher.start()++ self.assertEqual(resp.status_code, 201, resp.json())+ self.assertEqual(resp.json()["experiment_targeting"], self.targeting)+ self.assertIsNone(resp.json()["estimated_monthly_observations"])+ mock_logger.exception.assert_not_called()+ # The save path records the skip, so the scanner is visible before the first hourly tick.+ self.assertEqual(REGISTRY.get_sample_value("replay_vision_estimate_outcomes_total", labels), before + 1)++ def test_unbuildable_query_keeps_the_estimate_failure_loud(self) -> None:+ # A deleted action or a bad cohort reference in the scanner's own query does not heal at+ # launch, so it must stay in error tracking instead of the quiet linkage outcome.+ self.mock_refresh_estimate.side_effect = DRFValidationError("Action ID 424242 does not exist!")+ labels = {"outcome": "experiment_linkage_unresolved"}+ before = REGISTRY.get_sample_value("replay_vision_estimate_outcomes_total", labels) or 0.0++ with patch("products.replay_vision.backend.api.scanners.logger") as mock_logger:+ resp = self.client.post(self.scanners_url, data=self._create_payload("broken-query"), format="json")++ self.assertEqual(resp.status_code, 201, resp.json())+ mock_logger.exception.assert_called_once()+ self.assertEqual(REGISTRY.get_sample_value("replay_vision_estimate_outcomes_total", labels) or 0.0, before)+@parameterized.expand([("missing_experiment", {"variant": "test"}),@@ -1017,11 +1056,39 @@ class TestScannerLifecycleTelemetry(_VisionAPITestCase):self.assertEqual(properties["credits_per_observation"], 15)self.assertEqual(properties["sampling_rate"], 0.25)self.assertTrue(properties["has_filters"])+ self.assertFalse(properties["has_experiment_targeting"])self.assertTrue(properties["enabled"])self.assertEqual(properties["organization_id"], str(self.team.organization_id))# Session auth resolves to "web" (the app UI), MCP callers to "mcp".self.assertEqual(properties["source"], "web")+ def test_create_with_experiment_targeting_reports_a_filtered_scanner(self) -> None:+ # The population lives in experiment_targeting, not in query keys, so an experiment-scoped+ # scanner must not read as unfiltered on launch dashboards.+ experiment = create_experiment(self.team, "telemetry-targeting")+ with patch("posthoganalytics.capture") as capture:+ resp = self.client.post(+ self.scanners_url,+ data={+ "name": "telemetry-targeting",+ "scanner_type": ScannerType.MONITOR,+ "scanner_config": {"prompt": "p"},+ "model": ScannerModel.GEMINI_3_8_FLASH,+ "experiment_targeting": {"experiment_id": experiment.id, "variant": None},+ "query": {"kind": "RecordingsQuery", "filter_test_accounts": True},+ },+ format="json",+ )++ self.assertEqual(resp.status_code, 201, resp.json())+ created = [+ call for call in capture.call_args_list if call.kwargs.get("event") == "replay_vision_scanner_created"+ ]+ self.assertEqual(len(created), 1)+ properties = created[0].kwargs["properties"]+ self.assertTrue(properties["has_filters"])+ self.assertTrue(properties["has_experiment_targeting"])+@parameterized.expand([("test_arm", "test"), ("control_arm", "control"), ("flag_off", False)])def test_create_reports_the_experiment_arm(self, _name: str, flag_value: str | bool) -> None:# The creation-flow experiment splits its conversion metric on this property. Dropping itdiff --git a/products/replay_vision/backend/tests/test_estimate_refresh.py b/products/replay_vision/backend/tests/test_estimate_refresh.pyindex f563108d77a5..f745f9aa3dbf 100644--- a/products/replay_vision/backend/tests/test_estimate_refresh.py+++ b/products/replay_vision/backend/tests/test_estimate_refresh.py@@ -8,6 +8,11 @@ from unittest.mock import AsyncMock, MagicMock, patchfrom django.utils import timezonefrom parameterized import parameterized+from prometheus_client import REGISTRY+from rest_framework.exceptions import (+ PermissionDenied,+ ValidationError as DRFValidationError,+)from temporalio.exceptions import ApplicationErrorfrom posthog.schema import FilterLogicalOperator, RecordingsQuery@@ -57,6 +62,8 @@ _ACTIVITY_HELPER = ("products.replay_vision.backend.temporal.activities.refresh_scanner_estimate.refresh_scanner_estimate")_ESTIMATE_QUERY = "products.replay_vision.backend.queries.scanner_volume_estimate.estimate_scanner_session_volume"+# The classifier defers this import, so the patch target is the facade attribute it reads.+_RESOLVE_LINKAGE = "products.experiments.backend.facade.replay.resolve_exposure_linkage"def _make_scanner(**overrides: Any) -> ReplayScanner:@@ -363,14 +370,58 @@ class TestRefreshScannerEstimateActivity:assert refreshed is Falsemock_refresh.assert_not_called()- def test_propagates_helper_errors(self) -> None:+ @parameterized.expand(+ [+ ("unexpected_error", RuntimeError("boom")),+ # Without experiment targeting there is no linkage to resolve: a DRF ValidationError+ # means the scanner's own query no longer builds, which must stay a failed activity.+ ("query_unbuildable", DRFValidationError("Action ID 424242 does not exist!")),+ ]+ )+ def test_propagates_helper_errors(self, _name: str, error: Exception) -> None:scanner = _make_scanner()- with patch(_ACTIVITY_HELPER, side_effect=RuntimeError("boom")):- with pytest.raises(RuntimeError, match="boom"):+ with patch(_ACTIVITY_HELPER, side_effect=error):+ with pytest.raises(type(error)):+ refresh_scanner_estimate_activity(+ RefreshScannerEstimateInputs(scanner_id=scanner.id, team_id=scanner.team_id)+ )++ def test_propagates_query_errors_when_the_linkage_resolves(self) -> None:+ # A targeted scanner can carry a broken query filter too. When the linkage itself+ # resolves, the failure is the query, which no launch heals, so it stays loud.+ scanner = _make_scanner(experiment_targeting={"experiment_id": 424242, "variant": None})+ with (+ patch(_ACTIVITY_HELPER, side_effect=DRFValidationError("Action ID 424242 does not exist!")),+ patch(_RESOLVE_LINKAGE, return_value=MagicMock()),+ ):+ with pytest.raises(DRFValidationError):refresh_scanner_estimate_activity(RefreshScannerEstimateInputs(scanner_id=scanner.id, team_id=scanner.team_id))+ @parameterized.expand(+ [+ ("experiment_cannot_answer", DRFValidationError("This experiment hasn't launched")),+ ("creator_lost_experiment_access", PermissionDenied("no access")),+ ]+ )+ def test_reports_an_unresolvable_experiment_as_not_refreshed(self, _name: str, error: Exception) -> None:+ # The nonexistent experiment id makes the classifier's re-resolution raise, which is the+ # linkage-unresolved state.+ scanner = _make_scanner(experiment_targeting={"experiment_id": 424242, "variant": None})+ labels = {"outcome": "experiment_linkage_unresolved"}+ before = REGISTRY.get_sample_value("replay_vision_estimate_outcomes_total", labels) or 0.0++ with patch(_ACTIVITY_HELPER, side_effect=error):+ refreshed = refresh_scanner_estimate_activity(+ RefreshScannerEstimateInputs(scanner_id=scanner.id, team_id=scanner.team_id)+ )++ assert refreshed is False+ # The workflow discards the return value, so this counter is the only thing that separates a+ # skipped scanner from a refreshed one.+ assert REGISTRY.get_sample_value("replay_vision_estimate_outcomes_total", labels) == before + 1+@pytest.mark.django_db(transaction=True)class TestListStaleScannerEstimatesActivity:diff --git a/products/replay_vision/backend/tests/test_metrics.py b/products/replay_vision/backend/tests/test_metrics.pyindex 4caafdebde50..d5efd313f8bb 100644--- a/products/replay_vision/backend/tests/test_metrics.py+++ b/products/replay_vision/backend/tests/test_metrics.py@@ -8,6 +8,7 @@ from prometheus_client import REGISTRYfrom products.replay_vision.backend.temporal.metrics import (record_activity_duration,record_credits_consumed,+ record_estimate_outcome,record_failure_kind,record_gemini_cleanup_backlog,record_ineligible_kind,@@ -92,6 +93,13 @@ class TestRecordHelpers(SimpleTestCase):{},3.0,),+ (+ "estimate_outcome",+ lambda: record_estimate_outcome("experiment_linkage_unresolved"),+ "replay_vision_estimate_outcomes_total",+ {"outcome": "experiment_linkage_unresolved"},+ 1.0,+ ),("observation_e2e",lambda: record_observation_e2e("monitor", 120.0),diff --git a/products/replay_vision/frontend/replay_scanners/experimentTargeting.ts b/products/replay_vision/frontend/replay_scanners/experimentTargeting.tsindex a2adefde1acd..a4360365df4b 100644--- a/products/replay_vision/frontend/replay_scanners/experimentTargeting.ts+++ b/products/replay_vision/frontend/replay_scanners/experimentTargeting.ts@@ -1,6 +1,6 @@import { getExperimentVariants } from 'scenes/experiments/utils'-import { NodeKind } from '~/queries/schema/schema-general'+import { NodeKind, type RecordingsQuery } from '~/queries/schema/schema-general'import { Experiment } from '~/types'import type { ScannerExperimentTargetingApi } from 'products/replay_vision/frontend/generated/api.schemas'@@ -64,6 +64,19 @@ export function buildExperimentTargeting(context: ExperimentScannerContext): Sca}}+/**+ * The query keys an experiment-scoped scanner takes from its experiment. The population is never+ * one of them: it lives in `experiment_targeting`, and the API rejects an exposure filter set here.+ * Every entry point that creates such a scanner reads this, so the test-account default cannot+ * drift between them.+ */+export function experimentScannerQuery(experiment: Experiment): Pick<RecordingsQuery, 'kind' | 'filter_test_accounts'> {+ return {+ kind: NodeKind.RecordingsQuery,+ filter_test_accounts: experiment.exposure_criteria?.filterTestAccounts ?? false,+ }+}+/*** Keeps the requested variant key only if the loaded experiment actually has it. A URL can carry a* stale `?variant=old-key`, which would target a variant that no longer exists; dropping it falls@@ -90,8 +103,8 @@ export function prefillScannerForExperiment(scanner: ReplayScanner, context: Expname: experimentScannerName(scanner.name, context.experiment.name),experiment_targeting: buildExperimentTargeting(context),query: {- ...(scanner.query ?? { kind: NodeKind.RecordingsQuery }),- filter_test_accounts: context.experiment.exposure_criteria?.filterTestAccounts ?? false,+ ...scanner.query,+ ...experimentScannerQuery(context.experiment),},}}