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(replay_vision): list a team's real pages for goal-based scanner setup (#88877)

Kim Svatos Duganb93b8913b72a
diff --git a/products/replay_vision/backend/queries/__init__.py b/products/replay_vision/backend/queries/__init__.py
index d4e417f9335b..a44d8735b6f9 100644
--- a/products/replay_vision/backend/queries/__init__.py
+++ b/products/replay_vision/backend/queries/__init__.py
@@ -17,6 +17,7 @@ from products.replay_vision.backend.queries.scanner_volume_estimate import (
project_monthly_observations,
refresh_scanner_estimate,
)
+from products.replay_vision.backend.queries.visited_paths import VisitedPath, fetch_visited_paths
__all__ = [
"DEFAULT_CANDIDATE_LIMIT",
@@ -31,7 +32,9 @@ __all__ = [
"CandidateSession",
"ScannerCandidateQuery",
"ScannerVolumeEstimate",
+ "VisitedPath",
"estimate_scanner_session_volume",
+ "fetch_visited_paths",
"project_monthly_observations",
"refresh_scanner_estimate",
]
diff --git a/products/replay_vision/backend/queries/visited_paths.py b/products/replay_vision/backend/queries/visited_paths.py
new file mode 100644
index 000000000000..429f8007b4e0
--- /dev/null
+++ b/products/replay_vision/backend/queries/visited_paths.py
@@ -0,0 +1,157 @@
+import datetime as dt
+
+from posthog.hogql import ast
+from posthog.hogql.constants import HogQLGlobalSettings
+from posthog.hogql.parser import parse_select
+from posthog.hogql.query import execute_hogql_query
+
+from posthog.clickhouse.client.connection import ClickHouseUser
+from posthog.clickhouse.query_tagging import Feature, Product, tag_queries
+from posthog.dataclasses import frozen
+from posthog.models import Team
+
+from products.replay_vision.backend.session_limits import (
+ MAX_ACTIVE_SECONDS_FOR_VIDEO_SCANNER_S,
+ MIN_ACTIVE_SECONDS_FOR_VIDEO_SCANNER_S,
+ MIN_SESSION_DURATION_FOR_VIDEO_SCANNER_S,
+)
+
+# One week is enough to describe a product's surfaces and short enough to partition-prune.
+_PATH_WINDOW_DAYS = 7
+# The list goes into a model prompt, so it has to stay small enough to fit alongside everything else.
+# On a large project the floor below leaves a few thousand paths; this keeps the busiest of them.
+_MAX_PATHS = 300
+# Below this a path is one person's visit, not a surface of the product.
+_MIN_SESSIONS_PER_PATH = 5
+# Visitors control their own URLs, so a fabricated path must not be able to blow up the prompt.
+_MAX_PATHNAME_CHARS = 256
+_PATH_QUERY_MAX_EXECUTION_SECONDS = 5
+
+# Identifiers in a path make one surface look like thousands. Each rule matches a WHOLE segment
+# between slashes — a partial match would eat the digits off a real page name and emit garbage
+# ("/2fa" must never become "/:idfa"). Every rule except the numeric one also demands a digit, so a
+# long real word is never mistaken for a token.
+_SEGMENT_NUMERIC = r"^[0-9]+$"
+_SEGMENT_DASHED_UUID = r"^[0-9a-fA-F-]{20,}$"
+_SEGMENT_HEX = r"^[0-9a-fA-F]{12,}$"
+_SEGMENT_TOKEN = r"^[a-zA-Z0-9]{16,}$"
+_ANY_DIGIT = r"[0-9]"
+# A path that is one all-digit segment is a page, not an ID: /404, /500.
+_TOPLEVEL_NUMERIC_PATH = r"^/[0-9]+$"
+_ID_PLACEHOLDER = ":id"
+
+
+@frozen
+class VisitedPath:
+ # Identifier segments are collapsed, so this reads "/invoice/:id" rather than "/invoice/8814".
+ pathname: str
+ sessions: int
+
+
+def fetch_visited_paths(
+ *,
+ team: Team,
+ window_days: int = _PATH_WINDOW_DAYS,
+ limit: int = _MAX_PATHS,
+ min_sessions: int = _MIN_SESSIONS_PER_PATH,
+ ch_user: ClickHouseUser = ClickHouseUser.APP,
+) -> tuple[VisitedPath, ...]:
+ """The product's page paths, busiest first, for grounding a model that reads a person's goal.
+
+ Someone asks about "money" and the product calls it "billing". Only a model bridges that, and only
+ if it can see the real pages, so this returns a list short enough to put in a prompt.
+
+ Collapsing identifier segments is what makes the list short. A segment collapses to ":id" only
+ when the whole segment is an identifier: all digits, a dashed UUID, a hex run, or a long token
+ holding a digit. Measured on a project with a million sessions a week: 991,985 distinct paths fall
+ to 117,569 collapsed, and the five-session floor leaves about 8,400; the limit then keeps the
+ busiest of those. Known limit: short mixed identifiers ("/insights/AbC123xY") stay uncollapsed.
+
+ The pathnames are visitor-controlled content — anyone can put any string in their own URL. Each is
+ capped at a fixed length here, and the consumer must still fence the list as untrusted data, the
+ way `scanner_draft.py` fences its briefing.
+
+ Reads `all_urls` because that is the column a `visited_page` recording filter compiles against, so
+ every path here matches a non-zero number of sessions. Counts only sessions long and active enough
+ for a scanner to observe, using the sweep's own bounds: a landing page collects many short visits
+ that no scanner will ever watch, and counting them overstates the page and mis-orders the list.
+
+ Raises on failure; the caller decides whether missing grounding is fatal.
+ """
+ window_start = dt.datetime.now(dt.UTC) - dt.timedelta(days=window_days)
+ query = parse_select(
+ """
+ SELECT pathname, count(DISTINCT session_id) AS sessions
+ FROM (
+ SELECT
+ session_id,
+ substring(
+ if(
+ match(raw_path, {toplevel_numeric}),
+ raw_path,
+ arrayStringConcat(
+ arrayMap(
+ s -> multiIf(
+ match(s, {segment_numeric}), {id_placeholder},
+ match(s, {segment_dashed_uuid}) and match(s, {any_digit}), {id_placeholder},
+ match(s, {segment_hex}) and match(s, {any_digit}), {id_placeholder},
+ match(s, {segment_token}) and match(s, {any_digit}), {id_placeholder},
+ s
+ ),
+ splitByChar('/', raw_path)
+ ),
+ '/'
+ )
+ ),
+ 1, {max_pathname_chars}
+ ) AS pathname
+ FROM (
+ SELECT
+ session_id,
+ arrayJoin(arrayDistinct(arrayMap(url -> path(url), groupUniqArrayArray(all_urls)))) AS raw_path
+ FROM raw_session_replay_events
+ WHERE min_first_timestamp >= {window_start}
+ GROUP BY session_id
+ HAVING dateDiff('second', min(min_first_timestamp), max(max_last_timestamp)) >= {min_duration}
+ AND sum(active_milliseconds) / 1000 >= {min_active}
+ AND sum(active_milliseconds) / 1000 <= {max_active}
+ )
+ )
+ WHERE pathname != ''
+ GROUP BY pathname
+ HAVING sessions >= {min_sessions}
+ ORDER BY sessions DESC, pathname ASC
+ LIMIT {limit}
+ """,
+ placeholders={
+ "window_start": ast.Constant(value=window_start),
+ "toplevel_numeric": ast.Constant(value=_TOPLEVEL_NUMERIC_PATH),
+ "segment_numeric": ast.Constant(value=_SEGMENT_NUMERIC),
+ "segment_dashed_uuid": ast.Constant(value=_SEGMENT_DASHED_UUID),
+ "segment_hex": ast.Constant(value=_SEGMENT_HEX),
+ "segment_token": ast.Constant(value=_SEGMENT_TOKEN),
+ "any_digit": ast.Constant(value=_ANY_DIGIT),
+ "id_placeholder": ast.Constant(value=_ID_PLACEHOLDER),
+ "max_pathname_chars": ast.Constant(value=_MAX_PATHNAME_CHARS),
+ "min_duration": ast.Constant(value=MIN_SESSION_DURATION_FOR_VIDEO_SCANNER_S),
+ "min_active": ast.Constant(value=MIN_ACTIVE_SECONDS_FOR_VIDEO_SCANNER_S),
+ "max_active": ast.Constant(value=MAX_ACTIVE_SECONDS_FOR_VIDEO_SCANNER_S),
+ "min_sessions": ast.Constant(value=min_sessions),
+ "limit": ast.Constant(value=limit),
+ },
+ )
+
+ tag_queries(team_id=team.id, product=Product.REPLAY_VISION, feature=Feature.QUERY)
+ response = execute_hogql_query(
+ query=query,
+ team=team,
+ query_type="ReplayVisionVisitedPathsQuery",
+ # "throw", not "break": on "break" ClickHouse returns partial aggregates, so the counts would
+ # be quietly wrong and the busiest-first order would be whatever it read first. Measured well
+ # inside this budget on a project with a million sessions a week.
+ settings=HogQLGlobalSettings(
+ max_execution_time=_PATH_QUERY_MAX_EXECUTION_SECONDS, timeout_overflow_mode="throw"
+ ),
+ ch_user=ch_user,
+ )
+ return tuple(VisitedPath(pathname=str(row[0]), sessions=int(row[1])) for row in response.results or [])
diff --git a/products/replay_vision/backend/tests/test_visited_paths.py b/products/replay_vision/backend/tests/test_visited_paths.py
new file mode 100644
index 000000000000..19702678b171
--- /dev/null
+++ b/products/replay_vision/backend/tests/test_visited_paths.py
@@ -0,0 +1,201 @@
+import datetime as dt
+
+import pytest
+from freezegun import freeze_time
+from posthog.test.base import ClickhouseTestMixin
+
+from posthog.schema import RecordingsQuery
+
+from posthog.clickhouse.client import sync_execute
+from posthog.session_recordings.queries.test.session_replay_sql import produce_replay_summary
+from posthog.session_recordings.sql.session_replay_event_sql import TRUNCATE_SESSION_REPLAY_EVENTS_TABLE_SQL
+
+from products.replay_vision.backend.queries.scanner_volume_estimate import (
+ PREVIEW_ESTIMATE_BUDGET,
+ estimate_scanner_session_volume,
+)
+from products.replay_vision.backend.queries.visited_paths import fetch_visited_paths
+
+_NOW = dt.datetime(2026, 5, 1, 12, 0, 0, tzinfo=dt.UTC)
+
+
+def _visited_page(*values: str) -> dict:
+ return {"type": "recording", "key": "visited_page", "value": list(values), "operator": "icontains"}
+
+
+def _produce(
+ team_id: int,
+ session_id: str,
+ urls: list[str],
+ ago: dt.timedelta = dt.timedelta(hours=1),
+ active_milliseconds: int = 30_000,
+ length: dt.timedelta = dt.timedelta(minutes=1),
+) -> None:
+ start = _NOW - ago
+ produce_replay_summary(
+ team_id=team_id,
+ session_id=session_id,
+ first_timestamp=start.isoformat(),
+ last_timestamp=(start + length).isoformat(),
+ all_urls=urls,
+ # Clears the eligibility floor by default, so a test about ranking is not quietly emptied by
+ # the eligibility filter.
+ active_milliseconds=active_milliseconds,
+ )
+
+
+@freeze_time(_NOW.strftime("%Y-%m-%dT%H:%M:%SZ"))
+class TestVisitedPaths(ClickhouseTestMixin):
+ def setup_method(self, _method) -> None:
+ sync_execute(TRUNCATE_SESSION_REPLAY_EVENTS_TABLE_SQL())
+
+ @pytest.mark.django_db
+ def test_identifier_segments_collapse_into_one_surface(self, team) -> None:
+ # The reason the list fits in a prompt at all. On a real project this is the difference
+ # between 991,985 paths and about 117,000: without it, invoice pages crowd out everything else.
+ for i in range(6):
+ _produce(team.id, f"invoice-{i}", [f"https://ex.test/invoice/{i}"])
+ _produce(team.id, "uuid-visit", ["https://ex.test/org/0198f4a1-8c2b-7d3e-9f10-2a3b4c5d6e7f/settings"])
+ for i in range(5):
+ _produce(team.id, f"settings-{i}", ["https://ex.test/settings"])
+
+ results = fetch_visited_paths(team=team, min_sessions=1)
+ by_path = {r.pathname: r.sessions for r in results}
+
+ assert by_path["/invoice/:id"] == 6
+ assert by_path["/org/:id/settings"] == 1
+ assert by_path["/settings"] == 5
+
+ @pytest.mark.parametrize(
+ "path,expected",
+ [
+ # An ID is a WHOLE segment. A partial match ate the digits off real page names and fed
+ # the model paths that exist nowhere: "/2fa" became "/:idfa", "/404" vanished into "/:id".
+ ("/2fa", "/2fa"),
+ ("/404", "/404"),
+ ("/123abc", "/123abc"),
+ ("/step1", "/step1"),
+ ("/v2/api", "/v2/api"),
+ ("/invoice/123/edit", "/invoice/:id/edit"),
+ # The shapes the collapse exists for: each would otherwise be one surface per ID.
+ ("/project/5f3a9c2e1b4d/settings", "/project/:id/settings"),
+ ("/user/01J8ZQ8G3R2Y4W5X6V7T8S9A0B", "/user/:id"),
+ ("/replay/0198f4a1-8c2b-7d3e-9f10-2a3b4c5d6e7f", "/replay/:id"),
+ # Known limit: short mixed identifiers stay. A rule loose enough to catch 8 characters
+ # would also collapse real page names.
+ ("/insights/AbC123xY", "/insights/AbC123xY"),
+ # A long real word is not a token: every token rule demands a digit.
+ ("/internationalization-settings", "/internationalization-settings"),
+ ],
+ )
+ @pytest.mark.django_db
+ def test_a_segment_collapses_only_when_it_is_entirely_an_identifier(self, team, path, expected) -> None:
+ _produce(team.id, "s", [f"https://ex.test{path}"])
+
+ results = fetch_visited_paths(team=team, min_sessions=1)
+
+ assert [r.pathname for r in results] == [expected]
+
+ @pytest.mark.django_db
+ def test_a_fabricated_path_cannot_blow_up_the_prompt(self, team) -> None:
+ # Visitors control their own URLs, so one crafted path must not inflate what reaches the model.
+ _produce(team.id, "s", ["https://ex.test/" + "a" * 2000])
+
+ results = fetch_visited_paths(team=team, min_sessions=1)
+
+ assert len(results) == 1
+ assert len(results[0].pathname) == 256
+
+ @pytest.mark.django_db
+ def test_the_list_keeps_the_busiest_paths_up_to_the_limit(self, team) -> None:
+ for i in range(4):
+ _produce(team.id, f"busy-{i}", ["https://ex.test/busy"])
+ for name in ("alpha", "beta", "gamma"):
+ _produce(team.id, f"one-{name}", [f"https://ex.test/{name}"])
+
+ results = fetch_visited_paths(team=team, min_sessions=1, limit=2)
+
+ assert [(r.pathname, r.sessions) for r in results] == [("/busy", 4), ("/alpha", 1)]
+
+ @pytest.mark.django_db
+ def test_one_person_visit_is_not_a_product_surface(self, team) -> None:
+ # Without a floor the list fills with pages one person opened once, and the real surfaces
+ # fall off the end of the prompt.
+ for i in range(5):
+ _produce(team.id, f"real-{i}", ["https://ex.test/billing"])
+ _produce(team.id, "one-off", ["https://ex.test/rare-corner"])
+
+ results = fetch_visited_paths(team=team, min_sessions=5)
+
+ assert [r.pathname for r in results] == ["/billing"]
+
+ @pytest.mark.django_db
+ def test_busiest_first_and_urls_normalize_to_path(self, team) -> None:
+ _produce(team.id, "a", ["https://app.ex.test/billing?tab=1", "https://other.ex.test/billing"])
+ _produce(team.id, "b", ["https://ex.test/billing"])
+ _produce(team.id, "c", ["https://ex.test/quiet"])
+
+ results = fetch_visited_paths(team=team, min_sessions=1)
+
+ assert [(r.pathname, r.sessions) for r in results] == [("/billing", 2), ("/quiet", 1)]
+
+ @pytest.mark.django_db
+ def test_sessions_a_scanner_cannot_observe_are_not_counted(self, team) -> None:
+ # A landing page collects many short visits. Counting them overstates the page and puts it
+ # above pages whose sessions a scanner would really watch.
+ _produce(team.id, "watchable", ["https://ex.test/deep"])
+ for i in range(5):
+ _produce(
+ team.id,
+ f"bounce-{i}",
+ ["https://ex.test/landing"],
+ active_milliseconds=1_000,
+ length=dt.timedelta(seconds=3),
+ )
+
+ results = fetch_visited_paths(team=team, min_sessions=1)
+
+ assert [(r.pathname, r.sessions) for r in results] == [("/deep", 1)]
+
+ @pytest.mark.django_db
+ def test_paths_outside_the_window_are_excluded(self, team) -> None:
+ _produce(team.id, "recent", ["https://ex.test/billing"])
+ _produce(team.id, "stale", ["https://ex.test/ancient"], ago=dt.timedelta(days=8))
+
+ results = fetch_visited_paths(team=team, min_sessions=1)
+
+ assert [r.pathname for r in results] == ["/billing"]
+
+
+@freeze_time(_NOW.strftime("%Y-%m-%dT%H:%M:%SZ"))
+class TestVisitedPageFilterSemantics(ClickhouseTestMixin):
+ """One `visited_page` property holding several values ORs them; several properties AND.
+
+ Whatever writes the scanner's filter — a model, or a person editing it — has to emit the first
+ shape. Asserted against real ClickHouse rather than by reading `posthog/hogql/property.py`,
+ because that compilation lives upstream of this product: if it ever changed, every filter would
+ quietly match almost nothing and no test of our own output would show it.
+ """
+
+ def setup_method(self, _method) -> None:
+ sync_execute(TRUNCATE_SESSION_REPLAY_EVENTS_TABLE_SQL())
+
+ @staticmethod
+ def _count(team, properties: list[dict]) -> int:
+ query = RecordingsQuery.model_validate({"kind": "RecordingsQuery", "properties": properties})
+ return estimate_scanner_session_volume(team=team, query=query, budget=PREVIEW_ESTIMATE_BUDGET).matched_sessions
+
+ @pytest.mark.django_db
+ def test_one_multi_value_property_ors_where_separate_properties_and(self, team) -> None:
+ # Each session opens exactly one of the three pages, so nothing can satisfy all three.
+ _produce(team.id, "cart", ["https://ex.test/cart"])
+ _produce(team.id, "checkout", ["https://ex.test/checkout"])
+ _produce(team.id, "payment", ["https://ex.test/payment"])
+
+ one_property = self._count(team, [_visited_page("/cart", "/checkout", "/payment")])
+ separate_properties = self._count(team, [_visited_page(p) for p in ("/cart", "/checkout", "/payment")])
+ single_page = self._count(team, [_visited_page("/cart")])
+
+ assert one_property == 3
+ assert separate_properties == 0
+ assert single_page == 1