Skip to content

:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.

feat(actions): notice for insights whose selector matching changed (#99493)

Thomas Obermüller84afe2a3fb59
diff --git a/.semgrep/rules/security/idor-team-scoped-models.yaml b/.semgrep/rules/security/idor-team-scoped-models.yaml
index 84069ef605e4..392ed2590b13 100644
--- a/.semgrep/rules/security/idor-team-scoped-models.yaml
+++ b/.semgrep/rules/security/idor-team-scoped-models.yaml
@@ -63,6 +63,7 @@ rules:
|AccountTrackRuleRun
|AccountView
|Action
+ |ActionSelectorMatchChange
|AEOCitationCheck
|AEOPrompt
|AgentApplication
@@ -516,6 +517,7 @@ rules:
|AccountTrackRuleRun
|AccountView
|Action
+ |ActionSelectorMatchChange
|AgentApplication
|AgentArtifact
|AgentIdentityCredential
diff --git a/docs/published/docs/product-analytics/action-selector-matching.md b/docs/published/docs/product-analytics/action-selector-matching.md
new file mode 100644
index 000000000000..1e5cc41d952f
--- /dev/null
+++ b/docs/published/docs/product-analytics/action-selector-matching.md
@@ -0,0 +1,42 @@
+# Action selector matching
+
+Actions that match elements by CSS selector used to match more elements than their selector describes. We have fixed this.
+
+Where we could rewrite a selector so that it kept matching the same events under the corrected rules, we updated the action for you and its counts did not change. For a smaller set of actions no such rewrite exists. Those counts are now lower, including for dates in the past.
+
+## What changed
+
+Conditions written together in a selector have to be met by the same element. A selector like `div.btn` means one element that is both a `div` and has the class `btn`.
+
+Before the fix, those conditions could be met by different elements. A `div` anywhere above a `.btn` in the page would satisfy `div.btn`, so the action counted clicks it was never meant to count.
+
+Two other combinators changed at the same time:
+
+- `>` now means a direct child, as it does in CSS. Before, it reached past elements in between.
+- A space now means any descendant. Before, a selector like `section button` only matched when the `button` sat directly under the `section`.
+
+## Actions we adapted for you
+
+Most affected selectors could be rewritten to keep matching the same events under the corrected rules, usually by replacing `>` with a space. We measured each rewrite against real traffic first, and applied it only where the counts came out the same.
+
+If this happened to one of your actions, its selector now reads slightly differently from the one you wrote, and it counts what it counted before. The edit appears in the action's activity log alongside your own changes.
+
+## Actions whose counts dropped
+
+For a smaller set there was no rewrite that kept the old counts. These actions were counting events they should not have counted, and no version of the selector reproduces the old number while still describing the element you meant. We left the selector alone, so the counts fell.
+
+If one of your insights uses one of these actions, the insight shows a notice naming the action and the selectors involved.
+
+## Why past dates changed too
+
+PostHog stores the elements of every autocapture event as they were when the event happened, and works out which actions match when you run a query. It does not store the match itself.
+
+So correcting how selectors are matched changes the answer for every date, not only for events captured after the fix. An insight you looked at last month can show a lower number today.
+
+## What to do
+
+Open the action and check that its selector describes the element you want.
+
+If the counts are now lower than you expect, the selector is probably matching fewer elements than you intended. Loosen it: use a space instead of `>` to allow elements in between, or drop a condition that the target element does not actually carry.
+
+The [toolbar](/docs/toolbar) is the fastest way to check. Open it on your site and select the element you want the action to match, and it writes a selector that matches that element under the current rules.
diff --git a/frontend/src/lib/constants.tsx b/frontend/src/lib/constants.tsx
index 8c1d24f74eb4..9a78d2fcd7da 100644
--- a/frontend/src/lib/constants.tsx
+++ b/frontend/src/lib/constants.tsx
@@ -525,6 +525,7 @@ export const FEATURE_FLAGS = {
SEARCH_DEBOUNCE_ALL: 'search-debounce-all', // owner: @adamleithp #team-platform-ux
SEARCH_RE_RANK: 'search-re-rank', // owner: @adamleithp #team-platform-ux
SEEKBAR_PREVIEW_SCRUBBING: 'seekbar-preview-scrubbing', // owner: @pauldambra #team-replay
+ SELECTOR_MATCH_CHANGE_NOTICE: 'selector-match-change-notice', // owner: @thmsobrmlr #team-product-analytics, gates the selector match change notice on insights
SHOPIFY_DWH: 'shopify-dwh', // owner: #team-warehouse-sources
SHOW_DATA_PIPELINES_NAV_ITEM: 'show-data-pipelines-nav-item', // owner: @raquelmsmith
SHOW_REFERRER_FAVICON: 'show-referrer-favicon', // owner: @jordanm-posthog #team-web-analytics
diff --git a/frontend/src/queries/nodes/InsightViz/InsightViz.tsx b/frontend/src/queries/nodes/InsightViz/InsightViz.tsx
index 92e3b6fddf7b..b2edcbaf109f 100644
--- a/frontend/src/queries/nodes/InsightViz/InsightViz.tsx
+++ b/frontend/src/queries/nodes/InsightViz/InsightViz.tsx
@@ -11,6 +11,7 @@ import { useAttachedLogic } from 'lib/logic/scenes/useAttachedLogic'
import { insightDataLogic } from 'scenes/insights/insightDataLogic'
import { insightLogic } from 'scenes/insights/insightLogic'
import { insightVizDataLogic } from 'scenes/insights/insightVizDataLogic'
+import { SelectorMatchChangeNotice } from 'scenes/insights/SelectorMatchChangeNotice'
import { ErrorBoundary } from '~/layout/ErrorBoundary'
import { AnyResponseType, DashboardFilter, HogQLVariable, InsightVizNode } from '~/queries/schema/schema-general'
@@ -140,7 +141,10 @@ export function InsightViz({
embedded={isEmbedded}
/>
{!isEmbedded ? (
- <div className="flex-1 max-h-full overflow-auto pb-8">{display}</div>
+ <div className="flex-1 max-h-full overflow-auto pb-8">
+ <SelectorMatchChangeNotice insightProps={insightProps} />
+ {display}
+ </div>
) : (
display
)}
diff --git a/frontend/src/scenes/insights/SelectorMatchChangeNotice.test.tsx b/frontend/src/scenes/insights/SelectorMatchChangeNotice.test.tsx
new file mode 100644
index 000000000000..d172fde14b83
--- /dev/null
+++ b/frontend/src/scenes/insights/SelectorMatchChangeNotice.test.tsx
@@ -0,0 +1,100 @@
+import '@testing-library/jest-dom'
+
+import { cleanup, render, screen, waitFor } from '@testing-library/react'
+import { Provider } from 'kea'
+
+import { FEATURE_FLAGS } from 'lib/constants'
+import { featureFlagLogic } from 'lib/logic/featureFlagLogic'
+import { insightVizDataLogic } from 'scenes/insights/insightVizDataLogic'
+import { SelectorMatchChangeNotice } from 'scenes/insights/SelectorMatchChangeNotice'
+import { urls } from 'scenes/urls'
+
+import { useMocks } from '~/mocks/jest'
+import { NodeKind, TrendsQuery } from '~/queries/schema/schema-general'
+import { initKeaTests } from '~/test/init'
+import { BaseMathType } from '~/types'
+
+import { ActionSelectorMatchChangeApi } from 'products/actions/frontend/generated/api.schemas'
+
+const insightProps = { dashboardItemId: 'new' as const }
+
+describe('SelectorMatchChangeNotice', () => {
+ const actionsRequest = jest.fn(() => [200, { results: [] }])
+ let selectorMatchChanges: ActionSelectorMatchChangeApi[] = []
+ const selectorMatchChangesRequest = jest.fn((_context: { request: Request }) => [200, selectorMatchChanges])
+
+ beforeEach(() => {
+ selectorMatchChanges = []
+ useMocks({
+ get: {
+ '/api/projects/:team_id/actions/': actionsRequest,
+ '/api/projects/:team_id/actions/selector_match_changes/': selectorMatchChangesRequest,
+ },
+ })
+ initKeaTests()
+ featureFlagLogic.mount()
+ })
+
+ afterEach(() => cleanup())
+
+ function setup(featureEnabled: boolean, actionId?: number): void {
+ featureFlagLogic.actions.setFeatureFlags(featureEnabled ? [FEATURE_FLAGS.SELECTOR_MATCH_CHANGE_NOTICE] : [], {
+ [FEATURE_FLAGS.SELECTOR_MATCH_CHANGE_NOTICE]: featureEnabled,
+ })
+
+ const vizDataLogic = insightVizDataLogic(insightProps)
+ vizDataLogic.mount()
+ vizDataLogic.actions.updateQuerySource({
+ kind: NodeKind.TrendsQuery,
+ series: actionId
+ ? [{ kind: NodeKind.ActionsNode, id: actionId }]
+ : [{ kind: NodeKind.EventsNode, event: '$pageview', math: BaseMathType.TotalCount }],
+ } as TrendsQuery)
+
+ render(
+ <Provider>
+ <SelectorMatchChangeNotice insightProps={insightProps} />
+ </Provider>
+ )
+ }
+
+ it.each([
+ ['the feature flag is off', false, 42],
+ ['the insight has no action series', true, undefined],
+ ])('does not load actions when %s', (_name, featureEnabled, actionId) => {
+ setup(featureEnabled, actionId)
+
+ expect(actionsRequest).not.toHaveBeenCalled()
+ expect(selectorMatchChangesRequest).not.toHaveBeenCalled()
+ })
+
+ it('loads only selector match changes for the insight action IDs', async () => {
+ setup(true, 42)
+
+ await waitFor(() => expect(selectorMatchChangesRequest).toHaveBeenCalledTimes(1))
+ expect(actionsRequest).not.toHaveBeenCalled()
+ const requestUrl = selectorMatchChangesRequest.mock.lastCall?.[0].request.url
+ expect(requestUrl).not.toBeUndefined()
+ expect(new URL(requestUrl ?? 'http://localhost').searchParams.get('action_ids')).toBe('42')
+ })
+
+ it('names each affected action, links to it, and lists its selectors', async () => {
+ selectorMatchChanges = [
+ { action_id: 42, action_name: 'Signup button clicked', selectors: ['div.btn.primary', '.cta > span'] },
+ ]
+ setup(true, 42)
+
+ const actionLink = await screen.findByText('Signup button clicked')
+ expect(actionLink.closest('a')).toHaveAttribute('href', expect.stringContaining(urls.action(42)))
+ expect(screen.getByText('div.btn.primary')).toBeInTheDocument()
+ expect(screen.getByText('.cta > span')).toBeInTheDocument()
+ expect(screen.getByText('Read more about action selector matching')).toBeInTheDocument()
+ })
+
+ it('renders nothing when no action in the insight is affected', async () => {
+ setup(true, 42)
+
+ await waitFor(() => expect(selectorMatchChangesRequest).toHaveBeenCalledTimes(1))
+ expect(screen.queryByText(/Counts in this insight are lower/)).not.toBeInTheDocument()
+ })
+})
diff --git a/frontend/src/scenes/insights/SelectorMatchChangeNotice.tsx b/frontend/src/scenes/insights/SelectorMatchChangeNotice.tsx
new file mode 100644
index 000000000000..6124ddf3a0f9
--- /dev/null
+++ b/frontend/src/scenes/insights/SelectorMatchChangeNotice.tsx
@@ -0,0 +1,87 @@
+import { useValues } from 'kea'
+
+import { LemonBanner } from '@posthog/lemon-ui'
+
+import { FEATURE_FLAGS } from 'lib/constants'
+import { Link } from 'lib/lemon-ui/Link'
+import { featureFlagLogic } from 'lib/logic/featureFlagLogic'
+import { insightVizDataLogic } from 'scenes/insights/insightVizDataLogic'
+import { getSelectorMatchChangeActionIds } from 'scenes/insights/selectorMatchChange'
+import { selectorMatchChangeNoticeLogic } from 'scenes/insights/selectorMatchChangeNoticeLogic'
+import { projectLogic } from 'scenes/projectLogic'
+import { urls } from 'scenes/urls'
+
+import { InsightVizNode } from '~/queries/schema/schema-general'
+import { InsightLogicProps } from '~/types'
+
+import { ActionSelectorMatchChangeApi } from 'products/actions/frontend/generated/api.schemas'
+
+interface SelectorMatchChangeNoticeProps {
+ insightProps: InsightLogicProps<InsightVizNode>
+}
+
+interface SelectorMatchChangeNoticeContentProps {
+ actionIds: number[]
+ projectId: number
+}
+
+// Remove after 2026-12-31, once affected owners have had a quarter to see it.
+export function SelectorMatchChangeNotice({ insightProps }: SelectorMatchChangeNoticeProps): JSX.Element | null {
+ const { featureFlags } = useValues(featureFlagLogic)
+ const { currentProjectId } = useValues(projectLogic)
+ const { querySource } = useValues(insightVizDataLogic(insightProps as InsightLogicProps))
+
+ if (!featureFlags[FEATURE_FLAGS.SELECTOR_MATCH_CHANGE_NOTICE]) {
+ return null
+ }
+ const actionIds = getSelectorMatchChangeActionIds(querySource)
+ if (currentProjectId === null || actionIds.length === 0) {
+ return null
+ }
+
+ return <SelectorMatchChangeNoticeContent actionIds={actionIds} projectId={currentProjectId} />
+}
+
+function SelectorMatchChangeNoticeContent({
+ actionIds,
+ projectId,
+}: SelectorMatchChangeNoticeContentProps): JSX.Element | null {
+ const { selectorMatchChanges } = useValues(selectorMatchChangeNoticeLogic({ actionIds, projectId }))
+
+ if (!selectorMatchChanges?.length) {
+ return null
+ }
+
+ return (
+ <LemonBanner type="warning" dismissKey={FEATURE_FLAGS.SELECTOR_MATCH_CHANGE_NOTICE} className="mb-4">
+ <p>
+ This insight uses an action that PostHog matched incorrectly. We've fixed how action selectors are
+ matched, but we couldn't rewrite this selector to keep its old counts. Counts in this insight are lower
+ than they were, including for past dates.
+ </p>
+ <p>
+ What changed: conditions written together in a selector, like a tag and a class, now have to be met by
+ the same element. Before, they could come from different elements.
+ </p>
+ <p>This changed the counts for:</p>
+ <ul className="list-disc list-inside">
+ {selectorMatchChanges.map((change: ActionSelectorMatchChangeApi) => (
+ <li key={change.action_id}>
+ <Link to={urls.action(change.action_id)}>{change.action_name || 'Untitled action'}</Link>
+ {change.selectors.map((selector, index) => (
+ <span key={`${selector}-${index}`}>
+ {index === 0 ? ': ' : ', '}
+ <span className="font-mono">{selector}</span>
+ </span>
+ ))}
+ </li>
+ ))}
+ </ul>
+ <p className="mt-2 mb-0">
+ <Link to="https://posthog.com/docs/product-analytics/action-selector-matching" target="_blank">
+ Read more about action selector matching
+ </Link>
+ </p>
+ </LemonBanner>
+ )
+}
diff --git a/frontend/src/scenes/insights/selectorMatchChange.test.ts b/frontend/src/scenes/insights/selectorMatchChange.test.ts
new file mode 100644
index 000000000000..2cf8b47f5478
--- /dev/null
+++ b/frontend/src/scenes/insights/selectorMatchChange.test.ts
@@ -0,0 +1,38 @@
+import { getSelectorMatchChangeActionIds } from 'scenes/insights/selectorMatchChange'
+
+import { NodeKind } from '~/queries/schema/schema-general'
+
+describe('getSelectorMatchChangeActionIds', () => {
+ const actionSeries = (id: number): Record<string, any> => ({ kind: NodeKind.ActionsNode, id })
+ const eventSeries = { kind: NodeKind.EventsNode, event: '$pageview' }
+ const retentionEntity = (id: number | string): Record<string, any> => ({ type: 'actions', id })
+
+ it.each<[string, Record<string, any> | null | undefined, number[]]>([
+ ['one action', { series: [actionSeries(1)] }, [1]],
+ ['an action alongside an event', { series: [eventSeries, actionSeries(1)] }, [1]],
+ ['the same action twice', { series: [actionSeries(1), actionSeries(1)] }, [1]],
+ ['several actions', { series: [actionSeries(4), actionSeries(2)] }, [2, 4]],
+ [
+ 'both retention entities',
+ { retentionFilter: { targetEntity: retentionEntity(3), returningEntity: retentionEntity(5) } },
+ [3, 5],
+ ],
+ ['a retention entity with a string id', { retentionFilter: { targetEntity: retentionEntity('7') } }, [7]],
+ [
+ 'a retention entity that is an event',
+ { retentionFilter: { targetEntity: { type: 'events', id: '$pageview' } } },
+ [],
+ ],
+ [
+ 'the funnel a paths query walks',
+ { funnelPathsFilter: { funnelSource: { series: [actionSeries(9), eventSeries] } } },
+ [9],
+ ],
+ ['events only', { series: [eventSeries] }, []],
+ ['no series', { series: null }, []],
+ ['an empty query source', {}, []],
+ ['an undefined query source', undefined, []],
+ ])('resolves %s', (_name, querySource, expected) => {
+ expect(getSelectorMatchChangeActionIds(querySource)).toEqual(expected)
+ })
+})
diff --git a/frontend/src/scenes/insights/selectorMatchChange.ts b/frontend/src/scenes/insights/selectorMatchChange.ts
new file mode 100644
index 000000000000..983f3fa974f4
--- /dev/null
+++ b/frontend/src/scenes/insights/selectorMatchChange.ts
@@ -0,0 +1,28 @@
+import { isActionsNode } from '~/queries/utils'
+
+const ACTIONS_ENTITY_TYPE = 'actions'
+
+function collectActionId(node: Record<string, any> | null | undefined, actionIds: Set<number>): void {
+ // A series node carries `kind: ActionsNode`, while a retention entity carries
+ // `type: 'actions'` and may hold its id as a string.
+ if (!node || !(isActionsNode(node) || node.type === ACTIONS_ENTITY_TYPE)) {
+ return
+ }
+ const id = typeof node.id === 'string' ? Number(node.id) : node.id
+ if (typeof id === 'number' && Number.isFinite(id)) {
+ actionIds.add(id)
+ }
+}
+
+export function getSelectorMatchChangeActionIds(querySource: Record<string, any> | null | undefined): number[] {
+ const actionIds = new Set<number>()
+ for (const node of querySource?.series ?? []) {
+ collectActionId(node, actionIds)
+ }
+ collectActionId(querySource?.retentionFilter?.targetEntity, actionIds)
+ collectActionId(querySource?.retentionFilter?.returningEntity, actionIds)
+ for (const node of querySource?.funnelPathsFilter?.funnelSource?.series ?? []) {
+ collectActionId(node, actionIds)
+ }
+ return [...actionIds].sort((left, right) => left - right)
+}
diff --git a/frontend/src/scenes/insights/selectorMatchChangeNoticeLogic.ts b/frontend/src/scenes/insights/selectorMatchChangeNoticeLogic.ts
new file mode 100644
index 000000000000..1209c66f65b2
--- /dev/null
+++ b/frontend/src/scenes/insights/selectorMatchChangeNoticeLogic.ts
@@ -0,0 +1,65 @@
+import { MakeLogicType, afterMount, kea, key, path, props } from 'kea'
+import { loaders } from 'kea-loaders'
+
+import { actionsSelectorMatchChangesList } from 'products/actions/frontend/generated/api'
+import { ActionSelectorMatchChangeApi } from 'products/actions/frontend/generated/api.schemas'
+
+export interface SelectorMatchChangeNoticeLogicProps {
+ actionIds: number[]
+ projectId: number
+}
+
+// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
+export interface selectorMatchChangeNoticeLogicValues {
+ selectorMatchChanges: ActionSelectorMatchChangeApi[] | null
+ selectorMatchChangesLoading: boolean
+}
+
+// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
+export interface selectorMatchChangeNoticeLogicActions {
+ loadSelectorMatchChanges: () => any
+ loadSelectorMatchChangesFailure: (
+ error: string,
+ errorObject?: any
+ ) => {
+ error: string
+ errorObject?: any
+ }
+ loadSelectorMatchChangesSuccess: (
+ selectorMatchChanges: ActionSelectorMatchChangeApi[],
+ payload?: any
+ ) => {
+ selectorMatchChanges: ActionSelectorMatchChangeApi[]
+ payload?: any
+ }
+}
+
+// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
+export interface selectorMatchChangeNoticeLogicMeta {
+ key: string
+}
+
+export type selectorMatchChangeNoticeLogicType = MakeLogicType<
+ selectorMatchChangeNoticeLogicValues,
+ selectorMatchChangeNoticeLogicActions,
+ SelectorMatchChangeNoticeLogicProps,
+ selectorMatchChangeNoticeLogicMeta
+>
+
+export const selectorMatchChangeNoticeLogic = kea<selectorMatchChangeNoticeLogicType>([
+ props({} as SelectorMatchChangeNoticeLogicProps),
+ key((props) => `${props.projectId}:${props.actionIds.join(',')}`),
+ path((key) => ['scenes', 'insights', 'selectorMatchChangeNoticeLogic', key]),
+ loaders(({ props }) => ({
+ selectorMatchChanges: [
+ null as ActionSelectorMatchChangeApi[] | null,
+ {
+ loadSelectorMatchChanges: async () =>
+ actionsSelectorMatchChangesList(String(props.projectId), { action_ids: props.actionIds }),
+ },
+ ],
+ })),
+ afterMount(({ actions }) => {
+ actions.loadSelectorMatchChanges()
+ }),
+])
diff --git a/posthog/models/activity_logging/activity_log.py b/posthog/models/activity_logging/activity_log.py
index 157dff68727f..dfdd8a7321bd 100644
--- a/posthog/models/activity_logging/activity_log.py
+++ b/posthog/models/activity_logging/activity_log.py
@@ -1039,6 +1039,8 @@ field_exclusions: dict[AuditableScope, list[str]] = {
"plugin_configs",
"tagged_items",
"survey",
+ # Derived migration output whose reverse manager is fail-closed. It is not part of an action edit.
+ "selector_match_changes",
],
"ExternalDataSource": [
"connection_id",
diff --git a/posthog/models/resource_transfer/test/__snapshots__/test_visitor_field_snapshots.ambr b/posthog/models/resource_transfer/test/__snapshots__/test_visitor_field_snapshots.ambr
index 7d186bac1fdd..cc721e7bacf9 100644
--- a/posthog/models/resource_transfer/test/__snapshots__/test_visitor_field_snapshots.ambr
+++ b/posthog/models/resource_transfer/test/__snapshots__/test_visitor_field_snapshots.ambr
@@ -485,6 +485,7 @@
'project_id',
'refresh_bytecode',
'save',
+ 'selector_match_changes',
'slack_message_format',
'steps',
'summary',
diff --git a/products/actions/backend/api/action.py b/products/actions/backend/api/action.py
index 4b8b5a890105..35e8fa2d0031 100644
--- a/products/actions/backend/api/action.py
+++ b/products/actions/backend/api/action.py
@@ -1,5 +1,5 @@
import json
-from collections import Counter
+from collections import Counter, defaultdict
from datetime import UTC, datetime
from typing import Any, cast
@@ -39,6 +39,7 @@ from products.access_control.backend.presentation.access_control import (
UserAccessControlSerializerMixin,
)
from products.actions.backend.models.action import ACTION_STEP_MATCHING_OPTIONS, Action
+from products.actions.backend.models.selector_match_change import ActionSelectorMatchChange
from products.cdp.backend.models.hog_functions.hog_function import HogFunction
from products.cohorts.backend.models.cohort import Cohort
from products.experiments.backend.models.experiment import Experiment
@@ -303,6 +304,27 @@ class ActionReferenceSerializer(serializers.Serializer):
created_by = UserBasicSerializer(help_text="User who created the resource", allow_null=True)
+class ActionSelectorMatchChangesQuerySerializer(serializers.Serializer):
+ action_ids = serializers.ListField(
+ child=serializers.IntegerField(min_value=1),
+ allow_empty=False,
+ max_length=100,
+ help_text="Action IDs used by the insight whose selector changes should be returned.",
+ )
+
+
+class ActionSelectorMatchChangeSerializer(serializers.Serializer):
+ action_id = serializers.IntegerField(help_text="ID of an affected action.")
+ action_name = serializers.CharField(
+ allow_null=True,
+ help_text="Name of the affected action, or null when it has no name.",
+ )
+ selectors = serializers.ListField(
+ child=serializers.CharField(),
+ help_text="CSS selectors whose matching behavior changed, in action step order.",
+ )
+
+
_ACTION_JSONPATH = (
'$.** ? ((@.kind == "ActionsNode" && (@.id == $id || @.id == $id_str))'
" || (@.actionId == $id || @.actionId == $id_str)"
@@ -566,6 +588,56 @@ class ActionViewSet(
queryset = queryset.annotate(count=Count(TREND_FILTER_TYPE_EVENTS))
return queryset.filter(team_id=self.team_id).order_by(*self.ordering)
+ @extend_schema(
+ parameters=[
+ OpenApiParameter(
+ "action_ids",
+ OpenApiTypes.INT,
+ location=OpenApiParameter.QUERY,
+ required=True,
+ many=True,
+ description="Action IDs used by the insight. Accepts repeated or comma-separated values.",
+ )
+ ],
+ responses={200: ActionSelectorMatchChangeSerializer(many=True)},
+ )
+ @drf_action(methods=["GET"], detail=False, required_scopes=["action:read"], pagination_class=None)
+ def selector_match_changes(self, request: request.Request, **kwargs: Any) -> Response:
+ raw_action_ids = [
+ part.strip()
+ for value in request.query_params.getlist("action_ids")
+ for part in value.split(",")
+ if part.strip()
+ ]
+ query = ActionSelectorMatchChangesQuerySerializer(data={"action_ids": raw_action_ids})
+ query.is_valid(raise_exception=True)
+ action_ids = list(dict.fromkeys(query.validated_data["action_ids"]))
+
+ visible_actions = self.user_access_control.filter_queryset_by_access_level(
+ Action.objects.filter(team_id=self.team_id, id__in=action_ids, deleted=False),
+ resource="action",
+ )
+ actions_by_id = {action.id: action for action in visible_actions}
+ selectors_by_action: dict[int, list[str]] = defaultdict(list)
+ stored_changes = (
+ ActionSelectorMatchChange.objects.for_team(self.team_id)
+ .filter(action_id__in=actions_by_id)
+ .order_by("action_id", "step_index")
+ )
+ for change in stored_changes:
+ if change.describes(actions_by_id[change.action_id]):
+ selectors_by_action[change.action_id].append(change.selector)
+
+ changes = [
+ {
+ "action_id": action_id,
+ "action_name": actions_by_id[action_id].name,
+ "selectors": selectors,
+ }
+ for action_id, selectors in sorted(selectors_by_action.items())
+ ]
+ return Response(ActionSelectorMatchChangeSerializer(changes, many=True).data)
+
@extend_schema(responses={200: ActionReferenceSerializer(many=True)})
@drf_action(methods=["GET"], detail=True, required_scopes=["action:read"], pagination_class=None)
def references(self, request: request.Request, **kwargs: Any) -> Response:
diff --git a/products/actions/backend/api/test/test_action.py b/products/actions/backend/api/test/test_action.py
index cac0ddc704ea..185bca926fb7 100644
--- a/products/actions/backend/api/test/test_action.py
+++ b/products/actions/backend/api/test/test_action.py
@@ -17,6 +17,7 @@ from posthog.models import Tag, User
from posthog.test.warehouse_access import WAREHOUSE_ACCESS_CONTROL_FLAG, deny_warehouse_table_to_member
from products.actions.backend.models.action import Action
+from products.actions.backend.models.selector_match_change import ActionSelectorMatchChange
from products.cdp.backend.models.hog_functions.hog_function import HogFunction
from products.cohorts.backend.models.cohort import Cohort
from products.product_analytics.backend.facade.models import Insight
@@ -333,6 +334,68 @@ class TestActionApi(ClickhouseTestMixin, APIBaseTest, QueryMatchingTest):
action = Action.objects.get(pk=response.json()["id"])
assert action.steps[0].event == "test_event "
+ def test_selector_match_changes_reports_only_requested_affected_actions(self) -> None:
+ changed = Action.objects.create(
+ team=self.team,
+ name="changed",
+ steps_json=[{"selector": "div .btn:nth-child(2)"}, {"selector": ".sibling"}],
+ )
+ unaffected = Action.objects.create(team=self.team, name="unaffected", steps_json=[{"selector": ".fine"}])
+ for step_index, selector in [(1, ".sibling"), (0, "div .btn:nth-child(2)")]:
+ ActionSelectorMatchChange.objects.for_team(self.team.id).create(
+ team=self.team,
+ action=changed,
+ step_index=step_index,
+ selector=selector,
+ old_match_count=900,
+ new_match_count=120,
+ measured_at=datetime(2026, 9, 11, tzinfo=UTC),
+ )
+
+ response = self.client.get(
+ f"/api/projects/{self.team.id}/actions/selector_match_changes/",
+ {"action_ids": f"{unaffected.id},{changed.id}"},
+ )
+
+ assert response.status_code == status.HTTP_200_OK
+ assert response.json() == [
+ {
+ "action_id": changed.id,
+ "action_name": "changed",
+ "selectors": ["div .btn:nth-child(2)", ".sibling"],
+ }
+ ]
+
+ @parameterized.expand(
+ [
+ ("the step now carries a different selector", [{"selector": ".rewritten"}]),
+ ("the step was removed", []),
+ ]
+ )
+ def test_selector_match_changes_drops_a_verdict_the_action_no_longer_matches(
+ self, _name: str, steps_json: list[dict]
+ ) -> None:
+ action = Action.objects.create(team=self.team, name="edited", steps_json=[{"selector": ".measured"}])
+ ActionSelectorMatchChange.objects.for_team(self.team.id).create(
+ team=self.team,
+ action=action,
+ step_index=0,
+ selector=".measured",
+ old_match_count=900,
+ new_match_count=120,
+ measured_at=datetime(2026, 9, 11, tzinfo=UTC),
+ )
+ action.steps_json = steps_json
+ action.save()
+
+ response = self.client.get(
+ f"/api/projects/{self.team.id}/actions/selector_match_changes/",
+ {"action_ids": str(action.id)},
+ )
+
+ assert response.status_code == status.HTTP_200_OK
+ assert response.json() == []
+
@time_machine.travel("2021-12-12", tick=False)
def test_listing_actions_is_not_nplus1(self) -> None:
# Pre-query to cache things like instance settings
diff --git a/products/actions/backend/management/__init__.py b/products/actions/backend/management/__init__.py
new file mode 100644
index 000000000000..e69de29bb2d1
diff --git a/products/actions/backend/management/commands/__init__.py b/products/actions/backend/management/commands/__init__.py
new file mode 100644
index 000000000000..e69de29bb2d1
diff --git a/products/actions/backend/management/commands/import_selector_match_changes.py b/products/actions/backend/management/commands/import_selector_match_changes.py
new file mode 100644
index 000000000000..e5fe13d2d56f
--- /dev/null
+++ b/products/actions/backend/management/commands/import_selector_match_changes.py
@@ -0,0 +1,112 @@
+import json
+from pathlib import Path
+from typing import Any
+
+from django.core.management.base import BaseCommand, CommandError
+from django.db import transaction
+from django.utils.dateparse import parse_datetime
+
+from posthog.storage import object_storage
+
+from products.actions.backend.models import Action, ActionSelectorMatchChange
+
+NO_FAITHFUL_FIX = "no_faithful_fix"
+OBJECT_URI_SCHEME = "s3://"
+
+
+def read_report(target: str) -> dict[str, Any]:
+ """The audit report at a local path or `s3://<bucket>/<key>`.
+
+ Deliberately not imported from the audit package: the audit runs from a
+ checkout in a toolbox pod and need not be deployed, while this command has
+ to run wherever the table lives.
+ """
+ if not target.startswith(OBJECT_URI_SCHEME):
+ return json.loads(Path(target).read_text(encoding="utf-8"))
+ bucket, _, key = target[len(OBJECT_URI_SCHEME) :].partition("/")
+ if not bucket or not key:
+ raise CommandError(f"expected {OBJECT_URI_SCHEME}<bucket>/<key>, got {target!r}")
+ body = object_storage.read(key, bucket=bucket)
+ if not body:
+ raise CommandError(f"no report at {target}")
+ return json.loads(body)
+
+
+class Command(BaseCommand):
+ help = (
+ "Import no-faithful-fix selector verdicts from an audit report into the database, so the "
+ "action API can tell an owner that the selector compiler change moved their numbers. "
+ "Read-only unless --live-run is passed."
+ )
+
+ def add_arguments(self, parser: Any) -> None:
+ parser.add_argument("--report", required=True, help="Audit report: a local path or s3://<bucket>/<key>")
+ parser.add_argument("--live-run", action="store_true", help="Actually write; default is dry-run")
+
+ def handle(self, *args: Any, **options: Any) -> None:
+ log = self.stdout.write
+ report = read_report(options["report"])
+ measured_at = parse_datetime(report.get("generated_at") or "")
+ if measured_at is None:
+ raise CommandError("report has no usable generated_at timestamp")
+
+ # Keyed by every team the audit covered, not only the affected ones, so a team
+ # that no longer has a no-faithful-fix selector has its stored rows cleared
+ # rather than left behind to show a notice the latest measurement disowns.
+ rows_by_team: dict[int, list[dict[str, Any]]] = {
+ int(team_key): [row for row in team.get("rows", []) if row.get("bucket") == NO_FAITHFUL_FIX]
+ for team_key, team in report.get("teams", {}).items()
+ }
+ if not rows_by_team:
+ log("report covers no teams; nothing to import")
+ return
+
+ total_rows = sum(len(rows) for rows in rows_by_team.values())
+ affected_teams = sum(1 for rows in rows_by_team.values() if rows)
+ log(
+ f"report covers {len(rows_by_team)} teams and holds {total_rows} no-faithful-fix "
+ f"selector steps across {affected_teams} of them"
+ )
+
+ imported = 0
+ stale = 0
+ for team_id, rows in sorted(rows_by_team.items()):
+ actions = {
+ action.id: action
+ for action in Action.objects.filter(team_id=team_id, id__in={row["action_id"] for row in rows})
+ }
+ changes = []
+ for row in rows:
+ action = actions.get(row["action_id"])
+ if action is None or action.deleted:
+ stale += 1
+ continue
+ change = ActionSelectorMatchChange(
+ team_id=team_id,
+ action=action,
+ step_index=row["step_index"],
+ selector=row["selector"],
+ old_match_count=row["counts"]["old_original"],
+ new_match_count=row["counts"]["new_original"],
+ measured_at=measured_at,
+ )
+ if not change.describes(action):
+ stale += 1
+ continue
+ changes.append(change)
+ imported += len(changes)
+ if not options["live_run"]:
+ continue
+ # The report is authoritative for every team it covers, so replacing
+ # the team's rows keeps a re-import from leaving behind verdicts the
+ # latest measurement no longer reaches.
+ with transaction.atomic():
+ # Both reads and writes go through a fail-closed manager, which refuses
+ # to build a queryset without a team scope.
+ ActionSelectorMatchChange.objects.for_team(team_id).delete()
+ ActionSelectorMatchChange.objects.for_team(team_id).bulk_create(changes)
+
+ if options["live_run"]:
+ log(self.style.SUCCESS(f"imported {imported} selector match changes, skipped {stale} stale rows"))
+ else:
+ log(f"dry-run: would import {imported} selector match changes, skipping {stale} stale rows")
diff --git a/products/actions/backend/management/test/test_import_selector_match_changes.py b/products/actions/backend/management/test/test_import_selector_match_changes.py
new file mode 100644
index 000000000000..b0ed3c445cae
--- /dev/null
+++ b/products/actions/backend/management/test/test_import_selector_match_changes.py
@@ -0,0 +1,75 @@
+import json
+
+import pytest
+
+from django.core.management import call_command
+
+from posthog.api.test.test_organization import create_organization
+from posthog.api.test.test_team import create_team
+
+from products.actions.backend.models import Action, ActionSelectorMatchChange
+
+pytestmark = [pytest.mark.django_db]
+
+
+def team():
+ return create_team(organization=create_organization("test org"))
+
+
+def _report(path, teams):
+ path.write_text(
+ json.dumps(
+ {
+ "generated_at": "2026-09-11T00:00:00+00:00",
+ "teams": {str(team_id): {"autocapture_events": 100, "rows": rows} for team_id, rows in teams.items()},
+ }
+ )
+ )
+ return str(path)
+
+
+def _flagged_row(team_id, action_id, selector):
+ return {
+ "team_id": team_id,
+ "action_id": action_id,
+ "step_index": 0,
+ "selector": selector,
+ "bucket": "no_faithful_fix",
+ "counts": {"old_original": 900, "new_original": 120},
+ }
+
+
+def test_re_import_clears_a_team_the_report_no_longer_flags(team, tmp_path):
+ action = Action.objects.create(team=team, name="checkout", steps_json=[{"selector": ".btn"}])
+ call_command(
+ "import_selector_match_changes",
+ report=_report(tmp_path / "first.json", {team.id: [_flagged_row(team.id, action.id, ".btn")]}),
+ live_run=True,
+ )
+ assert ActionSelectorMatchChange.objects.for_team(team.id).count() == 1
+
+ call_command(
+ "import_selector_match_changes",
+ report=_report(tmp_path / "second.json", {team.id: []}),
+ live_run=True,
+ )
+ assert ActionSelectorMatchChange.objects.for_team(team.id).count() == 0
+
+
+def test_import_leaves_a_team_the_report_does_not_cover(team, tmp_path):
+ other = create_team(organization=create_organization("other org"))
+ action = Action.objects.create(team=other, name="checkout", steps_json=[{"selector": ".btn"}])
+ call_command(
+ "import_selector_match_changes",
+ report=_report(tmp_path / "first.json", {other.id: [_flagged_row(other.id, action.id, ".btn")]}),
+ live_run=True,
+ )
+
+ call_command(
+ "import_selector_match_changes",
+ report=_report(tmp_path / "second.json", {team.id: []}),
+ live_run=True,
+ )
+
+ assert ActionSelectorMatchChange.objects.for_team(other.id).count() == 1
diff --git a/products/actions/backend/migrations/0003_actionselectormatchchange.py b/products/actions/backend/migrations/0003_actionselectormatchchange.py
new file mode 100644
index 000000000000..2bf1c422a2e4
--- /dev/null
+++ b/products/actions/backend/migrations/0003_actionselectormatchchange.py
@@ -0,0 +1,59 @@
+# Generated by Django 5.2.17 on 2026-09-11 17:55
+
+import django.db.models.deletion
+from django.db import migrations, models
+
+
+class Migration(migrations.Migration):
+ dependencies = [
+ ("actions", "0002_alter_action_created_by_alter_action_events_and_more"),
+ ("posthog", "1352_email_lookup_indexes"),
+ ]
+
+ operations = [
+ migrations.CreateModel(
+ name="ActionSelectorMatchChange",
+ fields=[
+ (
+ "id",
+ models.BigAutoField(
+ auto_created=True,
+ primary_key=True,
+ serialize=False,
+ verbose_name="ID",
+ ),
+ ),
+ ("step_index", models.IntegerField()),
+ ("selector", models.TextField()),
+ ("old_match_count", models.BigIntegerField()),
+ ("new_match_count", models.BigIntegerField()),
+ ("measured_at", models.DateTimeField()),
+ ("created_at", models.DateTimeField(auto_now_add=True)),
+ (
+ "action",
+ models.ForeignKey(
+ on_delete=django.db.models.deletion.CASCADE,
+ related_name="selector_match_changes",
+ to="actions.action",
+ ),
+ ),
+ (
+ "team",
+ models.ForeignKey(
+ db_constraint=False,
+ on_delete=django.db.models.deletion.CASCADE,
+ related_name="+",
+ to="posthog.team",
+ ),
+ ),
+ ],
+ options={
+ "constraints": [
+ models.UniqueConstraint(
+ fields=("action", "step_index"),
+ name="unique_selector_match_change_per_step",
+ )
+ ],
+ },
+ ),
+ ]
diff --git a/products/actions/backend/migrations/max_migration.txt b/products/actions/backend/migrations/max_migration.txt
index 0da63b992d0e..8c6467c1f4d5 100644
--- a/products/actions/backend/migrations/max_migration.txt
+++ b/products/actions/backend/migrations/max_migration.txt
@@ -1 +1 @@
-0002_alter_action_created_by_alter_action_events_and_more
+0003_actionselectormatchchange
diff --git a/products/actions/backend/models/__init__.py b/products/actions/backend/models/__init__.py
index a182089a39ec..8f3d799bf6fa 100644
--- a/products/actions/backend/models/__init__.py
+++ b/products/actions/backend/models/__init__.py
@@ -1,8 +1,10 @@
from .action import Action, ActionStepJSON
from .action_step import ActionStep
+from .selector_match_change import ActionSelectorMatchChange
__all__ = [
"Action",
+ "ActionSelectorMatchChange",
"ActionStep",
"ActionStepJSON",
]
diff --git a/products/actions/backend/models/selector_match_change.py b/products/actions/backend/models/selector_match_change.py
new file mode 100644
index 000000000000..58ccc24a0ce4
--- /dev/null
+++ b/products/actions/backend/models/selector_match_change.py
@@ -0,0 +1,46 @@
+from typing import TYPE_CHECKING
+
+from django.db import models
+
+from posthog.models.scoping.root_mixin import TeamScopedRootMixin
+
+if TYPE_CHECKING:
+ from products.actions.backend.models.action import Action
+
+
+class ActionSelectorMatchChange(TeamScopedRootMixin):
+ """Classified by counting real `$autocapture` traffic under both compilers, so it cannot be
+ derived from the selector text or recomputed while serving a request.
+ `manage.py import_selector_match_changes` writes these rows; the action API reads them.
+ """
+
+ # Targets a hot table, so the FK carries no database constraint: creating one
+ # locks posthog_team against every write while it is taken. Django still
+ # cascades, because it collects related rows itself when deleting a team.
+ team = models.ForeignKey("posthog.Team", on_delete=models.CASCADE, db_constraint=False, related_name="+")
+ action = models.ForeignKey(
+ "actions.Action",
+ on_delete=models.CASCADE,
+ related_name="selector_match_changes",
+ )
+ step_index = models.IntegerField()
+ selector = models.TextField()
+ old_match_count = models.BigIntegerField()
+ new_match_count = models.BigIntegerField()
+ measured_at = models.DateTimeField()
+ created_at = models.DateTimeField(auto_now_add=True)
+
+ class Meta:
+ constraints = [
+ models.UniqueConstraint(fields=["action", "step_index"], name="unique_selector_match_change_per_step")
+ ]
+
+ def describes(self, action: "Action") -> bool:
+ """Whether the measured selector is still the one at that step. A step edited since
+ the measurement is a different selector, and these counts say nothing about it."""
+ if self.step_index >= len(action.steps):
+ return False
+ return (action.steps[self.step_index].selector or "").strip() == self.selector
+
+ def __str__(self) -> str:
+ return f"action {self.action_id} step {self.step_index}"
diff --git a/products/actions/frontend/generated/api.schemas.ts b/products/actions/frontend/generated/api.schemas.ts
index 46552382d142..e910a8ed5904 100644
--- a/products/actions/frontend/generated/api.schemas.ts
+++ b/products/actions/frontend/generated/api.schemas.ts
@@ -718,6 +718,18 @@ export interface BulkUpdateTagsResponseApi {
skipped: BulkUpdateTagsErrorApi[]
}
+export interface ActionSelectorMatchChangeApi {
+ /** ID of an affected action. */
+ action_id: number
+ /**
+ * Name of the affected action, or null when it has no name.
+ * @nullable
+ */
+ action_name: string | null
+ /** CSS selectors whose matching behavior changed, in action step order. */
+ selectors: string[]
+}
+
export type ActionsListParams = {
/**
* Comma-separated list of creator user ids. Returns only actions created by these users.
@@ -830,3 +842,19 @@ export const ActionsBulkUpdateTagsCreateFormat = {
Csv: 'csv',
Json: 'json',
} as const
+
+export type ActionsSelectorMatchChangesListParams = {
+ /**
+ * Action IDs used by the insight. Accepts repeated or comma-separated values.
+ */
+ action_ids: number[]
+ format?: ActionsSelectorMatchChangesListFormat
+}
+
+export type ActionsSelectorMatchChangesListFormat =
+ (typeof ActionsSelectorMatchChangesListFormat)[keyof typeof ActionsSelectorMatchChangesListFormat]
+
+export const ActionsSelectorMatchChangesListFormat = {
+ Csv: 'csv',
+ Json: 'json',
+} as const
diff --git a/products/actions/frontend/generated/api.ts b/products/actions/frontend/generated/api.ts
index aba455bf70a8..299ccf269997 100644
--- a/products/actions/frontend/generated/api.ts
+++ b/products/actions/frontend/generated/api.ts
@@ -11,6 +11,7 @@ import { apiMutator } from '../../../../frontend/src/lib/api-orval-mutator'
import type {
ActionApi,
ActionReferenceApi,
+ ActionSelectorMatchChangeApi,
ActionsBulkUpdateTagsCreateParams,
ActionsCreateParams,
ActionsDestroyParams,
@@ -18,6 +19,7 @@ import type {
ActionsPartialUpdateParams,
ActionsReferencesListParams,
ActionsRetrieveParams,
+ ActionsSelectorMatchChangesListParams,
ActionsUpdateParams,
BulkUpdateTagsRequestApi,
BulkUpdateTagsResponseApi,
@@ -296,3 +298,33 @@ export const actionsBulkUpdateTagsCreate = async (
body: JSON.stringify(bulkUpdateTagsRequestApi),
})
}
+
+export const getActionsSelectorMatchChangesListUrl = (
+ projectId: string,
+ params: ActionsSelectorMatchChangesListParams
+) => {
+ const normalizedParams = new URLSearchParams()
+
+ Object.entries(params || {}).forEach(([key, value]) => {
+ if (value !== undefined) {
+ normalizedParams.append(key, value === null ? 'null' : String(value))
+ }
+ })
+
+ const stringifiedParams = normalizedParams.toString()
+
+ return stringifiedParams.length > 0
+ ? `/api/projects/${projectId}/actions/selector_match_changes/?${stringifiedParams}`
+ : `/api/projects/${projectId}/actions/selector_match_changes/`
+}
+
+export const actionsSelectorMatchChangesList = async (
+ projectId: string,
+ params: ActionsSelectorMatchChangesListParams,
+ options?: RequestInit
+): Promise<ActionSelectorMatchChangeApi[]> => {
+ return apiMutator<ActionSelectorMatchChangeApi[]>(getActionsSelectorMatchChangesListUrl(projectId, params), {
+ ...options,
+ method: 'GET',
+ })
+}
diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.ts
index ef9e2983ed1b..93aa3295b571 100644
--- a/services/mcp/src/api/generated.ts
+++ b/services/mcp/src/api/generated.ts
@@ -4226,6 +4226,18 @@ export namespace Schemas {
created_by: UserBasic | null;
}
+ export interface ActionSelectorMatchChange {
+ /** ID of an affected action. */
+ action_id: number;
+ /**
+ * Name of the affected action, or null when it has no name.
+ * @nullable
+ */
+ action_name: string | null;
+ /** CSS selectors whose matching behavior changed, in action step order. */
+ selectors: string[];
+ }
+
/**
* * `immediately_actionable` - immediately_actionable
* * `requires_human_input` - requires_human_input
@@ -114956,6 +114968,22 @@ export namespace Schemas {
Json: 'json',
} as const;
+ export type ActionsSelectorMatchChangesListParams = {
+ /**
+ * Action IDs used by the insight. Accepts repeated or comma-separated values.
+ */
+ action_ids: number[];
+ format?: ActionsSelectorMatchChangesListFormat;
+ };
+
+ export type ActionsSelectorMatchChangesListFormat = typeof ActionsSelectorMatchChangesListFormat[keyof typeof ActionsSelectorMatchChangesListFormat];
+
+
+ export const ActionsSelectorMatchChangesListFormat = {
+ Csv: 'csv',
+ Json: 'json',
+ } as const;
+
export type ActivityLogListParams = {
/**
* Filter by the ID of the affected resource.