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(web-analytics): AI path-cleaning suggestions (#77653)

Lucas Ricoy27a7624f5133
diff --git a/frontend/src/lib/agentScopes.generated.ts b/frontend/src/lib/agentScopes.generated.ts
index 162225b28e30..ae0ae408c124 100644
--- a/frontend/src/lib/agentScopes.generated.ts
+++ b/frontend/src/lib/agentScopes.generated.ts
@@ -140,4 +140,5 @@ export const AGENT_USE_CASE_SCOPES = [
'warehouse_view:read',
'warehouse_view:write',
'web_analytics:read',
+ 'web_analytics:write',
] as const
diff --git a/frontend/src/lib/constants.tsx b/frontend/src/lib/constants.tsx
index 6767bd78afec..5f4d752983b3 100644
--- a/frontend/src/lib/constants.tsx
+++ b/frontend/src/lib/constants.tsx
@@ -245,6 +245,7 @@ export const FEATURE_FLAGS = {
TRACK_REACT_FRAMERATE: 'track-react-framerate', // owner: @pauldambra #team-replay
WEB_ANALYTICS_API: 'web-analytics-api', // owner: #team-web-analytics
WEB_ANALYTICS_FOR_MOBILE: 'web-analytics-for-mobile', // owner: #team-web-analytics
+ WEB_ANALYTICS_PATH_CLEANING_SUGGESTIONS: 'web-analytics-path-cleaning-suggestions', // owner: @lricoy #team-web-analytics
WEB_ANALYTICS_REFERRER_URL_DRILLDOWN: 'web-analytics-referrer-url-drilldown', // owner: @jabahamondes #team-web-analytics
// Temporary feature flags, still WIP, should be removed eventually
diff --git a/frontend/src/scenes/health/components/WebAnalyticsHealthTable.tsx b/frontend/src/scenes/health/components/WebAnalyticsHealthTable.tsx
index 595e4eadb5dc..64da30c18872 100644
--- a/frontend/src/scenes/health/components/WebAnalyticsHealthTable.tsx
+++ b/frontend/src/scenes/health/components/WebAnalyticsHealthTable.tsx
@@ -47,6 +47,13 @@ const CHECK_META: Record<string, CheckMeta> = {
'Core Web Vitals (LCP, INP, CLS) measure real user experience. Google uses these metrics for search ranking.',
docsUrl: 'https://posthog.com/docs/web-analytics/web-vitals',
},
+ path_cleaning_suggestions: {
+ title: 'Path cleaning',
+ description:
+ 'AI-suggested path cleaning rules are ready to review. Applying them groups similar pages (like /users/123 and /users/456) in your breakdowns.',
+ docsUrl: urls.settings('environment-product-analytics', 'path-cleaning'),
+ linkLabel: 'Review suggestions',
+ },
}
export function WebAnalyticsHealthTable({
diff --git a/frontend/src/scenes/health/healthCategories.tsx b/frontend/src/scenes/health/healthCategories.tsx
index 9b1bf0a3c0aa..35dac7361e92 100644
--- a/frontend/src/scenes/health/healthCategories.tsx
+++ b/frontend/src/scenes/health/healthCategories.tsx
@@ -17,6 +17,7 @@ export type HealthIssueKind =
| 'reverse_proxy'
| 'partial_proxy'
| 'web_vitals'
+ | 'path_cleaning_suggestions'
| 'ingestion_lag'
| 'ingestion_warning'
| 'sdk_outdated'
@@ -108,6 +109,7 @@ const KIND_TO_CATEGORY: Record<HealthIssueKind, HealthIssueCategory> = {
reverse_proxy: 'web_analytics',
partial_proxy: 'web_analytics',
web_vitals: 'web_analytics',
+ path_cleaning_suggestions: 'web_analytics',
}
export const KIND_LABELS: Record<HealthIssueKind, string> = {
@@ -118,6 +120,7 @@ export const KIND_LABELS: Record<HealthIssueKind, string> = {
reverse_proxy: 'No reverse proxy',
partial_proxy: 'Partial reverse proxy',
web_vitals: 'No web vitals',
+ path_cleaning_suggestions: 'Path cleaning suggestions',
ingestion_lag: 'Ingestion lag',
external_data_failure: 'External data failures',
ingestion_warning: 'Ingestion warning',
diff --git a/frontend/src/scenes/health/issueRenderers.tsx b/frontend/src/scenes/health/issueRenderers.tsx
index 917704ac9851..a3534b9598a6 100644
--- a/frontend/src/scenes/health/issueRenderers.tsx
+++ b/frontend/src/scenes/health/issueRenderers.tsx
@@ -1,6 +1,10 @@
import { ComponentType } from 'react'
+import { IconArrowRight } from '@posthog/icons'
+import { Link } from '@posthog/lemon-ui'
+
import { TZLabel } from 'lib/components/TZLabel'
+import { urls } from 'scenes/urls'
import { GenericIssueRenderer } from './renderers/GenericIssueRenderer'
import { SdkOutdatedRenderer } from './renderers/SdkOutdatedRenderer'
@@ -60,11 +64,37 @@ const PipelineFailureRenderer = ({ issue }: { issue: HealthIssue }): JSX.Element
)
}
+const PathCleaningSuggestionsRenderer = ({ issue }: { issue: HealthIssue }): JSX.Element => {
+ const rules: { regex?: string; alias?: string; match_count?: number }[] = issue.payload.rules ?? []
+ const sampledCount = issue.payload.sampled_path_count
+ return (
+ <div className="text-xs bg-surface-secondary rounded p-2 mt-1 space-y-1">
+ {rules.map((rule, index) => (
+ <div key={index} className="flex flex-wrap items-center gap-2 font-mono">
+ <code className="bg-fill-primary px-1 rounded">{rule.regex}</code>
+ <IconArrowRight />
+ <code className="bg-fill-primary px-1 rounded">{rule.alias}</code>
+ {rule.match_count != null && (
+ <span className="text-muted font-sans">
+ groups {rule.match_count}
+ {sampledCount ? ` of your top ${sampledCount}` : ''} paths
+ </span>
+ )}
+ </div>
+ ))}
+ <Link to={urls.settings('environment-product-analytics', 'path-cleaning')} className="font-medium">
+ Review and apply in settings
+ </Link>
+ </div>
+ )
+}
+
const HEALTH_ISSUE_RENDERERS: Record<string, ComponentType<{ issue: HealthIssue }>> = {
sdk_outdated: SdkOutdatedRenderer,
ingestion_warning: IngestionWarningRenderer,
external_data_failure: PipelineFailureRenderer,
materialized_view_failure: PipelineFailureRenderer,
+ path_cleaning_suggestions: PathCleaningSuggestionsRenderer,
}
export const getIssueRenderer = (kind: string): ComponentType<{ issue: HealthIssue }> => {
diff --git a/frontend/src/scenes/onboarding/legacy/onboardingLogic.test.ts b/frontend/src/scenes/onboarding/legacy/onboardingLogic.test.ts
index a458f0d25e33..a439cc219ad0 100644
--- a/frontend/src/scenes/onboarding/legacy/onboardingLogic.test.ts
+++ b/frontend/src/scenes/onboarding/legacy/onboardingLogic.test.ts
@@ -103,6 +103,16 @@ describe('onboardingLogic — flow composition', () => {
expect(logic.values.flow).toEqual([])
expect(logic.values.currentFlowStep).toBeNull()
})
+
+ it('includes the web analytics path cleaning step only when its flag is enabled', () => {
+ featureFlagLogic
+ .findMounted()
+ ?.actions.setFeatureFlags([FEATURE_FLAGS.WEB_ANALYTICS_PATH_CLEANING_SUGGESTIONS], {
+ [FEATURE_FLAGS.WEB_ANALYTICS_PATH_CLEANING_SUGGESTIONS]: true,
+ })
+ logic.actions.setProductKey(ProductKey.WEB_ANALYTICS)
+ expect(flowIds()).toContain('path_cleaning:web_analytics')
+ })
})
describe('install-step dedup — POSTHOG_JS', () => {
diff --git a/frontend/src/scenes/onboarding/legacy/onboardingLogic.tsx b/frontend/src/scenes/onboarding/legacy/onboardingLogic.tsx
index 9b6221248643..c40dbecf54ab 100644
--- a/frontend/src/scenes/onboarding/legacy/onboardingLogic.tsx
+++ b/frontend/src/scenes/onboarding/legacy/onboardingLogic.tsx
@@ -195,7 +195,8 @@ export interface onboardingLogicMeta {
shouldShowBillingStep: boolean,
isCloudOrDev: boolean | undefined,
subscribedDuringOnboarding: boolean,
- canInviteTeammates: boolean
+ canInviteTeammates: boolean,
+ featureFlags: FeatureFlagsSet
) => OnboardingStepDescriptor[]
onboardingStepKeys: (flow: OnboardingStepDescriptor[]) => OnboardingStepKey[]
currentFlowStep: (flow: OnboardingStepDescriptor[], stepId: string) => OnboardingStepDescriptor | null
@@ -420,6 +421,7 @@ export const onboardingLogic = kea<onboardingLogicType>([
s.isCloudOrDev,
s.subscribedDuringOnboarding,
s.canInviteTeammates,
+ s.featureFlags,
],
(
primary: ProductKey | null,
@@ -430,7 +432,8 @@ export const onboardingLogic = kea<onboardingLogicType>([
shouldShowBilling: boolean,
isCloudOrDev: boolean | undefined,
subscribedDuringOnboarding: boolean,
- canInviteTeammates: boolean
+ canInviteTeammates: boolean,
+ featureFlags: FeatureFlagsSet
): OnboardingStepDescriptor[] => {
if (!primary) {
return []
@@ -444,6 +447,7 @@ export const onboardingLogic = kea<onboardingLogicType>([
isCloudOrDev: Boolean(isCloudOrDev),
subscribedDuringOnboarding,
canInviteTeammates,
+ featureFlags,
}
const productSteps = orderedProducts.flatMap((p, i) => {
const provider = onboardingProviderRegistry[p]
diff --git a/frontend/src/scenes/onboarding/legacy/stepProviderRegistry.test.ts b/frontend/src/scenes/onboarding/legacy/stepProviderRegistry.test.ts
index 49aa36e573c4..0ce73b74910c 100644
--- a/frontend/src/scenes/onboarding/legacy/stepProviderRegistry.test.ts
+++ b/frontend/src/scenes/onboarding/legacy/stepProviderRegistry.test.ts
@@ -15,6 +15,7 @@ function context(primary: ProductKey): OnboardingFlowContext {
isCloudOrDev: true,
subscribedDuringOnboarding: false,
canInviteTeammates: true,
+ featureFlags: {},
}
}
diff --git a/frontend/src/scenes/onboarding/legacy/types.ts b/frontend/src/scenes/onboarding/legacy/types.ts
index 9cdd4c712c2c..94b430eae595 100644
--- a/frontend/src/scenes/onboarding/legacy/types.ts
+++ b/frontend/src/scenes/onboarding/legacy/types.ts
@@ -1,4 +1,5 @@
import { type SetupTaskId } from 'lib/components/ProductSetup'
+import { type FeatureFlagsSet } from 'lib/logic/featureFlagLogic'
import { ProductKey } from '~/queries/schema/schema-general'
import { type BillingType, OnboardingStepKey, type TeamPublicType, type TeamType } from '~/types'
@@ -63,6 +64,12 @@ export interface OnboardingFlowContext {
subscribedDuringOnboarding: boolean
/** Members can invite teammates — drives the trailing invite step. */
canInviteTeammates: boolean
+ /**
+ * Current feature flags, threaded through the flow selector so flag-gated steps
+ * recompute when flags are delivered — providers must read flags from here, not
+ * via `featureFlagLogic.findMounted()` (an imperative read never re-fires the flow).
+ */
+ featureFlags: FeatureFlagsSet
}
export type StepProvider = (ctx: OnboardingFlowContext) => OnboardingStepDescriptor[]
diff --git a/frontend/src/scenes/onboarding/legacy/web-analytics/OnboardingWebAnalyticsPathCleaningStep.tsx b/frontend/src/scenes/onboarding/legacy/web-analytics/OnboardingWebAnalyticsPathCleaningStep.tsx
new file mode 100644
index 000000000000..361419571294
--- /dev/null
+++ b/frontend/src/scenes/onboarding/legacy/web-analytics/OnboardingWebAnalyticsPathCleaningStep.tsx
@@ -0,0 +1,37 @@
+import { useValues } from 'kea'
+
+import { PathCleaningSuggestionsBanner } from 'scenes/settings/environment/PathCleaningSuggestionsBanner'
+import { pathCleaningSuggestionsLogic } from 'scenes/settings/environment/pathCleaningSuggestionsLogic'
+
+import { OnboardingStepKey } from '~/types'
+
+import { OnboardingStepComponentType } from '../onboardingLogic'
+import { OnboardingStep } from '../OnboardingStep'
+
+export const OnboardingWebAnalyticsPathCleaningStep: OnboardingStepComponentType = () => {
+ const { latestSuggestion, suggestionsLoading } = useValues(pathCleaningSuggestionsLogic)
+
+ return (
+ <OnboardingStep title="Clean up your paths" stepKey={OnboardingStepKey.PATH_CLEANING} showSkip>
+ <p>
+ When your site has dynamic URLs like <code>/users/123</code> and <code>/users/456</code>, Web analytics
+ shows them as separate rows. Path cleaning rules collapse them into one readable template (
+ <code>/users/&lt;id&gt;</code>).
+ </p>
+ {latestSuggestion ? (
+ <>
+ <p>We analyzed your traffic and prepared a few rules for you:</p>
+ <PathCleaningSuggestionsBanner />
+ </>
+ ) : (
+ <p className="text-secondary">
+ {suggestionsLoading
+ ? 'Looking for path patterns in your traffic…'
+ : "Once we've seen enough traffic we'll suggest path cleaning rules here. You can always add them later in project settings."}
+ </p>
+ )}
+ </OnboardingStep>
+ )
+}
+
+OnboardingWebAnalyticsPathCleaningStep.stepKey = OnboardingStepKey.PATH_CLEANING
diff --git a/frontend/src/scenes/settings/environment/PathCleaningFiltersConfig.tsx b/frontend/src/scenes/settings/environment/PathCleaningFiltersConfig.tsx
index b3790aacd1b8..6eec292d3c38 100644
--- a/frontend/src/scenes/settings/environment/PathCleaningFiltersConfig.tsx
+++ b/frontend/src/scenes/settings/environment/PathCleaningFiltersConfig.tsx
@@ -11,6 +11,7 @@ import { PathCleaningRulesDebugger } from 'lib/components/PathCleanFilters/PathC
import { RestrictionScope, useRestrictedArea } from 'lib/components/RestrictedArea'
import { TeamMembershipLevel } from 'lib/constants'
import { isValidRegexp } from 'lib/utils/regexp'
+import { PathCleaningSuggestionsBanner } from 'scenes/settings/environment/PathCleaningSuggestionsBanner'
import { teamLogic } from 'scenes/teamLogic'
import { userLogic } from 'scenes/userLogic'
@@ -72,6 +73,7 @@ export function PathCleaningFiltersConfig(): JSX.Element | null {
return (
<>
+ <PathCleaningSuggestionsBanner />
<div className="flex flex-col gap-4">
<PathCleanFiltersTable filters={currentTeam.path_cleaning_filters || []} setFilters={updateFilters} />
<div>
diff --git a/frontend/src/scenes/settings/environment/PathCleaningSuggestionsBanner.tsx b/frontend/src/scenes/settings/environment/PathCleaningSuggestionsBanner.tsx
new file mode 100644
index 000000000000..f0a426a5d732
--- /dev/null
+++ b/frontend/src/scenes/settings/environment/PathCleaningSuggestionsBanner.tsx
@@ -0,0 +1,137 @@
+import { useActions, useValues } from 'kea'
+
+import { IconArrowRight } from '@posthog/icons'
+import { LemonBanner, LemonButton, LemonModal, Spinner } from '@posthog/lemon-ui'
+
+import { RestrictionScope, useRestrictedArea } from 'lib/components/RestrictedArea'
+import { TeamMembershipLevel } from 'lib/constants'
+import { useFeatureFlag } from 'lib/hooks/useFeatureFlag'
+import { humanFriendlyLargeNumber } from 'lib/utils/numbers'
+
+import { pathCleaningSuggestionsLogic } from './pathCleaningSuggestionsLogic'
+
+function PathCleaningPreviewModal({
+ suggestionId,
+ restrictedReason,
+}: {
+ suggestionId: string
+ restrictedReason: string | null
+}): JSX.Element {
+ const { previewOpen, preview, previewLoading, applying } = useValues(pathCleaningSuggestionsLogic)
+ const { closePreview, applySuggestion } = useActions(pathCleaningSuggestionsLogic)
+
+ return (
+ <LemonModal
+ isOpen={previewOpen}
+ onClose={closePreview}
+ title="Preview on your real paths"
+ description="Your most-viewed paths from the last 30 days, with all suggested rules applied in order. Nothing changes until you apply."
+ width={720}
+ footer={
+ <>
+ <LemonButton type="secondary" onClick={closePreview}>
+ Close
+ </LemonButton>
+ <LemonButton
+ type="primary"
+ onClick={() => applySuggestion(suggestionId)}
+ disabledReason={restrictedReason}
+ loading={applying}
+ >
+ Apply all
+ </LemonButton>
+ </>
+ }
+ >
+ {previewLoading || !preview ? (
+ <div className="flex items-center justify-center py-8">
+ <Spinner className="text-2xl" />
+ </div>
+ ) : (
+ <div className="flex flex-col gap-2">
+ <span className="text-secondary">
+ These rules group <strong>{preview.changed_path_count}</strong> of your top{' '}
+ <strong>{preview.sampled_path_count}</strong> paths
+ {preview.changed_path_count > preview.examples.length
+ ? ` — showing the first ${preview.examples.length}`
+ : ''}
+ .
+ </span>
+ <div className="flex flex-col gap-1 max-h-[30rem] overflow-y-auto">
+ {preview.examples.map((example) => (
+ <div
+ key={example.before}
+ className="flex flex-wrap items-center gap-2 font-mono text-xs border rounded p-2"
+ >
+ <code>{example.before}</code>
+ <IconArrowRight />
+ <code className="font-semibold">{example.after}</code>
+ <span className="text-secondary ml-auto font-sans">
+ {humanFriendlyLargeNumber(example.views)} views
+ </span>
+ </div>
+ ))}
+ </div>
+ </div>
+ )}
+ </LemonModal>
+ )
+}
+
+export function PathCleaningSuggestionsBanner(): JSX.Element | null {
+ const flagEnabled = useFeatureFlag('WEB_ANALYTICS_PATH_CLEANING_SUGGESTIONS')
+ const { latestSuggestion, suggestionsLoading, applying } = useValues(pathCleaningSuggestionsLogic)
+ const { applySuggestion, dismissSuggestion, openPreview } = useActions(pathCleaningSuggestionsLogic)
+ // Applying writes path_cleaning_filters, an admin-gated team field — mirror the backend gate.
+ const restrictedReason = useRestrictedArea({
+ scope: RestrictionScope.Project,
+ minimumAccessLevel: TeamMembershipLevel.Admin,
+ })
+
+ if (!flagEnabled || suggestionsLoading || !latestSuggestion || latestSuggestion.rules.length === 0) {
+ return null
+ }
+
+ const ruleCount = latestSuggestion.rules.length
+
+ return (
+ <>
+ <LemonBanner
+ type="info"
+ className="mb-4"
+ action={{
+ children: 'Apply all',
+ onClick: () => applySuggestion(latestSuggestion.id),
+ disabledReason: restrictedReason,
+ loading: applying,
+ }}
+ onClose={() => dismissSuggestion(latestSuggestion.id)}
+ >
+ <div className="flex flex-col gap-2">
+ <span>
+ We analyzed your traffic and suggest <strong>{ruleCount}</strong> path cleaning{' '}
+ {ruleCount === 1 ? 'rule' : 'rules'} to group similar pages. Review and apply them:
+ </span>
+ <div className="flex flex-col gap-1">
+ {latestSuggestion.rules.map((rule) => (
+ <div key={rule.order} className="flex flex-wrap items-center gap-2 font-mono text-xs">
+ <code>{rule.regex}</code>
+ <IconArrowRight />
+ <code>{rule.alias}</code>
+ <span className="text-secondary">
+ groups {rule.match_count} of your top {latestSuggestion.sampled_path_count} paths
+ </span>
+ </div>
+ ))}
+ </div>
+ <div>
+ <LemonButton type="secondary" size="xsmall" onClick={() => openPreview(latestSuggestion.id)}>
+ Preview on your paths
+ </LemonButton>
+ </div>
+ </div>
+ </LemonBanner>
+ <PathCleaningPreviewModal suggestionId={latestSuggestion.id} restrictedReason={restrictedReason} />
+ </>
+ )
+}
diff --git a/frontend/src/scenes/settings/environment/pathCleaningSuggestionsLogic.ts b/frontend/src/scenes/settings/environment/pathCleaningSuggestionsLogic.ts
new file mode 100644
index 000000000000..42b42d1a934d
--- /dev/null
+++ b/frontend/src/scenes/settings/environment/pathCleaningSuggestionsLogic.ts
@@ -0,0 +1,306 @@
+import { MakeLogicType, actions, afterMount, connect, kea, listeners, path, reducers, selectors } from 'kea'
+import { loaders } from 'kea-loaders'
+import { subscriptions } from 'kea-subscriptions'
+
+import { lemonToast } from '@posthog/lemon-ui'
+
+import api from 'lib/api'
+import { teamLogic } from 'scenes/teamLogic'
+
+import {
+ webAnalyticsPathCleaningSuggestionsApply,
+ webAnalyticsPathCleaningSuggestionsPreview,
+} from 'products/web_analytics/frontend/generated/api'
+import type {
+ PathCleaningSuggestionIssueApi,
+ PreviewPathCleaningSuggestionResponseApi,
+} from 'products/web_analytics/frontend/generated/api.schemas'
+
+export const PATH_CLEANING_SUGGESTIONS_KIND = 'path_cleaning_suggestions'
+
+interface HealthIssueRecord {
+ id: string
+ created_at: string
+ payload: Record<string, any>
+}
+
+const toSuggestion = (issue: HealthIssueRecord): PathCleaningSuggestionIssueApi => ({
+ id: issue.id,
+ created_at: issue.created_at,
+ rules: issue.payload?.rules ?? [],
+ model: issue.payload?.model ?? '',
+ sampled_path_count: issue.payload?.sampled_path_count ?? 0,
+ distinct_path_count: issue.payload?.distinct_path_count ?? 0,
+})
+
+// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
+export interface pathCleaningSuggestionsLogicValues {
+ currentTeamId: number | null // teamLogic
+ applying: boolean
+ handledIds: string[]
+ latestSuggestion: PathCleaningSuggestionIssueApi | null
+ preview: PreviewPathCleaningSuggestionResponseApi | null
+ previewLoading: boolean
+ previewOpen: boolean
+ suggestions: PathCleaningSuggestionIssueApi[]
+ suggestionsLoading: boolean
+}
+
+// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
+export interface pathCleaningSuggestionsLogicActions {
+ loadCurrentTeam: () => any // teamLogic
+ applySuggestion: (id: string) => {
+ id: string
+ }
+ applySuggestionFinished: () => {
+ value: true
+ }
+ closePreview: () => {
+ value: true
+ }
+ closePreviewFailure: (
+ error: string,
+ errorObject?: any
+ ) => {
+ error: string
+ errorObject?: any
+ }
+ closePreviewSuccess: (
+ preview: null,
+ payload?: {
+ value: true
+ }
+ ) => {
+ preview: null
+ payload?: {
+ value: true
+ }
+ }
+ dismissSuggestion: (id: string) => {
+ id: string
+ }
+ loadPreview: ({ id }: { id: string }) => {
+ id: string
+ }
+ loadPreviewFailure: (
+ error: string,
+ errorObject?: any
+ ) => {
+ error: string
+ errorObject?: any
+ }
+ loadPreviewSuccess: (
+ preview: PreviewPathCleaningSuggestionResponseApi | null,
+ payload?: {
+ id: string
+ }
+ ) => {
+ preview: PreviewPathCleaningSuggestionResponseApi | null
+ payload?: {
+ id: string
+ }
+ }
+ loadSuggestions: () => any
+ loadSuggestionsFailure: (
+ error: string,
+ errorObject?: any
+ ) => {
+ error: string
+ errorObject?: any
+ }
+ loadSuggestionsSuccess: (
+ suggestions: PathCleaningSuggestionIssueApi[],
+ payload?: any
+ ) => {
+ suggestions: PathCleaningSuggestionIssueApi[]
+ payload?: any
+ }
+ openPreview: (id: string) => {
+ id: string
+ }
+ resetForTeamChange: () => {
+ value: true
+ }
+ resetForTeamChangeFailure: (
+ error: string,
+ errorObject?: any
+ ) => {
+ error: string
+ errorObject?: any
+ }
+ resetForTeamChangeSuccess: (
+ preview: null,
+ payload?: {
+ value: true
+ }
+ ) => {
+ preview: null
+ payload?: {
+ value: true
+ }
+ }
+ unhandleSuggestion: (id: string) => {
+ id: string
+ }
+}
+
+// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
+export interface pathCleaningSuggestionsLogicMeta {
+ __keaTypeGenInternalSelectorTypes: {
+ latestSuggestion: (
+ suggestions: PathCleaningSuggestionIssueApi[],
+ handledIds: string[]
+ ) => PathCleaningSuggestionIssueApi | null
+ }
+}
+
+export type pathCleaningSuggestionsLogicType = MakeLogicType<
+ pathCleaningSuggestionsLogicValues,
+ pathCleaningSuggestionsLogicActions,
+ Record<string, any>,
+ pathCleaningSuggestionsLogicMeta
+>
+
+export const pathCleaningSuggestionsLogic = kea<pathCleaningSuggestionsLogicType>([
+ path(['scenes', 'settings', 'environment', 'pathCleaningSuggestionsLogic']),
+ connect(() => ({
+ values: [teamLogic, ['currentTeamId']],
+ actions: [teamLogic, ['loadCurrentTeam']],
+ })),
+ actions({
+ applySuggestion: (id: string) => ({ id }),
+ dismissSuggestion: (id: string) => ({ id }),
+ unhandleSuggestion: (id: string) => ({ id }),
+ openPreview: (id: string) => ({ id }),
+ closePreview: true,
+ resetForTeamChange: true,
+ applySuggestionFinished: true,
+ }),
+ loaders(({ values }) => ({
+ preview: [
+ null as PreviewPathCleaningSuggestionResponseApi | null,
+ {
+ loadPreview: async ({ id }: { id: string }) => {
+ if (!values.currentTeamId) {
+ return null
+ }
+ return await webAnalyticsPathCleaningSuggestionsPreview(String(values.currentTeamId), id)
+ },
+ closePreview: () => null,
+ resetForTeamChange: () => null,
+ },
+ ],
+ suggestions: [
+ [] as PathCleaningSuggestionIssueApi[],
+ {
+ loadSuggestions: async () => {
+ if (!values.currentTeamId) {
+ return []
+ }
+ // Suggestions are stored as health issues; the newest active, non-dismissed one is
+ // the actionable suggestion.
+ const response = await api.get<{ results: HealthIssueRecord[] }>(
+ `api/projects/${values.currentTeamId}/health_issues/?kind=${PATH_CLEANING_SUGGESTIONS_KIND}&status=active&dismissed=false`
+ )
+ return response.results.map(toSuggestion)
+ },
+ resetForTeamChange: () => [],
+ },
+ ],
+ })),
+ reducers({
+ // Optimistically hide a suggestion the moment it's applied or dismissed.
+ handledIds: [
+ [] as string[],
+ {
+ applySuggestion: (state, { id }) => [...state, id],
+ dismissSuggestion: (state, { id }) => [...state, id],
+ unhandleSuggestion: (state, { id }) => state.filter((handledId) => handledId !== id),
+ resetForTeamChange: () => [],
+ },
+ ],
+ // In-flight guard: both Apply buttons disable while the POST is running.
+ applying: [
+ false,
+ {
+ applySuggestion: () => true,
+ applySuggestionFinished: () => false,
+ resetForTeamChange: () => false,
+ },
+ ],
+ previewOpen: [
+ false,
+ {
+ openPreview: () => true,
+ closePreview: () => false,
+ // Applying or dismissing from the modal is a terminal action for the suggestion.
+ applySuggestion: () => false,
+ dismissSuggestion: () => false,
+ resetForTeamChange: () => false,
+ },
+ ],
+ }),
+ selectors({
+ latestSuggestion: [
+ (s) => [s.suggestions, s.handledIds],
+ (
+ suggestions: PathCleaningSuggestionIssueApi[],
+ handledIds: string[]
+ ): PathCleaningSuggestionIssueApi | null =>
+ suggestions.find((suggestion) => !handledIds.includes(suggestion.id)) ?? null,
+ ],
+ }),
+ listeners(({ values, actions }) => ({
+ openPreview: async ({ id }) => {
+ actions.loadPreview({ id })
+ },
+ loadPreviewFailure: () => {
+ actions.closePreview()
+ lemonToast.error('Could not load the preview. Please try again.')
+ },
+ applySuggestion: async ({ id }) => {
+ if (!values.currentTeamId) {
+ actions.applySuggestionFinished()
+ return
+ }
+ try {
+ const result = await webAnalyticsPathCleaningSuggestionsApply(String(values.currentTeamId), id)
+ lemonToast.success(`Applied ${result.applied} path cleaning rule${result.applied === 1 ? '' : 's'}`)
+ // Refresh the team so the rules table reflects the merged path_cleaning_filters.
+ actions.loadCurrentTeam()
+ } catch {
+ // Roll back the optimistic hide and tell the user, so nothing is silently lost.
+ actions.unhandleSuggestion(id)
+ lemonToast.error('Could not apply the path cleaning suggestions. Please try again.')
+ } finally {
+ actions.applySuggestionFinished()
+ }
+ },
+ dismissSuggestion: async ({ id }) => {
+ if (!values.currentTeamId) {
+ return
+ }
+ try {
+ await api.update(`api/projects/${values.currentTeamId}/health_issues/${id}/`, { dismissed: true })
+ } catch {
+ actions.unhandleSuggestion(id)
+ lemonToast.error('Could not dismiss the suggestion. Please try again.')
+ }
+ },
+ })),
+ subscriptions(({ actions }) => ({
+ // The logic outlives project switches; a team change must drop the previous
+ // project's suggestion state so preview/apply can't target a stale issue id.
+ currentTeamId: (teamId: number | null, oldTeamId: number | null | undefined) => {
+ if (oldTeamId !== undefined && teamId !== oldTeamId) {
+ actions.resetForTeamChange()
+ if (teamId) {
+ actions.loadSuggestions()
+ }
+ }
+ },
+ })),
+ afterMount(({ actions }) => {
+ actions.loadSuggestions()
+ }),
+])
diff --git a/frontend/src/scenes/web-analytics/health/healthCheckTypes.ts b/frontend/src/scenes/web-analytics/health/healthCheckTypes.ts
index 032f40cd34c4..e06f468c3e87 100644
--- a/frontend/src/scenes/web-analytics/health/healthCheckTypes.ts
+++ b/frontend/src/scenes/web-analytics/health/healthCheckTypes.ts
@@ -35,6 +35,7 @@ export enum HealthCheckId {
AUTHORIZED_URLS = 'authorized_urls',
REVERSE_PROXY = 'reverse_proxy',
+ PATH_CLEANING_SUGGESTIONS = 'path_cleaning_suggestions',
WEB_VITALS = 'web_vitals',
}
diff --git a/frontend/src/scenes/web-analytics/health/webAnalyticsHealthLogic.ts b/frontend/src/scenes/web-analytics/health/webAnalyticsHealthLogic.ts
index 63b7ff71000a..cf265a0f8442 100644
--- a/frontend/src/scenes/web-analytics/health/webAnalyticsHealthLogic.ts
+++ b/frontend/src/scenes/web-analytics/health/webAnalyticsHealthLogic.ts
@@ -2,7 +2,10 @@ import { MakeLogicType, actions, afterMount, connect, kea, listeners, path, redu
import { loaders } from 'kea-loaders'
import api, { ApiError } from 'lib/api'
+import { FEATURE_FLAGS } from 'lib/constants'
import { lemonToast } from 'lib/lemon-ui/LemonToast/LemonToast'
+import { featureFlagLogic } from 'lib/logic/featureFlagLogic'
+import type { FeatureFlagsSet } from 'lib/logic/featureFlagLogic'
import { humanFriendlyDuration } from 'lib/utils/durations'
import { eventUsageLogic } from 'lib/utils/eventUsageLogic'
import type { HealthIssuesResponse } from 'scenes/health/healthSceneLogic'
@@ -112,6 +115,22 @@ const WEB_HEALTH_CHECKS: WebHealthCheckConfig[] = [
docsUrl: 'https://posthog.com/docs/advanced/proxy',
urgent: true,
},
+ {
+ id: HealthCheckId.PATH_CLEANING_SUGGESTIONS,
+ kind: 'path_cleaning_suggestions',
+ category: 'configuration',
+ title: 'Path cleaning',
+ passingDescription:
+ 'No pending path cleaning suggestions. Path cleaning rules group similar pages (like /users/123 and /users/456) in your breakdowns.',
+ failingDescription:
+ 'AI-suggested path cleaning rules are ready to review. Applying them groups similar pages (like /users/123 and /users/456) in your Paths and Web analytics breakdowns.',
+ passingAction: { label: 'Manage rules', to: urls.settings('environment-product-analytics', 'path-cleaning') },
+ failingAction: {
+ label: 'Review suggestions',
+ to: urls.settings('environment-product-analytics', 'path-cleaning'),
+ },
+ docsUrl: 'https://posthog.com/docs/product-analytics/paths#path-cleaning-rules',
+ },
{
id: HealthCheckId.WEB_VITALS,
kind: 'web_vitals',
@@ -131,6 +150,7 @@ const WEB_HEALTH_CHECKS: WebHealthCheckConfig[] = [
// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface webAnalyticsHealthLogicValues {
+ featureFlags: FeatureFlagsSet // featureFlagLogic
currentTeamIdStrict: number | string // teamLogic
activeIssuesByKind: Record<string, HealthIssue>
allChecks: HealthCheck[]
@@ -262,7 +282,8 @@ export interface webAnalyticsHealthLogicMeta {
allChecks: (
activeIssuesByKind: Record<string, HealthIssue>,
healthIssuesLoading: boolean,
- healthIssues: HealthIssuesResponse | null
+ healthIssues: HealthIssuesResponse | null,
+ featureFlags: FeatureFlagsSet
) => HealthCheck[]
checksByCategory: (allChecks: HealthCheck[]) => Record<HealthCheckCategory, HealthCheck[]>
overallHealthStatus: (allChecks: HealthCheck[]) => OverallHealthStatus
@@ -284,7 +305,7 @@ export const webAnalyticsHealthLogic = kea<webAnalyticsHealthLogicType>([
path(['scenes', 'web-analytics', 'health', 'webAnalyticsHealthLogic']),
connect(() => ({
- values: [teamLogic, ['currentTeamIdStrict']],
+ values: [teamLogic, ['currentTeamIdStrict'], featureFlagLogic, ['featureFlags']],
actions: [
eventUsageLogic,
[
@@ -357,13 +378,17 @@ export const webAnalyticsHealthLogic = kea<webAnalyticsHealthLogicType>([
],
allChecks: [
- (s) => [s.activeIssuesByKind, s.healthIssuesLoading, s.healthIssues],
+ (s) => [s.activeIssuesByKind, s.healthIssuesLoading, s.healthIssues, s.featureFlags],
(
activeIssuesByKind: Record<string, HealthIssue>,
loading: boolean,
- healthIssues: HealthIssuesResponse | null
+ healthIssues: HealthIssuesResponse | null,
+ featureFlags: FeatureFlagsSet
): HealthCheck[] => {
- return WEB_HEALTH_CHECKS.map((config) => {
+ const enabledChecks = featureFlags[FEATURE_FLAGS.WEB_ANALYTICS_PATH_CLEANING_SUGGESTIONS]
+ ? WEB_HEALTH_CHECKS
+ : WEB_HEALTH_CHECKS.filter((config) => config.kind !== 'path_cleaning_suggestions')
+ return enabledChecks.map((config) => {
// Show loading only on the first load (no data yet), like the rest of the health UI.
if (loading && !healthIssues) {
return {
diff --git a/frontend/src/types.ts b/frontend/src/types.ts
index 21bb0df5b2e4..7ea44a5e1614 100644
--- a/frontend/src/types.ts
+++ b/frontend/src/types.ts
@@ -7844,6 +7844,7 @@ export enum OnboardingStepKey {
AUTHORIZED_DOMAINS = 'authorized_domains',
SOURCE_MAPS = 'source_maps',
ALERTS = 'alerts',
+ PATH_CLEANING = 'path_cleaning',
}
// Managed viewset
diff --git a/posthog/llm/gateway_client.py b/posthog/llm/gateway_client.py
index 6544a2e0f7fe..a2509d5393c4 100644
--- a/posthog/llm/gateway_client.py
+++ b/posthog/llm/gateway_client.py
@@ -35,6 +35,7 @@ Product = Literal[
"conversations",
"warehouse_semantic_enrichment",
"warehouse_custom_source_builder",
+ "web_analytics",
"stamphog",
] # If you add a product here, make sure it's also in services/llm-gateway/src/llm_gateway/products/config.py
diff --git a/posthog/settings/web.py b/posthog/settings/web.py
index f08b0cc5705c..66c0ec291669 100644
--- a/posthog/settings/web.py
+++ b/posthog/settings/web.py
@@ -1249,6 +1249,25 @@ WEB_ANALYTICS_PRECOMPUTE_MAX_SHAPES_PER_TEAM: int = get_from_env(
"WEB_ANALYTICS_PRECOMPUTE_MAX_SHAPES_PER_TEAM", 1000, type_cast=int
)
+# Cohort the weekly AI path-cleaning-suggestion job runs for. Defaults to the precompute enrollment
+# list (the teams "selected to test out precomputed analytics tables") so the two cohorts track each
+# other unless explicitly overridden. Comma-separated env-var override, like the lists above.
+WEB_ANALYTICS_PATH_CLEANING_SUGGESTIONS_TEAM_IDS: list[int] = [
+ int(team_id)
+ for team_id in get_list(
+ get_from_env(
+ "WEB_ANALYTICS_PATH_CLEANING_SUGGESTIONS_TEAM_IDS",
+ ",".join(str(t) for t in WEB_ANALYTICS_LAZY_PRECOMPUTE_TEAM_IDS),
+ )
+ )
+]
+
+# Model the path-cleaning-suggestion job sends to the LLM gateway. Must be in the `web_analytics`
+# product allowlist in services/llm-gateway/src/llm_gateway/products/config.py.
+WEB_ANALYTICS_PATH_CLEANING_SUGGESTIONS_MODEL: str = get_from_env(
+ "WEB_ANALYTICS_PATH_CLEANING_SUGGESTIONS_MODEL", "claude-haiku-4-5"
+)
+
# Teams whose web analytics queries (overview, paths tile) skip the events↔sessions join
# when nothing in the query (property filters, conversion goal, test-account filters,
# sampling) constrains which sessions qualify. In that shape the join only multiplies
diff --git a/posthog/temporal/health_checks/registry.py b/posthog/temporal/health_checks/registry.py
index 8968513c363d..3f413f94d7a3 100644
--- a/posthog/temporal/health_checks/registry.py
+++ b/posthog/temporal/health_checks/registry.py
@@ -24,6 +24,7 @@ HEALTH_CHECK_MODULES = [
"products.web_analytics.backend.temporal.health_checks.reverse_proxy",
"products.web_analytics.backend.temporal.health_checks.partial_proxy",
"products.web_analytics.backend.temporal.health_checks.web_vitals",
+ "products.web_analytics.backend.temporal.health_checks.path_cleaning_suggestions",
"products.error_tracking.backend.temporal.health_checks.missing_source_maps",
]
diff --git a/products/posthog_ai/frontend/policy/toolPolicy.ts b/products/posthog_ai/frontend/policy/toolPolicy.ts
index a45ecbeb5ad6..da51c7c67414 100644
--- a/products/posthog_ai/frontend/policy/toolPolicy.ts
+++ b/products/posthog_ai/frontend/policy/toolPolicy.ts
@@ -59,6 +59,7 @@ const POSTHOG_DESTRUCTIVE_SUB_TOOLS = new Set([
'skill-archive',
'user-interview-topics-remove-interviewee',
'visual-review-runs-finalize-create',
+ 'web-analytics-path-cleaning-suggestions-apply',
'workflows-discard-draft',
'workflows-publish',
'workflows-restore-revision',
diff --git a/products/tasks/backend/constants.py b/products/tasks/backend/constants.py
index 42dac07e1bc9..c25c0406f526 100644
--- a/products/tasks/backend/constants.py
+++ b/products/tasks/backend/constants.py
@@ -164,6 +164,7 @@ POSTHOG_EXEC_DESTRUCTIVE_SUB_TOOLS: tuple[str, ...] = (
"skill-archive",
"user-interview-topics-remove-interviewee",
"visual-review-runs-finalize-create",
+ "web-analytics-path-cleaning-suggestions-apply",
"workflows-discard-draft",
"workflows-publish",
"workflows-restore-revision",
diff --git a/products/web_analytics/backend/api/web_analytics_path_cleaning_suggestions.py b/products/web_analytics/backend/api/web_analytics_path_cleaning_suggestions.py
new file mode 100644
index 000000000000..ae471e824988
--- /dev/null
+++ b/products/web_analytics/backend/api/web_analytics_path_cleaning_suggestions.py
@@ -0,0 +1,192 @@
+from typing import Any
+
+from django.db import transaction
+
+import posthoganalytics
+from drf_spectacular.utils import extend_schema
+from rest_framework import serializers, viewsets
+from rest_framework.decorators import action
+from rest_framework.exceptions import NotFound, PermissionDenied
+from rest_framework.request import Request
+from rest_framework.response import Response
+
+from posthog.api.routing import TeamAndOrgViewSetMixin
+from posthog.models.health_issue import HealthIssue
+from posthog.models.organization import OrganizationMembership
+from posthog.rate_limit import AIBurstRateThrottle, AISustainedRateThrottle
+
+from products.web_analytics.backend.path_cleaning_suggestions.service import (
+ AnnotatedRule,
+ apply_suggestions_to_team,
+ build_suggestion_payload,
+ generate_suggestions_for_team,
+ preview_rules_on_team,
+)
+
+SUGGESTIONS_KIND = "path_cleaning_suggestions"
+FEATURE_FLAG_KEY = "web-analytics-path-cleaning-suggestions"
+
+
+class SuggestedRuleSerializer(serializers.Serializer):
+ regex = serializers.CharField(help_text="re2 pattern matching the dynamic path segment.")
+ alias = serializers.CharField(help_text="Replacement with angle-bracket placeholders, e.g. /users/<id>.")
+ order = serializers.IntegerField(help_text="Apply order; rules run sequentially, output feeds the next.")
+ match_count = serializers.IntegerField(
+ help_text="How many of the sampled paths this rule rewrites — evidence the rule was validated on real traffic."
+ )
+
+
+class PathCleaningSuggestionIssueSerializer(serializers.Serializer):
+ """A path-cleaning suggestion, stored as a `path_cleaning_suggestions` health issue."""
+
+ id = serializers.UUIDField(help_text="Health-issue id; pass it to the apply endpoint or the health-issues API.")
+ created_at = serializers.DateTimeField(help_text="When the suggestion was generated (ISO 8601).")
+ rules = SuggestedRuleSerializer(
+ many=True, help_text="Validated path-cleaning rules proposed for this team, most specific first."
+ )
+ model = serializers.CharField(help_text="LLM that generated the rules.")
+ sampled_path_count = serializers.IntegerField(help_text="How many real paths were sampled for generation.")
+ distinct_path_count = serializers.IntegerField(help_text="Distinct pathnames seen in the sampling window.")
+
+ @staticmethod
+ def from_issue(issue: HealthIssue) -> dict[str, Any]:
+ payload = issue.payload or {}
+ return {
+ "id": str(issue.id),
+ "created_at": issue.created_at,
+ "rules": payload.get("rules", []),
+ "model": payload.get("model", ""),
+ "sampled_path_count": payload.get("sampled_path_count", 0),
+ "distinct_path_count": payload.get("distinct_path_count", 0),
+ }
+
+
+class GeneratePathCleaningSuggestionResponseSerializer(serializers.Serializer):
+ status = serializers.CharField(
+ help_text="generated, skipped_low_cardinality, skipped_no_paths, skipped_configured, or error."
+ )
+ suggestion = PathCleaningSuggestionIssueSerializer(
+ required=False, allow_null=True, help_text="The stored suggestion when status is generated, else null."
+ )
+
+
+class ApplyPathCleaningSuggestionResponseSerializer(serializers.Serializer):
+ applied = serializers.IntegerField(help_text="Number of rules merged into the team's path_cleaning_filters.")
+
+
+class PathCleaningPreviewExampleSerializer(serializers.Serializer):
+ before = serializers.CharField(help_text="A real sampled path before the suggested rules are applied.")
+ after = serializers.CharField(help_text="The same path after all suggested rules run in order.")
+ views = serializers.IntegerField(help_text="Pageviews this path received in the sampling window.")
+
+
+class PreviewPathCleaningSuggestionResponseSerializer(serializers.Serializer):
+ examples = PathCleaningPreviewExampleSerializer(
+ many=True, help_text="Up to 20 before/after pairs for sampled paths the suggested rules would rewrite."
+ )
+ changed_path_count = serializers.IntegerField(
+ help_text="How many of the sampled paths the suggested rules rewrite in total."
+ )
+ sampled_path_count = serializers.IntegerField(help_text="How many top paths were sampled for this preview.")
+
+
+class WebAnalyticsPathCleaningSuggestionViewSet(TeamAndOrgViewSetMixin, viewsets.ViewSet):
+ """Path-cleaning suggestions live as `path_cleaning_suggestions` health issues — list and
+ dismiss them through the generic health-issues API. This viewset owns only the two
+ web-analytics-specific verbs: on-demand generation and applying rules to the team."""
+
+ scope_object = "web_analytics"
+
+ def get_throttles(self):
+ if self.action in {"generate", "preview"}:
+ # generation runs a ClickHouse path sample plus an LLM call, and preview runs a
+ # fresh ClickHouse sample per request — cap both for session-authenticated users
+ # the same way token-based AI callers are capped (the default throttles exempt
+ # session requests entirely)
+ return [AIBurstRateThrottle(), AISustainedRateThrottle()]
+ return super().get_throttles()
+
+ @extend_schema(
+ operation_id="web_analytics_path_cleaning_suggestions_generate",
+ summary="Generate path-cleaning suggestions on demand",
+ description="Samples the team's recent paths, asks the LLM for cleaning rules, validates them against the "
+ "real paths, and stores the result as a `path_cleaning_suggestions` health issue (replacing any previous "
+ "active one). Runs even if the team already has rules. Returns the suggestion (or a skip status when there "
+ "aren't enough paths to suggest from).",
+ request=None,
+ responses={200: GeneratePathCleaningSuggestionResponseSerializer},
+ )
+ @action(detail=False, methods=["post"], required_scopes=["web_analytics:write"])
+ def generate(self, request: Request, **kwargs: Any) -> Response:
+ # Dogfooding gate on the one verb that spends money (ClickHouse sampling + an LLM call).
+ # preview/apply only operate on already-stored suggestions, so they stay scope/admin-gated.
+ distinct_id = getattr(request.user, "distinct_id", None)
+ if not distinct_id or not posthoganalytics.feature_enabled(
+ FEATURE_FLAG_KEY,
+ distinct_id,
+ groups={"organization": str(self.organization.id)},
+ group_properties={"organization": {"id": str(self.organization.id)}},
+ ):
+ raise PermissionDenied("This feature is not available.")
+
+ result = generate_suggestions_for_team(self.team, visited_within_days=None, include_configured=True)
+ if result.status != "generated" or not result.rules:
+ return Response({"status": result.status, "suggestion": None})
+
+ issue, _ = HealthIssue.upsert_issue(
+ team_id=self.team.id,
+ kind=SUGGESTIONS_KIND,
+ severity=HealthIssue.Severity.INFO,
+ payload=build_suggestion_payload(result),
+ hash_keys=[],
+ )
+ return Response(
+ {"status": result.status, "suggestion": PathCleaningSuggestionIssueSerializer.from_issue(issue)}
+ )
+
+ @extend_schema(
+ operation_id="web_analytics_path_cleaning_suggestions_preview",
+ summary="Preview a path-cleaning suggestion on real paths",
+ description="Applies the suggestion's rules (in order) to a fresh sample of the team's top paths and returns "
+ "before/after pairs for the paths that would change. Computed on demand; path samples are never stored. "
+ "Nothing is modified.",
+ request=None,
+ responses={200: PreviewPathCleaningSuggestionResponseSerializer},
+ )
+ @action(detail=True, methods=["get"], required_scopes=["web_analytics:read"])
+ def preview(self, request: Request, pk: str | None = None, **kwargs: Any) -> Response:
+ issue = HealthIssue.objects.filter(team_id=self.team.id, kind=SUGGESTIONS_KIND, id=pk).first() if pk else None
+ if issue is None:
+ raise NotFound("No such path-cleaning suggestion.")
+ rules = [AnnotatedRule(**rule) for rule in (issue.payload or {}).get("rules", [])]
+ return Response(preview_rules_on_team(self.team, rules))
+
+ @extend_schema(
+ operation_id="web_analytics_path_cleaning_suggestions_apply",
+ summary="Apply a path-cleaning suggestion",
+ description="Merges the suggestion's rules into the team's path_cleaning_filters (never overwrites existing "
+ "rules) and resolves the underlying health issue. Requires project admin, matching the team API's gate on "
+ "path_cleaning_filters.",
+ request=None,
+ responses={200: ApplyPathCleaningSuggestionResponseSerializer},
+ )
+ @action(detail=True, methods=["post"], required_scopes=["web_analytics:write"])
+ def apply(self, request: Request, pk: str | None = None, **kwargs: Any) -> Response:
+ # path_cleaning_filters is a project-admin field on the team API (TEAM_CONFIG_ADMIN_FIELDS_SET);
+ # writing it through this endpoint must not be a way around that gate.
+ membership_level = self.user_permissions.team(self.team).effective_membership_level
+ if membership_level is None or membership_level < OrganizationMembership.Level.ADMIN:
+ raise PermissionDenied("Only project admins can apply path cleaning suggestions.")
+ if pk is None:
+ raise NotFound("No such path-cleaning suggestion.")
+ issue = HealthIssue.objects.filter(team_id=self.team.id, kind=SUGGESTIONS_KIND, id=pk).first()
+ if issue is None:
+ raise NotFound("No such path-cleaning suggestion.")
+ rules = [AnnotatedRule(**rule) for rule in (issue.payload or {}).get("rules", [])]
+ # Merge the rules and resolve the issue together — if the resolve failed on its own the
+ # banner would reappear and offer "Apply all" again for rules already applied.
+ with transaction.atomic():
+ added = apply_suggestions_to_team(self.team, rules)
+ if issue.status == HealthIssue.Status.ACTIVE:
+ issue.resolve()
+ return Response({"applied": added})
diff --git a/products/web_analytics/backend/management/__init__.py b/products/web_analytics/backend/management/__init__.py
new file mode 100644
index 000000000000..e69de29bb2d1
diff --git a/products/web_analytics/backend/management/commands/__init__.py b/products/web_analytics/backend/management/commands/__init__.py
new file mode 100644
index 000000000000..e69de29bb2d1
diff --git a/products/web_analytics/backend/management/commands/suggest_path_cleaning_rules.py b/products/web_analytics/backend/management/commands/suggest_path_cleaning_rules.py
new file mode 100644
index 000000000000..1283d7b32953
--- /dev/null
+++ b/products/web_analytics/backend/management/commands/suggest_path_cleaning_rules.py
@@ -0,0 +1,160 @@
+"""Generate AI-suggested path-cleaning rules for web-analytics teams and print them for review.
+
+Suggests only — applying rewrites historical numbers in every cleaned chart, so it stays a human
+decision. `--apply` merges the generated rules into a team's existing `path_cleaning_filters`
+(never overwriting) and is opt-in; review the printed suggestions first.
+
+ # Default cohort (WEB_ANALYTICS_PATH_CLEANING_SUGGESTIONS_TEAM_IDS), print + store health issues:
+ python manage.py suggest_path_cleaning_rules
+
+ # Specific teams, don't write health-issue rows (pure dry run):
+ python manage.py suggest_path_cleaning_rules --teams 2,19279 --no-store
+
+ # Generate and apply for one reviewed team:
+ python manage.py suggest_path_cleaning_rules --teams 2 --apply
+"""
+
+from typing import Any
+
+from django.conf import settings
+from django.core.management.base import BaseCommand, CommandError
+
+from posthog.models import Team
+from posthog.models.health_issue import HealthIssue
+
+from products.web_analytics.backend.path_cleaning_suggestions.service import (
+ DEFAULT_MIN_DISTINCT_PATHS,
+ DEFAULT_SAMPLE_DAYS,
+ DEFAULT_SAMPLE_LIMIT,
+ DEFAULT_VISITED_WITHIN_DAYS,
+ apply_suggestions_to_team,
+ build_suggestion_payload,
+ generate_suggestions_for_team,
+)
+
+SUGGESTIONS_KIND = "path_cleaning_suggestions"
+
+
+class Command(BaseCommand):
+ help = "Generate AI-suggested path-cleaning rules for web-analytics teams."
+
+ def add_arguments(self, parser: Any) -> None:
+ group = parser.add_mutually_exclusive_group()
+ group.add_argument("--teams", type=str, help="Comma-separated team ids (default: configured cohort).")
+ group.add_argument("--teams-file", type=str, help="File with comma- or newline-separated team ids.")
+ parser.add_argument("--days", type=int, default=DEFAULT_SAMPLE_DAYS, help="Lookback window in days.")
+ parser.add_argument("--limit", type=int, default=DEFAULT_SAMPLE_LIMIT, help="Top-N paths to sample.")
+ parser.add_argument(
+ "--min-distinct-paths",
+ type=int,
+ default=DEFAULT_MIN_DISTINCT_PATHS,
+ help="Skip teams with fewer distinct paths than this (low cardinality => no value).",
+ )
+ parser.add_argument(
+ "--include-configured",
+ action="store_true",
+ help="Also process teams that already have path cleaning rules (default: skip them).",
+ )
+ parser.add_argument(
+ "--no-store", action="store_true", help="Don't persist suggestions as health issues (print only)."
+ )
+ parser.add_argument(
+ "--visited-within-days",
+ type=int,
+ default=DEFAULT_VISITED_WITHIN_DAYS,
+ help="Only process teams that opened Web analytics within this many days.",
+ )
+ parser.add_argument(
+ "--ignore-visit-gate",
+ action="store_true",
+ help="Process teams even if they haven't recently opened Web analytics.",
+ )
+ parser.add_argument(
+ "--apply",
+ action="store_true",
+ help="Merge generated rules into each team's path_cleaning_filters (never overwrites). Opt-in.",
+ )
+
+ def handle(self, *args: Any, **options: Any) -> None:
+ team_ids = self._resolve_team_ids(options)
+ teams = {t.id: t for t in Team.objects.filter(id__in=team_ids)}
+ missing = sorted(set(team_ids) - set(teams.keys()))
+ if missing:
+ self.stderr.write(f"skipping {len(missing)} unknown team ids: {missing[:20]}")
+
+ store = not options["no_store"]
+ counts: dict[str, int] = {}
+ applied_total = 0
+
+ for team_id in team_ids:
+ team = teams.get(team_id)
+ if team is None:
+ continue
+
+ result = generate_suggestions_for_team(
+ team,
+ days=options["days"],
+ limit=options["limit"],
+ min_distinct_paths=options["min_distinct_paths"],
+ include_configured=options["include_configured"],
+ visited_within_days=None if options["ignore_visit_gate"] else options["visited_within_days"],
+ )
+ counts[result.status] = counts.get(result.status, 0) + 1
+ self._print_team_result(team_id, result)
+
+ issue = None
+ if store and result.status == "generated" and result.rules:
+ issue, _ = HealthIssue.upsert_issue(
+ team_id=team.id,
+ kind=SUGGESTIONS_KIND,
+ severity=HealthIssue.Severity.INFO,
+ payload=build_suggestion_payload(result),
+ hash_keys=[],
+ )
+
+ if options["apply"] and result.status == "generated" and result.rules:
+ added = apply_suggestions_to_team(team, result.rules)
+ applied_total += added
+ if issue is not None and issue.status == HealthIssue.Status.ACTIVE:
+ issue.resolve()
+ self.stdout.write(f" applied {added} new rule(s) to team {team_id}")
+
+ summary = " ".join(f"{status}={n}" for status, n in sorted(counts.items()))
+ self.stdout.write(f"\nsummary: {summary} applied_rules={applied_total}")
+
+ def _print_team_result(self, team_id: int, result: Any) -> None:
+ if result.status != "generated":
+ detail = f" — {result.error}" if result.error else ""
+ self.stdout.write(f"team {team_id}: {result.status}{detail}")
+ return
+
+ self.stdout.write(
+ f"team {team_id}: {len(result.rules)} rule(s) from {result.sampled_path_count} sampled paths "
+ f"({result.distinct_path_count} distinct), model={result.model}"
+ )
+ for rule in result.rules:
+ self.stdout.write(f" [{rule.order}] {rule.regex} -> {rule.alias} (matches {rule.match_count} paths)")
+ for ex in rule.examples[:2]:
+ self.stdout.write(f" {ex['before']} -> {ex['after']}")
+
+ def _resolve_team_ids(self, options: dict[str, Any]) -> list[int]:
+ if options.get("teams"):
+ return self._parse_ids(options["teams"])
+ if options.get("teams_file"):
+ with open(options["teams_file"]) as f:
+ return self._parse_ids(f.read())
+ cohort = settings.WEB_ANALYTICS_PATH_CLEANING_SUGGESTIONS_TEAM_IDS
+ if not cohort:
+ raise CommandError(
+ "no teams given and WEB_ANALYTICS_PATH_CLEANING_SUGGESTIONS_TEAM_IDS is empty; "
+ "pass --teams or --teams-file"
+ )
+ return list(cohort)
+
+ def _parse_ids(self, raw: str) -> list[int]:
+ ids: list[int] = []
+ for token in raw.replace("\n", ",").split(","):
+ token = token.strip()
+ if token:
+ ids.append(int(token))
+ return ids
diff --git a/products/web_analytics/backend/path_cleaning_suggestions/__init__.py b/products/web_analytics/backend/path_cleaning_suggestions/__init__.py
new file mode 100644
index 000000000000..7fea5eed9ed6
--- /dev/null
+++ b/products/web_analytics/backend/path_cleaning_suggestions/__init__.py
@@ -0,0 +1,13 @@
+from products.web_analytics.backend.path_cleaning_suggestions.service import (
+ AnnotatedRule,
+ TeamSuggestionResult,
+ apply_suggestions_to_team,
+ generate_suggestions_for_team,
+)
+
+__all__ = [
+ "AnnotatedRule",
+ "TeamSuggestionResult",
+ "apply_suggestions_to_team",
+ "generate_suggestions_for_team",
+]
diff --git a/products/web_analytics/backend/path_cleaning_suggestions/prompts.py b/products/web_analytics/backend/path_cleaning_suggestions/prompts.py
new file mode 100644
index 000000000000..8cc349c71bbb
--- /dev/null
+++ b/products/web_analytics/backend/path_cleaning_suggestions/prompts.py
@@ -0,0 +1,55 @@
+from pydantic import BaseModel, ConfigDict
+
+# Mirrors the AiRegexHelper prompt style (posthog/session_recordings/ai_data/ai_regex_prompts.py)
+# but inverts the task: given real URL paths, propose path-cleaning rules.
+SYSTEM_PROMPT = """You are a web analytics expert who writes URL path-cleaning rules for PostHog.
+
+Path cleaning rules normalize the `$pathname` property so that pages sharing the same template
+(`/users/123/profile`, `/users/456/profile`, …) collapse into one row (`/users/<id>/profile`) in
+Web analytics tiles and Paths insights. Without them, dynamic segments (numeric IDs, UUIDs, slugs,
+dates, locales) fragment a breakdown across thousands of near-identical URLs.
+
+You will be given a sample of a single project's most-viewed URL paths (with view counts). Identify
+the dynamic segments and propose a small, high-leverage set of cleaning rules.
+
+Rules:
+- Each rule is a `regex` (Google re2 syntax — do NOT escape `/`) and an `alias` (the literal
+ replacement). The alias is NOT a regex template: use angle-bracket placeholders like `<id>`,
+ `<uuid>`, `<slug>`, `<date>`, `<locale>` so the cleaned path stays human-readable. Do not use
+ backreferences.
+- Anchor with `^` only when the segment must be at the start of the path; end with `$` (or `(/|$)`)
+ to stop a generic rule like `\\d+` from matching every numeric run mid-path.
+- Order matters: rules apply sequentially, each rule's output feeds the next. List the MOST SPECIFIC
+ rules first and the most general (catch-all) rules last, so a generic rule never swallows a path a
+ specific rule should have handled.
+- Only propose rules that match real patterns in the provided sample. Prefer 3–10 strong rules over
+ many speculative ones. If the paths are already clean (no dynamic segments worth collapsing),
+ return an empty list.
+
+Return ONLY a JSON object, no prose, in exactly this shape:
+{
+ "rules": [
+ {"regex": "/users/\\\\d+/profile", "alias": "/users/<id>/profile", "reason": "numeric user id"}
+ ]
+}
+"""
+
+
+class SuggestedRule(BaseModel):
+ model_config = ConfigDict(extra="ignore")
+ regex: str
+ alias: str
+ reason: str = ""
+
+
+class SuggestedRulesResponse(BaseModel):
+ model_config = ConfigDict(extra="ignore")
+ rules: list[SuggestedRule] = []
+
+
+def build_user_prompt(paths: list[tuple[str, int]]) -> str:
+ lines = [f"{views:>10} {path}" for path, views in paths]
+ return (
+ "Here are the most-viewed URL paths for this project (views, path). "
+ "Propose path-cleaning rules.\n\n" + "\n".join(lines)
+ )
diff --git a/products/web_analytics/backend/path_cleaning_suggestions/service.py b/products/web_analytics/backend/path_cleaning_suggestions/service.py
new file mode 100644
index 000000000000..9942aa841848
--- /dev/null
+++ b/products/web_analytics/backend/path_cleaning_suggestions/service.py
@@ -0,0 +1,346 @@
+import json
+import dataclasses
+from typing import Any
+
+from django.conf import settings
+from django.db import transaction
+
+import re2
+import structlog
+
+from posthog.hogql.query import execute_hogql_query
+
+from posthog.clickhouse.query_tagging import Feature, Product, tags_context
+from posthog.llm.gateway_client import get_llm_client
+from posthog.models import Team
+
+from products.web_analytics.backend.path_cleaning_suggestions.prompts import (
+ SYSTEM_PROMPT,
+ SuggestedRule,
+ SuggestedRulesResponse,
+ build_user_prompt,
+)
+
+logger = structlog.get_logger(__name__)
+
+DEFAULT_SAMPLE_DAYS = 30
+DEFAULT_SAMPLE_LIMIT = 300
+DEFAULT_MIN_DISTINCT_PATHS = 50
+MAX_EXAMPLES_PER_RULE = 3
+
+
+class AnnotatedRule:
+ regex: str
+ alias: str
+ order: int
+ match_count: int
+ # `reason` and `examples` can echo real sampled paths (the model quotes them freely), so both
+ # are kept in memory for the management command's printout but never stored in the
+ # health-issue payload (see build_suggestion_payload).
+ reason: str = ""
+ examples: list[dict[str, str]] = dataclasses.field(default_factory=list)
+
+
+class TeamSuggestionResult:
+ # status: generated | skipped_inactive | skipped_configured | skipped_low_cardinality
+ # | skipped_no_paths | error
+ team_id: int
+ status: str
+ rules: list[AnnotatedRule]
+ sampled_path_count: int
+ distinct_path_count: int
+ existing_rule_count: int
+ model: str = ""
+ error: str | None = None
+
+
+DEFAULT_VISITED_WITHIN_DAYS = 30
+
+
+def _resolve_model() -> str:
+ return getattr(settings, "WEB_ANALYTICS_PATH_CLEANING_SUGGESTIONS_MODEL", "claude-haiku-4-5")
+
+
+def has_recent_pageviews(team: Team, *, days: int) -> bool:
+ """True if the team sent any `$pageview` within the window — a cheap proxy for "actively using
+ web analytics". `LIMIT 1` lets ClickHouse early-terminate instead of counting the full window."""
+ query = f"""
+ SELECT 1
+ FROM events
+ WHERE event = '$pageview'
+ AND timestamp >= now() - toIntervalDay({int(days)})
+ LIMIT 1
+ """
+ response = execute_hogql_query(query=query, team=team, query_type="web_path_cleaning_recent_pageviews")
+ return bool(response.results)
+
+
+def sample_pathnames(team: Team, *, days: int, limit: int) -> list[tuple[str, int]]:
+ # days/limit are internal ints (settings / argparse), safe to inline — not user input.
+ query = f"""
+ SELECT properties.$pathname AS path, count() AS views
+ FROM events
+ WHERE event = '$pageview'
+ AND timestamp >= now() - toIntervalDay({int(days)})
+ AND properties.$pathname IS NOT NULL
+ AND properties.$pathname != ''
+ GROUP BY path
+ ORDER BY views DESC
+ LIMIT {int(limit)}
+ """
+ response = execute_hogql_query(query=query, team=team, query_type="web_path_cleaning_sample")
+ return [(str(row[0]), int(row[1])) for row in response.results or []]
+
+
+def count_distinct_pathnames(team: Team, *, days: int) -> int:
+ query = f"""
+ SELECT count(DISTINCT properties.$pathname)
+ FROM events
+ WHERE event = '$pageview'
+ AND timestamp >= now() - toIntervalDay({int(days)})
+ AND properties.$pathname IS NOT NULL
+ AND properties.$pathname != ''
+ """
+ response = execute_hogql_query(query=query, team=team, query_type="web_path_cleaning_distinct")
+ rows = response.results or []
+ return int(rows[0][0]) if rows and rows[0] and rows[0][0] is not None else 0
+
+
+def _extract_json(content: str) -> dict:
+ text = content.strip()
+ if text.startswith("```"):
+ # strip a ```json … ``` fence
+ text = text.split("```", 2)[1] if text.count("```") >= 2 else text.strip("`")
+ if text.lstrip().startswith("json"):
+ text = text.lstrip()[4:]
+ start = text.find("{")
+ end = text.rfind("}")
+ if start == -1 or end == -1 or end < start:
+ raise ValueError("LLM response contained no JSON object")
+ return json.loads(text[start : end + 1])
+
+
+def call_llm_for_rules(team: Team, paths: list[tuple[str, int]], *, model: str) -> SuggestedRulesResponse:
+ client = get_llm_client(product="web_analytics", team_id=team.id)
+ completion = client.chat.completions.create(
+ model=model,
+ messages=[
+ {"role": "system", "content": SYSTEM_PROMPT},
+ {"role": "user", "content": build_user_prompt(paths)},
+ ],
+ temperature=0.2,
+ user=f"team-{team.id}",
+ )
+ content = completion.choices[0].message.content or ""
+ return SuggestedRulesResponse.model_validate(_extract_json(content))
+
+
+def validate_and_annotate_rules(
+ rules: list[SuggestedRule], sampled_paths: list[tuple[str, int]]
+) -> list[AnnotatedRule]:
+ """Compile each suggested regex with re2 (the same engine ClickHouse `replaceRegexpAll` uses) and
+ test-apply it to the real sampled paths. Drop rules that don't compile or match nothing, and
+ re-number `order` densely in the model's most-specific-first order."""
+ paths = [path for path, _ in sampled_paths]
+ annotated: list[AnnotatedRule] = []
+ order = 0
+ for rule in rules:
+ if not rule.regex or not rule.alias:
+ continue
+ try:
+ compiled = re2.compile(rule.regex)
+ except re2.error:
+ logger.info("path_cleaning_suggestion_invalid_regex", regex=rule.regex)
+ continue
+
+ examples: list[dict[str, str]] = []
+ match_count = 0
+ alias_valid = True
+ for path in paths:
+ try:
+ cleaned = compiled.sub(rule.alias, path)
+ except (re2.error, IndexError):
+ # LLM produced an alias with a backreference the regex can't satisfy (e.g. `\1` with
+ # no capture group). Drop the rule rather than let it fail the whole team's run.
+ logger.info("path_cleaning_suggestion_invalid_alias", regex=rule.regex, alias=rule.alias)
+ alias_valid = False
+ break
+ if cleaned != path:
+ match_count += 1
+ if len(examples) < MAX_EXAMPLES_PER_RULE:
+ examples.append({"before": path, "after": cleaned})
+
+ if not alias_valid or match_count == 0:
+ continue
+
+ annotated.append(
+ AnnotatedRule(
+ regex=rule.regex,
+ alias=rule.alias,
+ order=order,
+ reason=rule.reason,
+ match_count=match_count,
+ examples=examples,
+ )
+ )
+ order += 1
+ return annotated
+
+
+def generate_suggestions_for_team(
+ team: Team,
+ *,
+ days: int = DEFAULT_SAMPLE_DAYS,
+ limit: int = DEFAULT_SAMPLE_LIMIT,
+ min_distinct_paths: int = DEFAULT_MIN_DISTINCT_PATHS,
+ include_configured: bool = False,
+ visited_within_days: int | None = DEFAULT_VISITED_WITHIN_DAYS,
+) -> TeamSuggestionResult:
+ existing_rules = team.path_cleaning_filters or []
+ existing_rule_count = len(existing_rules)
+
+ def _result(
+ status: str, rules: list[AnnotatedRule], distinct: int, sampled: int, error: str | None = None
+ ) -> TeamSuggestionResult:
+ return TeamSuggestionResult(
+ team_id=team.id,
+ status=status,
+ rules=rules,
+ sampled_path_count=sampled,
+ distinct_path_count=distinct,
+ existing_rule_count=existing_rule_count,
+ model=_resolve_model() if status in ("generated", "error") else "",
+ error=error,
+ )
+
+ if existing_rule_count > 0 and not include_configured:
+ return _result("skipped_configured", [], 0, 0)
+
+ try:
+ # The whole suggestion pipeline rides the health-check framework, so its ClickHouse
+ # queries are tagged as such regardless of the caller (API, command, or scheduled check).
+ with tags_context(
+ product=Product.WEB_ANALYTICS, feature=Feature.HEALTH_CHECK, team_id=team.pk, org_id=team.organization_id
+ ):
+ # The activity gate runs a ClickHouse query, so it lives inside the guard with the
+ # rest — a transient query failure must surface as this team's error result, not
+ # propagate out of a cohort sweep.
+ if visited_within_days is not None and not has_recent_pageviews(team, days=visited_within_days):
+ return _result("skipped_inactive", [], 0, 0)
+
+ distinct = count_distinct_pathnames(team, days=days)
+ if distinct < min_distinct_paths:
+ return _result("skipped_low_cardinality", [], distinct, 0)
+
+ paths = sample_pathnames(team, days=days, limit=limit)
+ if not paths:
+ return _result("skipped_no_paths", [], distinct, 0)
+
+ response = call_llm_for_rules(team, paths, model=_resolve_model())
+ annotated = validate_and_annotate_rules(response.rules, paths)
+ return _result("generated", annotated, distinct, len(paths))
+ except Exception as exc: # noqa: BLE001 — one bad team must not abort the cohort sweep
+ logger.exception("path_cleaning_suggestion_failed", team_id=team.id)
+ return _result("error", [], 0, 0, error=f"{type(exc).__name__}: {exc}")
+
+
+def build_suggestion_payload(result: TeamSuggestionResult) -> dict[str, Any]:
+ """The `HealthIssue.payload` shape for a generated suggestion. One place, so the health
+ check, the on-demand API, and the frontend banner all agree on the field names.
+
+ `examples` (real sampled paths) and the model's free-text `reason` (which can quote them)
+ are deliberately excluded: health-issue payloads are readable with just `health_issue:read`,
+ which must not leak a team's event data."""
+ return {
+ "rules": [
+ {
+ "regex": rule.regex,
+ "alias": rule.alias,
+ "order": rule.order,
+ "match_count": rule.match_count,
+ }
+ for rule in result.rules
+ ],
+ "model": result.model,
+ "sampled_path_count": result.sampled_path_count,
+ "distinct_path_count": result.distinct_path_count,
+ }
+
+
+MAX_PREVIEW_EXAMPLES = 20
+
+
+def preview_rules_on_team(
+ team: Team,
+ rules: list[AnnotatedRule],
+ *,
+ days: int = DEFAULT_SAMPLE_DAYS,
+ limit: int = DEFAULT_SAMPLE_LIMIT,
+ max_examples: int = MAX_PREVIEW_EXAMPLES,
+) -> dict[str, Any]:
+ """Apply the suggested rules (in order, output feeding the next — exactly how ClickHouse
+ applies configured rules) to a fresh sample of the team's top paths. Returns before/after
+ pairs for the paths that change, computed on demand and never stored."""
+ compiled: list[tuple[Any, str]] = []
+ for rule in sorted(rules, key=lambda r: r.order):
+ try:
+ compiled.append((re2.compile(rule.regex), rule.alias))
+ except re2.error:
+ logger.info("path_cleaning_preview_invalid_regex", regex=rule.regex)
+
+ with tags_context(
+ product=Product.WEB_ANALYTICS, feature=Feature.HEALTH_CHECK, team_id=team.pk, org_id=team.organization_id
+ ):
+ sampled = sample_pathnames(team, days=days, limit=limit)
+ examples: list[dict[str, Any]] = []
+ changed = 0
+ for path, views in sampled:
+ cleaned = path
+ for compiled_regex, alias in compiled:
+ try:
+ cleaned = compiled_regex.sub(alias, cleaned)
+ except (re2.error, IndexError):
+ continue
+ if cleaned != path:
+ changed += 1
+ if len(examples) < max_examples:
+ examples.append({"before": path, "after": cleaned, "views": views})
+
+ return {
+ "examples": examples,
+ "changed_path_count": changed,
+ "sampled_path_count": len(sampled),
+ }
+
+
+def apply_suggestions_to_team(team: Team, rules: list[AnnotatedRule]) -> int:
+ """Merge suggested rules into the team's existing `path_cleaning_filters`. Never overwrites: rules
+ whose regex already exists are skipped, new ones are appended after the current max order. Returns
+ the number of rules actually added."""
+ with transaction.atomic():
+ # Lock the row so an overlapping apply or settings save can't read the same base list
+ # and clobber the other writer's rules on save.
+ team = Team.objects.select_for_update().get(pk=team.pk)
+ return _merge_rules_into_team(team, rules)
+
+
+def _merge_rules_into_team(team: Team, rules: list[AnnotatedRule]) -> int:
+ existing = list(team.path_cleaning_filters or [])
+ existing_regexes = {f.get("regex") for f in existing}
+ next_order = max((int(f.get("order", 0)) for f in existing), default=-1) + 1
+
+ added = 0
+ for rule in rules:
+ if rule.regex in existing_regexes:
+ continue
+ existing.append({"regex": rule.regex, "alias": rule.alias, "order": next_order})
+ existing_regexes.add(rule.regex)
+ next_order += 1
+ added += 1
+
+ if added:
+ team.path_cleaning_filters = existing
+ team.save(update_fields=["path_cleaning_filters"])
+ return added
diff --git a/products/web_analytics/backend/routes.py b/products/web_analytics/backend/routes.py
index c3488314e9ef..8b933f6c0161 100644
--- a/products/web_analytics/backend/routes.py
+++ b/products/web_analytics/backend/routes.py
@@ -9,6 +9,9 @@ from products.web_analytics.backend.api.heatmaps_api import (
)
from products.web_analytics.backend.api.web_analytics_achievements import WebAnalyticsAchievementsViewSet
from products.web_analytics.backend.api.web_analytics_filter_preset import WebAnalyticsFilterPresetViewSet
+from products.web_analytics.backend.api.web_analytics_path_cleaning_suggestions import (
+ WebAnalyticsPathCleaningSuggestionViewSet,
+)
def register_routes(routers: RouterRegistry) -> None:
@@ -31,3 +34,9 @@ def register_routes(routers: RouterRegistry) -> None:
"project_web_analytics_achievements",
["team_id"],
)
+ routers.projects.register(
+ r"web_analytics_path_cleaning_suggestions",
+ WebAnalyticsPathCleaningSuggestionViewSet,
+ "project_web_analytics_path_cleaning_suggestions",
+ ["team_id"],
+ )
diff --git a/products/web_analytics/backend/temporal/health_checks/path_cleaning_suggestions.py b/products/web_analytics/backend/temporal/health_checks/path_cleaning_suggestions.py
new file mode 100644
index 000000000000..7e1fb490150d
--- /dev/null
+++ b/products/web_analytics/backend/temporal/health_checks/path_cleaning_suggestions.py
@@ -0,0 +1,122 @@
+from django.conf import settings
+
+import structlog
+
+from posthog.clickhouse.query_tagging import Product
+from posthog.dags.common.owners import JobOwners
+from posthog.models import Team
+from posthog.models.health_issue import HealthIssue
+from posthog.temporal.health_checks.detectors import HealthExecutionPolicy
+from posthog.temporal.health_checks.framework import AlertContent, HealthCheck, Remediation
+from posthog.temporal.health_checks.models import HealthCheckResult
+
+from products.web_analytics.backend.path_cleaning_suggestions.service import (
+ build_suggestion_payload,
+ generate_suggestions_for_team,
+)
+
+logger = structlog.get_logger(__name__)
+
+# The framework enumerates every active team before batching — it has no way to
+# pre-target the enrolled cohort — so batches must stay large or Cloud turns into
+# thousands of serial no-op activities that each filter down to zero candidates.
+# The expensive part (one LLM call per candidate) is bounded inside detect():
+# candidates are the cohort intersection, processed strictly sequentially, so a
+# big batch costs one activity, not a burst of LLM calls.
+LLM_EXECUTION_POLICY = HealthExecutionPolicy(batch_size=5000, max_concurrent=1)
+
+
+class PathCleaningSuggestionsCheck(HealthCheck):
+ """Suggests AI-generated path-cleaning rules for teams with messy path cardinality.
+
+ Unlike the other web-analytics checks this is an *opportunity*, not a defect —
+ severity stays INFO and the issue carries the validated suggested rules in its
+ payload so the settings banner and the health page can offer one-click apply.
+ The issue auto-resolves once the team configures any path-cleaning rules
+ (applied via the suggestion or by hand), because configured teams are reported
+ healthy on the next run.
+ """
+
+ name = "path_cleaning_suggestions"
+ kind = "path_cleaning_suggestions"
+ owner = JobOwners.TEAM_WEB_ANALYTICS
+ product = Product.WEB_ANALYTICS
+ policy = LLM_EXECUTION_POLICY
+ schedule = "23 6 * * 1" # weekly, Monday 06:23 UTC
+ remediation = Remediation(
+ human="""
+ Open Settings → Product analytics → Path cleaning rules. Review the suggested rules —
+ each one shows the regex, the replacement alias, and how many of your real paths it matched —
+ then apply them all or add the ones you want by hand. Rules collapse dynamic URL segments
+ (IDs, slugs, tokens) so the Paths table groups equivalent pages together.
+ """,
+ agent="""
+ Fetch this issue's payload: `rules` is a list of validated path-cleaning rules
+ (regex, alias, order, and match_count — how many of the team's real sampled paths the
+ rule rewrote). To apply them, call the web-analytics path-cleaning-suggestions `apply`
+ endpoint with this issue's id (requires project admin) — it merges the rules into the
+ team's `path_cleaning_filters` without overwriting existing rules and resolves this
+ issue. To regenerate fresher suggestions first, call the `generate` endpoint.
+ """,
+ )
+
+ def detect(self, team_ids: list[int]) -> dict[int, list[HealthCheckResult]]:
+ cohort = set(settings.WEB_ANALYTICS_PATH_CLEANING_SUGGESTIONS_TEAM_IDS)
+ candidate_ids = [team_id for team_id in team_ids if team_id in cohort]
+ if not candidate_ids:
+ return {}
+
+ issues: dict[int, list[HealthCheckResult]] = {}
+
+ # Teams with an ACTIVE suggestion keep it alive without a fresh LLM round trip —
+ # re-emitting the stored payload preserves the row (and its dismissed flag) while
+ # letting the framework resolve it the moment the team configures rules.
+ existing_by_team = {
+ issue.team_id: issue
+ for issue in HealthIssue.objects.filter(
+ team_id__in=candidate_ids, kind=self.kind, status=HealthIssue.Status.ACTIVE
+ )
+ }
+
+ teams = {team.id: team for team in Team.objects.filter(id__in=candidate_ids)}
+ for team_id in candidate_ids:
+ team = teams.get(team_id)
+ if team is None:
+ continue
+ # Every gate runs inside the per-team guard: a ClickHouse or LLM failure for
+ # one team must not abort the batch (the framework counts it as unprocessed).
+ try:
+ if team.path_cleaning_filters:
+ continue # healthy → any active suggestion auto-resolves
+ existing = existing_by_team.get(team_id)
+ if existing is not None:
+ issues[team_id] = [
+ HealthCheckResult(severity=HealthIssue.Severity.INFO, payload=existing.payload, hash_keys=[])
+ ]
+ continue
+ result = generate_suggestions_for_team(team)
+ if result.status != "generated" or not result.rules:
+ # Skips and empty generations store nothing — an empty suggestion row
+ # would shadow an actionable one in every "latest suggestion" read.
+ continue
+ issues[team_id] = [
+ HealthCheckResult(
+ severity=HealthIssue.Severity.INFO,
+ payload=build_suggestion_payload(result),
+ hash_keys=[],
+ )
+ ]
+ except Exception:
+ logger.exception("path_cleaning_suggestions_check_failed", team_id=team_id)
+
+ return issues
+
+ @classmethod
+ def render_alert(cls, issue: HealthIssue) -> AlertContent:
+ rule_count = len(issue.payload.get("rules", []))
+ return AlertContent(
+ title="Path cleaning suggestions available",
+ summary=f"{rule_count} suggested path-cleaning rule{'s' if rule_count != 1 else ''} "
+ "ready to review, generated from your real page paths",
+ link="/settings/environment-product-analytics#path-cleaning",
+ )
diff --git a/products/web_analytics/backend/test/test_path_cleaning_suggestions.py b/products/web_analytics/backend/test/test_path_cleaning_suggestions.py
new file mode 100644
index 000000000000..f2e1179839ac
--- /dev/null
+++ b/products/web_analytics/backend/test/test_path_cleaning_suggestions.py
@@ -0,0 +1,312 @@
+from posthog.test.base import BaseTest
+from unittest.mock import patch
+
+from parameterized import parameterized
+
+from products.web_analytics.backend.path_cleaning_suggestions import service
+from products.web_analytics.backend.path_cleaning_suggestions.prompts import SuggestedRule, SuggestedRulesResponse
+from products.web_analytics.backend.path_cleaning_suggestions.service import (
+ AnnotatedRule,
+ apply_suggestions_to_team,
+ build_suggestion_payload,
+ generate_suggestions_for_team,
+ validate_and_annotate_rules,
+)
+
+SAMPLE_PATHS = [
+ ("/users/123/profile", 100),
+ ("/users/456/profile", 80),
+ ("/users/789/profile", 60),
+ ("/about", 40),
+]
+
+
+class TestValidateAndAnnotateRules(BaseTest):
+ def test_keeps_valid_rule_with_dense_order_and_annotations(self) -> None:
+ rules = [SuggestedRule(regex=r"/users/\d+/profile", alias="/users/<id>/profile", reason="user id")]
+ annotated = validate_and_annotate_rules(rules, SAMPLE_PATHS)
+
+ self.assertEqual(len(annotated), 1)
+ rule = annotated[0]
+ self.assertEqual(rule.order, 0)
+ self.assertEqual(rule.match_count, 3) # 3 of 4 sampled paths match
+ self.assertEqual(rule.examples[0], {"before": "/users/123/profile", "after": "/users/<id>/profile"})
+
+ @parameterized.expand(
+ [
+ ("invalid_regex", r"/users/(\d+/profile", "/users/<id>/profile"), # unbalanced paren -> re2 error
+ ("matches_nothing", r"/orders/\d+$", "/orders/<id>"), # no /orders path in sample
+ ("empty_regex", "", "/x"),
+ ("empty_alias", r"/users/\d+", ""),
+ # alias backreference with no capture group -> re2 raises on sub; must be dropped, not crash
+ ("alias_backreference_no_group", r"/users/\d+/profile", r"/users/\1"),
+ ]
+ )
+ def test_drops_unusable_rules(self, _name: str, regex: str, alias: str) -> None:
+ annotated = validate_and_annotate_rules([SuggestedRule(regex=regex, alias=alias)], SAMPLE_PATHS)
+ self.assertEqual(annotated, [])
+
+ def test_renumbers_order_densely_when_a_rule_is_dropped(self) -> None:
+ rules = [
+ SuggestedRule(regex=r"/orders/\d+$", alias="/orders/<id>"), # dropped: matches nothing
+ SuggestedRule(regex=r"/users/\d+/profile", alias="/users/<id>/profile"), # kept
+ ]
+ annotated = validate_and_annotate_rules(rules, SAMPLE_PATHS)
+ self.assertEqual(len(annotated), 1)
+ self.assertEqual(annotated[0].order, 0)
+
+
+class TestExtractJson(BaseTest):
+ @parameterized.expand(
+ [
+ ("plain", '{"rules": []}'),
+ ("fenced", '```json\n{"rules": []}\n```'),
+ ("prose_wrapped", 'Here are the rules:\n{"rules": []}\nHope that helps!'),
+ ]
+ )
+ def test_extracts_json_object(self, _name: str, content: str) -> None:
+ self.assertEqual(service._extract_json(content), {"rules": []})
+
+ def test_raises_without_json(self) -> None:
+ with self.assertRaises(ValueError):
+ service._extract_json("no json here")
+
+
+class TestApplySuggestionsToTeam(BaseTest):
+ def _rule(self, regex: str, alias: str) -> AnnotatedRule:
+ return AnnotatedRule(regex=regex, alias=alias, order=0, reason="", match_count=1, examples=[])
+
+ def test_appends_to_empty_with_sequential_order(self) -> None:
+ self.team.path_cleaning_filters = []
+ self.team.save()
+ added = apply_suggestions_to_team(
+ self.team,
+ [self._rule(r"/users/\d+", "/users/<id>"), self._rule(r"/orders/\d+", "/orders/<id>")],
+ )
+ self.team.refresh_from_db()
+ self.assertEqual(added, 2)
+ self.assertEqual([f["order"] for f in self.team.path_cleaning_filters], [0, 1])
+
+ def test_merges_without_overwriting_and_dedupes(self) -> None:
+ self.team.path_cleaning_filters = [{"regex": r"/users/\d+", "alias": "/users/<id>", "order": 0}]
+ self.team.save()
+ added = apply_suggestions_to_team(
+ self.team,
+ [
+ self._rule(r"/users/\d+", "/users/<id>"), # duplicate regex -> skipped
+ self._rule(r"/orders/\d+", "/orders/<id>"), # new -> appended after max order
+ ],
+ )
+ self.team.refresh_from_db()
+ self.assertEqual(added, 1)
+ self.assertEqual(len(self.team.path_cleaning_filters), 2)
+ self.assertEqual(
+ self.team.path_cleaning_filters[1], {"regex": r"/orders/\d+", "alias": "/orders/<id>", "order": 1}
+ )
+
+ def test_no_rules_is_noop(self) -> None:
+ self.team.path_cleaning_filters = [{"regex": r"/a", "alias": "/b", "order": 0}]
+ self.team.save()
+ added = apply_suggestions_to_team(self.team, [])
+ self.team.refresh_from_db()
+ self.assertEqual(added, 0)
+ self.assertEqual(len(self.team.path_cleaning_filters), 1)
+
+
+class TestGenerateSuggestionsForTeam(BaseTest):
+ def test_skips_inactive_team(self) -> None:
+ self.team.path_cleaning_filters = []
+ self.team.save()
+ with (
+ patch.object(service, "has_recent_pageviews", return_value=False),
+ patch.object(service, "count_distinct_pathnames") as mock_count,
+ ):
+ result = generate_suggestions_for_team(self.team, visited_within_days=30)
+
+ self.assertEqual(result.status, "skipped_inactive")
+ mock_count.assert_not_called() # gate short-circuits before any further ClickHouse work
+
+ def test_skips_team_with_existing_rules(self) -> None:
+ self.team.path_cleaning_filters = [{"regex": r"/x", "alias": "/y", "order": 0}]
+ self.team.save()
+ with (
+ patch.object(service, "count_distinct_pathnames") as mock_count,
+ patch.object(service, "call_llm_for_rules") as mock_llm,
+ ):
+ result = generate_suggestions_for_team(self.team, include_configured=False, visited_within_days=None)
+
+ self.assertEqual(result.status, "skipped_configured")
+ mock_count.assert_not_called()
+ mock_llm.assert_not_called()
+
+ def test_skips_low_cardinality(self) -> None:
+ self.team.path_cleaning_filters = []
+ self.team.save()
+ with (
+ patch.object(service, "count_distinct_pathnames", return_value=3),
+ patch.object(service, "call_llm_for_rules") as mock_llm,
+ ):
+ result = generate_suggestions_for_team(self.team, min_distinct_paths=50, visited_within_days=None)
+
+ self.assertEqual(result.status, "skipped_low_cardinality")
+ self.assertEqual(result.distinct_path_count, 3)
+ mock_llm.assert_not_called()
+
+ def test_generates_and_validates(self) -> None:
+ self.team.path_cleaning_filters = []
+ self.team.save()
+ llm_response = SuggestedRulesResponse(
+ rules=[
+ SuggestedRule(regex=r"/users/\d+/profile", alias="/users/<id>/profile", reason="id"),
+ SuggestedRule(regex=r"/orders/\d+$", alias="/orders/<id>"), # matches nothing -> dropped
+ ]
+ )
+ with (
+ patch.object(service, "has_recent_pageviews", return_value=True), # exercises the gate's happy path
+ patch.object(service, "count_distinct_pathnames", return_value=500),
+ patch.object(service, "sample_pathnames", return_value=SAMPLE_PATHS),
+ patch.object(service, "call_llm_for_rules", return_value=llm_response),
+ ):
+ result = generate_suggestions_for_team(self.team, visited_within_days=30)
+
+ self.assertEqual(result.status, "generated")
+ self.assertEqual(len(result.rules), 1) # invalid/no-match rule dropped by validation
+ payload = build_suggestion_payload(result)
+ self.assertEqual(len(payload["rules"]), 1)
+ self.assertEqual(payload["distinct_path_count"], 500)
+ # Health-issue payloads are readable with just health_issue:read — real sampled paths
+ # (the examples, and the model's free-text reason which can quote them) must never be
+ # stored in them.
+ self.assertNotIn("examples", payload["rules"][0])
+ self.assertNotIn("reason", payload["rules"][0])
+
+ def test_error_is_captured_not_raised(self) -> None:
+ self.team.path_cleaning_filters = []
+ self.team.save()
+ with patch.object(service, "count_distinct_pathnames", side_effect=RuntimeError("clickhouse down")):
+ result = generate_suggestions_for_team(self.team, visited_within_days=None)
+
+ self.assertEqual(result.status, "error")
+ self.assertIn("clickhouse down", result.error or "")
+
+ def test_visit_gate_failure_is_captured_not_raised(self) -> None:
+ # The gate query runs inside the per-team guard: a ClickHouse failure there must
+ # produce an error result, not propagate out of a cohort sweep.
+ self.team.path_cleaning_filters = []
+ self.team.save()
+ with patch.object(service, "has_recent_pageviews", side_effect=RuntimeError("clickhouse down")):
+ result = generate_suggestions_for_team(self.team, visited_within_days=30)
+
+ self.assertEqual(result.status, "error")
+ self.assertIn("clickhouse down", result.error or "")
+
+
+class TestPathCleaningSuggestionsCheck(BaseTest):
+ def _check(self):
+ from products.web_analytics.backend.temporal.health_checks.path_cleaning_suggestions import (
+ PathCleaningSuggestionsCheck,
+ )
+
+ return PathCleaningSuggestionsCheck()
+
+ def _generated_result(self) -> "service.TeamSuggestionResult":
+ return service.TeamSuggestionResult(
+ team_id=self.team.id,
+ status="generated",
+ rules=[AnnotatedRule(regex=r"/u/\d+", alias="/u/<id>", order=0, reason="", match_count=2, examples=[])],
+ sampled_path_count=4,
+ distinct_path_count=500,
+ existing_rule_count=0,
+ model="claude-haiku-4-5",
+ )
+
+ def test_existing_active_issue_is_reemitted_without_llm(self) -> None:
+ # If this breaks, every scheduled run re-bills the LLM for every enrolled team and
+ # silently replaces suggestions users are mid-review on.
+ from posthog.models.health_issue import HealthIssue
+
+ from products.web_analytics.backend.temporal.health_checks import path_cleaning_suggestions as check_module
+
+ self.team.path_cleaning_filters = []
+ self.team.save()
+ issue, _ = HealthIssue.upsert_issue(
+ team_id=self.team.id,
+ kind="path_cleaning_suggestions",
+ severity=HealthIssue.Severity.INFO,
+ payload={
+ "rules": [{"regex": "/a", "alias": "/b"}],
+ "model": "m",
+ "sampled_path_count": 1,
+ "distinct_path_count": 100,
+ },
+ hash_keys=[],
+ )
+ with (
+ self.settings(WEB_ANALYTICS_PATH_CLEANING_SUGGESTIONS_TEAM_IDS=[self.team.id]),
+ patch.object(check_module, "generate_suggestions_for_team") as mock_generate,
+ ):
+ results = self._check().detect([self.team.id])
+
+ mock_generate.assert_not_called()
+ self.assertEqual(results[self.team.id][0].payload, issue.payload)
+
+ def test_configured_team_is_reported_healthy(self) -> None:
+ # A team that configured rules (via apply or by hand) must come back healthy so the
+ # framework auto-resolves its suggestion — otherwise applied suggestions linger forever.
+ from products.web_analytics.backend.temporal.health_checks import path_cleaning_suggestions as check_module
+
+ self.team.path_cleaning_filters = [{"regex": "/a", "alias": "/b", "order": 0}]
+ self.team.save()
+ with (
+ self.settings(WEB_ANALYTICS_PATH_CLEANING_SUGGESTIONS_TEAM_IDS=[self.team.id]),
+ patch.object(check_module, "generate_suggestions_for_team") as mock_generate,
+ ):
+ results = self._check().detect([self.team.id])
+
+ mock_generate.assert_not_called()
+ self.assertEqual(results, {})
+
+ def test_empty_generation_stores_nothing(self) -> None:
+ # An empty suggestion must not create an issue — it would shadow nothing useful and
+ # surface a rule-less banner.
+ from products.web_analytics.backend.temporal.health_checks import path_cleaning_suggestions as check_module
+
+ self.team.path_cleaning_filters = []
+ self.team.save()
+ empty = self._generated_result()
+ empty.rules = []
+ with (
+ self.settings(WEB_ANALYTICS_PATH_CLEANING_SUGGESTIONS_TEAM_IDS=[self.team.id]),
+ patch.object(check_module, "generate_suggestions_for_team", return_value=empty),
+ ):
+ results = self._check().detect([self.team.id])
+
+ self.assertEqual(results, {})
+
+ def test_generated_rules_become_an_info_issue(self) -> None:
+ from posthog.models.health_issue import HealthIssue
+
+ from products.web_analytics.backend.temporal.health_checks import path_cleaning_suggestions as check_module
+
+ self.team.path_cleaning_filters = []
+ self.team.save()
+ with (
+ self.settings(WEB_ANALYTICS_PATH_CLEANING_SUGGESTIONS_TEAM_IDS=[self.team.id]),
+ patch.object(check_module, "generate_suggestions_for_team", return_value=self._generated_result()),
+ ):
+ results = self._check().detect([self.team.id])
+
+ self.assertEqual(results[self.team.id][0].severity, HealthIssue.Severity.INFO)
+ self.assertEqual(len(results[self.team.id][0].payload["rules"]), 1)
+
+ def test_team_outside_cohort_is_ignored(self) -> None:
+ from products.web_analytics.backend.temporal.health_checks import path_cleaning_suggestions as check_module
+
+ with (
+ self.settings(WEB_ANALYTICS_PATH_CLEANING_SUGGESTIONS_TEAM_IDS=[]),
+ patch.object(check_module, "generate_suggestions_for_team") as mock_generate,
+ ):
+ results = self._check().detect([self.team.id])
+
+ mock_generate.assert_not_called()
+ self.assertEqual(results, {})
diff --git a/products/web_analytics/backend/test/test_path_cleaning_suggestions_api.py b/products/web_analytics/backend/test/test_path_cleaning_suggestions_api.py
new file mode 100644
index 000000000000..ee17861c3cb1
--- /dev/null
+++ b/products/web_analytics/backend/test/test_path_cleaning_suggestions_api.py
@@ -0,0 +1,208 @@
+from posthog.test.base import APIBaseTest
+from unittest.mock import patch
+
+from parameterized import parameterized
+from rest_framework import status
+
+from posthog.models import Organization, OrganizationMembership, Team
+from posthog.models.health_issue import HealthIssue
+from posthog.models.personal_api_key import PersonalAPIKey, hash_key_value
+from posthog.models.utils import generate_random_token_personal
+
+from products.web_analytics.backend.path_cleaning_suggestions import service
+from products.web_analytics.backend.path_cleaning_suggestions.prompts import SuggestedRule, SuggestedRulesResponse
+
+# Mirrors the stored payload shape: no `examples` and no `reason` — real paths (and model
+# free-text that can quote them) never land in health-issue payloads.
+RULES = [
+ {
+ "regex": r"/users/\d+/profile",
+ "alias": "/users/<id>/profile",
+ "order": 0,
+ "match_count": 3,
+ }
+]
+
+KIND = "path_cleaning_suggestions"
+
+
+class TestPathCleaningSuggestionsAPI(APIBaseTest):
+ def setUp(self) -> None:
+ super().setUp()
+ # apply is project-admin gated (path_cleaning_filters is an admin-only team field), so the
+ # default test user is elevated; the non-admin test demotes explicitly.
+ self.organization_membership.level = OrganizationMembership.Level.ADMIN
+ self.organization_membership.save()
+
+ def _url(self, suffix: str = "") -> str:
+ return f"/api/projects/{self.team.id}/web_analytics_path_cleaning_suggestions/{suffix}"
+
+ def _make_suggestion(self, team: Team) -> HealthIssue:
+ issue, _ = HealthIssue.upsert_issue(
+ team_id=team.id,
+ kind=KIND,
+ severity=HealthIssue.Severity.INFO,
+ payload={"rules": RULES, "model": "claude-haiku-4-5", "sampled_path_count": 4, "distinct_path_count": 500},
+ hash_keys=[],
+ )
+ return issue
+
+ def test_apply_merges_rules_and_resolves_issue(self) -> None:
+ self.team.path_cleaning_filters = []
+ self.team.save()
+ suggestion = self._make_suggestion(self.team)
+
+ response = self.client.post(self._url(f"{suggestion.id}/apply/"))
+ self.assertEqual(response.status_code, status.HTTP_200_OK)
+ self.assertEqual(response.json()["applied"], 1)
+
+ self.team.refresh_from_db()
+ self.assertEqual(self.team.path_cleaning_filters[0]["regex"], r"/users/\d+/profile")
+ suggestion.refresh_from_db()
+ self.assertEqual(suggestion.status, HealthIssue.Status.RESOLVED)
+
+ def test_apply_does_not_overwrite_existing_rules(self) -> None:
+ self.team.path_cleaning_filters = [{"regex": r"/keep", "alias": "/keep", "order": 0}]
+ self.team.save()
+ suggestion = self._make_suggestion(self.team)
+
+ self.client.post(self._url(f"{suggestion.id}/apply/"))
+ self.team.refresh_from_db()
+ regexes = [f["regex"] for f in self.team.path_cleaning_filters]
+ self.assertIn(r"/keep", regexes)
+ self.assertIn(r"/users/\d+/profile", regexes)
+
+ @parameterized.expand(
+ [
+ ("write_scope_allows", ["web_analytics:write"], status.HTTP_200_OK),
+ ("read_scope_forbidden", ["web_analytics:read"], status.HTTP_403_FORBIDDEN),
+ ]
+ )
+ def test_apply_requires_write_scope_for_token_auth(self, _name: str, scopes: list[str], expected: int) -> None:
+ # The write actions must declare required_scopes, or personal-API-key / OAuth token access
+ # (how the MCP server authenticates) is rejected outright. Session auth bypasses scope
+ # checks, so we drop the session and authenticate with a scoped key.
+ self.team.path_cleaning_filters = []
+ self.team.save()
+ suggestion = self._make_suggestion(self.team)
+ value = generate_random_token_personal()
+ PersonalAPIKey.objects.create(
+ user=self.user,
+ label="mcp",
+ secure_value=hash_key_value(value),
+ scopes=scopes,
+ scoped_teams=[self.team.id],
+ )
+ self.client.logout()
+ response = self.client.post(self._url(f"{suggestion.id}/apply/"), headers={"authorization": f"Bearer {value}"})
+ self.assertEqual(response.status_code, expected)
+
+ def test_apply_requires_project_admin(self) -> None:
+ # path_cleaning_filters is admin-gated on the team API; this endpoint must not be a bypass.
+ self.organization_membership.level = OrganizationMembership.Level.MEMBER
+ self.organization_membership.save()
+ self.team.path_cleaning_filters = []
+ self.team.save()
+ suggestion = self._make_suggestion(self.team)
+
+ response = self.client.post(self._url(f"{suggestion.id}/apply/"))
+ self.assertEqual(response.status_code, status.HTTP_403_FORBIDDEN)
+ self.team.refresh_from_db()
+ self.assertEqual(self.team.path_cleaning_filters, [])
+
+ def test_generate_stores_health_issue_and_returns_suggestion(self) -> None:
+ self.team.path_cleaning_filters = []
+ self.team.save()
+ llm_response = SuggestedRulesResponse(
+ rules=[SuggestedRule(regex=r"/users/\d+/profile", alias="/users/<id>/profile")]
+ )
+ with (
+ patch("posthoganalytics.feature_enabled", return_value=True),
+ patch.object(service, "count_distinct_pathnames", return_value=500),
+ patch.object(service, "sample_pathnames", return_value=[("/users/1/profile", 5), ("/users/2/profile", 3)]),
+ patch.object(service, "call_llm_for_rules", return_value=llm_response),
+ ):
+ response = self.client.post(self._url("generate/"))
+
+ self.assertEqual(response.status_code, status.HTTP_200_OK)
+ body = response.json()
+ self.assertEqual(body["status"], "generated")
+ self.assertEqual(len(body["suggestion"]["rules"]), 1)
+ self.assertEqual(body["suggestion"]["rules"][0]["alias"], "/users/<id>/profile")
+ issue = HealthIssue.objects.get(team_id=self.team.id, kind=KIND)
+ self.assertEqual(issue.status, HealthIssue.Status.ACTIVE)
+ self.assertEqual(str(issue.id), body["suggestion"]["id"])
+
+ def test_generate_replaces_previous_active_suggestion(self) -> None:
+ # hash_keys=[] means one active suggestion per team — a regeneration must update the
+ # existing row, not accumulate stale siblings that shadow each other in list reads.
+ self.team.path_cleaning_filters = []
+ self.team.save()
+ first = self._make_suggestion(self.team)
+ llm_response = SuggestedRulesResponse(rules=[SuggestedRule(regex=r"/posts/\d+", alias="/posts/<id>")])
+ with (
+ patch("posthoganalytics.feature_enabled", return_value=True),
+ patch.object(service, "count_distinct_pathnames", return_value=500),
+ patch.object(service, "sample_pathnames", return_value=[("/posts/1", 5), ("/posts/2", 3)]),
+ patch.object(service, "call_llm_for_rules", return_value=llm_response),
+ ):
+ response = self.client.post(self._url("generate/"))
+
+ self.assertEqual(response.status_code, status.HTTP_200_OK)
+ self.assertEqual(HealthIssue.objects.filter(team_id=self.team.id, kind=KIND).count(), 1)
+ first.refresh_from_db()
+ self.assertEqual(first.payload["rules"][0]["alias"], "/posts/<id>")
+
+ def test_generate_requires_feature_flag(self) -> None:
+ # Dogfooding gate: without the flag, generate must not spend a ClickHouse sample + LLM call.
+ with patch("posthoganalytics.feature_enabled", return_value=False):
+ response = self.client.post(self._url("generate/"))
+ self.assertEqual(response.status_code, status.HTTP_403_FORBIDDEN)
+
+ def test_cannot_apply_another_teams_suggestion(self) -> None:
+ other_team = Team.objects.create(organization=Organization.objects.create(name="other"))
+ other_suggestion = self._make_suggestion(other_team)
+
+ response = self.client.post(self._url(f"{other_suggestion.id}/apply/"))
+ self.assertEqual(response.status_code, status.HTTP_404_NOT_FOUND)
+
+ def test_preview_applies_rules_in_order_and_returns_only_changed_paths(self) -> None:
+ suggestion = self._make_suggestion(self.team)
+ sampled = [("/users/1/profile", 100), ("/about", 40)]
+ with patch.object(service, "sample_pathnames", return_value=sampled):
+ response = self.client.get(self._url(f"{suggestion.id}/preview/"))
+
+ self.assertEqual(response.status_code, status.HTTP_200_OK)
+ body = response.json()
+ self.assertEqual(body["sampled_path_count"], 2)
+ self.assertEqual(body["changed_path_count"], 1)
+ self.assertEqual(
+ body["examples"], [{"before": "/users/1/profile", "after": "/users/<id>/profile", "views": 100}]
+ )
+
+ def test_preview_allows_read_scope_and_non_admin(self) -> None:
+ # The preview modal must work for read-only tokens and plain members — it changes nothing.
+ self.organization_membership.level = OrganizationMembership.Level.MEMBER
+ self.organization_membership.save()
+ suggestion = self._make_suggestion(self.team)
+ value = generate_random_token_personal()
+ PersonalAPIKey.objects.create(
+ user=self.user,
+ label="mcp-read",
+ secure_value=hash_key_value(value),
+ scopes=["web_analytics:read"],
+ scoped_teams=[self.team.id],
+ )
+ self.client.logout()
+ with patch.object(service, "sample_pathnames", return_value=[("/users/1/profile", 5)]):
+ response = self.client.get(
+ self._url(f"{suggestion.id}/preview/"), headers={"authorization": f"Bearer {value}"}
+ )
+ self.assertEqual(response.status_code, status.HTTP_200_OK)
+
+ def test_cannot_preview_another_teams_suggestion(self) -> None:
+ other_team = Team.objects.create(organization=Organization.objects.create(name="other-preview"))
+ other_suggestion = self._make_suggestion(other_team)
+
+ response = self.client.get(self._url(f"{other_suggestion.id}/preview/"))
+ self.assertEqual(response.status_code, status.HTTP_404_NOT_FOUND)
diff --git a/products/web_analytics/frontend/generated/api.schemas.ts b/products/web_analytics/frontend/generated/api.schemas.ts
index dbde51482c44..e12668579cde 100644
--- a/products/web_analytics/frontend/generated/api.schemas.ts
+++ b/products/web_analytics/frontend/generated/api.schemas.ts
@@ -676,6 +676,65 @@ export interface PatchedWebAnalyticsFilterPresetApi {
readonly last_modified_by?: UserBasicApi
}
+export interface ApplyPathCleaningSuggestionResponseApi {
+ /** Number of rules merged into the team's path_cleaning_filters. */
+ applied: number
+}
+
+export interface PathCleaningPreviewExampleApi {
+ /** A real sampled path before the suggested rules are applied. */
+ before: string
+ /** The same path after all suggested rules run in order. */
+ after: string
+ /** Pageviews this path received in the sampling window. */
+ views: number
+}
+
+export interface PreviewPathCleaningSuggestionResponseApi {
+ /** Up to 20 before/after pairs for sampled paths the suggested rules would rewrite. */
+ examples: PathCleaningPreviewExampleApi[]
+ /** How many of the sampled paths the suggested rules rewrite in total. */
+ changed_path_count: number
+ /** How many top paths were sampled for this preview. */
+ sampled_path_count: number
+}
+
+export interface SuggestedRuleApi {
+ /** re2 pattern matching the dynamic path segment. */
+ regex: string
+ /** Replacement with angle-bracket placeholders, e.g. /users/<id>. */
+ alias: string
+ /** Apply order; rules run sequentially, output feeds the next. */
+ order: number
+ /** How many of the sampled paths this rule rewrites — evidence the rule was validated on real traffic. */
+ match_count: number
+}
+
+/**
+ * A path-cleaning suggestion, stored as a `path_cleaning_suggestions` health issue.
+ */
+export interface PathCleaningSuggestionIssueApi {
+ /** Health-issue id; pass it to the apply endpoint or the health-issues API. */
+ id: string
+ /** When the suggestion was generated (ISO 8601). */
+ created_at: string
+ /** Validated path-cleaning rules proposed for this team, most specific first. */
+ rules: SuggestedRuleApi[]
+ /** LLM that generated the rules. */
+ model: string
+ /** How many real paths were sampled for generation. */
+ sampled_path_count: number
+ /** Distinct pathnames seen in the sampling window. */
+ distinct_path_count: number
+}
+
+export interface GeneratePathCleaningSuggestionResponseApi {
+ /** generated, skipped_low_cardinality, skipped_no_paths, skipped_configured, or error. */
+ status: string
+ /** The stored suggestion when status is generated, else null. */
+ suggestion?: PathCleaningSuggestionIssueApi | null
+}
+
export type HeatmapScreenshotsContentRetrieveParams = {
/**
* Viewport width (CSS pixels) to fetch. Defaults to 1024. If no exact render exists for this width the closest available one is returned.
diff --git a/products/web_analytics/frontend/generated/api.ts b/products/web_analytics/frontend/generated/api.ts
index 0508541dfe4d..ba9506d71262 100644
--- a/products/web_analytics/frontend/generated/api.ts
+++ b/products/web_analytics/frontend/generated/api.ts
@@ -12,6 +12,8 @@ import type {
AchievementsListResponseApi,
AcknowledgeCelebrationRequestApi,
AcknowledgeCelebrationResponseApi,
+ ApplyPathCleaningSuggestionResponseApi,
+ GeneratePathCleaningSuggestionResponseApi,
HeatmapEventsResponseApi,
HeatmapPreflightRequestApi,
HeatmapPreflightResponseApi,
@@ -24,6 +26,7 @@ import type {
PaginatedWebAnalyticsFilterPresetListApi,
PatchedSavedHeatmapRequestApi,
PatchedWebAnalyticsFilterPresetApi,
+ PreviewPathCleaningSuggestionResponseApi,
RecordInteractionRequestApi,
RecordInteractionResponseApi,
RecordVisitResponseApi,
@@ -616,3 +619,68 @@ export const webAnalyticsFilterPresetsDestroy = async (
method: 'DELETE',
})
}
+
+export const getWebAnalyticsPathCleaningSuggestionsApplyUrl = (projectId: string, id: string) => {
+ return `/api/projects/${projectId}/web_analytics_path_cleaning_suggestions/${id}/apply/`
+}
+
+/**
+ * Merges the suggestion's rules into the team's path_cleaning_filters (never overwrites existing rules) and resolves the underlying health issue. Requires project admin, matching the team API's gate on path_cleaning_filters.
+ * @summary Apply a path-cleaning suggestion
+ */
+export const webAnalyticsPathCleaningSuggestionsApply = async (
+ projectId: string,
+ id: string,
+ options?: RequestInit
+): Promise<ApplyPathCleaningSuggestionResponseApi> => {
+ return apiMutator<ApplyPathCleaningSuggestionResponseApi>(
+ getWebAnalyticsPathCleaningSuggestionsApplyUrl(projectId, id),
+ {
+ ...options,
+ method: 'POST',
+ }
+ )
+}
+
+export const getWebAnalyticsPathCleaningSuggestionsPreviewUrl = (projectId: string, id: string) => {
+ return `/api/projects/${projectId}/web_analytics_path_cleaning_suggestions/${id}/preview/`
+}
+
+/**
+ * Applies the suggestion's rules (in order) to a fresh sample of the team's top paths and returns before/after pairs for the paths that would change. Computed on demand; path samples are never stored. Nothing is modified.
+ * @summary Preview a path-cleaning suggestion on real paths
+ */
+export const webAnalyticsPathCleaningSuggestionsPreview = async (
+ projectId: string,
+ id: string,
+ options?: RequestInit
+): Promise<PreviewPathCleaningSuggestionResponseApi> => {
+ return apiMutator<PreviewPathCleaningSuggestionResponseApi>(
+ getWebAnalyticsPathCleaningSuggestionsPreviewUrl(projectId, id),
+ {
+ ...options,
+ method: 'GET',
+ }
+ )
+}
+
+export const getWebAnalyticsPathCleaningSuggestionsGenerateUrl = (projectId: string) => {
+ return `/api/projects/${projectId}/web_analytics_path_cleaning_suggestions/generate/`
+}
+
+/**
+ * Samples the team's recent paths, asks the LLM for cleaning rules, validates them against the real paths, and stores the result as a `path_cleaning_suggestions` health issue (replacing any previous active one). Runs even if the team already has rules. Returns the suggestion (or a skip status when there aren't enough paths to suggest from).
+ * @summary Generate path-cleaning suggestions on demand
+ */
+export const webAnalyticsPathCleaningSuggestionsGenerate = async (
+ projectId: string,
+ options?: RequestInit
+): Promise<GeneratePathCleaningSuggestionResponseApi> => {
+ return apiMutator<GeneratePathCleaningSuggestionResponseApi>(
+ getWebAnalyticsPathCleaningSuggestionsGenerateUrl(projectId),
+ {
+ ...options,
+ method: 'POST',
+ }
+ )
+}
diff --git a/products/web_analytics/frontend/onboarding/steps.tsx b/products/web_analytics/frontend/onboarding/steps.tsx
index 5be687cadb4c..d713227c3991 100644
--- a/products/web_analytics/frontend/onboarding/steps.tsx
+++ b/products/web_analytics/frontend/onboarding/steps.tsx
@@ -1,10 +1,12 @@
import { SetupTaskId } from 'lib/components/ProductSetup'
+import { FEATURE_FLAGS } from 'lib/constants'
import { OnboardingProductConfiguration } from 'scenes/onboarding/legacy/OnboardingProductConfiguration'
import { type ProductConfigOption } from 'scenes/onboarding/legacy/onboardingProductConfigurationLogic'
import { OnboardingInstallStep } from 'scenes/onboarding/legacy/sdks/OnboardingInstallStep'
import { WebAnalyticsSDKInstructions } from 'scenes/onboarding/legacy/sdks/web-analytics/WebAnalyticsSDKInstructions'
import { INSTALL_DEDUP_KEYS, type ProductOnboardingProvider } from 'scenes/onboarding/legacy/types'
import { OnboardingWebAnalyticsAuthorizedDomainsStep } from 'scenes/onboarding/legacy/web-analytics/OnboardingWebAnalyticsAuthorizedDomainsStep'
+import { OnboardingWebAnalyticsPathCleaningStep } from 'scenes/onboarding/legacy/web-analytics/OnboardingWebAnalyticsPathCleaningStep'
import { urls } from 'scenes/urls'
import { ProductKey } from '~/queries/schema/schema-general'
@@ -102,6 +104,19 @@ export const webAnalyticsOnboarding: ProductOnboardingProvider = {
setupTaskId: SetupTaskId.AddAuthorizedDomain,
render: () => <OnboardingWebAnalyticsAuthorizedDomainsStep />,
},
+ // Dogfooding gate: suggestions (and this step surfacing them) stay flag-only for now.
+ // Read from ctx so the flow recomputes when flags are delivered after first render.
+ ...(ctx.featureFlags[FEATURE_FLAGS.WEB_ANALYTICS_PATH_CLEANING_SUGGESTIONS]
+ ? [
+ {
+ id: `${OnboardingStepKey.PATH_CLEANING}:${ProductKey.WEB_ANALYTICS}`,
+ productKey: ProductKey.WEB_ANALYTICS,
+ stepKey: OnboardingStepKey.PATH_CLEANING,
+ role: ctx.role,
+ render: () => <OnboardingWebAnalyticsPathCleaningStep />,
+ },
+ ]
+ : []),
{
id: `${OnboardingStepKey.PRODUCT_CONFIGURATION}:${ProductKey.WEB_ANALYTICS}`,
productKey: ProductKey.WEB_ANALYTICS,
diff --git a/products/web_analytics/mcp/tools.yaml b/products/web_analytics/mcp/tools.yaml
index a8f58242b452..78e034161fc0 100644
--- a/products/web_analytics/mcp/tools.yaml
+++ b/products/web_analytics/mcp/tools.yaml
@@ -183,6 +183,49 @@ tools:
web-analytics-filter-presets-update:
operation: web_analytics_filter_presets_update
enabled: false
+ web-analytics-path-cleaning-suggestions-apply:
+ operation: web_analytics_path_cleaning_suggestions_apply
+ enabled: true
+ scopes:
+ - web_analytics:write
+ annotations:
+ readOnly: false
+ destructive: true
+ idempotent: false
+ title: Apply a path-cleaning suggestion
+ description: >
+ Apply a suggested set of path-cleaning rules by its health-issue `id`, merging them into the project's path
+ cleaning configuration. Existing rules are never overwritten — only new rules are appended — and the
+ underlying `path_cleaning_suggestions` health issue is resolved. Returns how many rules were added. Requires
+ project admin (the same gate as editing path cleaning rules in team settings). Applying changes historical
+ numbers in every Web analytics and Paths chart that has cleaning enabled, so confirm with the user before
+ calling this.
+ feature_flag: web-analytics-path-cleaning-suggestions
+ web-analytics-path-cleaning-suggestions-generate:
+ operation: web_analytics_path_cleaning_suggestions_generate
+ enabled: true
+ scopes:
+ - web_analytics:write
+ annotations:
+ readOnly: false
+ destructive: false
+ idempotent: false
+ title: Generate path-cleaning suggestions
+ description: >
+ Analyze the project's recent URL paths and generate suggested path-cleaning rules on demand. Samples the
+ most-viewed paths, asks the model for `{regex, alias}` rules, and validates each against the real paths
+ (dropping any that don't match), then stores the result as a `path_cleaning_suggestions` health issue.
+ Returns `status` ('generated' with a `suggestion`, or a skip reason like 'skipped_no_paths' /
+ 'skipped_low_cardinality' when there isn't enough to suggest from). Pending suggestions surface through the
+ health-issues API (filter `kind=path_cleaning_suggestions`); dismiss one by PATCHing the issue's `dismissed`
+ flag. Use when the user asks to clean up or normalize their paths and no suggestion exists yet. This only
+ proposes rules — apply them with `web-analytics-path-cleaning-suggestions-apply`; nothing changes until
+ then.
+ requires_ai_consent: true
+ feature_flag: web-analytics-path-cleaning-suggestions
+ web-analytics-path-cleaning-suggestions-preview:
+ operation: web_analytics_path_cleaning_suggestions_preview
+ enabled: false
web-analytics-recap:
operation: web_analytics_recap
enabled: false
diff --git a/products/web_analytics/skills/suggesting-path-cleaning-rules/SKILL.md b/products/web_analytics/skills/suggesting-path-cleaning-rules/SKILL.md
new file mode 100644
index 000000000000..23915b372f8f
--- /dev/null
+++ b/products/web_analytics/skills/suggesting-path-cleaning-rules/SKILL.md
@@ -0,0 +1,125 @@
+---
+name: suggesting-path-cleaning-rules
+description: 'Runs and reasons about the automated AI health check that suggests path-cleaning rules for web-analytics teams. Use when asked to generate path-cleaning suggestions for a team or cohort, to run the suggestion check, to review/apply AI-suggested rules, to inspect path_cleaning_suggestions health issues, or to extend the suggestion pipeline. Covers the suggest_path_cleaning_rules management command, the path_cleaning_suggestions health check, the cohort gating (precompute teams), and how suggestions are validated against real paths before storage. For hand-authoring or applying rules directly, use managing-path-cleaning-rules instead.'
+---
+
+# Suggesting path-cleaning rules
+
+Many teams never configure path cleaning, so their Web analytics breakdowns fragment across
+thousands of near-identical URLs. This feature **proactively suggests** cleaning rules for the
+web-analytics precompute cohort: weekly, for each team, it samples real paths, asks the LLM for
+`{regex, alias}` rules, validates them against the team's own paths, and stores them for review.
+
+It **only suggests** — it never auto-applies. Applying rewrites historical numbers in every cleaned
+chart, so that stays a human decision (the existing settings UI, or the `--apply` flag below after
+review). To hand-author or directly apply rules, use the `managing-path-cleaning-rules` skill.
+
+## Architecture
+
+- **Core**: `products/web_analytics/backend/path_cleaning_suggestions/service.py`
+ - `sample_pathnames` / `count_distinct_pathnames` — top `$pathname` by views via HogQL.
+ - `call_llm_for_rules` — one-shot call through the LLM gateway
+ (`get_llm_client(product="web_analytics", team_id=...)`, model
+ `WEB_ANALYTICS_PATH_CLEANING_SUGGESTIONS_MODEL`, default `claude-haiku-4-5`).
+ - `validate_and_annotate_rules` — compiles each regex with **re2** (the engine ClickHouse
+ `replaceRegexpAll` uses) and test-applies it to the sampled paths. Rules that don't compile or
+ match nothing are dropped; survivors get a dense `order`, a `match_count`, and in-memory
+ before/after `examples` (printed by the management command, never stored — health-issue
+ payloads are readable with just `health_issue:read` and must not leak real paths). This is
+ the skill's "test before saving" step, automated.
+ - `generate_suggestions_for_team` — orchestrates the above with gating (see below); pure
+ generation, no storage.
+ - `apply_suggestions_to_team` — **merges** rules into `path_cleaning_filters`, never overwrites
+ (dedupes by regex, continues `order`).
+- **Storage**: a `path_cleaning_suggestions` **health issue** (`HealthIssue`, severity `info`) — no
+ dedicated model. One active issue per team (`hash_keys=[]`); `payload` carries `rules`, `model`,
+ `sampled_path_count`, `distinct_path_count`. Applying (or hand-configuring rules) resolves the
+ issue on the next check run; dismissal is the health-issue `dismissed` flag.
+- **Schedule**: `PathCleaningSuggestionsCheck`
+ (`products/web_analytics/backend/temporal/health_checks/path_cleaning_suggestions.py`), a health
+ check on the shared health-check framework, weekly (Mon 06:23 UTC), small sequential batches
+ because each eligible team costs an LLM call. Teams with an existing active suggestion are
+ re-emitted without a fresh LLM round trip.
+- **Cohort**: `WEB_ANALYTICS_PATH_CLEANING_SUGGESTIONS_TEAM_IDS`, defaulting to the precompute
+ enrollment list `WEB_ANALYTICS_LAZY_PRECOMPUTE_TEAM_IDS`.
+
+## Gating (why a team is skipped)
+
+`generate_suggestions_for_team` returns a status:
+
+- `skipped_inactive` — team sent no `$pageview` within `visited_within_days` (default 30); we only
+ suggest for teams actively using web analytics. Bypass with `--ignore-visit-gate`.
+- `skipped_configured` — team already has path cleaning rules (override with `include_configured`).
+- `skipped_low_cardinality` — fewer distinct paths than `min_distinct_paths` (default 50); cleaning
+ adds no value, so we don't spend tokens.
+- `skipped_no_paths` — no pageviews in the window.
+- `generated` — rules produced (may be an empty list if paths are already clean; empty generations
+ are never stored, so they can't shadow an actionable suggestion).
+- `error` — sampling/LLM failed; captured per-team, never aborts the cohort sweep.
+
+## How users see and apply suggestions
+
+- **Settings banner**: `PathCleaningSuggestionsBanner` on `/settings/project#path_cleaning` shows the
+ latest `suggested` row as regex → alias previews with match counts; "Apply all" (project admins
+ only) merges the rules, the close button dismisses. Driven by `pathCleaningSuggestionsLogic`.
+- **Onboarding step**: `OnboardingWebAnalyticsPathCleaningStep` (stepKey `path_cleaning`) surfaces the
+ same banner during Web analytics onboarding.
+- **API** (`products/web_analytics/backend/api/web_analytics_path_cleaning_suggestions.py`):
+ `POST /api/projects/:id/web_analytics_path_cleaning_suggestions/generate/` produces and stores a
+ fresh suggestion on demand; `GET .../{issue_id}/preview/` applies the rules to a fresh sample of
+ the team's top paths and returns before/after pairs (read scope, computed on demand, never
+ stored — this backs the banner's "Preview on your paths" modal); `POST .../{issue_id}/apply/`
+ merges the rules and resolves the issue (project admin only — the same gate the team API puts on
+ `path_cleaning_filters`).
+ Listing and dismissing go through the generic health-issues API
+ (`GET /api/projects/:id/health_issues/?kind=path_cleaning_suggestions&status=active&dismissed=false`,
+ `PATCH .../health_issues/{id}/` with `{"dismissed": true}`).
+- **Health page**: the check renders on `/web/health` alongside the other web-analytics checks, with
+ remediation guidance for humans and agents.
+- **PostHog AI (Max)**: generate/apply are exposed as MCP tools in
+ `products/web_analytics/mcp/tools.yaml` (`web-analytics-path-cleaning-suggestions-{generate,apply}`),
+ so a user can ask Max to suggest path-cleaning rules and apply them conversationally. Apply is
+ `destructive` (it changes historical chart numbers), so the MCP confirmation gate applies.
+
+## Running it
+
+```sh
+# Default cohort, print suggestions, store health issues:
+python manage.py suggest_path_cleaning_rules
+
+# Specific teams, dry run (nothing stored):
+python manage.py suggest_path_cleaning_rules --teams 2,19279 --no-store
+
+# Generate AND apply for one reviewed team (merges, never overwrites):
+python manage.py suggest_path_cleaning_rules --teams 2 --apply
+```
+
+Useful flags: `--days` (lookback), `--limit` (top-N paths sampled), `--min-distinct-paths`,
+`--include-configured`, `--no-store`, `--apply`.
+
+The health check can also be triggered per team from the health-issues `refresh` endpoint or the
+admin UI, like any other health check.
+
+## Reviewing suggestions
+
+Read a team's active suggestion:
+
+```python
+HealthIssue.objects.filter(team_id=team_id, kind="path_cleaning_suggestions", status="active").first()
+```
+
+Each rule in `payload["rules"]` carries `regex`, `alias`, `order`, `reason`, and `match_count` —
+that's what to show a human deciding whether to apply. Before/after examples on real paths are only
+printed by the management command at generation time; they are deliberately kept out of the stored
+payload.
+
+## Extending
+
+- Adding a surfacing channel (in-app notification, settings banner, onboarding wizard step): read the
+ team's active `path_cleaning_suggestions` health issue and render its `payload["rules"]`. Keep
+ apply manual.
+- Changing the model: it must be allowlisted for the `web_analytics` product in
+ `services/llm-gateway/src/llm_gateway/products/config.py`.
+- The agentic alternative — a `signals-scout-web-analytics-path-cleaning` scout — is sketched in the
+ design notes; prefer the dedicated job for the precompute cohort because it targets that exact
+ cohort and surfaces structured, validated rows rather than Signals-inbox findings.
diff --git a/services/llm-gateway/src/llm_gateway/config.py b/services/llm-gateway/src/llm_gateway/config.py
index f6ec1fd272f7..843d99fe7bd3 100644
--- a/services/llm-gateway/src/llm_gateway/config.py
+++ b/services/llm-gateway/src/llm_gateway/config.py
@@ -36,6 +36,10 @@ DEFAULT_PRODUCT_COST_LIMITS: dict[str, "ProductCostLimit"] = {
"signals": ProductCostLimit(limit_usd=25000.0, window_seconds=86400),
"posthog_ai": ProductCostLimit(limit_usd=5000.0, window_seconds=86400),
"changelog_bot": ProductCostLimit(limit_usd=500.0, window_seconds=86400),
+ # Path-cleaning suggestions: haiku-only, a few short calls per team per week. The product is
+ # unbilled and reachable with any feature-gated llm_gateway:read key, so a tight cap bounds
+ # abuse of the shared budget rather than real usage.
+ "web_analytics": ProductCostLimit(limit_usd=100.0, window_seconds=86400),
}
DEFAULT_USER_COST_LIMITS: dict[str, "UserCostLimit"] = {
diff --git a/services/llm-gateway/src/llm_gateway/products/config.py b/services/llm-gateway/src/llm_gateway/products/config.py
index 389c7235fd62..99752eb2786e 100644
--- a/services/llm-gateway/src/llm_gateway/products/config.py
+++ b/services/llm-gateway/src/llm_gateway/products/config.py
@@ -325,6 +325,12 @@ PRODUCTS: Final[dict[str, ProductConfig]] = {
allow_api_keys=True,
credit_bucket=CreditBucket.AI_CREDITS,
),
+ "web_analytics": ProductConfig(
+ allowed_application_ids=None,
+ allowed_models=frozenset({"claude-haiku-4-5"}),
+ allow_api_keys=True,
+ credit_bucket=None,
+ ),
# changelog-bot. Exact-pinned to these two ids (the agent sends "openai/"-prefixed).
"changelog_bot": ProductConfig(
allowed_application_ids=None,
diff --git a/services/mcp/schema/generated-tool-definitions.json b/services/mcp/schema/generated-tool-definitions.json
index 346851cd476f..208b172e05ea 100644
--- a/services/mcp/schema/generated-tool-definitions.json
+++ b/services/mcp/schema/generated-tool-definitions.json
@@ -10701,6 +10701,37 @@
"readOnlyHint": false
}
},
+ "web-analytics-path-cleaning-suggestions-apply": {
+ "description": "Apply a suggested set of path-cleaning rules by its health-issue `id`, merging them into the project's path cleaning configuration. Existing rules are never overwritten — only new rules are appended — and the underlying `path_cleaning_suggestions` health issue is resolved. Returns how many rules were added. Requires project admin (the same gate as editing path cleaning rules in team settings). Applying changes historical numbers in every Web analytics and Paths chart that has cleaning enabled, so confirm with the user before calling this.",
+ "category": "Web analytics",
+ "feature": "web_analytics",
+ "summary": "Apply a path-cleaning suggestion",
+ "title": "Apply a path-cleaning suggestion",
+ "required_scopes": ["web_analytics:write"],
+ "annotations": {
+ "destructiveHint": true,
+ "idempotentHint": false,
+ "openWorldHint": true,
+ "readOnlyHint": false
+ },
+ "feature_flag": "web-analytics-path-cleaning-suggestions"
+ },
+ "web-analytics-path-cleaning-suggestions-generate": {
+ "description": "Analyze the project's recent URL paths and generate suggested path-cleaning rules on demand. Samples the most-viewed paths, asks the model for `{regex, alias}` rules, and validates each against the real paths (dropping any that don't match), then stores the result as a `path_cleaning_suggestions` health issue. Returns `status` ('generated' with a `suggestion`, or a skip reason like 'skipped_no_paths' / 'skipped_low_cardinality' when there isn't enough to suggest from). Pending suggestions surface through the health-issues API (filter `kind=path_cleaning_suggestions`); dismiss one by PATCHing the issue's `dismissed` flag. Use when the user asks to clean up or normalize their paths and no suggestion exists yet. This only proposes rules — apply them with `web-analytics-path-cleaning-suggestions-apply`; nothing changes until then.",
+ "category": "Web analytics",
+ "feature": "web_analytics",
+ "summary": "Generate path-cleaning suggestions",
+ "title": "Generate path-cleaning suggestions",
+ "required_scopes": ["web_analytics:write"],
+ "annotations": {
+ "destructiveHint": false,
+ "idempotentHint": false,
+ "openWorldHint": true,
+ "readOnlyHint": false
+ },
+ "requires_ai_consent": true,
+ "feature_flag": "web-analytics-path-cleaning-suggestions"
+ },
"web-analytics-weekly-digest": {
"description": "Summarizes a project's web analytics over a lookback window (default 7 days): unique visitors, pageviews, sessions, bounce rate, and average session duration with period-over-period comparisons, plus the top 5 pages, top 5 traffic sources, and goal conversions. Accepts optional `days` (1–90, default 7) and `compare` (bool, default true) query params — pass `days=30` to summarize the last month, or `compare=false` to skip the period-over-period comparison for a faster response. Use this to answer questions like \"how are my web analytics?\", \"how did the site do last week?\", or \"what's my traffic looking like this month?\".",
"category": "Web analytics",
diff --git a/services/mcp/schema/tool-definitions-all.json b/services/mcp/schema/tool-definitions-all.json
index b0b0fd616997..29e30b4a9e77 100644
--- a/services/mcp/schema/tool-definitions-all.json
+++ b/services/mcp/schema/tool-definitions-all.json
@@ -11341,6 +11341,37 @@
"readOnlyHint": false
}
},
+ "web-analytics-path-cleaning-suggestions-apply": {
+ "description": "Apply a suggested set of path-cleaning rules by its health-issue `id`, merging them into the project's path cleaning configuration. Existing rules are never overwritten — only new rules are appended — and the underlying `path_cleaning_suggestions` health issue is resolved. Returns how many rules were added. Requires project admin (the same gate as editing path cleaning rules in team settings). Applying changes historical numbers in every Web analytics and Paths chart that has cleaning enabled, so confirm with the user before calling this.",
+ "category": "Web analytics",
+ "feature": "web_analytics",
+ "summary": "Apply a path-cleaning suggestion",
+ "title": "Apply a path-cleaning suggestion",
+ "required_scopes": ["web_analytics:write"],
+ "annotations": {
+ "destructiveHint": true,
+ "idempotentHint": false,
+ "openWorldHint": true,
+ "readOnlyHint": false
+ },
+ "feature_flag": "web-analytics-path-cleaning-suggestions"
+ },
+ "web-analytics-path-cleaning-suggestions-generate": {
+ "description": "Analyze the project's recent URL paths and generate suggested path-cleaning rules on demand. Samples the most-viewed paths, asks the model for `{regex, alias}` rules, and validates each against the real paths (dropping any that don't match), then stores the result as a `path_cleaning_suggestions` health issue. Returns `status` ('generated' with a `suggestion`, or a skip reason like 'skipped_no_paths' / 'skipped_low_cardinality' when there isn't enough to suggest from). Pending suggestions surface through the health-issues API (filter `kind=path_cleaning_suggestions`); dismiss one by PATCHing the issue's `dismissed` flag. Use when the user asks to clean up or normalize their paths and no suggestion exists yet. This only proposes rules — apply them with `web-analytics-path-cleaning-suggestions-apply`; nothing changes until then.",
+ "category": "Web analytics",
+ "feature": "web_analytics",
+ "summary": "Generate path-cleaning suggestions",
+ "title": "Generate path-cleaning suggestions",
+ "required_scopes": ["web_analytics:write"],
+ "annotations": {
+ "destructiveHint": false,
+ "idempotentHint": false,
+ "openWorldHint": true,
+ "readOnlyHint": false
+ },
+ "requires_ai_consent": true,
+ "feature_flag": "web-analytics-path-cleaning-suggestions"
+ },
"web-analytics-weekly-digest": {
"description": "Summarizes a project's web analytics over a lookback window (default 7 days): unique visitors, pageviews, sessions, bounce rate, and average session duration with period-over-period comparisons, plus the top 5 pages, top 5 traffic sources, and goal conversions. Accepts optional `days` (1–90, default 7) and `compare` (bool, default true) query params — pass `days=30` to summarize the last month, or `compare=false` to skip the period-over-period comparison for a faster response. Use this to answer questions like \"how are my web analytics?\", \"how did the site do last week?\", or \"what's my traffic looking like this month?\".",
"category": "Web analytics",
diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.ts
index 9080a765052a..28e763b01149 100644
--- a/services/mcp/src/api/generated.ts
+++ b/services/mcp/src/api/generated.ts
@@ -9271,6 +9271,11 @@ export namespace Schemas {
Agents: 'agents',
} as const;
+ export interface ApplyPathCleaningSuggestionResponse {
+ /** Number of rules merged into the team's path_cleaning_filters. */
+ applied: number;
+ }
+
/**
* * `members` - members
* * `agents` - agents
@@ -34053,6 +34058,42 @@ export namespace Schemas {
period?: Period;
}
+ export interface SuggestedRule {
+ /** re2 pattern matching the dynamic path segment. */
+ regex: string;
+ /** Replacement with angle-bracket placeholders, e.g. /users/<id>. */
+ alias: string;
+ /** Apply order; rules run sequentially, output feeds the next. */
+ order: number;
+ /** How many of the sampled paths this rule rewrites — evidence the rule was validated on real traffic. */
+ match_count: number;
+ }
+
+ /**
+ * A path-cleaning suggestion, stored as a `path_cleaning_suggestions` health issue.
+ */
+ export interface PathCleaningSuggestionIssue {
+ /** Health-issue id; pass it to the apply endpoint or the health-issues API. */
+ id: string;
+ /** When the suggestion was generated (ISO 8601). */
+ created_at: string;
+ /** Validated path-cleaning rules proposed for this team, most specific first. */
+ rules: SuggestedRule[];
+ /** LLM that generated the rules. */
+ model: string;
+ /** How many real paths were sampled for generation. */
+ sampled_path_count: number;
+ /** Distinct pathnames seen in the sampling window. */
+ distinct_path_count: number;
+ }
+
+ export interface GeneratePathCleaningSuggestionResponse {
+ /** generated, skipped_low_cardinality, skipped_no_paths, skipped_configured, or error. */
+ status: string;
+ /** The stored suggestion when status is generated, else null. */
+ suggestion?: PathCleaningSuggestionIssue | null;
+ }
+
export type GenerateRequestStepsItem = { [key: string]: unknown };
export interface GenerateRequest {
@@ -58134,6 +58175,15 @@ export namespace Schemas {
variants?: unknown;
}
+ export interface PathCleaningPreviewExample {
+ /** A real sampled path before the suggested rules are applied. */
+ before: string;
+ /** The same path after all suggested rules run in order. */
+ after: string;
+ /** Pageviews this path received in the sampling window. */
+ views: number;
+ }
+
export interface PauseResponse {
/** Always 'paused'. */
status: string;
@@ -58558,6 +58608,15 @@ export namespace Schemas {
is_preview_link: boolean;
}
+ export interface PreviewPathCleaningSuggestionResponse {
+ /** Up to 20 before/after pairs for sampled paths the suggested rules would rewrite. */
+ examples: PathCleaningPreviewExample[];
+ /** How many of the sampled paths the suggested rules rewrite in total. */
+ changed_path_count: number;
+ /** How many top paths were sampled for this preview. */
+ sampled_path_count: number;
+ }
+
/**
* Mapping from event name to the team-configured primary property for that event. Names without a configured primary property are omitted; callers should fall back to the core taxonomy defaults for those.
*/
diff --git a/services/mcp/src/generated/web_analytics/api.ts b/services/mcp/src/generated/web_analytics/api.ts
index 319a3b05be5b..48b5846e719a 100644
--- a/services/mcp/src/generated/web_analytics/api.ts
+++ b/services/mcp/src/generated/web_analytics/api.ts
@@ -3,7 +3,7 @@
* MCP service uses these Zod schemas for generated tool handlers.
* To regenerate: hogli build:openapi
*
- * PostHog API - MCP 8 enabled ops
+ * PostHog API - MCP 10 enabled ops
* OpenAPI spec version: 1.0.0
*/
import * as zod from 'zod'
@@ -415,3 +415,28 @@ export const WebAnalyticsWeeklyDigestQueryParams = /* @__PURE__ */ zod.object({
.default(webAnalyticsWeeklyDigestQueryDaysDefault)
.describe('Lookback window in days (1–90). Defaults to 7.'),
})
+
+/**
+ * Merges the suggestion's rules into the team's path_cleaning_filters (never overwrites existing rules) and resolves the underlying health issue. Requires project admin, matching the team API's gate on path_cleaning_filters.
+ * @summary Apply a path-cleaning suggestion
+ */
+export const WebAnalyticsPathCleaningSuggestionsApplyParams = /* @__PURE__ */ zod.object({
+ id: zod.string(),
+ project_id: zod
+ .string()
+ .describe(
+ "Project ID of the project you're trying to access. To find the ID of the project, make a call to \/api\/projects\/."
+ ),
+})
+
+/**
+ * Samples the team's recent paths, asks the LLM for cleaning rules, validates them against the real paths, and stores the result as a `path_cleaning_suggestions` health issue (replacing any previous active one). Runs even if the team already has rules. Returns the suggestion (or a skip status when there aren't enough paths to suggest from).
+ * @summary Generate path-cleaning suggestions on demand
+ */
+export const WebAnalyticsPathCleaningSuggestionsGenerateParams = /* @__PURE__ */ zod.object({
+ project_id: zod
+ .string()
+ .describe(
+ "Project ID of the project you're trying to access. To find the ID of the project, make a call to \/api\/projects\/."
+ ),
+})
diff --git a/services/mcp/src/tools/generated/web_analytics.ts b/services/mcp/src/tools/generated/web_analytics.ts
index a6cc9fd77410..1d8b7cde632d 100644
--- a/services/mcp/src/tools/generated/web_analytics.ts
+++ b/services/mcp/src/tools/generated/web_analytics.ts
@@ -11,6 +11,7 @@ import {
SavedPartialUpdateParams,
SavedRegenerateCreateParams,
SavedRetrieveParams,
+ WebAnalyticsPathCleaningSuggestionsApplyParams,
WebAnalyticsWeeklyDigestQueryParams,
} from '@/generated/web_analytics/api'
import { createQueryWrapper } from '@/tools/query-wrapper-factory'
@@ -213,6 +214,45 @@ const heatmapsSavedUpdate = (): ToolBase<typeof HeatmapsSavedUpdateSchema, Schem
},
})
+const WebAnalyticsPathCleaningSuggestionsApplySchema = WebAnalyticsPathCleaningSuggestionsApplyParams.omit({
+ project_id: true,
+})
+
+const webAnalyticsPathCleaningSuggestionsApply = (): ToolBase<
+ typeof WebAnalyticsPathCleaningSuggestionsApplySchema,
+ Schemas.ApplyPathCleaningSuggestionResponse
+> => ({
+ name: 'web-analytics-path-cleaning-suggestions-apply',
+ schema: WebAnalyticsPathCleaningSuggestionsApplySchema,
+ handler: async (context: Context, params: z.infer<typeof WebAnalyticsPathCleaningSuggestionsApplySchema>) => {
+ const projectId = await context.stateManager.getProjectId()
+ const result = await context.api.request<Schemas.ApplyPathCleaningSuggestionResponse>({
+ method: 'POST',
+ path: `/api/projects/${encodeURIComponent(String(projectId))}/web_analytics_path_cleaning_suggestions/${encodeURIComponent(String(params.id))}/apply/`,
+ })
+ return result
+ },
+})
+
+const WebAnalyticsPathCleaningSuggestionsGenerateSchema = z.object({})
+
+const webAnalyticsPathCleaningSuggestionsGenerate = (): ToolBase<
+ typeof WebAnalyticsPathCleaningSuggestionsGenerateSchema,
+ Schemas.GeneratePathCleaningSuggestionResponse
+> => ({
+ name: 'web-analytics-path-cleaning-suggestions-generate',
+ schema: WebAnalyticsPathCleaningSuggestionsGenerateSchema,
+ // eslint-disable-next-line no-unused-vars
+ handler: async (context: Context, params: z.infer<typeof WebAnalyticsPathCleaningSuggestionsGenerateSchema>) => {
+ const projectId = await context.stateManager.getProjectId()
+ const result = await context.api.request<Schemas.GeneratePathCleaningSuggestionResponse>({
+ method: 'POST',
+ path: `/api/projects/${encodeURIComponent(String(projectId))}/web_analytics_path_cleaning_suggestions/generate/`,
+ })
+ return result
+ },
+})
+
const WebAnalyticsWeeklyDigestSchema = WebAnalyticsWeeklyDigestQueryParams
const webAnalyticsWeeklyDigest = (): ToolBase<typeof WebAnalyticsWeeklyDigestSchema, Schemas.WeeklyDigestResponse> => ({
@@ -542,6 +582,8 @@ export const GENERATED_TOOLS: Record<string, () => ToolBase<ZodObjectAny>> = {
'heatmaps-saved-list': heatmapsSavedList,
'heatmaps-saved-regenerate': heatmapsSavedRegenerate,
'heatmaps-saved-update': heatmapsSavedUpdate,
+ 'web-analytics-path-cleaning-suggestions-apply': webAnalyticsPathCleaningSuggestionsApply,
+ 'web-analytics-path-cleaning-suggestions-generate': webAnalyticsPathCleaningSuggestionsGenerate,
'web-analytics-weekly-digest': webAnalyticsWeeklyDigest,
'query-web-overview': createQueryWrapper({
name: 'query-web-overview',
diff --git a/services/mcp/tests/unit/tool-filtering.test.ts b/services/mcp/tests/unit/tool-filtering.test.ts
index 3ea3e7e2bab9..ba44b06209ea 100644
--- a/services/mcp/tests/unit/tool-filtering.test.ts
+++ b/services/mcp/tests/unit/tool-filtering.test.ts
@@ -852,6 +852,7 @@ describe('Tool Filtering - Feature Flags', () => {
'metrics',
'endpoints-ai-materialization-fix',
'engineering-analytics',
+ 'web-analytics-path-cleaning-suggestions',
'stamphog',
'product-data-catalog',
'loops',
@@ -860,7 +861,7 @@ describe('Tool Filtering - Feature Flags', () => {
'streamlit-apps',
])
)
- expect(flags).toHaveLength(28)
+ expect(flags).toHaveLength(29)
})
it('every loops tool is gated on the loops flag', () => {