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(paths): support capture groups in path cleaning aliases (#78193)

Xanderb1967ec2d543
diff --git a/frontend/src/lib/components/PathCleanFilters/PathCleaningRulesDebugger.tsx b/frontend/src/lib/components/PathCleanFilters/PathCleaningRulesDebugger.tsx
index 8e0b24328492..ca923f452ca1 100644
--- a/frontend/src/lib/components/PathCleanFilters/PathCleaningRulesDebugger.tsx
+++ b/frontend/src/lib/components/PathCleanFilters/PathCleaningRulesDebugger.tsx
@@ -6,6 +6,7 @@ import { isValidRegexp } from 'lib/utils/regexp'
import { PathCleaningFilter } from '~/types'
import { parseAliasToReadable } from './PathCleanFilterItem'
+import { applyPathCleaningRule } from './pathCleaningUtils'
interface ProcessingStep {
stepNumber: number
@@ -28,11 +29,7 @@ const cleanPathWithDebugSteps = (path: string, filters: PathCleaningFilter[]): P
filters.forEach((filter, index) => {
const isValidRegex = isValidRegexp(filter.regex ?? '')
- let outputPath = currentPath
-
- if (isValidRegex) {
- outputPath = currentPath.replace(new RegExp(filter.regex ?? '', 'gi'), filter.alias ?? '')
- }
+ const outputPath = applyPathCleaningRule(currentPath, filter)
steps.push({
stepNumber: index + 1,
diff --git a/frontend/src/lib/components/PathCleanFilters/PathRegexModal.tsx b/frontend/src/lib/components/PathCleanFilters/PathRegexModal.tsx
index 04fbe14116c1..62024bd53214 100644
--- a/frontend/src/lib/components/PathCleanFilters/PathRegexModal.tsx
+++ b/frontend/src/lib/components/PathCleanFilters/PathRegexModal.tsx
@@ -2,12 +2,13 @@ import { useEffect, useState } from 'react'
import { LemonButton, LemonInput, LemonModal, Link } from '@posthog/lemon-ui'
-import { isValidRegexp } from 'lib/utils/regexp'
import { AiRegexHelperButton } from 'scenes/session-recordings/components/AiRegexHelper/AiRegexHelper'
import { AiRegexHelper } from 'scenes/session-recordings/components/AiRegexHelper/AiRegexHelper'
import { PathCleaningFilter } from '~/types'
+import { isValidPathCleaningRegex } from './pathCleaningUtils'
+
export interface PathRegexModalProps {
isOpen: boolean
onSave: (filter: PathCleaningFilter) => void
@@ -24,7 +25,7 @@ export function PathRegexModal({ filter, isOpen, onSave, onClose }: PathRegexMod
? 'Alias is required'
: !regex
? 'Regex is required'
- : !isValidRegexp(regex)
+ : !isValidPathCleaningRegex(regex)
? 'Malformed regex'
: null
@@ -82,6 +83,17 @@ export function PathRegexModal({ filter, isOpen, onSave, onClose }: PathRegexMod
Example:{' '}
<span className="font-mono text-accent text-xs">{'/merchant/<id>/dashboard'}</span>
</span>
+ <br />
+ <span>
+ To keep part of the original path, reference a capture group from the regex with{' '}
+ <span className="font-mono text-accent text-xs">{'\\1'}</span>,{' '}
+ <span className="font-mono text-accent text-xs">{'\\2'}</span>, and so on. For
+ example, regex{' '}
+ <span className="font-mono text-accent text-xs">{'/user/(\\d+)/profile'}</span> with
+ alias <span className="font-mono text-accent text-xs">{'/user/\\1'}</span> keeps the
+ id. Capture groups slow queries down, so use them when one rule can replace several
+ near-identical ones.
+ </span>
</p>
</div>
</div>
diff --git a/frontend/src/lib/components/PathCleanFilters/pathCleaningUtils.test.ts b/frontend/src/lib/components/PathCleanFilters/pathCleaningUtils.test.ts
new file mode 100644
index 000000000000..4097fd8e2781
--- /dev/null
+++ b/frontend/src/lib/components/PathCleanFilters/pathCleaningUtils.test.ts
@@ -0,0 +1,62 @@
+import { applyPathCleaning, applyPathCleaningRule, expandAlias } from './pathCleaningUtils'
+
+// [name, alias, groups (index 0 is the whole match), expected]
+const EXPAND_CASES: [string, string, (string | undefined)[], string][] = [
+ ['group reference', '/u/\\1', ['/users/42', '42'], '/u/42'],
+ ['whole-match reference', '[\\0]', ['/users/42', '42'], '[/users/42]'],
+ ['escaped backslash before a digit is literal', '\\\\1', ['/users/42', '42'], '\\1'],
+ // ClickHouse emits `$` verbatim, so the preview must not read it as a group reference.
+ ['dollar stays literal', '/u/$1', ['/users/42', '42'], '/u/$1'],
+ // re2 has no `\10` — it reads group 1 then a literal `0`, where JS `$10` would take group 10.
+ ['two-digit reference is group 1 then a literal', '\\10', ['ab', 'a', 'b'], 'a0'],
+ ['group the pattern never filled substitutes as empty', '/u/\\2', ['/users/42', '42', undefined], '/u/'],
+]
+
+describe('pathCleaningUtils', () => {
+ it.each(EXPAND_CASES)('expandAlias: %s', (_name, alias, groups, expected) => {
+ expect(expandAlias(alias, groups)).toBe(expected)
+ })
+
+ it.each([
+ // Reuses capture group 1, matching what ClickHouse replaceRegexpAll does on the backend.
+ ['keeps a captured id', '/users/42/profile', '/users/(\\d+)/profile', '/users/\\1', '/users/42'],
+ [
+ 'captures leading segments and drops the hash',
+ '/a/b/c/#random',
+ '^(/[^/#]+/[^/#]+/[^/#]+)/#.*$',
+ '\\1',
+ '/a/b/c',
+ ],
+ // A `$1` alias is a literal in ClickHouse, so the preview must not treat it as a group ref.
+ ['dollar-one is not a group reference', '/users/42', '/users/(\\d+)', '/u/$1', '/u/$1'],
+ // With ten groups in play, a JS `$10` replacement string would wrongly resolve to group 10.
+ [
+ 'two-digit reference resolves against re2 rules, not JavaScript ones',
+ 'abcdefghij',
+ '(a)(b)(c)(d)(e)(f)(g)(h)(i)(j)',
+ '\\10',
+ 'a0',
+ ],
+ // re2 is case-sensitive, so a case-mismatched rule must not clean here either — otherwise the
+ // preview promises a cleaning the query never performs.
+ ['case mismatch does not match', '/users/42', '/Users/(\\d+)', '/u/\\1', '/users/42'],
+ // `(?i)` is how re2 opts into case-insensitive matching, and JavaScript rejects it inline.
+ ['a (?i) prefix matches case-insensitively', '/users/42', '(?i)/Users/(\\d+)', '/u/\\1', '/u/42'],
+ ])('applyPathCleaningRule: %s', (_name, path, regex, alias, expected) => {
+ expect(applyPathCleaningRule(path, { regex, alias })).toBe(expected)
+ })
+
+ it('skips invalid or empty regexes without throwing', () => {
+ expect(applyPathCleaningRule('/x', { regex: '(', alias: '/y' })).toBe('/x')
+ expect(applyPathCleaningRule('/x', { regex: '', alias: '/y' })).toBe('/x')
+ expect(applyPathCleaningRule('/x', { regex: '(?i)', alias: '/y' })).toBe('/x')
+ })
+
+ it('chains rules in order, each feeding the next', () => {
+ const filters = [
+ { regex: '/users/(\\d+)/.*', alias: '/users/\\1' },
+ { regex: '/users/42', alias: '/users/me' },
+ ]
+ expect(applyPathCleaning('/users/42/settings', filters)).toBe('/users/me')
+ })
+})
diff --git a/frontend/src/lib/components/PathCleanFilters/pathCleaningUtils.ts b/frontend/src/lib/components/PathCleanFilters/pathCleaningUtils.ts
index 3fa9647b6ffd..4c4a8653bcf8 100644
--- a/frontend/src/lib/components/PathCleanFilters/pathCleaningUtils.ts
+++ b/frontend/src/lib/components/PathCleanFilters/pathCleaningUtils.ts
@@ -1,5 +1,99 @@
import { PathCleaningFilter } from '~/types'
+/**
+ * Expand a stored alias against one regex match, so the in-app preview agrees with the query that
+ * actually runs.
+ *
+ * The alias is written in ClickHouse `replaceRegexpAll` (re2) syntax: `\0` is the whole match, `\1`
+ * to `\9` are capture groups, `\\` is a literal backslash, and everything else is literal. That is
+ * the only syntax users need to know, and the only one the backend understands.
+ *
+ * Expanding against the match here, rather than handing JavaScript a translated `$1`-style
+ * replacement string, is what keeps three re2 rules JavaScript would otherwise break: `$` stays
+ * literal, `\10` is group 1 followed by `0` rather than group 10, and a group the pattern never
+ * filled substitutes as empty.
+ */
+export function expandAlias(alias: string, groups: (string | undefined)[]): string {
+ let out = ''
+ for (let i = 0; i < alias.length; i++) {
+ const char = alias[i]
+ if (char !== '\\') {
+ out += char
+ continue
+ }
+ const next = alias[i + 1]
+ if (next === '\\') {
+ out += '\\'
+ i++
+ } else if (next !== undefined && next >= '0' && next <= '9') {
+ out += groups[Number(next)] ?? ''
+ i++
+ } else {
+ out += '\\'
+ }
+ }
+ return out
+}
+
+const RE2_INLINE_FLAGS = /^\(\?([imsUx]+)\)/
+
+/**
+ * Compile a re2 pattern into a JS RegExp for the preview. re2 has no flags argument — it takes them
+ * as a leading inline group like `(?i)`, which JavaScript rejects outright, so translate the ones JS
+ * has an equivalent for. Everything else stays case-sensitive, matching re2's default.
+ *
+ * Kept in step with `compileForPreview` in the MCP `update-path-cleaning` tool, so both previews of
+ * the same rule set agree with each other as well as with the query.
+ */
+function compileForPreview(regex: string): RegExp | null {
+ const match = regex.match(RE2_INLINE_FLAGS)
+ const inlineFlags = match ? match[1]! : ''
+ const pattern = match ? regex.slice(match[0].length) : regex
+ if (!pattern) {
+ return null
+ }
+ // Ignore U and x — neither has a JS equivalent, and both are rare in path cleaning.
+ const flags = 'g' + ['i', 'm', 's'].filter((flag) => inlineFlags.includes(flag)).join('')
+ try {
+ return new RegExp(pattern, flags)
+ } catch {
+ // A rule using re2-only syntax may not compile under JS RegExp. Skip it rather than throw.
+ return null
+ }
+}
+
+/** Whether the preview can run this regex, so the editor refuses what it would not be able to show. */
+export function isValidPathCleaningRegex(regex: string): boolean {
+ return compileForPreview(regex) !== null
+}
+
+/**
+ * Apply a single path-cleaning rule to a path, matching how the backend runs `replaceRegexpAll` per
+ * rule. Invalid or empty regexes are skipped so a half-written rule can't blank out the preview.
+ */
+export function applyPathCleaningRule(path: string, filter: PathCleaningFilter): string {
+ const pattern = filter.regex ? compileForPreview(filter.regex) : null
+ if (!pattern) {
+ return path
+ }
+ const alias = filter.alias ?? ''
+ return path.replace(pattern, (match: string, ...rest: unknown[]): string => {
+ // Replacer arguments run (match, p1…pN, offset, whole string, named groups?). A group the
+ // pattern didn't fill arrives as undefined, so the first number is the offset and marks
+ // where the capture values stop.
+ const offsetIndex = rest.findIndex((arg) => typeof arg === 'number')
+ const captures = (offsetIndex === -1 ? [] : rest.slice(0, offsetIndex)) as (string | undefined)[]
+ return expandAlias(alias, [match, ...captures])
+ })
+}
+
+/**
+ * Chain every rule in order, each feeding the next — mirrors the sequential backend application.
+ */
+export function applyPathCleaning(path: string, filters: PathCleaningFilter[]): string {
+ return filters.reduce((cleaned, filter) => applyPathCleaningRule(cleaned, filter), path)
+}
+
/**
* Ensures all filters have order values, using array position as fallback
*/
diff --git a/frontend/src/queries/schema.json b/frontend/src/queries/schema.json
index 9f3a91d68a87..107435144c88 100644
--- a/frontend/src/queries/schema.json
+++ b/frontend/src/queries/schema.json
@@ -36633,6 +36633,7 @@
"additionalProperties": false,
"properties": {
"alias": {
+ "description": "The replacement for the matched path. Use angle-bracket placeholders (`<id>`, `<uuid>`, `<slug>`) by convention, or reuse a capture group from the regex with ClickHouse `replaceRegexpAll` replacement syntax: `\\1` to `\\9` for a group and `\\0` for the whole match.",
"type": "string"
},
"order": {
diff --git a/frontend/src/scenes/settings/environment/PathCleaningFiltersConfig.tsx b/frontend/src/scenes/settings/environment/PathCleaningFiltersConfig.tsx
index 6eec292d3c38..079fec686d2b 100644
--- a/frontend/src/scenes/settings/environment/PathCleaningFiltersConfig.tsx
+++ b/frontend/src/scenes/settings/environment/PathCleaningFiltersConfig.tsx
@@ -8,26 +8,15 @@ import { PathCleanFilterAddItemButton } from 'lib/components/PathCleanFilters/Pa
import { parseAliasToReadable } from 'lib/components/PathCleanFilters/PathCleanFilterItem'
import { PathCleanFiltersTable } from 'lib/components/PathCleanFilters/PathCleanFiltersTable'
import { PathCleaningRulesDebugger } from 'lib/components/PathCleanFilters/PathCleaningRulesDebugger'
+import { applyPathCleaning } from 'lib/components/PathCleanFilters/pathCleaningUtils'
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'
import { AvailableFeature, PathCleaningFilter } from '~/types'
-const cleanPathWithRegexes = (path: string, filters: PathCleaningFilter[]): string => {
- return filters.reduce((text, filter) => {
- // If for some reason we don't have a valid RegExp, don't attempt to clean the path
- if (!isValidRegexp(filter.regex ?? '')) {
- return text
- }
-
- return text.replace(new RegExp(filter.regex ?? '', 'gi'), filter.alias ?? '')
- }, path)
-}
-
export function PathCleaningFiltersConfig(): JSX.Element | null {
const [testValue, setTestValue] = useState('')
@@ -56,7 +45,7 @@ export function PathCleaningFiltersConfig(): JSX.Element | null {
)
}
- const cleanedTestPath = cleanPathWithRegexes(testValue, currentTeam.path_cleaning_filters ?? [])
+ const cleanedTestPath = applyPathCleaning(testValue, currentTeam.path_cleaning_filters ?? [])
const readableTestPath = parseAliasToReadable(cleanedTestPath)
const updateFilters = (filters: PathCleaningFilter[]): void => {
diff --git a/frontend/src/scenes/web-analytics/pageReportsLogic.ts b/frontend/src/scenes/web-analytics/pageReportsLogic.ts
index 6421d9c8aff2..a5ec1a9f304b 100644
--- a/frontend/src/scenes/web-analytics/pageReportsLogic.ts
+++ b/frontend/src/scenes/web-analytics/pageReportsLogic.ts
@@ -2,9 +2,9 @@ import { MakeLogicType, kea } from 'kea'
import { router } from 'kea-router'
import api from 'lib/api'
+import { applyPathCleaning } from 'lib/components/PathCleanFilters/pathCleaningUtils'
import { FEATURE_FLAGS } from 'lib/constants'
import { featureFlagLogic } from 'lib/logic/featureFlagLogic'
-import { isValidRegexp } from 'lib/utils/regexp'
import { teamLogic } from 'scenes/teamLogic'
import {
@@ -133,12 +133,7 @@ export function applyPathCleaningToFilters(
}
export function cleanPathnameForDisplay(pathname: string, filters: PathCleaningFilter[]): string {
- return filters.reduce((cleaned, filter) => {
- if (!filter.regex || !isValidRegexp(filter.regex)) {
- return cleaned
- }
- return cleaned.replace(new RegExp(filter.regex, 'gi'), filter.alias ?? '')
- }, pathname)
+ return applyPathCleaning(pathname, filters)
}
export function cleanPageURLForDisplay(url: string, filters: PathCleaningFilter[]): string {
diff --git a/frontend/src/types.ts b/frontend/src/types.ts
index aafd05725ee4..23df7efd2fb3 100644
--- a/frontend/src/types.ts
+++ b/frontend/src/types.ts
@@ -1033,6 +1033,11 @@ export interface ToolbarProps extends ToolbarParams {
}
export type PathCleaningFilter = {
+ /**
+ * The replacement for the matched path. Use angle-bracket placeholders (`<id>`, `<uuid>`, `<slug>`)
+ * by convention, or reuse a capture group from the regex with ClickHouse `replaceRegexpAll`
+ * replacement syntax: `\1` to `\9` for a group and `\0` for the whole match.
+ */
alias?: string
regex?: string
order?: number
diff --git a/posthog/api/project.py b/posthog/api/project.py
index fbd61fb1e536..83a56f25b8fd 100644
--- a/posthog/api/project.py
+++ b/posthog/api/project.py
@@ -1024,6 +1024,10 @@ class ProjectBackwardCompatSerializer(
def validate_test_account_filters(value: object) -> list[dict[str, object]]:
return TeamSerializer.validate_test_account_filters(value)
+ @staticmethod
+ def validate_path_cleaning_filters(value: object) -> object:
+ return TeamSerializer.validate_path_cleaning_filters(value)
+
def validate_proactive_tasks_enabled(self, value: bool | None) -> bool | None:
return TeamSerializer.validate_proactive_tasks_enabled(cast(TeamSerializer, self), value)
diff --git a/posthog/api/team.py b/posthog/api/team.py
index 9a2f6b8c4ba1..623bf787c237 100644
--- a/posthog/api/team.py
+++ b/posthog/api/team.py
@@ -11,6 +11,7 @@ from django.shortcuts import get_object_or_404
from django.utils import timezone
from django.utils.dateparse import parse_datetime
+import re2
import posthoganalytics
from drf_spectacular.types import OpenApiTypes
from drf_spectacular.utils import OpenApiParameter, extend_schema, extend_schema_field, extend_schema_view
@@ -842,6 +843,64 @@ def validate_test_account_filters(value: object) -> list[dict[str, object]]:
return cast(list[dict[str, object]], value)
+def _alias_backreferences(alias: str) -> list[int]:
+ """Return the capture-group numbers a re2 replacement alias references (`\\1`..`\\9`, `\\0` for the
+ whole match). A doubled `\\\\` is a literal backslash, not a back-reference, so it's skipped."""
+ refs: list[int] = []
+ i = 0
+ while i < len(alias):
+ if alias[i] == "\\" and i + 1 < len(alias):
+ nxt = alias[i + 1]
+ if nxt == "\\":
+ i += 2
+ continue
+ # ASCII digits only. `str.isdigit()` also accepts characters like `²` and `٣`, which re2
+ # substitutes as literal text, and `int()` rejects `²` outright.
+ if "0" <= nxt <= "9":
+ refs.append(int(nxt))
+ i += 2
+ continue
+ i += 1
+ return refs
+
+
+def validate_path_cleaning_filters(value: object) -> object:
+ """Validate path cleaning rules before they're saved. Each regex must compile under re2 (the
+ engine ClickHouse `replaceRegexpAll` uses), and any `\\1`..`\\9` back-reference in the alias must
+ point at a capture group the regex defines. This surfaces a mistake at save time instead of
+ letting it fail the query later, when path cleaning runs."""
+ if not value:
+ return value
+ if not isinstance(value, list):
+ raise exceptions.ValidationError("Must provide a list of path cleaning rules.")
+
+ for rule in value:
+ if not isinstance(rule, dict):
+ continue
+ regex = rule.get("regex")
+ alias = rule.get("alias")
+ # A missing or empty regex still reaches ClickHouse, where `replaceRegexpAll` returns NULL for
+ # a NULL pattern and an empty pattern matches at every position, interleaving the alias
+ # through the whole path. Neither is recoverable at query time, so refuse the rule.
+ if not isinstance(regex, str) or not regex:
+ raise exceptions.ValidationError("A path cleaning rule needs a regex. Remove the rule or give it one.")
+ try:
+ compiled = re2.compile(regex)
+ except re2.error as error:
+ raise exceptions.ValidationError(f"Invalid path cleaning regex '{regex}': {error}") from error
+
+ if not alias or not isinstance(alias, str):
+ continue
+ group_count = compiled.groups
+ for ref in _alias_backreferences(alias):
+ if ref > group_count:
+ raise exceptions.ValidationError(
+ f"The alias '{alias}' references capture group \\{ref}, but its regex has "
+ f"{group_count} capture group(s). Add the group to the regex or fix the reference."
+ )
+ return value
+
+
_default_theme_id_cache: int | None = None
@@ -1084,6 +1143,10 @@ class TeamSerializer(serializers.ModelSerializer, UserPermissionsSerializerMixin
def validate_test_account_filters(value: object) -> list[dict[str, object]]:
return validate_test_account_filters(value)
+ @staticmethod
+ def validate_path_cleaning_filters(value: object) -> object:
+ return validate_path_cleaning_filters(value)
+
@staticmethod
def validate_revenue_analytics_config(value):
if value is None:
diff --git a/posthog/api/test/test_path_cleaning_validation.py b/posthog/api/test/test_path_cleaning_validation.py
new file mode 100644
index 000000000000..4dfa03f1d98e
--- /dev/null
+++ b/posthog/api/test/test_path_cleaning_validation.py
@@ -0,0 +1,52 @@
+from django.test import SimpleTestCase
+
+from parameterized import parameterized
+from rest_framework import exceptions
+
+from posthog.api.team import TeamSerializer, validate_path_cleaning_filters
+
+
+class TestPathCleaningFilterValidation(SimpleTestCase):
+ @parameterized.expand(
+ [
+ ("uncompilable_regex", [{"regex": "/users/((", "alias": "/users/x"}]),
+ ("backreference_out_of_range", [{"regex": "/users/(\\d+)", "alias": "/users/\\2"}]),
+ ("backreference_with_no_group", [{"regex": "/users/\\d+", "alias": "/users/\\1"}]),
+ ("value_that_is_not_a_list", "not-a-list"),
+ # An empty pattern matches everywhere and a missing one reaches ClickHouse as NULL, so
+ # both mangle every path the rule touches rather than doing nothing.
+ ("empty_regex", [{"regex": "", "alias": "/users/x"}]),
+ ("rule_without_a_regex", [{"alias": "/users/<id>"}]),
+ ]
+ )
+ def test_rejects_invalid_rules(self, _name, filters):
+ with self.assertRaises(exceptions.ValidationError):
+ validate_path_cleaning_filters(filters)
+
+ @parameterized.expand(
+ [
+ ("valid_backreference", [{"regex": "/users/(\\d+)", "alias": "/users/\\1"}]),
+ ("whole_match_reference", [{"regex": "/users/(\\d+)", "alias": "/x/\\0"}]),
+ # A doubled backslash is a literal backslash, not a back-reference, so \\1 needs no group.
+ ("escaped_backslash_is_literal", [{"regex": "/users/\\d+", "alias": "/users/\\\\1"}]),
+ ("static_placeholder_alias", [{"regex": "/users/\\d+", "alias": "/users/<id>"}]),
+ ("empty_list", []),
+ # re2 reads only ASCII digits as a back-reference, so these are literal text. Matching on
+ # str.isdigit() instead crashes on the superscript and misreads the Arabic-Indic digit.
+ ("superscript_digit_is_literal", [{"regex": "/users/\\d+", "alias": "/users/\\²"}]),
+ ("arabic_indic_digit_is_literal", [{"regex": "/users/\\d+", "alias": "/users/\\٣"}]),
+ # Pydantic drops a rule that isn't a dict before the query runs, so it can't corrupt a path.
+ ("rule_that_is_not_a_dict", ["not-a-rule"]),
+ ("rule_without_an_alias", [{"regex": "/users/\\d+"}]),
+ ]
+ )
+ def test_accepts_valid_rules(self, _name, filters):
+ assert validate_path_cleaning_filters(filters) == filters
+
+ def test_serializer_wires_up_the_validator(self):
+ serializer = TeamSerializer(
+ data={"path_cleaning_filters": [{"regex": "/users/(\\d+)", "alias": "/users/\\2"}]},
+ partial=True,
+ )
+ assert not serializer.is_valid()
+ assert "path_cleaning_filters" in serializer.errors
diff --git a/posthog/schema.py b/posthog/schema.py
index 85212ccc9265..d13119cf7fcd 100644
--- a/posthog/schema.py
+++ b/posthog/schema.py
@@ -2270,7 +2270,15 @@ class PathCleaningFilter(BaseModel):
model_config = ConfigDict(
extra="forbid",
)
- alias: str | None = None
+ alias: str | None = Field(
+ default=None,
+ description=(
+ "The replacement for the matched path. Use angle-bracket placeholders"
+ " (`<id>`, `<uuid>`, `<slug>`) by convention, or reuse a capture group from"
+ " the regex with ClickHouse `replaceRegexpAll` replacement syntax: `\\1` to"
+ " `\\9` for a group and `\\0` for the whole match."
+ ),
+ )
order: float | None = None
regex: str | None = None
diff --git a/products/dashboards/frontend/generated/api.schemas.ts b/products/dashboards/frontend/generated/api.schemas.ts
index 413e89a317d3..6ac6c02f42d2 100644
--- a/products/dashboards/frontend/generated/api.schemas.ts
+++ b/products/dashboards/frontend/generated/api.schemas.ts
@@ -3239,6 +3239,7 @@ export const PathTypeApi = {
} as const
export interface PathCleaningFilterApi {
+ /** The replacement for the matched path. Use angle-bracket placeholders (`<id>`, `<uuid>`, `<slug>`) by convention, or reuse a capture group from the regex with ClickHouse `replaceRegexpAll` replacement syntax: `\1` to `\9` for a group and `\0` for the whole match. */
alias?: string | null
order?: number | null
regex?: string | null
diff --git a/products/product_analytics/backend/hogql_queries/paths/test/test_paths_query_runner.py b/products/product_analytics/backend/hogql_queries/paths/test/test_paths_query_runner.py
index f14611d2c3e2..931712e22ddf 100644
--- a/products/product_analytics/backend/hogql_queries/paths/test/test_paths_query_runner.py
+++ b/products/product_analytics/backend/hogql_queries/paths/test/test_paths_query_runner.py
@@ -1117,3 +1117,41 @@ class TestPaths(ClickhouseTestMixin, APIBaseTest):
sources_and_targets = [r.source + r.target for r in result.results]
combined = " ".join(sources_and_targets)
assert "123" in combined or "456" in combined
+
+ @freeze_time("2012-01-15T03:21:34.000Z")
+ def test_path_replacements_apply_capture_group_backreference_alias(self):
+ """A team cleaning alias can reuse regex capture groups via re2 `\\1` syntax. The paths runner
+ builds its own replaceRegexpAll chain, so this guards backreference substitution on that path
+ separately from web analytics — a regression treating the alias as a literal would fail here."""
+ _create_person(team_id=self.team.pk, distinct_ids=["person_1"])
+ _create_event(
+ properties={"$current_url": "/merchant/123/dashboard"},
+ distinct_id="person_1",
+ event="$pageview",
+ team=self.team,
+ timestamp="2012-01-14 03:21:34",
+ )
+ _create_event(
+ properties={"$current_url": "/merchant/123/orders"},
+ distinct_id="person_1",
+ event="$pageview",
+ team=self.team,
+ timestamp="2012-01-14 03:22:34",
+ )
+
+ self.team.path_cleaning_filters = [{"alias": "/m/\\1/\\2", "regex": "/merchant/(\\d+)/(\\w+)"}]
+ self.team.save()
+
+ result = PathsQueryRunner(
+ query={
+ "kind": "PathsQuery",
+ "pathsFilter": {"pathReplacements": True},
+ },
+ team=self.team,
+ ).run()
+ assert isinstance(result, CachedPathsQueryResponse)
+ combined = " ".join(r.source + r.target for r in result.results)
+ assert "/m/123/dashboard" in combined
+ assert "/m/123/orders" in combined
+ # The capture groups were substituted, not passed through literally.
+ assert "\\1" not in combined
diff --git a/products/product_analytics/frontend/generated/api.schemas.ts b/products/product_analytics/frontend/generated/api.schemas.ts
index 86dad29191ae..ca6bdc664c5f 100644
--- a/products/product_analytics/frontend/generated/api.schemas.ts
+++ b/products/product_analytics/frontend/generated/api.schemas.ts
@@ -2569,6 +2569,7 @@ export const PathTypeApi = {
} as const
export interface PathCleaningFilterApi {
+ /** The replacement for the matched path. Use angle-bracket placeholders (`<id>`, `<uuid>`, `<slug>`) by convention, or reuse a capture group from the regex with ClickHouse `replaceRegexpAll` replacement syntax: `\1` to `\9` for a group and `\0` for the whole match. */
alias?: string | null
order?: number | null
regex?: string | null
diff --git a/products/web_analytics/backend/hogql_queries/test/__snapshots__/test_web_stats_table.ambr b/products/web_analytics/backend/hogql_queries/test/__snapshots__/test_web_stats_table.ambr
index cdecea45c49e..9733cdc27655 100644
--- a/products/web_analytics/backend/hogql_queries/test/__snapshots__/test_web_stats_table.ambr
+++ b/products/web_analytics/backend/hogql_queries/test/__snapshots__/test_web_stats_table.ambr
@@ -5747,6 +5747,69 @@
use_hive_partitioning=0
'''
# ---
+# name: TestWebStatsTableQueryRunner.test_path_cleaning_filters_with_capture_group_backreference
+ '''
+ SELECT toTimeZone(events.timestamp, 'UTC') AS timestamp
+ FROM events
+ WHERE and(equals(events.team_id, 99999), greater(events.timestamp, toDateTime64('2015-01-01 00:00:00.000000', 6, 'UTC')))
+ ORDER BY toTimeZone(events.timestamp, 'UTC') ASC
+ LIMIT 1 SETTINGS readonly=2,
+ max_execution_time=60,
+ allow_experimental_object_type=1,
+ max_ast_elements=4000000,
+ max_expanded_ast_elements=4000000,
+ max_bytes_before_external_group_by=0,
+ transform_null_in=1,
+ optimize_min_equality_disjunction_chain_length=4294967295,
+ optimize_rewrite_aggregate_function_with_if=0,
+ optimize_min_inequality_conjunction_chain_length=4294967295,
+ allow_experimental_join_condition=1,
+ use_hive_partitioning=0
+ '''
+# ---
+# name: TestWebStatsTableQueryRunner.test_path_cleaning_filters_with_capture_group_backreference.1
+ '''
+ SELECT breakdown_value AS `context.columns.breakdown_value`,
+ tuple(uniq(filtered_person_id), NULL) AS `context.columns.visitors`,
+ tuple(sum(filtered_pageview_count), NULL) AS `context.columns.views`,
+ divide(`context.columns.visitors`.1, sum(`context.columns.visitors`.1) OVER ()) AS `context.columns.ui_fill_fraction`
+ FROM
+ (SELECT any(if(not(empty(events__override.distinct_id)), events__override.person_id, events.person_id)) AS filtered_person_id,
+ count() AS filtered_pageview_count,
+ replaceRegexpAll(replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(events.properties, '$pathname'), ''), 'null'), '^"|"$', ''), '\\/item\\/(\\d+)\\/detail\\/\\d+', '/item/\\1') AS breakdown_value,
+ if(ifNull(equals(bitAnd(bitShiftRight(events.`$session_id_uuid`, 76), 15), 7), 0), events.`$session_id`, NULL) AS session_id,
+ any(if(ifNull(equals(bitAnd(bitShiftRight(events.`$session_id_uuid`, 76), 15), 7), 0), fromUnixTimestamp(intDiv(accurateCastOrNull(bitShiftRight(events.`$session_id_uuid`, 80), 'Int64'), 1000)), NULL)) AS start_timestamp
+ FROM events
+ LEFT OUTER JOIN
+ (SELECT argMax(person_distinct_id_overrides.person_id, person_distinct_id_overrides.version) AS person_id,
+ person_distinct_id_overrides.distinct_id AS distinct_id
+ FROM person_distinct_id_overrides
+ WHERE equals(person_distinct_id_overrides.team_id, 99999)
+ GROUP BY person_distinct_id_overrides.distinct_id
+ HAVING equals(argMax(person_distinct_id_overrides.is_deleted, person_distinct_id_overrides.version), 0) SETTINGS optimize_aggregation_in_order=1) AS events__override ON equals(events.distinct_id, events__override.distinct_id)
+ WHERE and(equals(events.team_id, 99999), and(or(and(greaterOrEquals(toTimeZone(events.timestamp, 'UTC'), assumeNotNull(toDateTime('2023-12-02 00:00:00', 'UTC'))), lessOrEquals(toTimeZone(events.timestamp, 'UTC'), assumeNotNull(toDateTime('2023-12-15 23:59:59', 'UTC')))), 0), or(equals(events.event, '$pageview'), equals(events.event, '$screen')), 1))
+ GROUP BY session_id,
+ breakdown_value)
+ GROUP BY `context.columns.breakdown_value`
+ HAVING isNotNull(`context.columns.breakdown_value`)
+ ORDER BY `context.columns.visitors` DESC,
+ `context.columns.views` DESC,
+ `context.columns.breakdown_value` ASC
+ LIMIT 101
+ OFFSET 0 SETTINGS readonly=2,
+ max_execution_time=60,
+ allow_experimental_object_type=1,
+ max_ast_elements=4000000,
+ max_expanded_ast_elements=4000000,
+ max_bytes_before_external_group_by=0,
+ transform_null_in=1,
+ optimize_min_equality_disjunction_chain_length=4294967295,
+ optimize_rewrite_aggregate_function_with_if=0,
+ optimize_min_inequality_conjunction_chain_length=4294967295,
+ allow_experimental_join_condition=1,
+ use_hive_partitioning=0
+ '''
+# ---
# name: TestWebStatsTableQueryRunner.test_path_cleaning_filters_with_cleanable_path_property
'''
SELECT toTimeZone(events.timestamp, 'UTC') AS timestamp
diff --git a/products/web_analytics/backend/hogql_queries/test/test_web_stats_table.py b/products/web_analytics/backend/hogql_queries/test/test_web_stats_table.py
index 0138a42b1700..6e55cc829598 100644
--- a/products/web_analytics/backend/hogql_queries/test/test_web_stats_table.py
+++ b/products/web_analytics/backend/hogql_queries/test/test_web_stats_table.py
@@ -572,6 +572,38 @@ class TestWebStatsTableQueryRunner(
["/other/123/path", (1.0, None), (1.0, None), 1 / 4, ""],
] == results
+ def test_path_cleaning_filters_with_capture_group_backreference(self):
+ s1 = str(uuid7("2023-12-02"))
+ s2 = str(uuid7("2023-12-10"))
+ s3 = str(uuid7("2023-12-11"))
+ s4 = str(uuid7("2023-12-12"))
+
+ self._create_events(
+ [
+ ("p1", [("2023-12-02", s1, "/item/123/detail/456")]),
+ ("p2", [("2023-12-10", s2, "/item/123/detail/789")]), # same item, different detail
+ ("p3", [("2023-12-11", s3, "/item/999/detail/111")]),
+ ("p4", [("2023-12-12", s4, "/other/1/path")]), # Should not match
+ ]
+ )
+
+ # The alias reuses capture group 1 with re2 `\1` syntax, keeping the item id and dropping the
+ # detail segment. This is passed straight to ClickHouse `replaceRegexpAll`, so it guards that
+ # the alias is never re-escaped or treated as a literal on its way to the query.
+ results = self._run_web_stats_table_query(
+ "all",
+ "2023-12-15",
+ path_cleaning_filters=[
+ {"regex": "\\/item\\/(\\d+)\\/detail\\/\\d+", "alias": "/item/\\1"},
+ ],
+ ).results
+
+ assert [
+ ["/item/123", (2.0, None), (2.0, None), 2 / 4, ""],
+ ["/item/999", (1.0, None), (1.0, None), 1 / 4, ""],
+ ["/other/1/path", (1.0, None), (1.0, None), 1 / 4, ""],
+ ] == results
+
def test_path_cleaning_filters_applied_in_order(self):
s1 = str(uuid7("2023-12-02"))
s2 = str(uuid7("2023-12-10"))
diff --git a/products/web_analytics/backend/path_cleaning_suggestions/prompts.py b/products/web_analytics/backend/path_cleaning_suggestions/prompts.py
index 8cc349c71bbb..b3ca60d1fabe 100644
--- a/products/web_analytics/backend/path_cleaning_suggestions/prompts.py
+++ b/products/web_analytics/backend/path_cleaning_suggestions/prompts.py
@@ -13,10 +13,10 @@ You will be given a sample of a single project's most-viewed URL paths (with vie
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.
+- Each rule is a `regex` (Google re2 syntax — do NOT escape `/`) and an `alias` (the
+ replacement). Use angle-bracket placeholders like `<id>`, `<uuid>`, `<slug>`, `<date>`,
+ `<locale>` so the cleaned path stays human-readable. Capture-group backreferences (`\\1`) are
+ supported by the query layer but are slower to evaluate, so do not propose them.
- 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
diff --git a/products/web_analytics/skills/managing-path-cleaning-rules/SKILL.md b/products/web_analytics/skills/managing-path-cleaning-rules/SKILL.md
index 5fa06839242a..ba358d784f95 100644
--- a/products/web_analytics/skills/managing-path-cleaning-rules/SKILL.md
+++ b/products/web_analytics/skills/managing-path-cleaning-rules/SKILL.md
@@ -35,10 +35,11 @@ This skill teaches you how to:
- **`regex`** — a [re2](https://github.com/google/re2/wiki/Syntax) pattern. No
need to escape `/`. Anchor with `^` / `$` when you mean it.
-- **`alias`** — the literal replacement. Use angle-bracket placeholders
- (`<id>`, `<slug>`, `<uuid>`, `<date>`) by convention so the cleaned path stays
- human-readable. The alias is _not_ a regex template — backreferences are not
- supported.
+- **`alias`** — the replacement. Default to angle-bracket placeholders
+ (`<id>`, `<slug>`, `<uuid>`, `<date>`) so the cleaned path stays
+ human-readable. Backreferences to the regex's capture groups also work, but
+ they cost more to evaluate — see the backreference pitfall below before
+ reaching for one.
- **`order`** — integer. Rules apply **sequentially** in `order` ascending,
each rule's output feeds the next.
@@ -166,6 +167,14 @@ The rules are stored once per project — they are not insight-scoped.
## Common pitfalls
+- **Prefer a placeholder alias over a backreference** — a rule that substitutes
+ a capture group costs roughly 3x more per row than the same rule with a fixed
+ alias, because re2 has to track submatch boundaries instead of answering
+ match/no-match on its fast path. Reach for one only when it collapses several
+ near-identical rules into one, which is a clear net win since cleaning
+ evaluates every rule against every row. Keep the regex `^`-anchored either
+ way: `replaceRegexpAll` keeps scanning for further matches, so an unanchored
+ pattern is much more expensive than an anchored one.
- **Backreferences in `alias` need double-escaping** — ClickHouse's
`replaceRegexpAll` supports `\0` (whole match) and `\1`–`\9` (capture
groups). In a JSON field or SQL string literal the backslash must be
diff --git a/services/mcp/schema/tool-inputs.json b/services/mcp/schema/tool-inputs.json
index de42d21e95d1..7ab77c0d0b40 100644
--- a/services/mcp/schema/tool-inputs.json
+++ b/services/mcp/schema/tool-inputs.json
@@ -613,7 +613,7 @@
},
"alias": {
"type": "string",
- "description": "The human-readable replacement, e.g. \"/users/<id>/profile\". Use angle-bracket placeholders (<id>, <uuid>, <slug>) by convention. An empty string is valid — it deletes the matched text (e.g. to strip a \"?page=N\" fragment). Not a regex template — backreferences are not supported."
+ "description": "The replacement for the matched path, e.g. \"/users/<id>/profile\". Default to angle-bracket placeholders (<id>, <uuid>, <slug>) by convention. An empty string is valid: it deletes the matched text (e.g. to strip a \"?page=N\" fragment). The alias can also reference a regex capture group with ClickHouse replaceRegexpAll syntax (\"\\1\" to \"\\9\" for a group, \"\\0\" for the whole match), but a rule with capture groups is roughly 3x more expensive per row, so only use one when it collapses several near-identical rules into one."
},
"regex": {
"type": "string",
@@ -639,7 +639,7 @@
},
"alias": {
"type": "string",
- "description": "The human-readable replacement, e.g. \"/users/<id>/profile\". Use angle-bracket placeholders (<id>, <uuid>, <slug>) by convention. An empty string is valid — it deletes the matched text (e.g. to strip a \"?page=N\" fragment). Not a regex template — backreferences are not supported."
+ "description": "The replacement for the matched path, e.g. \"/users/<id>/profile\". Default to angle-bracket placeholders (<id>, <uuid>, <slug>) by convention. An empty string is valid: it deletes the matched text (e.g. to strip a \"?page=N\" fragment). The alias can also reference a regex capture group with ClickHouse replaceRegexpAll syntax (\"\\1\" to \"\\9\" for a group, \"\\0\" for the whole match), but a rule with capture groups is roughly 3x more expensive per row, so only use one when it collapses several near-identical rules into one."
},
"regex": {
"type": "string",
diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.ts
index 1024ffb2b966..7e973381b5b4 100644
--- a/services/mcp/src/api/generated.ts
+++ b/services/mcp/src/api/generated.ts
@@ -3687,6 +3687,7 @@ export namespace Schemas {
} as const;
export interface PathCleaningFilter {
+ /** The replacement for the matched path. Use angle-bracket placeholders (`<id>`, `<uuid>`, `<slug>`) by convention, or reuse a capture group from the regex with ClickHouse `replaceRegexpAll` replacement syntax: `\1` to `\9` for a group and `\0` for the whole match. */
alias?: string | null;
order?: number | null;
regex?: string | null;
diff --git a/services/mcp/src/schema/tool-inputs.ts b/services/mcp/src/schema/tool-inputs.ts
index 5f66b9522c94..b36b6f8b6325 100644
--- a/services/mcp/src/schema/tool-inputs.ts
+++ b/services/mcp/src/schema/tool-inputs.ts
@@ -480,7 +480,7 @@ export const PropertyDefinitionUpdateSchema = z.object({
const PathCleaningAliasField = z
.string()
.describe(
- 'The human-readable replacement, e.g. "/users/<id>/profile". Use angle-bracket placeholders (<id>, <uuid>, <slug>) by convention. An empty string is valid — it deletes the matched text (e.g. to strip a "?page=N" fragment). Not a regex template — backreferences are not supported.'
+ 'The replacement for the matched path, e.g. "/users/<id>/profile". Default to angle-bracket placeholders (<id>, <uuid>, <slug>) by convention. An empty string is valid: it deletes the matched text (e.g. to strip a "?page=N" fragment). The alias can also reference a regex capture group with ClickHouse replaceRegexpAll syntax ("\\1" to "\\9" for a group, "\\0" for the whole match), but a rule with capture groups is roughly 3x more expensive per row, so only use one when it collapses several near-identical rules into one.'
)
const PathCleaningRegexField = z
.string()
diff --git a/services/mcp/src/tools/projects/updatePathCleaning.ts b/services/mcp/src/tools/projects/updatePathCleaning.ts
index 7d5b2d75f7f5..e1f081f0b740 100644
--- a/services/mcp/src/tools/projects/updatePathCleaning.ts
+++ b/services/mcp/src/tools/projects/updatePathCleaning.ts
@@ -205,6 +205,37 @@ function compileForPreview(regex: string): RegExp | null {
}
}
+/**
+ * Expand an alias against one regex match, so the preview substitutes capture groups the same way
+ * the real query does. The alias is re2 replacement syntax: `\0` is the whole match, `\1` to `\9`
+ * are capture groups, `\\` is a literal backslash, and everything else is literal.
+ *
+ * Expanding against the match here, rather than translating to a `$1`-style replacement string,
+ * keeps three re2 rules JavaScript would otherwise break: `$` stays literal, `\10` is group 1
+ * followed by `0` rather than group 10, and an unfilled group substitutes as empty.
+ */
+export function expandAlias(alias: string, groups: (string | undefined)[]): string {
+ let out = ''
+ for (let i = 0; i < alias.length; i++) {
+ const char = alias[i]
+ if (char !== '\\') {
+ out += char
+ continue
+ }
+ const next = alias[i + 1]
+ if (next === '\\') {
+ out += '\\'
+ i++
+ } else if (next !== undefined && next >= '0' && next <= '9') {
+ out += groups[Number(next)] ?? ''
+ i++
+ } else {
+ out += '\\'
+ }
+ }
+ return out
+}
+
/** Chain a path through every rule in order, mirroring ClickHouse `replaceRegexpAll` per rule. */
function applyChain(path: string, rules: PathCleaningRule[]): string {
let out = path
@@ -213,8 +244,14 @@ function applyChain(path: string, rules: PathCleaningRule[]): string {
if (re === null) {
continue
}
- // `alias` is a literal; escape `$` so JS's replace() doesn't treat it as a group ref.
- out = out.replace(re, rule.alias.replace(/\$/g, '$$$$'))
+ out = out.replace(re, (match: string, ...rest: unknown[]): string => {
+ // Replacer arguments run (match, p1…pN, offset, whole string, named groups?). A group
+ // the pattern didn't fill arrives as undefined, so the first number is the offset and
+ // marks where the capture values stop.
+ const offsetIndex = rest.findIndex((arg) => typeof arg === 'number')
+ const captures = (offsetIndex === -1 ? [] : rest.slice(0, offsetIndex)) as (string | undefined)[]
+ return expandAlias(rule.alias, [match, ...captures])
+ })
}
return out
}
diff --git a/services/mcp/tests/unit/__snapshots__/tool-schemas/path-cleaning-rules-update.json b/services/mcp/tests/unit/__snapshots__/tool-schemas/path-cleaning-rules-update.json
index a1f1ebe4f72a..699c3644ed04 100644
--- a/services/mcp/tests/unit/__snapshots__/tool-schemas/path-cleaning-rules-update.json
+++ b/services/mcp/tests/unit/__snapshots__/tool-schemas/path-cleaning-rules-update.json
@@ -18,7 +18,7 @@
"type": "string"
},
"alias": {
- "description": "The human-readable replacement, e.g. \"/users/<id>/profile\". Use angle-bracket placeholders (<id>, <uuid>, <slug>) by convention. An empty string is valid — it deletes the matched text (e.g. to strip a \"?page=N\" fragment). Not a regex template — backreferences are not supported.",
+ "description": "The replacement for the matched path, e.g. \"/users/<id>/profile\". Default to angle-bracket placeholders (<id>, <uuid>, <slug>) by convention. An empty string is valid: it deletes the matched text (e.g. to strip a \"?page=N\" fragment). The alias can also reference a regex capture group with ClickHouse replaceRegexpAll syntax (\"\\1\" to \"\\9\" for a group, \"\\0\" for the whole match), but a rule with capture groups is roughly 3x more expensive per row, so only use one when it collapses several near-identical rules into one.",
"type": "string"
},
"regex": {
@@ -38,7 +38,7 @@
"type": "string"
},
"alias": {
- "description": "The human-readable replacement, e.g. \"/users/<id>/profile\". Use angle-bracket placeholders (<id>, <uuid>, <slug>) by convention. An empty string is valid — it deletes the matched text (e.g. to strip a \"?page=N\" fragment). Not a regex template — backreferences are not supported.",
+ "description": "The replacement for the matched path, e.g. \"/users/<id>/profile\". Default to angle-bracket placeholders (<id>, <uuid>, <slug>) by convention. An empty string is valid: it deletes the matched text (e.g. to strip a \"?page=N\" fragment). The alias can also reference a regex capture group with ClickHouse replaceRegexpAll syntax (\"\\1\" to \"\\9\" for a group, \"\\0\" for the whole match), but a rule with capture groups is roughly 3x more expensive per row, so only use one when it collapses several near-identical rules into one.",
"type": "string"
},
"index": {
diff --git a/services/mcp/tests/unit/path-cleaning-rules-update.test.ts b/services/mcp/tests/unit/path-cleaning-rules-update.test.ts
index 703e6003c1ff..1bc8049bd928 100644
--- a/services/mcp/tests/unit/path-cleaning-rules-update.test.ts
+++ b/services/mcp/tests/unit/path-cleaning-rules-update.test.ts
@@ -2,6 +2,7 @@ import { describe, expect, it, vi } from 'vitest'
import updatePathCleaning, {
applyOperations,
+ expandAlias,
normalizePathCleaningFilters,
type PathCleaningRule,
renumber,
@@ -9,6 +10,22 @@ import updatePathCleaning, {
} from '@/tools/projects/updatePathCleaning'
import type { Context } from '@/tools/types'
+describe('expandAlias', () => {
+ // The sample preview has to agree with ClickHouse, whose re2 replacement rules differ from
+ // JavaScript's: `$` is literal, `\10` is group 1 then `0` rather than group 10, and a group the
+ // pattern never filled substitutes as empty.
+ it.each<[string, string, (string | undefined)[], string]>([
+ ['substitutes a group', '/u/\\1', ['/users/42', '42'], '/u/42'],
+ ['substitutes the whole match', '[\\0]', ['/users/42', '42'], '[/users/42]'],
+ ['keeps a dollar literal', '/u/$1', ['/users/42', '42'], '/u/$1'],
+ ['reads \\10 as group 1 then a literal', '\\10', ['ab', 'a', 'b'], 'a0'],
+ ['substitutes an unfilled group as empty', '/u/\\2', ['/users/42', '42', undefined], '/u/'],
+ ['keeps an escaped backslash literal', '\\\\1', ['/users/42', '42'], '\\1'],
+ ])('%s', (_name, alias, groups, expected) => {
+ expect(expandAlias(alias, groups)).toBe(expected)
+ })
+})
+
describe('normalizePathCleaningFilters', () => {
it('preserves stored array order (not the order field) and drops only entries with no regex', () => {
// The backend applies rules in array order and ignores `order`, so normalize must NOT