:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
fix(replay_vision): match the whole page path, wildcarding route ids (#90930)
Kim Svatos Dugan5d6fe2d905c5
diff --git a/products/replay_vision/backend/scanner_draft.py b/products/replay_vision/backend/scanner_draft.pyindex 9d49256d8d6f..6b0b09a861bb 100644--- a/products/replay_vision/backend/scanner_draft.py+++ b/products/replay_vision/backend/scanner_draft.py@@ -81,6 +81,9 @@ _MIN_SCREEN_FILTER_CHARS = 3# v2 filter pages become ONE multi-value visited_page property, which ORs its values, so several are# safe. More than this and the filter stops describing one flow._MAX_FILTER_PAGES = 5+# Replaces a collapsed ":id" run when building the page regex. Matches one path segment, so the+# literal segments on both sides of the id stay anchored to the real URL structure.+_ID_WILDCARD = "[^/]+"class DraftError(Exception):@@ -720,19 +723,26 @@ def _build_user_content_v2(return "\n".join(lines)-def _page_filter_value(pathname: str) -> str | None:- """The `icontains` filter value for a grounded page, or None when the page cannot filter.+def _page_filter_regex(pathname: str) -> str | None:+ """A ClickHouse regex matching real URLs for a collapsed grounding path, or None when the path+ cannot narrow.- The grounding list collapses identifier segments to ":id", but real URLs contain the real IDs, so- a value holding ":id" matches nothing. The prefix up to the first ":id" still matches every such- URL — broader than the exact page, and under OR semantics broader only adds sessions.+ The grounding list collapses identifier segments to ":id", but real URLs hold real IDs. Replacing+ each ":id" with a single-segment wildcard keeps the WHOLE path specific: the collapsed page+ "/project/:id/replay-vision/scanners" becomes a regex matching "/project/<id>/replay-vision/+ scanners" and nothing broader. Matching a single static substring instead would lose the segments+ around the id and could collapse to a bare prefix that matches every page."""- value = pathname.split(":id")[0] if ":id" in pathname else pathname- if len(value.strip().replace("/", "")) < _MIN_SCREEN_FILTER_CHARS:- # `icontains` on "/" or a two-letter prefix matches nearly every URL: it would render as a- # narrowing filter while narrowing nothing.+ # The literal segments, ignoring the ":id" runs, are the only real content to match on. A path+ # with too little (e.g. "/", "/:id", or "/ab") would match nearly every URL, so draft no filter+ # rather than one that narrows nothing. Any other shape is kept: the scanner watches the+ # customer's product, so we don't assume their URL structure.+ static_chars = len(pathname.replace(":id", "").replace("/", ""))+ if static_chars < _MIN_SCREEN_FILTER_CHARS:return None- return value+ # Escape the literal parts so a path character like "." or "-" cannot act as a regex+ # metacharacter, then rejoin with the id wildcard.+ return _ID_WILDCARD.join(re.escape(part) for part in pathname.split(":id"))def _strip_page_count(page: str) -> str:@@ -743,15 +753,16 @@ def _strip_page_count(page: str) -> str:def _v2_query(pathnames: Sequence[str], events: Sequence[str]) -> dict[str, Any] | None:"""The scanner's recording filter from the grounded pages and events.- Pages become ONE multi-value `visited_page` property (its values OR). Events go in the `events`- list, where each event ANDs, with the other events and with the page property. The estimate the- caller runs, and the review page's Save-at-zero gate, catch an over-constrained AND before it- ever becomes a scanner.+ Pages become ONE multi-value `visited_page` property (its values OR). Each value is a regex that+ matches the collapsed page against real URLs, with ":id" runs wildcarded. Events go in the+ `events` list, where each event ANDs, with the other events and with the page property. The+ estimate the caller runs, and the review page's Save-at-zero gate, catch an over-constrained AND+ before it ever becomes a scanner."""query: dict[str, Any] = {"kind": "RecordingsQuery"}- values = list(dict.fromkeys(v for p in pathnames if (v := _page_filter_value(p)) is not None))+ values = list(dict.fromkeys(v for p in pathnames if (v := _page_filter_regex(p)) is not None))if values:- query["properties"] = [{"type": "recording", "key": "visited_page", "value": values, "operator": "icontains"}]+ query["properties"] = [{"type": "recording", "key": "visited_page", "value": values, "operator": "regex"}]if events:# The shape the replay filter UI produces for an event condition.query["events"] = [{"id": event, "name": event, "type": "events", "order": 0} for event in events]diff --git a/products/replay_vision/backend/tests/test_scanner_draft.py b/products/replay_vision/backend/tests/test_scanner_draft.pyindex 4c6eb9e2e414..259940ca8a24 100644--- a/products/replay_vision/backend/tests/test_scanner_draft.py+++ b/products/replay_vision/backend/tests/test_scanner_draft.py@@ -590,7 +590,7 @@ class TestDraftScannerEndpoint(_VisionAPITestCase):class TestV2Query:def test_pages_become_one_multi_value_property(self):# Separate properties would AND and match almost nothing: measured 68 sessions where the- # one-property shape matched 44,523.+ # one-property shape matched 44,523. A page with no id is a plain regex of itself.query = _v2_query(["/billing", "/checkout", "/payment"], [])assert query is not None@@ -599,7 +599,7 @@ class TestV2Query:"type": "recording","key": "visited_page","value": ["/billing", "/checkout", "/payment"],- "operator": "icontains",+ "operator": "regex",}assert "events" not in query@@ -624,25 +624,52 @@ class TestV2Query:def test_no_pages_and_no_events_is_no_query(self):assert _v2_query([], []) is None- def test_collapsed_id_pages_filter_by_their_prefix(self):- # The grounding list says "/invoice/:id" but real URLs hold real IDs, so the literal value- # would match zero sessions. The prefix still matches every such URL.+ def test_a_collapsed_id_becomes_a_wildcard(self):+ # The grounding list says "/invoice/:id" but real URLs hold real IDs. The regex wildcards the+ # id so it matches "/invoice/<any>" without matching a bare "/invoices-archive".query = _v2_query(["/invoice/:id", "/billing"], [])assert query is not None- assert query["properties"][0]["value"] == ["/invoice/", "/billing"]+ assert query["properties"][0]["value"] == ["/invoice/[^/]+", "/billing"]@pytest.mark.parametrize("pathname", ["/", "/:id", "/a/:id/b"])def test_a_page_that_cannot_narrow_is_dropped(self, pathname):- # "/a/:id/b" prefixes to "/a/", two non-slash chars: icontains on it matches nearly every+ # "/a/:id/b" has two one-character static segments: any pattern from it matches nearly every# URL, so it reads as a narrowing filter while narrowing nothing.assert _v2_query([pathname], []) is None- def test_prefix_collisions_are_deduped(self):+ def test_an_id_prefixed_route_keeps_the_whole_path(self):+ # When the id sits before the distinctive segment, the whole-path regex keeps+ # "/replay-vision/scanners" instead of collapsing to the "/project/" prefix in front.+ query = _v2_query(["/project/:id/replay-vision/scanners"], [])++ assert query is not None+ assert query["properties"][0]["value"] == ["/project/[^/]+/replay\\-vision/scanners"]++ def test_a_route_with_ids_on_both_sides_wildcards_each(self):+ # "/project/:id/replay-home/:id" is ambiguous for a substring rule, but the full-path regex+ # keeps "replay-home" between two wildcards, so it stays specific to that page.+ query = _v2_query(["/project/:id/replay-home/:id"], [])++ assert query is not None+ assert query["properties"][0]["value"] == ["/project/[^/]+/replay\\-home/[^/]+"]++ def test_a_generic_looking_path_is_still_kept(self):+ # "/project/:id" reads like a routing container in PostHog, but a scanner watches the+ # customer's product, where "/project/<id>" may be a real page. So keep it as a wildcarded+ # regex rather than assuming any team's URL shape.+ query = _v2_query(["/project/:id"], [])++ assert query is not None+ assert query["properties"][0]["value"] == ["/project/[^/]+"]++ def test_paths_that_differ_only_after_the_id_stay_distinct(self):+ # The whole path is matched, so "/invoice/:id" and "/invoice/:id/edit" produce different+ # regexes rather than collapsing to a shared prefix.query = _v2_query(["/invoice/:id", "/invoice/:id/edit"], [])assert query is not None- assert query["properties"][0]["value"] == ["/invoice/"]+ assert query["properties"][0]["value"] == ["/invoice/[^/]+", "/invoice/[^/]+/edit"]class TestFinalizeV2: