: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
chore(replay): remove new-URL synthetic collections and retire flag (#63843)
Kim Svatos Dugan349197322e43
diff --git a/frontend/src/lib/constants.tsx b/frontend/src/lib/constants.tsxindex 4223f7170067..1100bbaf13ed 100644--- a/frontend/src/lib/constants.tsx+++ b/frontend/src/lib/constants.tsx@@ -451,7 +451,6 @@ export const FEATURE_FLAGS = {REMOTE_CONFIG: 'remote-config', // owner: #team-platform-featuresREPLAY_COLLAPSE_INSPECTOR_ITEMS: 'replay-collapse-inspector-items', // owner: @fasyy612 #team-replayREPLAY_FILTERS_REDESIGN: 'replay-filters-redesign', // owner: @ksvat #team-replay- REPLAY_NEW_DETECTED_URL_COLLECTIONS: 'replay-new-detected-url-collections', // owner: @ksvat #team-replay multivariate=trueREPLAY_TRIGGERS_V2: 'replay-triggers-v2', // owner: #team-replayREPLAY_UI_REDESIGN_2026: 'replay-ui-redesign-2026', // owner: #team-replay, New UI layout for replayREPLAY_VIDEO_BASED_SUMMARIZATION: 'replay-video-based-summarization', // owner: #team-replaydiff --git a/frontend/src/scenes/session-recordings/collections/SessionRecordingCollections.tsx b/frontend/src/scenes/session-recordings/collections/SessionRecordingCollections.tsxindex 2adeae6cb09c..015d1b4308fa 100644--- a/frontend/src/scenes/session-recordings/collections/SessionRecordingCollections.tsx+++ b/frontend/src/scenes/session-recordings/collections/SessionRecordingCollections.tsx@@ -17,11 +17,9 @@ import { AccessControlAction } from 'lib/components/AccessControlAction'import { DateFilter } from 'lib/components/DateFilter/DateFilter'import { MemberSelect } from 'lib/components/MemberSelect'import { TZLabel } from 'lib/components/TZLabel'-import { FEATURE_FLAGS } from 'lib/constants'import { More } from 'lib/lemon-ui/LemonButton/More'import { LemonTableColumn, LemonTableColumns } from 'lib/lemon-ui/LemonTable'import { createdByColumn } from 'lib/lemon-ui/LemonTable/columnUtils'-import { featureFlagLogic } from 'lib/logic/featureFlagLogic'import { isObject } from 'lib/utils'import { urls } from 'scenes/urls'@@ -136,7 +134,6 @@ export function SessionRecordingCollections(): JSX.Element {const { setSavedPlaylistsFilters, updatePlaylist, duplicatePlaylist, deletePlaylist } = useActions(sessionRecordingCollectionsLogic)- const { featureFlags } = useValues(featureFlagLogic)const columns: LemonTableColumns<SessionRecordingPlaylistType> = [{@@ -281,14 +278,6 @@ export function SessionRecordingCollections(): JSX.Element {label: 'Automatic',value: 'synthetic',},- ...(featureFlags[FEATURE_FLAGS.REPLAY_NEW_DETECTED_URL_COLLECTIONS] === 'test'- ? [- {- label: 'New URLs',- value: 'new-urls',- },- ]- : []),]}/></div>diff --git a/frontend/src/types.ts b/frontend/src/types.tsindex b999205983db..3ccafa993b47 100644--- a/frontend/src/types.ts+++ b/frontend/src/types.ts@@ -1881,7 +1881,7 @@ export interface SavedSessionRecordingPlaylistsFilters {page: numberpinned: booleantype?: 'collection' | 'saved_filters'- collectionType: 'custom' | 'synthetic' | 'new-urls' | null+ collectionType: 'custom' | 'synthetic' | null}export interface SavedSessionRecordingPlaylistsResult extends PaginatedResponse<SessionRecordingPlaylistType> {diff --git a/posthog/session_recordings/session_recording_playlist_api.py b/posthog/session_recordings/session_recording_playlist_api.pyindex b7707fff7956..f536ec819efe 100644--- a/posthog/session_recordings/session_recording_playlist_api.py+++ b/posthog/session_recordings/session_recording_playlist_api.py@@ -148,7 +148,7 @@ def count_synthetic_playlist(playlist: SessionRecordingPlaylist, user: User, team: Team) -> dict[str, int | bool | None]:"""Count recordings in a synthetic playlist using efficient database-level counting"""- synthetic_def = get_synthetic_playlist(playlist.short_id, team=team)+ synthetic_def = get_synthetic_playlist(playlist.short_id)if not synthetic_def:return {"count": None,@@ -579,7 +579,7 @@ class SessionRecordingPlaylistViewSet(# Check if this is a synthetic playlistif lookup_value and lookup_value.startswith("synthetic-"):- synthetic_def = get_synthetic_playlist(lookup_value, team=self.team)+ synthetic_def = get_synthetic_playlist(lookup_value)if synthetic_def:return create_synthetic_playlist_instance(synthetic_def, self.team, cast(User, self.request.user))@@ -603,8 +603,8 @@ class SessionRecordingPlaylistViewSet(page_number = int(request.GET.get("page", 1))is_first_page = offset == 0 and page_number == 1- # Create synthetic playlist instances (includes both static and dynamic)- all_synthetic_playlists = get_all_synthetic_playlists(self.team)+ # Create synthetic playlist instances+ all_synthetic_playlists = get_all_synthetic_playlists()synthetic_instances = [create_synthetic_playlist_instance(sp, self.team, cast(User, request.user))for sp in all_synthetic_playlists@@ -694,8 +694,8 @@ class SessionRecordingPlaylistViewSet(elif request_value == SessionRecordingPlaylist.PlaylistType.FILTERS:queryset = queryset.filter(type=SessionRecordingPlaylist.PlaylistType.FILTERS)elif key == "collection_type":- if request_value in ("synthetic", "new-urls"):- # Exclude all DB playlists when filtering for synthetic or new-urls+ if request_value == "synthetic":+ # Exclude all DB playlists when filtering for syntheticqueryset = queryset.none()elif key == "pinned":queryset = queryset.filter(pinned=True)@@ -738,9 +738,6 @@ class SessionRecordingPlaylistViewSet(if request_value == "custom":# Custom means user-created only, exclude all synthetic playlistsreturn []- elif request_value == "new-urls":- # Filter for only new-urls synthetic playlists- filtered = [p for p in filtered if p.short_id.startswith("synthetic-new-url-")]elif key == "pinned":# Synthetic playlists are never pinned, so exclude themreturn []@@ -789,7 +786,7 @@ class SessionRecordingPlaylistViewSet(# Handle synthetic playlists differentlyif getattr(playlist, "_is_synthetic", False):- synthetic_def = get_synthetic_playlist(playlist.short_id, team=self.team)+ synthetic_def = get_synthetic_playlist(playlist.short_id)if synthetic_def:playlist_items = synthetic_def.get_session_ids(self.team, cast(User, request.user), limit, offset)else:diff --git a/posthog/session_recordings/synthetic_playlists.py b/posthog/session_recordings/synthetic_playlists.pyindex f5cc9f826dce..e4f92678a751 100644--- a/posthog/session_recordings/synthetic_playlists.py+++ b/posthog/session_recordings/synthetic_playlists.py@@ -3,18 +3,13 @@ Synthetic playlists are virtual playlists that are dynamically calculated and avThey are not stored in the database but appear alongside regular playlists in the API."""-import re-import hashlibfrom abc import ABC, abstractmethodfrom dataclasses import dataclassfrom datetime import UTC, datetime, timedeltafrom typing import Protocol-from urllib.parse import urlparsefrom django.core.cache import cache-import posthoganalytics-from posthog.schema import RecordingOrder, RecordingsQueryfrom posthog.clickhouse.client import sync_execute@@ -45,9 +40,7 @@ class CountSessionIdsCallable(Protocol):class SyntheticPlaylistSource(ABC):"""Base class for synthetic playlist sources.- Subclasses can implement either:- 1. to_synthetic_playlist() for static playlists (one playlist per source)- 2. generate_dynamic_playlists() for dynamic playlists (multiple playlists generated on-demand)+ Subclasses implement to_synthetic_playlist() to return one static playlist per source."""@staticmethod@@ -77,22 +70,6 @@ class SyntheticPlaylistSource(ABC):def to_synthetic_playlist(self) -> "SyntheticPlaylistDefinition | None":"""Return a single static synthetic playlist definition.- Return None if this source only generates dynamic playlists.- """- return None-- def generate_dynamic_playlists(self, team: Team) -> list["SyntheticPlaylistDefinition"]:- """- Generate multiple dynamic playlist definitions for this source.- Override this method to create playlists that vary based on data (e.g., one per URL).- Return empty list if this source only generates a static playlist.- """- return []-- def get_dynamic_playlist_by_id(self, short_id: str, team: Team) -> "SyntheticPlaylistDefinition | None":- """- Retrieve a specific dynamic playlist by its short_id.- Override this method for dynamic playlist sources."""return None@@ -374,295 +351,6 @@ class FrustrationSignalsPlaylistSource(SyntheticPlaylistSource):)-@dataclass-class NewUrlsSyntheticPlaylistSource(SyntheticPlaylistSource):- """- Dynamic synthetic playlist source that creates one playlist per new URL detected in the last 14 days.- A URL is considered "new" if it first appeared in recordings within the last 14 days, and not previously seen within the last 90 days.- """-- url: str | None = None-- CACHE_KEY_PREFIX = "new_urls_synthetic_playlist"- CACHE_TTL = 3600 # 1 hour- LOOKBACK_DAYS = 14- MIN_ID = -1000 # Start IDs from -1000 for new URL playlists-- @staticmethod- def _get_cache_key(team_id: int) -> str:- """Generate cache key for new URLs list"""- return f"{NewUrlsSyntheticPlaylistSource.CACHE_KEY_PREFIX}_team_{team_id}"-- @staticmethod- def _url_to_hash(url: str) -> str:- """Convert URL to a stable short hash for use in short_id"""- return hashlib.sha256(url.encode()).hexdigest()[:12]-- @staticmethod- def _short_id_to_url(short_id: str) -> str | None:- """Extract URL from short_id. Returns None if not a valid new-url playlist ID."""- # Format: synthetic-new-url-{hash}- # We can't reverse the hash, so we need to look it up- # This is handled by get_dynamic_playlist_by_id which queries all new URLs- return None-- @staticmethod- def _normalize_url(url: str) -> str:- """- Normalize a URL by:- 1. Removing query parameters and fragments- 2. Replacing country-code subdomains with {country} placeholder- 3. Replacing path segments that look like IDs with placeholders-- This groups:- - /billing?id=1 and /billing?id=2 -> /billing- - us.example.com and uk.example.com -> {country}.example.com- - /project/1/settings and /project/2/settings -> /project/{id}/settings- - /user/abc-123-def/profile -> /user/{uuid}/profile- - /item/xYz123AbC456DeF789 -> /item/{hash}- """- try:- parsed = urlparse(url)- path = parsed.path- domain = parsed.netloc-- # Normalize country-code subdomains (e.g., us.example.com -> {country}.example.com)- # Common 2-letter country codes as subdomains- domain_parts = domain.split(".")- if len(domain_parts) >= 3: # Has subdomain- # Check if first part is a 2-letter country code- subdomain = domain_parts[0].lower()- # Common country codes used as subdomains- if len(subdomain) == 2 and subdomain.isalpha():- # Replace country subdomain with placeholder- domain_parts[0] = "{country}"- domain = ".".join(domain_parts)-- # Split path into segments- segments = path.split("/")- normalized_segments: list[str] = []-- for segment in segments:- if not segment: # Empty segment (leading/trailing slash)- normalized_segments.append(segment)- # Check if segment looks like a UUID (standard format)- elif re.match(r"^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$", segment, re.I):- normalized_segments.append("{uuid}")- # Check if segment is purely numeric (likely an ID)- elif re.match(r"^\d+$", segment):- normalized_segments.append("{id}")- # Check if segment is a long alphanumeric string (likely hash/encoded ID)- # Must be at least 16 chars to avoid false positives with normal words- elif re.match(r"^[a-z0-9_-]{16,}$", segment, re.I):- normalized_segments.append("{hash}")- else:- # Keep segment as-is- normalized_segments.append(segment)-- normalized_path = "/".join(normalized_segments)- normalized = f"{parsed.scheme}://{domain}{normalized_path}"-- # Remove trailing slash for consistency (except for root path)- if normalized.endswith("/") and len(normalized_path) > 1:- normalized = normalized.rstrip("/")-- return normalized- except Exception:- # If URL parsing fails, return original URL- return url-- @staticmethod- def _get_new_urls_with_sessions(team: Team) -> tuple[dict[str, int], dict[str, list[str]]]:- """- Query ClickHouse to find URL patterns that first appeared in the last 14 days.- Pre-computes BOTH session counts AND session IDs for each pattern in a SINGLE query.-- Returns: tuple of (pattern -> count dict, pattern -> session_ids list dict)- """- cache_key = f"{NewUrlsSyntheticPlaylistSource.CACHE_KEY_PREFIX}_with_sessions_{team.pk}"- cached_data = cache.get(cache_key)- if cached_data is not None:- return cached_data-- now = datetime.now(UTC)- lookback_start = now - timedelta(days=NewUrlsSyntheticPlaylistSource.LOOKBACK_DAYS)- history_window_start = now - timedelta(days=90)-- # Fetch URLs from last 90 days for pattern detection- # AND from last 14 days for counting (we'll do both in one pass)- query = """- SELECT- session_id,- arrayJoin(all_urls) as url,- min(min_first_timestamp) as first_seen- FROM session_replay_events- WHERE team_id = %(team_id)s- AND min_first_timestamp >= %(history_start)s- AND url != ''- GROUP BY session_id, url- ORDER BY first_seen DESC- LIMIT 50000- """-- tag_queries(product=Product.REPLAY, feature=Feature.QUERY, team_id=team.pk)- result = sync_execute(- query,- {- "team_id": team.pk,- "history_start": history_window_start,- },- )-- # Build pattern tracking data structures- pattern_first_seen: dict[str, datetime] = {}- pattern_sessions: dict[str, set[str]] = {} # pattern -> set of session_ids-- for session_id, raw_url, first_seen_ts in result:- normalized = NewUrlsSyntheticPlaylistSource._normalize_url(raw_url)-- # Track earliest appearance of this pattern- if normalized not in pattern_first_seen or first_seen_ts < pattern_first_seen[normalized]:- pattern_first_seen[normalized] = first_seen_ts-- # Track sessions for patterns in the lookback window (for counting)- if lookback_start <= first_seen_ts <= now:- if normalized not in pattern_sessions:- pattern_sessions[normalized] = set()- pattern_sessions[normalized].add(session_id)-- # Filter to patterns that FIRST appeared within the lookback window- new_patterns_with_counts = {- pattern: len(pattern_sessions.get(pattern, set()))- for pattern, first_seen in pattern_first_seen.items()- if lookback_start <= first_seen <= now- }-- # Sort by count (descending) then by pattern name, take top 20- sorted_patterns = sorted(- new_patterns_with_counts.items(),- key=lambda x: (-x[1], x[0]), # Sort by count desc, then pattern asc- )[:20]-- counts_dict = dict(sorted_patterns)-- # Also prepare session IDs for the top patterns (convert sets to sorted lists)- sessions_dict = {pattern: sorted(pattern_sessions.get(pattern, set())) for pattern in counts_dict.keys()}-- result_tuple = (counts_dict, sessions_dict)- cache.set(cache_key, result_tuple, NewUrlsSyntheticPlaylistSource.CACHE_TTL)- return result_tuple-- @staticmethod- def _get_new_urls_with_counts(team: Team) -> dict[str, int]:- """- Query ClickHouse to find URL patterns that first appeared in the last 14 days.- Also pre-computes session counts for each pattern in a SINGLE query for performance.-- Returns: dict mapping pattern -> session count- """- counts_dict, _ = NewUrlsSyntheticPlaylistSource._get_new_urls_with_sessions(team)- return counts_dict-- @staticmethod- def _get_new_urls(team: Team) -> list[str]:- """- Get just the list of new URL patterns (for backwards compatibility).- """- return list(NewUrlsSyntheticPlaylistSource._get_new_urls_with_counts(team).keys())-- def get_session_ids(self, team: Team, user: User, limit: int | None = None, offset: int | None = None) -> list[str]:- """- Get session IDs for sessions that visited URLs matching this pattern.- Uses pre-computed session IDs from _get_new_urls_with_sessions for performance.- """- if not self.url:- return []-- # Get pre-computed session IDs (cached for 1 hour)- _, sessions_dict = self._get_new_urls_with_sessions(team)-- # Look up session IDs for this pattern- session_ids = sessions_dict.get(self.url, [])-- return self._paginate_list(session_ids, limit, offset)-- def count_session_ids(self, team: Team, user: User) -> int:- """- Count sessions that visited URLs matching this pattern.- Uses pre-computed counts from _get_new_urls_with_counts for performance.- """- if not self.url:- return 0-- # Try to get the pre-computed count first (fast path)- counts_dict = self._get_new_urls_with_counts(team)- if self.url in counts_dict:- return counts_dict[self.url]-- # Fallback: if not in pre-computed cache, use the expensive query- # (This shouldn't happen in normal operation)- all_session_ids = self.get_session_ids(team, user, limit=None, offset=None)- return len(all_session_ids)-- def generate_dynamic_playlists(self, team: Team) -> list["SyntheticPlaylistDefinition"]:- """Generate a playlist for each new URL"""- new_urls = self._get_new_urls(team)- playlists = []-- for idx, url in enumerate(new_urls):- # Create a source instance for this specific URL- url_source = NewUrlsSyntheticPlaylistSource(url=url)- url_hash = self._url_to_hash(url)- short_id = f"synthetic-new-url-{url_hash}"-- # Truncate URL for display if too long- display_url = url if len(url) <= 60 else url[:57] + "..."-- playlists.append(- SyntheticPlaylistDefinition(- id=self.MIN_ID - idx, # Negative IDs to avoid conflicts- short_id=short_id,- name=f"New URL: {display_url}",- description=f"Recordings from the last {self.LOOKBACK_DAYS} days on a page not previously seen within the last 90 days",- type="collection",- get_session_ids=url_source.get_session_ids,- count_session_ids=url_source.count_session_ids,- metadata={"icon": "IconSparkles", "is_user_specific": False, "url": url},- )- )-- return playlists-- def get_dynamic_playlist_by_id(self, short_id: str, team: Team) -> "SyntheticPlaylistDefinition | None":- """Retrieve a specific new URL playlist by its short_id"""- if not short_id.startswith("synthetic-new-url-"):- return None-- # Extract hash from short_id- url_hash = short_id.replace("synthetic-new-url-", "")-- # Get all new URLs and find the one matching this hash- new_urls = self._get_new_urls(team)- for url in new_urls:- if self._url_to_hash(url) == url_hash:- # Create a source instance for this specific URL- url_source = NewUrlsSyntheticPlaylistSource(url=url)- display_url = url if len(url) <= 60 else url[:57] + "..."-- return SyntheticPlaylistDefinition(- id=self.MIN_ID, # Use a consistent ID for individual lookups- short_id=short_id,- name=f"New URL: {display_url}",- description=f"Recordings from the last {self.LOOKBACK_DAYS} days on a page not previously seen within the last 90 days",- type="collection",- get_session_ids=url_source.get_session_ids,- count_session_ids=url_source.count_session_ids,- metadata={"icon": "IconSparkles", "is_user_specific": False, "url": url},- )-- return None--@dataclassclass SyntheticPlaylistDefinition:"""Definition of a synthetic playlist that will be computed on-demand"""@@ -694,79 +382,33 @@ def _get_static_synthetic_playlists() -> list[SyntheticPlaylistDefinition]:if HAS_EE:playlists.append(SummarisedPlaylistSource().to_synthetic_playlist())- # Filter out None values (sources that only generate dynamic playlists)+ # Filter out None values (sources that conditionally return a playlist)return [p for p in playlists if p is not None]-# Registry of dynamic synthetic playlist sources-def _get_dynamic_synthetic_playlist_sources() -> list[SyntheticPlaylistSource]:- return [- NewUrlsSyntheticPlaylistSource(),- ]--# fixed list of synthetic playlists, including Watch History, Expiring Soon, etcSYNTHETIC_PLAYLISTS: list[SyntheticPlaylistDefinition] = _get_static_synthetic_playlists()-# dynamic synthetic playlists, detecting newly seen URLs-DYNAMIC_SYNTHETIC_PLAYLIST_SOURCES: list[SyntheticPlaylistSource] = _get_dynamic_synthetic_playlist_sources()-def get_synthetic_playlist(short_id: str, team: Team | None = None) -> SyntheticPlaylistDefinition | None:+def get_synthetic_playlist(short_id: str) -> SyntheticPlaylistDefinition | None:"""Get a synthetic playlist by short_id.- Checks both static playlists and dynamic playlists (if team is provided).++ Returns the static playlist definition only; tenant scoping happens at the+ data layer (get_session_ids / count_session_ids), which still receives team."""- # Check static playlists firstfor playlist in SYNTHETIC_PLAYLISTS:if playlist.short_id == short_id:return playlist- # Check dynamic playlists if team is provided- if team:- for source in DYNAMIC_SYNTHETIC_PLAYLIST_SOURCES:- # Gate new URL collections behind feature flag- if isinstance(source, NewUrlsSyntheticPlaylistSource):- try:- flag_result = posthoganalytics.get_feature_flag(- "replay-new-detected-url-collections",- str(team.uuid),- groups={"organization": str(team.organization_id)},- )- # Skip if flag is not set to "test" variant- if flag_result is None or flag_result != "test": # type: ignore[comparison-overlap]- continue- except Exception:- # If feature flag check fails, skip this source- continue-- dynamic_playlist = source.get_dynamic_playlist_by_id(short_id, team)- if dynamic_playlist:- return dynamic_playlist-return None-def get_all_synthetic_playlists(team: Team) -> list[SyntheticPlaylistDefinition]:+def get_all_synthetic_playlists() -> list[SyntheticPlaylistDefinition]:"""- Get all synthetic playlists for a team, including both static and dynamic ones.+ Get all synthetic playlist definitions.++ Returns static playlist definitions only; tenant scoping happens at the data+ layer (get_session_ids / count_session_ids), which still receives team."""- all_playlists = list(SYNTHETIC_PLAYLISTS)- # Add dynamic playlists from each source- for source in DYNAMIC_SYNTHETIC_PLAYLIST_SOURCES:- # Gate new URL collections behind feature flag- if isinstance(source, NewUrlsSyntheticPlaylistSource):- try:- flag_result = posthoganalytics.get_feature_flag(- "replay-new-detected-url-collections",- str(team.uuid),- groups={"organization": str(team.organization_id)},- )- if flag_result is None or flag_result != "test": # type: ignore[comparison-overlap]- continue- except Exception:- # If feature flag check fails, skip this source- continue-- all_playlists.extend(source.generate_dynamic_playlists(team))-- return all_playlists+ return list(SYNTHETIC_PLAYLISTS)diff --git a/posthog/session_recordings/test/test_synthetic_playlists.py b/posthog/session_recordings/test/test_synthetic_playlists.pyindex 4b211582d664..f43c7ee3b53a 100644--- a/posthog/session_recordings/test/test_synthetic_playlists.py+++ b/posthog/session_recordings/test/test_synthetic_playlists.py@@ -1,7 +1,6 @@from datetime import datetime, timedelta-from posthog.test.base import APIBaseTest, BaseTest, _create_event, flush_persons_and_events-from unittest.mock import patch+from posthog.test.base import APIBaseTest, _create_event, flush_persons_and_eventsfrom django.core.cache import cachefrom django.utils.timezone import now@@ -13,10 +12,7 @@ from posthog.models import Comment, SessionRecordingPlaylistfrom posthog.models.sharing_configuration import SharingConfigurationfrom posthog.models.utils import uuid7from posthog.session_recordings.models.session_recording_event import SessionRecordingViewed-from posthog.session_recordings.synthetic_playlists import (- FrustrationSignalsPlaylistSource,- NewUrlsSyntheticPlaylistSource,-)+from posthog.session_recordings.synthetic_playlists import FrustrationSignalsPlaylistSourcefrom products.exports.backend.models.exported_asset import ExportedAsset@@ -300,572 +296,6 @@ class TestSyntheticPlaylists(APIBaseTest):assert results[i]["short_id"].startswith("synthetic-")-class TestNewUrlsSyntheticPlaylists(APIBaseTest):- """Tests for the dynamic new URLs synthetic playlists"""-- def setUp(self):- super().setUp()- from posthog.clickhouse.client import sync_execute-- # Clear replay events table before each test- sync_execute("TRUNCATE TABLE sharded_session_replay_events")-- # Mock the feature flag to return "test" string directly- self.feature_flag_patcher = patch("posthoganalytics.get_feature_flag")- mock_get_feature_flag = self.feature_flag_patcher.start()- mock_get_feature_flag.return_value = "test"-- def tearDown(self):- self.feature_flag_patcher.stop()- super().tearDown()-- def _produce_replay_with_urls(- self, session_id: str, urls: list[str], timestamp: str | datetime | None = None- ) -> None:- """Helper to create a replay event with specific URLs"""- from posthog.session_recordings.queries.test.session_replay_sql import produce_replay_summary-- # Use the standard helper function which has proper type handling- produce_replay_summary(- team_id=self.team.pk,- session_id=session_id,- distinct_id="user",- first_timestamp=timestamp,- last_timestamp=timestamp,- first_url=urls[0] if urls else None,- all_urls=urls,- ensure_analytics_event_in_session=False, # Don't create analytics events for these tests- )-- def _get_playlists_response(self, query_params: str = "") -> dict:- url = f"/api/projects/{self.team.id}/session_recording_playlists{query_params}"- response = self.client.get(url)- assert response.status_code == status.HTTP_200_OK- return response.json()-- def _get_new_url_playlists(self) -> list[dict]:- """Get all new-url synthetic playlists from the list endpoint"""- response_data = self._get_playlists_response()- return [p for p in response_data["results"] if p["short_id"].startswith("synthetic-new-url-")]-- def _get_synthetic_playlist(self, short_id: str) -> dict:- response = self.client.get(f"/api/projects/{self.team.id}/session_recording_playlists/{short_id}")- assert response.status_code == status.HTTP_200_OK- return response.json()-- def test_new_urls_creates_dynamic_playlists(self) -> None:- """Test that new URLs detected in last 14 days create dynamic synthetic playlists"""- # Clear cache to ensure fresh detection- from django.core.cache import cache-- cache.clear()-- # Create recordings with new URLs (within last 14 days)- now_time = datetime.now()- self._produce_replay_with_urls("session-1", ["https://new-page.com/checkout"], now_time - timedelta(days=1))- self._produce_replay_with_urls("session-2", ["https://new-page.com/pricing"], now_time - timedelta(days=2))-- # Get playlists- new_url_playlists = self._get_new_url_playlists()-- # Should have 2 dynamic playlists, one for each unique URL- assert len(new_url_playlists) == 2-- # Check that playlist names include the URLs- playlist_names = {p["name"] for p in new_url_playlists}- assert "New URL: https://new-page.com/checkout" in playlist_names- assert "New URL: https://new-page.com/pricing" in playlist_names-- def test_new_urls_ignores_historical_urls(self) -> None:- """Test that URLs that appeared before the 14-day window are not considered new"""- from django.core.cache import cache-- cache.clear()-- now_time = datetime.now()-- # Create old recording (> 14 days ago) with a URL- self._produce_replay_with_urls("old-session", ["https://old-page.com"], now_time - timedelta(days=20))-- # Create recent recording with the same URL- self._produce_replay_with_urls("recent-session", ["https://old-page.com"], now_time - timedelta(days=1))-- # Get playlists- new_url_playlists = self._get_new_url_playlists()-- # Should have NO dynamic playlists since the URL existed before- assert len(new_url_playlists) == 0-- def test_new_urls_only_truly_new(self) -> None:- """Test that only truly new URLs (first seen in last 14 days) are included"""- from django.core.cache import cache-- cache.clear()-- now_time = datetime.now()-- # Old URL (>14 days)- self._produce_replay_with_urls("old-1", ["https://old.com"], now_time - timedelta(days=20))-- # Mix of old and new URLs in recent session- self._produce_replay_with_urls("recent-1", ["https://old.com", "https://new.com"], now_time - timedelta(days=1))-- # Get playlists- new_url_playlists = self._get_new_url_playlists()-- # Should have 1 playlist only for the truly new URL- assert len(new_url_playlists) == 1- assert new_url_playlists[0]["name"] == "New URL: https://new.com"-- def test_retrieve_new_url_playlist(self) -> None:- """Test retrieving a specific new URL playlist by its short_id"""- from django.core.cache import cache-- cache.clear()-- now_time = datetime.now()- self._produce_replay_with_urls("session-1", ["https://test.com/page"], now_time - timedelta(days=1))- self._produce_replay_with_urls("session-2", ["https://test.com/page"], now_time - timedelta(days=2))-- # Get the playlist list to find the short_id- new_url_playlists = self._get_new_url_playlists()- assert len(new_url_playlists) == 1-- short_id = new_url_playlists[0]["short_id"]- assert short_id.startswith("synthetic-new-url-")-- # Retrieve the specific playlist- playlist = self._get_synthetic_playlist(short_id)-- assert playlist["short_id"] == short_id- assert playlist["name"] == "New URL: https://test.com/page"- assert playlist["type"] == "collection"- assert playlist["is_synthetic"] is True- assert playlist["recordings_counts"]["collection"]["count"] == 2-- def test_new_url_playlist_count(self) -> None:- """Test that new URL playlists correctly count recordings"""- from django.core.cache import cache-- cache.clear()-- now_time = datetime.now()-- # Create 3 sessions visiting the same new URL- self._produce_replay_with_urls("session-1", ["https://new-url.com"], now_time - timedelta(days=1))- self._produce_replay_with_urls("session-2", ["https://new-url.com"], now_time - timedelta(days=2))- self._produce_replay_with_urls("session-3", ["https://new-url.com"], now_time - timedelta(days=3))-- new_url_playlists = self._get_new_url_playlists()- assert len(new_url_playlists) == 1-- # Check the count- assert new_url_playlists[0]["recordings_counts"]["collection"]["count"] == 3-- def test_new_url_caching(self) -> None:- """Test that new URL detection results are cached"""- from django.core.cache import cache-- cache.clear()-- now_time = datetime.now()- self._produce_replay_with_urls("session-1", ["https://cached-url.com"], now_time - timedelta(days=1))-- # First call should hit the database - cache should be empty- cache_key = f"new_urls_synthetic_playlist_with_sessions_{self.team.pk}"- assert cache.get(cache_key) is None-- # Get playlists (should populate cache)- new_url_playlists = self._get_new_url_playlists()- assert len(new_url_playlists) == 1-- # Cache should now be populated with (counts_dict, sessions_dict) tuple- cached_data = cache.get(cache_key)- assert cached_data is not None- counts_dict, sessions_dict = cached_data- assert "https://cached-url.com" in counts_dict- assert "https://cached-url.com" in sessions_dict-- # Second call should use cache (even if we add more data)- self._produce_replay_with_urls("session-2", ["https://another-url.com"], now_time - timedelta(days=1))-- # Should still show only 1 playlist (from cache)- new_url_playlists = self._get_new_url_playlists()- assert len(new_url_playlists) == 1-- def test_long_url_truncation(self) -> None:- """Test that very long URLs are truncated in playlist names"""- from django.core.cache import cache-- cache.clear()-- now_time = datetime.now()- # Very long URL with multiple path segments (won't get normalized to placeholders)- long_url = "https://example.com/very/long/path/with/many/segments/that/should/be/truncated/in/the/display"-- self._produce_replay_with_urls("session-1", [long_url], now_time - timedelta(days=1))-- new_url_playlists = self._get_new_url_playlists()- assert len(new_url_playlists) == 1-- # Name should be truncated with ellipsis- assert new_url_playlists[0]["name"].startswith("New URL: ")- assert len(new_url_playlists[0]["name"]) <= 73 # "New URL: " (9) + 60 chars + "..." (3) = 72- assert new_url_playlists[0]["name"].endswith("...")-- def test_url_grouping_with_numeric_ids(self) -> None:- """Test that URLs with different numeric IDs are grouped into one playlist"""- from django.core.cache import cache-- cache.clear()-- now_time = datetime.now()-- # Create recordings with URLs containing different numeric IDs- self._produce_replay_with_urls(- "session-1", ["https://app.posthog.com/project/1/settings"], now_time - timedelta(days=1)- )- self._produce_replay_with_urls(- "session-2", ["https://app.posthog.com/project/2/settings"], now_time - timedelta(days=2)- )- self._produce_replay_with_urls(- "session-3", ["https://app.posthog.com/project/999/settings"], now_time - timedelta(days=3)- )-- new_url_playlists = self._get_new_url_playlists()-- # Should have only 1 playlist since all URLs normalize to the same pattern- assert len(new_url_playlists) == 1- assert "project/{id}/settings" in new_url_playlists[0]["name"]-- # The playlist should contain all 3 sessions- assert new_url_playlists[0]["recordings_counts"]["collection"]["count"] == 3-- def test_url_grouping_with_uuids(self) -> None:- """Test that URLs with different UUIDs are grouped into one playlist"""- from django.core.cache import cache-- cache.clear()-- now_time = datetime.now()-- # Create recordings with URLs containing different UUIDs- self._produce_replay_with_urls(- "session-1",- ["https://app.posthog.com/order/550e8400-e29b-41d4-a716-446655440000/details"],- now_time - timedelta(days=1),- )- self._produce_replay_with_urls(- "session-2",- ["https://app.posthog.com/order/123e4567-e89b-12d3-a456-426614174000/details"],- now_time - timedelta(days=2),- )-- new_url_playlists = self._get_new_url_playlists()-- # Should have only 1 playlist- assert len(new_url_playlists) == 1- assert "order/{uuid}/details" in new_url_playlists[0]["name"]-- # Should contain both sessions- assert new_url_playlists[0]["recordings_counts"]["collection"]["count"] == 2-- def test_url_grouping_with_query_params(self) -> None:- """Test that URLs with different query parameters are grouped together"""- from django.core.cache import cache-- cache.clear()-- now_time = datetime.now()-- # Create recordings with same path but different query params- self._produce_replay_with_urls(- "session-1", ["https://app.posthog.com/billing?id=1"], now_time - timedelta(days=1)- )- self._produce_replay_with_urls(- "session-2", ["https://app.posthog.com/billing?id=2&foo=bar"], now_time - timedelta(days=2)- )- self._produce_replay_with_urls("session-3", ["https://app.posthog.com/billing"], now_time - timedelta(days=3))-- new_url_playlists = self._get_new_url_playlists()-- # Should have only 1 playlist (query params are stripped)- assert len(new_url_playlists) == 1- assert new_url_playlists[0]["name"] == "New URL: https://app.posthog.com/billing"-- # Should contain all 3 sessions- assert new_url_playlists[0]["recordings_counts"]["collection"]["count"] == 3-- def test_url_grouping_preserves_different_paths(self) -> None:- """Test that genuinely different URLs create separate playlists"""- from django.core.cache import cache-- cache.clear()-- now_time = datetime.now()-- # Create recordings with different paths (even though they have similar IDs)- self._produce_replay_with_urls(- "session-1", ["https://app.posthog.com/project/1/settings"], now_time - timedelta(days=1)- )- self._produce_replay_with_urls(- "session-2", ["https://app.posthog.com/project/1/billing"], now_time - timedelta(days=2)- )- self._produce_replay_with_urls(- "session-3", ["https://app.posthog.com/user/1/settings"], now_time - timedelta(days=3)- )-- new_url_playlists = self._get_new_url_playlists()-- # Should have 3 different playlists- assert len(new_url_playlists) == 3-- playlist_names = {p["name"] for p in new_url_playlists}- assert "New URL: https://app.posthog.com/project/{id}/settings" in playlist_names- assert "New URL: https://app.posthog.com/project/{id}/billing" in playlist_names- assert "New URL: https://app.posthog.com/user/{id}/settings" in playlist_names-- # Each should have 1 session- for playlist in new_url_playlists:- assert playlist["recordings_counts"]["collection"]["count"] == 1-- def test_url_grouping_mixed_patterns(self) -> None:- """Test URL grouping with a realistic mix of patterns"""- from django.core.cache import cache-- cache.clear()-- now_time = datetime.now()-- # Simulate a realistic scenario with various URL patterns- urls_and_sessions = [- # Project settings with different IDs (should group)- ("session-1", ["https://app.posthog.com/project/123/settings"]),- ("session-2", ["https://app.posthog.com/project/456/settings"]),- # Same project, different tab (should be separate)- ("session-3", ["https://app.posthog.com/project/789/insights"]),- # Recording with hash ID (should group with session-5)- ("session-4", ["https://app.posthog.com/recording/abc123def456ghi789jkl"]),- ("session-5", ["https://app.posthog.com/recording/xyz999uuu888vvv777www"]),- # Static pages (should remain separate)- ("session-6", ["https://app.posthog.com/dashboard"]),- ]-- for session_id, urls in urls_and_sessions:- self._produce_replay_with_urls(session_id, urls, now_time - timedelta(days=1))-- new_url_playlists = self._get_new_url_playlists()-- # Should have 4 playlists:- # 1. project/{id}/settings (sessions 1-2)- # 2. project/{id}/insights (session 3)- # 3. recording/{hash} (sessions 4-5)- # 4. dashboard (session 6)- assert len(new_url_playlists) == 4-- # Verify counts- playlist_by_name = {p["name"]: p for p in new_url_playlists}-- settings_playlist = playlist_by_name.get("New URL: https://app.posthog.com/project/{id}/settings")- assert settings_playlist is not None- assert settings_playlist["recordings_counts"]["collection"]["count"] == 2-- insights_playlist = playlist_by_name.get("New URL: https://app.posthog.com/project/{id}/insights")- assert insights_playlist is not None- assert insights_playlist["recordings_counts"]["collection"]["count"] == 1-- recording_playlist = playlist_by_name.get("New URL: https://app.posthog.com/recording/{hash}")- assert recording_playlist is not None- assert recording_playlist["recordings_counts"]["collection"]["count"] == 2-- dashboard_playlist = playlist_by_name.get("New URL: https://app.posthog.com/dashboard")- assert dashboard_playlist is not None- assert dashboard_playlist["recordings_counts"]["collection"]["count"] == 1---class TestUrlNormalization(BaseTest):- """Unit tests for URL normalization logic"""-- @parameterized.expand(- [- # Query parameter removal- ("https://example.com/billing?id=1", "https://example.com/billing"),- ("https://example.com/billing?id=1&foo=bar", "https://example.com/billing"),- # Fragment removal- ("https://example.com/page#section", "https://example.com/page"),- ("https://example.com/page?q=1#section", "https://example.com/page"),- # Numeric ID normalization- ("https://example.com/project/123/settings", "https://example.com/project/{id}/settings"),- ("https://example.com/project/1/settings", "https://example.com/project/{id}/settings"),- ("https://example.com/user/456/profile/789/edit", "https://example.com/user/{id}/profile/{id}/edit"),- # UUID normalization- ("https://example.com/item/550e8400-e29b-41d4-a716-446655440000", "https://example.com/item/{uuid}"),- (- "https://example.com/order/123e4567-e89b-12d3-a456-426614174000/details",- "https://example.com/order/{uuid}/details",- ),- # Hash/encoded ID normalization (16+ chars)- ("https://example.com/session/xYz123AbC456DeF789", "https://example.com/session/{hash}"),- ("https://example.com/recording/aBcDeFgHiJkLmNoPqRsTuVwXyZ", "https://example.com/recording/{hash}"),- ("https://example.com/token/abc_def_ghi_jkl_mno", "https://example.com/token/{hash}"),- # Short strings preserved (not hashes)- ("https://example.com/api/v1/users", "https://example.com/api/v1/users"),- ("https://example.com/admin/dashboard", "https://example.com/admin/dashboard"),- ("https://example.com/en-US/about", "https://example.com/en-US/about"),- # Trailing slash removal- ("https://example.com/billing/", "https://example.com/billing"),- ("https://example.com/", "https://example.com/"),- # Combined cases- (- "https://example.com/project/123/settings?tab=general#section",- "https://example.com/project/{id}/settings",- ),- (- "https://example.com/user/550e8400-e29b-41d4-a716-446655440000/edit?foo=bar",- "https://example.com/user/{uuid}/edit",- ),- (- "https://example.com/api/v1/recording/xYz123AbC456DeF789?format=json",- "https://example.com/api/v1/recording/{hash}",- ),- # Edge cases: don't normalize version numbers or language codes- ("https://example.com/api/v2/endpoint", "https://example.com/api/v2/endpoint"),- ("https://example.com/en/about", "https://example.com/en/about"),- ("https://example.com/fr/contact", "https://example.com/fr/contact"),- ]- )- def test_normalize_url_patterns(self, input_url: str, expected_output: str) -> None:- """Test various URL normalization patterns"""- result = NewUrlsSyntheticPlaylistSource._normalize_url(input_url)- assert result == expected_output, f"Expected {expected_output}, got {result}"-- def test_normalize_url_groups_similar_urls(self) -> None:- """Test that URLs with different IDs are normalized to the same value"""- urls = [- "https://example.com/project/1/settings",- "https://example.com/project/2/settings",- "https://example.com/project/999/settings",- ]-- normalized = [NewUrlsSyntheticPlaylistSource._normalize_url(url) for url in urls]-- # All should normalize to the same value- assert len(set(normalized)) == 1- assert normalized[0] == "https://example.com/project/{id}/settings"-- def test_normalize_url_preserves_different_paths(self) -> None:- """Test that genuinely different URLs remain different after normalization"""- urls = [- "https://example.com/project/123/settings",- "https://example.com/project/123/billing",- "https://example.com/user/123/settings",- ]-- normalized = [NewUrlsSyntheticPlaylistSource._normalize_url(url) for url in urls]-- # Should have 3 different normalized values- assert len(set(normalized)) == 3- assert set(normalized) == {- "https://example.com/project/{id}/settings",- "https://example.com/project/{id}/billing",- "https://example.com/user/{id}/settings",- }-- def test_normalize_url_handles_malformed_urls(self) -> None:- """Test that malformed URLs are returned as-is"""- malformed_urls = [- "",- "not-a-url",- "://missing-scheme",- ]-- for url in malformed_urls:- result = NewUrlsSyntheticPlaylistSource._normalize_url(url)- # Should return original URL if parsing fails- assert result == url or result != "" # Either returns as-is or handles gracefully-- def test_normalize_url_groups_country_subdomains(self) -> None:- """Test that URLs with different country-code subdomains are grouped together"""- urls = [- "https://us.example.com/pricing",- "https://uk.example.com/pricing",- "https://fr.example.com/pricing",- "https://de.example.com/pricing",- ]-- normalized = [NewUrlsSyntheticPlaylistSource._normalize_url(url) for url in urls]-- # All should normalize to the same value- assert len(set(normalized)) == 1- assert normalized[0] == "https://{country}.example.com/pricing"-- def test_normalize_url_preserves_non_country_subdomains(self) -> None:- """Test that non-country-code subdomains are preserved"""- urls = [- "https://app.example.com/dashboard",- "https://api.example.com/v1/users",- "https://www.example.com/home",- ]-- normalized = [NewUrlsSyntheticPlaylistSource._normalize_url(url) for url in urls]-- # All should remain different (not treated as country codes)- assert len(set(normalized)) == 3- assert "https://app.example.com/dashboard" in normalized- assert "https://api.example.com/v1/users" in normalized- assert "https://www.example.com/home" in normalized-- def test_pattern_newness_not_url_newness(self) -> None:- """- Test that we detect NEW PATTERNS, not just new URLs.- If we saw /billing/1/summary months ago, then /billing/2/summary today- should NOT be considered a new pattern.- """- from datetime import datetime, timedelta-- now = datetime.now()- six_months_ago = now - timedelta(days=180)- today = now - timedelta(days=1)-- # Mock ClickHouse query results- mock_results = [- # Old URL that normalizes to /billing/{id}/summary- ("https://example.com/billing/1/summary", six_months_ago),- # New URL but same pattern- ("https://example.com/billing/2/summary", today),- # Truly new pattern- ("https://example.com/admin/dashboard", today),- ]-- # Build pattern_first_seen the same way _get_new_urls does- pattern_first_seen: dict[str, datetime] = {}- for raw_url, first_seen_ts in mock_results:- normalized = NewUrlsSyntheticPlaylistSource._normalize_url(raw_url)- if normalized not in pattern_first_seen or first_seen_ts < pattern_first_seen[normalized]:- pattern_first_seen[normalized] = first_seen_ts-- # Check that /billing/{id}/summary has the OLD timestamp (6 months ago)- billing_pattern = "https://example.com/billing/{id}/summary"- assert billing_pattern in pattern_first_seen- assert pattern_first_seen[billing_pattern] == six_months_ago-- # Check that /admin/dashboard has the NEW timestamp (today)- admin_pattern = "https://example.com/admin/dashboard"- assert admin_pattern in pattern_first_seen- assert pattern_first_seen[admin_pattern] == today-- # Filter to patterns that appeared in last 14 days- lookback_start = now - timedelta(days=14)- new_patterns = [- pattern for pattern, first_seen in pattern_first_seen.items() if lookback_start <= first_seen <= now- ]-- # Only /admin/dashboard should be considered "new"- assert admin_pattern in new_patterns- assert billing_pattern not in new_patterns- assert len(new_patterns) == 1--class TestFrustrationSignalsSyntheticPlaylist(APIBaseTest):"""Tests for the frustration signals synthetic playlist"""