: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
feat(marketing-analytics): open exact conversion recordings (#110907)
Javier Bahamondes3734db30ceba
diff --git a/.github/new-events-schema-targets.txt b/.github/new-events-schema-targets.txtindex 375fb3437e04..267875b43662 100644--- a/.github/new-events-schema-targets.txt+++ b/.github/new-events-schema-targets.txt@@ -30,6 +30,7 @@ products/error_tracking/backend/hogql_queriesproducts/experimentsproducts/marketing_analytics/backend/hogql_queriesproducts/marketing_analytics/backend/services/test_attribution_health.py+products/marketing_analytics/backend/services/test_conversion_recordings.pyproducts/mcp_analytics/backend/tests/test_dashboard_series.pyproducts/mcp_analytics/backend/tests/test_harness_breakdown.pyproducts/mcp_analytics/backend/tests/test_missing_capabilities.pydiff --git a/docs/internal/web-analytics-query-serving.md b/docs/internal/web-analytics-query-serving.mdindex 29dfee42bdbf..800e64e2a5cf 100644--- a/docs/internal/web-analytics-query-serving.md+++ b/docs/internal/web-analytics-query-serving.md@@ -200,6 +200,10 @@ Explicit column options in a shared URL take precedence over saved preferences,Changing tabs or dashboard filters preserves those column options in the URL.Reset to defaults clears the custom selection, sorting, and pins for later visits.+### Conversion recordings++See [Marketing analytics conversion recordings](../../products/marketing_analytics/conversion-recordings.md) for row selection, session attribution, and replay behavior.+## Marketing metric chartThe standalone metric chart receives prepared series, ISO date labels, a selected breakdown key, and callbacks.diff --git a/frontend/snapshots.yml b/frontend/snapshots.ymlindex 453f87bb4453..37fe1d556c55 100644--- a/frontend/snapshots.yml+++ b/frontend/snapshots.yml@@ -5828,6 +5828,26 @@ snapshots:hash: v1.k794b7964.6ab679994aa458fc15fd650db178bf805d878d726265ad51e3502d9029e63903.z12MB5eLM0VM1Bs8-v2_5d5HH5VaDT25r8GuqvBC4dsmarketing-analytics-add-source--sources-disabled--light:hash: v1.k794b7964.a40f8610ed453a1401dbbc1fb3bb921eeb3f55656138dc3e26b4751f6e38b7e8.0Ura8ZyXPrrQdqAbS1DDqkmoEZMPWEe4Y5EcDqQ39Xk+ marketing-analytics-conversion-recordings--empty--dark:+ hash: v1.k794b7964.8982a2852c9527ff952b660792885e04c2fd81a3302a2c5c820c30e040182a06.h2Rie6hdM7FmCIHijYzFOkelhYaqzQboMKzRrwcxu8w+ marketing-analytics-conversion-recordings--empty--light:+ hash: v1.k794b7964.64f4ef4d7a1dcf0c943fcb6692a27c73b581294925dd35816fbd51dbfc0f3474.ZRuR0TXVftKY3k_mTN6FywmW3wNyQngclUN6rT6Cygk+ marketing-analytics-conversion-recordings--no-recordings--dark:+ hash: v1.k794b7964.8caf34a05a4fe8c6f0b83ff011ffbf9ddc0cb2173d353ae9ec7300bd6138a298.7sNqFbinsbbvypgAPtWWR-ZF_bytKXDS-9VI6O1U2gc+ marketing-analytics-conversion-recordings--no-recordings--light:+ hash: v1.k794b7964.83f0638cb4988ba700c184c187e01758ded2fa4e4fed099a62b969b8fe5d83bf.j_QuZ_XjgANGfN2e3uqfgUMNKr-gihEBONil6UeWtA8+ marketing-analytics-conversion-recordings--preparing--dark:+ hash: v1.k794b7964.75f45c89b93ba70ec05d87508bb716a5b13dd64fe20313dbf99984af4c6a7bfc.06oSU1nmIYrT9ON6r3eYHFe7iSmlV3iZFddd5s2oEuc+ marketing-analytics-conversion-recordings--preparing--light:+ hash: v1.k794b7964.e51fa7fc11d8226715adfe65796f990cab83cb2965878f4a85373c2c416f3d0a.xmDxVzr_cfY3DCueVm06pVF-XkmpjrKm4b9_7Kv4kRY+ marketing-analytics-conversion-recordings--query-error--dark:+ hash: v1.k794b7964.fa62136c8ebb16410d7586b10c352e8ddfc31aa6f806a2e410f7c3cdc7a99de0.4dpr5YaWuJkW-swBHtbaeWiFHG7CAKtXGyIRv7HjHhQ+ marketing-analytics-conversion-recordings--query-error--light:+ hash: v1.k794b7964.c32a81254ecf704df432890875e747e34a0265cdd9aae7bd4a0b932d56f1026a.P5ahAUoGy5S_M5myQ_gs2VeSCa3KUAKm0HDUW7Nfd0g+ marketing-analytics-conversion-recordings--with-recordings--dark:+ hash: v1.k794b7964.84d264975d666896a8dc20d4d6ee73c1ffbcfd4a9b644505f2fccc1a1b1ebf6f.8iBnwapA5-_NJJK0vx51st375zOTNzUAgSjefe0JYzw+ marketing-analytics-conversion-recordings--with-recordings--light:+ hash: v1.k794b7964.0156e1ff6ad567d07c997e131d28d4ebafe77c7e3c611a236a3fa9d93b9ea373.61r_omMvYqAZ4kZdVH7IOfg1WxVlTd02n1YB-_kPy5kmarketing-analytics-customer-acquisition-cards--configuration-loading--dark:hash: v1.k794b7964.4e3295796230b8ccc9ce5cb239d9ffe000af9d00324d31584d3fa6fde8550fe9.04jR2iHz7Mn5n3Z6KmK4yt-R520UGYL9im_4Icykhxkmarketing-analytics-customer-acquisition-cards--configuration-loading--light:diff --git a/frontend/src/lib/constants.tsx b/frontend/src/lib/constants.tsxindex 09a57fc8944e..7b054733dc03 100644--- a/frontend/src/lib/constants.tsx+++ b/frontend/src/lib/constants.tsx@@ -405,6 +405,7 @@ export const FEATURE_FLAGS = {MARKETING_ANALYTICS_AMAZON_ADS: 'marketing-analytics-amazon-ads', // owner: @jabahamondes #team-web-analyticsMARKETING_ANALYTICS_APPLE_ADS: 'marketing-analytics-apple-ads', // owner: @jabahamondes #team-web-analyticsMARKETING_ANALYTICS_ATTRIBUTION: 'marketing-analytics-attribution', // owner: @jabahamondes #team-web-analytics — gates the legacy Attribution explorer tab; the new dashboard ignores it+ MARKETING_ANALYTICS_CONVERSION_RECORDINGS: 'marketing-analytics-conversion-recordings', // owner: @jabahamondes #team-web-analyticsMARKETING_ANALYTICS_COSTS_PRECOMPUTATION: 'marketing-analytics-costs-precomputation', // owner: @jabahamondes #team-web-analytics — gates reading the native cost precompute tableMARKETING_ANALYTICS_EXTENDED_DRILL_DOWN: 'marketing-analytics-extended-drill-down', // owner: @jabahamondes #team-web-analyticsMARKETING_ANALYTICS_MCP: 'marketing-analytics-mcp', // owner: @jabahamondes #team-web-analytics — gates MCP tool exposure (read-only marketing-analytics tools)diff --git a/frontend/src/scenes/web-analytics/tabs/marketing-analytics/frontend/components/MarketingAnalyticsTable/MarketingAnalyticsTable.tsx b/frontend/src/scenes/web-analytics/tabs/marketing-analytics/frontend/components/MarketingAnalyticsTable/MarketingAnalyticsTable.tsxindex c8a13619ec9a..1a239a96097e 100644--- a/frontend/src/scenes/web-analytics/tabs/marketing-analytics/frontend/components/MarketingAnalyticsTable/MarketingAnalyticsTable.tsx+++ b/frontend/src/scenes/web-analytics/tabs/marketing-analytics/frontend/components/MarketingAnalyticsTable/MarketingAnalyticsTable.tsx@@ -1,13 +1,15 @@import './MarketingAnalyticsTableStyleOverride.scss'import { BuiltLogic, LogicWrapper, useActions, useValues } from 'kea'-import { useMemo, useState } from 'react'+import { useId, useMemo, useState } from 'react'import { IconGear, IconInfo } from '@posthog/icons'import { LemonButton, LemonInput, LemonSelect, Tooltip } from '@posthog/lemon-ui'import { useFeatureFlag } from 'lib/hooks/useFeatureFlag'+import { teamLogic } from 'scenes/teamLogic'+import { isSharedView } from '~/exporter/exporterViewLogic'import { ColumnFeature } from '~/queries/nodes/DataTable/DataTable'import { Query } from '~/queries/Query/Query'import {@@ -16,6 +18,7 @@ import {MarketingAnalyticsBaseColumns,MarketingAnalyticsConstants,MarketingAnalyticsDrillDownLevel,+ MarketingAnalyticsItem,MarketingAnalyticsTableQuery,} from '~/queries/schema/schema-general'import { QueryContext, QueryContextColumn } from '~/queries/types'@@ -25,6 +28,13 @@ import { useMarketingAnalyticsPrecompute } from '~/scenes/marketing-analytics/usimport { webAnalyticsDataTableQueryContext } from '~/scenes/web-analytics/tiles/WebAnalyticsTile'import { InsightLogicProps } from '~/types'+import { ConversionRecordingsModal } from 'products/marketing_analytics/frontend/ConversionRecordingsModal'+import {+ conversionRecordingsRequest,+ conversionRecordingsTableQuery,+ restoreConversionRecordingsColumns,+} from 'products/marketing_analytics/frontend/conversionRecordingsRequest'+import { marketingAnalyticsLogic } from '../../logic/marketingAnalyticsLogic'import { marketingAnalyticsSettingsLogic } from '../../logic/marketingAnalyticsSettingsLogic'import { marketingAnalyticsTableLogic } from '../../logic/marketingAnalyticsTableLogic'@@ -48,14 +58,27 @@ export const MarketingAnalyticsTable = ({insightProps,attachTo,}: MarketingAnalyticsTableProps): JSX.Element => {- const { setQuery } = useActions(marketingAnalyticsTableLogic)+ const { setQuery, setConversionRecordings } = useActions(marketingAnalyticsTableLogic)+ const { conversionRecordings } = useValues(marketingAnalyticsTableLogic)+ const { currentTeamId } = useValues(teamLogic)+ const tableId = useId()+ const tableKey = `${currentTeamId}:${tableId}`const { showColumnConfigModal, setDrillDownLevel } = useActions(marketingAnalyticsLogic)const { drillDownLevel, nativeSourcesHierarchyStatus } = useValues(marketingAnalyticsLogic)const hasExtendedDrillDown = useFeatureFlag('MARKETING_ANALYTICS_EXTENDED_DRILL_DOWN')+ const hasConversionRecordings = useFeatureFlag('MARKETING_ANALYTICS_CONVERSION_RECORDINGS')const { conversion_goals } = useValues(marketingAnalyticsSettingsLogic)- const { notReady: precomputeNotReady, computedAt } = useMarketingAnalyticsPrecompute(query.source, insightProps)const [searchTerm, setSearchTerm] = useState('')+ const recordings = conversionRecordings?.tableKey === tableKey ? conversionRecordings : null+ const tableQuery = useMemo(+ () => conversionRecordingsTableQuery(query, !!hasConversionRecordings && !isSharedView()),+ [query, hasConversionRecordings]+ )+ const { notReady: precomputeNotReady, computedAt } = useMarketingAnalyticsPrecompute(+ tableQuery.source,+ insightProps+ )const validationWarnings = useMemo(() => validateConversionGoals(conversion_goals), [conversion_goals])@@ -94,18 +117,59 @@ export const MarketingAnalyticsTable = ({...conversionGoalColumns,...((query.source as MarketingAnalyticsTableQuery).select ?? []),])+ const draftConversionGoal = (query.source as MarketingAnalyticsTableQuery).draftConversionGoal+ const drillDownGoals = draftConversionGoal+ ? [draftConversionGoal, ...conversion_goals]+ : conversion_goalsreturn Array.from(allKnownColumns).reduce((acc, column) => {const isGroupingColumn = allGroupingAliases.includes(column)+ const goal = drillDownGoals.find((goal) => goal.conversion_goal_name === column)acc[column] = {- render: (props) => (- <MarketingAnalyticsCell- {...props}- style={{- maxWidth: isGroupingColumn ? '200px' : undefined,- }}- />- ),+ render: (props) => {+ const cell = (+ <MarketingAnalyticsCell+ {...props}+ style={{+ maxWidth: isGroupingColumn ? '200px' : undefined,+ }}+ />+ )+ const value = (props.value as MarketingAnalyticsItem | null)?.value+ const request =+ hasConversionRecordings &&+ !isSharedView() &&+ goal &&+ goal.kind !== 'DataWarehouseNode' &&+ typeof value === 'number' &&+ value > 0+ ? conversionRecordingsRequest(+ (props.query as DataTableNode).source as MarketingAnalyticsTableQuery,+ props.record,+ goal.conversion_goal_id+ )+ : null+ return request && goal ? (+ <LemonButton+ type="tertiary"+ fullWidth+ className="[&_.cursor-default]:cursor-pointer"+ data-attr="marketing-analytics-conversion-recordings"+ tooltip="View recordings of these conversion sessions"+ onClick={() =>+ setConversionRecordings({+ tableKey,+ request,+ goalName: goal.conversion_goal_name,+ })+ }+ >+ {cell}+ </LemonButton>+ ) : (+ cell+ )+ },}return acc},@@ -113,11 +177,20 @@ export const MarketingAnalyticsTable = ({)})(),}),- [insightProps, query.source, searchTerm, conversion_goals]+ [+ insightProps,+ query.source,+ searchTerm,+ conversion_goals,+ hasConversionRecordings,+ tableKey,+ setConversionRecordings,+ ])return (<div className="bg-surface-primary">+ {recordings && <ConversionRecordingsModal {...recordings} onClose={() => setConversionRecordings(null)} />}<div className="p-4 border-b border-border bg-bg-light"><div className="flex flex-wrap gap-4 justify-between items-center"><div className="flex items-center gap-2">@@ -225,10 +298,14 @@ export const MarketingAnalyticsTable = ({<div className="relative marketing-analytics-table-container"><QueryattachTo={attachTo}- query={query}+ query={tableQuery}readOnly={false}context={marketingAnalyticsContext}- setQuery={setQuery}+ setQuery={(updated) =>+ setQuery(+ tableQuery === query ? updated : restoreConversionRecordingsColumns(updated, query)+ )+ }/></div>)}diff --git a/frontend/src/scenes/web-analytics/tabs/marketing-analytics/frontend/logic/marketingAnalyticsTableLogic.ts b/frontend/src/scenes/web-analytics/tabs/marketing-analytics/frontend/logic/marketingAnalyticsTableLogic.tsindex 457ff87d9954..2eea6a20eec9 100644--- a/frontend/src/scenes/web-analytics/tabs/marketing-analytics/frontend/logic/marketingAnalyticsTableLogic.ts+++ b/frontend/src/scenes/web-analytics/tabs/marketing-analytics/frontend/logic/marketingAnalyticsTableLogic.ts@@ -22,6 +22,8 @@ import {} from '~/queries/schema/schema-general'import { DataWarehouseSettingsTab, ExternalDataSource } from '~/types'+import { ConversionRecordingsSelection } from 'products/marketing_analytics/frontend/conversionRecordingsRequest'+import { marketingAnalyticsLogic } from './marketingAnalyticsLogic'import { createMarketingAnalyticsOrderBy, goalSumsAProperty, isDraftConversionGoalColumn } from './utils'@@ -85,6 +87,7 @@ export interface marketingAnalyticsTableLogicValues {drillDownLevel: MarketingAnalyticsDrillDownLevel // marketingAnalyticsLogic_query: DataTableNode | nullcolumnConfiguration: ColumnConfiguration | null+ conversionRecordings: ConversionRecordingsSelection | nulldefaultColumns: string[]query: DataTableNode | nullsortedColumns: string[]@@ -98,6 +101,9 @@ export interface marketingAnalyticsTableLogicActions {setColumnConfiguration: (columnConfiguration: ColumnConfiguration) => {columnConfiguration: ColumnConfiguration}+ setConversionRecordings: (selection: ConversionRecordingsSelection | null) => {+ selection: ConversionRecordingsSelection | null+ }setQuery: (query: DataTableNode) => {query: DataTableNode}@@ -135,10 +141,15 @@ export const marketingAnalyticsTableLogic = kea<marketingAnalyticsTableLogicTypeactions: [marketingAnalyticsLogic, ['setDraftConversionGoal']],})),actions({+ setConversionRecordings: (selection: ConversionRecordingsSelection | null) => ({ selection }),setQuery: (query: DataTableNode) => ({ query }),setColumnConfiguration: (columnConfiguration: ColumnConfiguration) => ({ columnConfiguration }),}),reducers(() => ({+ conversionRecordings: [+ null as ConversionRecordingsSelection | null,+ { setConversionRecordings: (_, { selection }) => selection, setQuery: () => null },+ ],columnConfiguration: [null as ColumnConfiguration | null,buildTeamScopedPersistenceConfig(),diff --git a/pnpm-lock.yaml b/pnpm-lock.yamlindex d0790248d75a..e4d7a064c037 100644--- a/pnpm-lock.yaml+++ b/pnpm-lock.yaml@@ -3980,12 +3980,19 @@ importers:kea:specifier: 'catalog:'version: 4.0.0-pre.6(patch_hash=139b8d1f1304f9d9da452a9a1244c94ea679dbcb85687d8999563146879fb6f5)([email protected])+ kea-loaders:+ specifier: 'catalog:'+ version: 3.1.1([email protected](patch_hash=139b8d1f1304f9d9da452a9a1244c94ea679dbcb85687d8999563146879fb6f5)([email protected]))kea-subscriptions:specifier: 'catalog:'version: 3.0.1([email protected](patch_hash=139b8d1f1304f9d9da452a9a1244c94ea679dbcb85687d8999563146879fb6f5)([email protected]))react:specifier: 18.3.1version: 18.3.1+ devDependencies:+ kea-test-utils:+ specifier: 'catalog:'+ version: 0.2.4([email protected](patch_hash=139b8d1f1304f9d9da452a9a1244c94ea679dbcb85687d8999563146879fb6f5)([email protected]))products/mcp_analytics:dependencies:diff --git a/products/marketing_analytics/backend/api.py b/products/marketing_analytics/backend/api.pyindex 74bb0dd0c65d..90f3667d01ec 100644--- a/products/marketing_analytics/backend/api.py+++ b/products/marketing_analytics/backend/api.py@@ -20,13 +20,20 @@ from pydantic import ()from rest_framework import serializers, statusfrom rest_framework.decorators import action-from rest_framework.exceptions import NotFound, PermissionDenied+from rest_framework.exceptions import NotFound, PermissionDenied, Throttledfrom rest_framework.permissions import IsAuthenticatedfrom rest_framework.request import Requestfrom rest_framework.response import Responsefrom rest_framework.viewsets import GenericViewSet-from posthog.schema import ConversionGoalFilter1, ConversionGoalFilter2, ConversionGoalFilter3, DateRange, SourceMap+from posthog.schema import (+ ConversionGoalFilter1,+ ConversionGoalFilter2,+ ConversionGoalFilter3,+ DateRange,+ MarketingAnalyticsTableQuery,+ SourceMap,+)from posthog.hogql import astfrom posthog.hogql.database.database import Database@@ -36,11 +43,25 @@ from posthog.api.documentation import _FallbackSerializerfrom posthog.api.mixins import validated_requestfrom posthog.api.project import capture_team_config_difffrom posthog.api.routing import TeamAndOrgViewSetMixin+from posthog.clickhouse.client.limit import (+ ConcurrencyLimitExceeded,+ get_api_team_rate_limiter,+ get_app_org_rate_limiter,+ get_org_app_concurrency_limit,+)+from posthog.clickhouse.query_tagging import (+ Feature,+ Product,+ get_query_tag_value,+ is_api_key_access_method,+ tag_queries,+)from posthog.models.organization import OrganizationMembershipfrom posthog.models.team.team import DEFAULT_CURRENCY, Teamfrom posthog.models.team.team_marketing_analytics_config import TeamMarketingAnalyticsConfigfrom posthog.models.user import Userfrom posthog.ph_client import feature_enabled_or_false+from posthog.rate_limit import ClickHouseBurstRateThrottle, ClickHouseSustainedRateThrottlefrom products.marketing_analytics.backend.hogql_queries.adapters.base import ExternalConfig, QueryContextfrom products.marketing_analytics.backend.hogql_queries.adapters.factory import MarketingSourceFactory@@ -51,6 +72,7 @@ from products.marketing_analytics.backend.services.conversion_goals_inspector imexplain_conversion_goal,list_conversion_goals,)+from products.marketing_analytics.backend.services.conversion_recordings import ConversionRecordingsQueryfrom products.marketing_analytics.backend.services.data_source_health import get_data_source_healthfrom products.marketing_analytics.backend.services.event_suggestions import suggest_conversion_goalsfrom products.marketing_analytics.backend.services.mapping_suggester import suggest_utm_mappings@@ -1094,6 +1116,57 @@ class ApplySetupOpsResponseSerializer(serializers.Serializer):marketing_analytics_config = serializers.JSONField(help_text="The config as it now stands")+@extend_schema_field(MarketingAnalyticsTableQuery) # type: ignore[arg-type] # Supported by the Pydantic schema extension.+class ConversionRecordingsSourceField(serializers.JSONField):+ def to_internal_value(self, data: object) -> dict[str, Any]:+ try:+ return MarketingAnalyticsTableQuery.model_validate(data).model_dump(mode="json")+ except PydanticValidationError:+ raise serializers.ValidationError("Provide a valid Marketing analytics table query.")+++class ConversionRecordingsRequestSerializer(serializers.Serializer):+ client_query_id = serializers.UUIDField(+ default=uuid.uuid4, help_text="A unique query ID for tracing this request in query logs."+ )+ source = ConversionRecordingsSourceField( # type: ignore[assignment]+ help_text="The table query whose conversion cell was selected."+ )+ goal_id = serializers.CharField(help_text="The selected conversion goal ID.")+ # The recordings query compares these row keys to table values exactly, and campaign names and UTM values+ # can keep surrounding spaces. A trimmed key selects another row or no row.+ group = serializers.CharField(+ allow_blank=True, trim_whitespace=False, help_text="The displayed row grouping value."+ )+ source_name = serializers.CharField(+ default="", allow_blank=True, trim_whitespace=False, help_text="The displayed row source."+ )+ campaign_id = serializers.CharField(+ required=False,+ allow_null=True,+ allow_blank=True,+ trim_whitespace=False,+ help_text="The displayed campaign ID, omitted for comparison rows.",+ )+ after = serializers.CharField(+ required=False,+ max_length=200,+ help_text="The last session ID returned by the previous page. Omit for the first page.",+ )+ limit = serializers.IntegerField(+ default=100, min_value=1, max_value=100, help_text="The maximum number of conversion session IDs to return."+ )+++class ConversionRecordingsResponseSerializer(serializers.Serializer):+ session_ids = serializers.ListField(+ child=serializers.CharField(),+ help_text="Sessions in which the attributed conversions occurred. A session might not have a recording.",+ )+ has_more = serializers.BooleanField(help_text="Whether another page of conversion sessions is available.")+ preparing = serializers.BooleanField(help_text="Whether the conversion data is still being prepared.")++class MarketingAnalyticsViewSet(TeamAndOrgViewSetMixin, GenericViewSet):# `marketing_analytics` is gated by the API scope of the same name and inherits# RBAC from `web_analytics` (see RESOURCE_INHERITANCE_MAP). Custom @action methods@@ -1103,6 +1176,55 @@ class MarketingAnalyticsViewSet(TeamAndOrgViewSetMixin, GenericViewSet):serializer_class = _FallbackSerializerpermission_classes = [IsAuthenticated]+ @validated_request(+ operation_id="marketing_analytics_conversion_recordings_list",+ request_serializer=ConversionRecordingsRequestSerializer,+ responses={200: ConversionRecordingsResponseSerializer},+ )+ @action(+ methods=["POST"],+ detail=False,+ required_scopes=["marketing_analytics:read", "session_recording:read"],+ throttle_classes=[ClickHouseBurstRateThrottle, ClickHouseSustainedRateThrottle],+ )+ def conversion_recordings(self, request: Request, *args: object, **kwargs: object) -> Response:+ data = request.validated_data+ tag_queries(+ team_id=self.team_id,+ product=Product.MARKETING_ANALYTICS,+ feature=Feature.QUERY,+ client_query_id=str(data["client_query_id"]),+ )+ runner = ConversionRecordingsQuery(+ query=MarketingAnalyticsTableQuery.model_validate(data["source"]),+ team=self.team,+ user=cast(User, request.user),+ )+ is_api = is_api_key_access_method(get_query_tag_value("access_method"))+ try:+ with (+ get_api_team_rate_limiter().run(+ team_id=self.team_id, is_api=is_api, limit=runner.get_api_queries_concurrency_limit()+ ),+ get_app_org_rate_limiter().run(+ org_id=self.team.organization_id,+ team_id=self.team_id,+ is_api=is_api,+ limit=get_org_app_concurrency_limit(self.team.organization_id),+ ),+ ):+ result = runner.sessions(+ goal_id=data["goal_id"],+ group=data["group"],+ source=data["source_name"],+ campaign_id=data.get("campaign_id"),+ after=str(data["after"]) if data.get("after") else None,+ limit=data["limit"],+ )+ except ConcurrencyLimitExceeded as error:+ raise Throttled(detail="Too many queries are running. Try again in a moment.") from error+ return Response(ConversionRecordingsResponseSerializer(result).data)+@validated_request(query_serializer=UtmAuditQuerySerializer,responses={diff --git a/products/marketing_analytics/backend/hogql_queries/conversion_goal_processor.py b/products/marketing_analytics/backend/hogql_queries/conversion_goal_processor.pyindex 5d31b17c1b67..490133a63208 100644--- a/products/marketing_analytics/backend/hogql_queries/conversion_goal_processor.py+++ b/products/marketing_analytics/backend/hogql_queries/conversion_goal_processor.py@@ -25,6 +25,7 @@ from posthog.hogql.database.schema.channel_type import ChannelTypeExprs, create_from posthog.hogql.database.schema.exchange_rate import convert_currency_callfrom posthog.hogql.database.schema.persons import REVENUE_ANALYTICS_VIRTUAL_PROPERTIESfrom posthog.hogql.modifiers import create_default_modifiers_for_team+from posthog.hogql.parser import parse_exprfrom posthog.hogql.timings import HogQLTimingsfrom posthog.dataclasses import frozen@@ -307,6 +308,7 @@ class ConversionGoalProcessor:# Oldest `computed_at` across this goal's served precomputes (touchpoints + conversions) — how old the# goal's data can be. The runner takes the oldest across all goals for the response's "data as of X".precompute_computed_at: datetime | None = None+ include_session_ids: bool = False_UTM_LEVEL_FIELD_MAP: ClassVar[dict[MarketingAnalyticsDrillDownLevel, str]] = {MarketingAnalyticsDrillDownLevel.MEDIUM: "medium",@@ -700,7 +702,6 @@ class ConversionGoalProcessor:ast.Alias(alias="person_id", expr=ast.Field(chain=["events", "person_id"])),ast.Alias(alias="conversion_timestamp", expr=ast.Field(chain=["events", "timestamp"])),ast.Alias(alias="conversion_math_value", expr=self._get_conversion_value_expr()),- # Stored for a future "show conversion session recordings" feature; the attribution read ignores it.ast.Alias(alias="session_id", expr=_prop_to_string("$session_id")),]# Conversion-side UTM value per tracked field, aliased to the {field}_name table columns.@@ -814,6 +815,8 @@ class ConversionGoalProcessor:select_columns: list[ast.Expr] = []for col in ("person_id", "conversion_timestamps", "conversion_math_values"):select_columns.append(ast.Alias(alias=col, expr=ast.Field(chain=["c", col])))+ if self.include_session_ids:+ select_columns.append(ast.Field(chain=["c", "conversion_session_ids"]))for field in TRACKED_FIELDS:select_columns.append(ast.Alias(alias=field.conversion_array, expr=ast.Field(chain=["c", field.conversion_array]))@@ -955,6 +958,13 @@ class ConversionGoalProcessor:))+ if self.include_session_ids:+ select_columns.append(+ ast.Alias(+ alias="conversion_session_ids",+ expr=parse_expr("groupArrayIf(session_id, toUnixTimestamp(conversion_timestamp) > 0)"),+ )+ )deduped_rows = self._build_distinct_preagg_rows(table="marketing_conversions_preaggregated",job_ids=job_ids,@@ -968,6 +978,12 @@ class ConversionGoalProcessor:date_to=date_to,timestamp_column="conversion_timestamp",)+ if self.include_session_ids:+ deduped_rows.distinct = False+ deduped_rows.group_by = list(deduped_rows.select)+ deduped_rows.select.append(+ ast.Alias(alias="session_id", expr=parse_expr("argMax(session_id, (computed_at, session_id))"))+ )return ast.SelectQuery(select=select_columns,@@ -1100,6 +1116,8 @@ class ConversionGoalProcessor:]# Add conversion arrays for each tracked field+ if self.include_session_ids:+ select_columns.append(self._build_conversion_session_ids_array(conversion_event))for field in TRACKED_FIELDS:select_columns.append(self._build_conversion_utm_array(field.conversion_array, conversion_event, resolved[field.name])@@ -1281,6 +1299,17 @@ class ConversionGoalProcessor:return ast.And(exprs=conditions) if conditions else ast.Constant(value=True)+ def _build_conversion_session_ids_array(self, conversion_event: Optional[str]) -> ast.Alias:+ # Keep empty IDs so session IDs stay aligned with the conversion timestamps.+ return ast.Alias(+ alias="conversion_session_ids",+ expr=parse_expr(+ "groupArrayIf(toString(ifNull(events.properties.$session_id, '')), "+ "{conversion} AND toUnixTimestamp(events.timestamp) > 0)",+ {"conversion": self._build_conversion_event_condition(conversion_event)},+ ),+ )+def _build_conversion_timestamps_array(self, conversion_event: Optional[str]) -> ast.Alias:"""Build conversion timestamps array.@@ -1548,6 +1577,13 @@ class ConversionGoalProcessor:]# Add conversion value and fallback for each tracked field+ if self.include_session_ids:+ select_columns.append(+ ast.Alias(+ alias="session_id",+ expr=parse_expr("conversion_session_ids[i]"),+ )+ )for field in TRACKED_FIELDS:select_columns.append(ast.Alias(@@ -1726,6 +1762,13 @@ class ConversionGoalProcessor:]# Add conversion value for each tracked field+ if self.include_session_ids:+ select_columns.append(+ ast.Alias(+ alias="session_id",+ expr=parse_expr("conversion_session_ids[i]"),+ )+ )for field in TRACKED_FIELDS:select_columns.append(ast.Alias(@@ -1841,6 +1884,8 @@ class ConversionGoalProcessor:ast.Field(chain=["person_id"]),ast.Field(chain=["conversion_math_value"]),]+ if self.include_session_ids:+ touchpoint_select.append(ast.Field(chain=["session_id"]))for field in TRACKED_FIELDS:touchpoint_select.append(ast.Field(chain=[field.conversion_value]))@@ -1885,6 +1930,8 @@ class ConversionGoalProcessor:outer_select: list[ast.Expr] = [person_id_field,]+ if self.include_session_ids:+ outer_select.append(ast.Field(chain=["session_id"]))for field in TRACKED_FIELDS:outer_select.append(@@ -1925,6 +1972,8 @@ class ConversionGoalProcessor:select_columns: list[ast.Expr] = [person_id_field,]+ if self.include_session_ids:+ select_columns.append(ast.Field(chain=["session_id"]))for field in TRACKED_FIELDS:select_columns.append(diff --git a/products/marketing_analytics/backend/hogql_queries/test_query_settings.py b/products/marketing_analytics/backend/hogql_queries/test_query_settings.pyindex 08acbcdf6267..440611e42fc9 100644--- a/products/marketing_analytics/backend/hogql_queries/test_query_settings.py+++ b/products/marketing_analytics/backend/hogql_queries/test_query_settings.py@@ -17,6 +17,8 @@ from posthog.schema import (from posthog.hogql.constants import MAX_BYTES_BEFORE_EXTERNAL_GROUP_BY+from posthog.hogql_queries import paginators+from products.marketing_analytics.backend.hogql_queries.attribution_paths_query_runner import (MarketingAnalyticsAttributionPathsQueryRunner,)@@ -27,6 +29,7 @@ from products.marketing_analytics.backend.hogql_queries.constants import MARKETIfrom products.marketing_analytics.backend.hogql_queries.marketing_analytics_table_query_runner import (MarketingAnalyticsTableQueryRunner,)+from products.marketing_analytics.backend.services.conversion_recordings import ConversionRecordingsQueryGOAL_ID = "goal-1"@@ -104,3 +107,26 @@ class TestMarketingQuerySettings(BaseTest):settings = captured.get("settings")assert settings is not None, f"{name} passed no settings to ClickHouse"self.assertEqual(settings.max_bytes_before_external_group_by, MARKETING_SPILL_AFTER_BYTES)++ def test_conversion_recordings_passes_the_spill_threshold(self):+ query = MarketingAnalyticsTableQuery(+ dateRange=DateRange(date_from="2023-01-01", date_to="2023-01-31"),+ properties=[],+ select=["Campaign", "Source", "Purchases"],+ )+ captured = {}++ def _capture(**kwargs):+ captured.update(kwargs)+ raise _Stop++ runner = ConversionRecordingsQuery(query=query, team=self.team)+ with patch.object(paginators, "execute_hogql_query", _capture):+ with self.assertRaises(_Stop):+ runner.sessions(+ goal_id=GOAL_ID, group="spring", source="google", campaign_id=None, after=None, limit=10+ )++ settings = captured.get("settings")+ assert settings is not None, "conversion recordings passed no settings to ClickHouse"+ self.assertEqual(settings.max_bytes_before_external_group_by, MARKETING_SPILL_AFTER_BYTES)diff --git a/products/marketing_analytics/backend/services/conversion_recordings.py b/products/marketing_analytics/backend/services/conversion_recordings.pynew file mode 100644index 000000000000..8e67e2ec6dff--- /dev/null+++ b/products/marketing_analytics/backend/services/conversion_recordings.py@@ -0,0 +1,152 @@+from typing import TypedDict++from rest_framework.exceptions import ValidationError++from posthog.schema import ConversionGoalFilter3, MarketingAnalyticsDrillDownLevel++from posthog.hogql import ast+from posthog.hogql.constants import HogQLGlobalSettings+from posthog.hogql.parser import parse_expr, parse_select++from posthog.hogql_queries.paginators import HogQLHasMorePaginator++from products.marketing_analytics.backend.hogql_queries.constants import MARKETING_SPILL_AFTER_BYTES+from products.marketing_analytics.backend.hogql_queries.conversion_goals_aggregator import ConversionGoalsAggregator+from products.marketing_analytics.backend.hogql_queries.errors import MarketingPrecomputeNotReady+from products.marketing_analytics.backend.hogql_queries.marketing_analytics_table_query_runner import (+ MarketingAnalyticsTableQueryRunner,+)+from products.marketing_analytics.backend.hogql_queries.marketing_lazy_precompute import handle_not_ready+++class ConversionRecordingsResponse(TypedDict):+ session_ids: list[str]+ has_more: bool+ preparing: bool+++class ConversionRecordingsQuery(MarketingAnalyticsTableQueryRunner):+ def sessions_query(self, goal_id: str, group: str, source: str, campaign_id: str | None) -> ast.SelectQuery:+ self.validate()+ self._apply_drill_down_level()+ level = self.config.drill_down_level+ if level in (MarketingAnalyticsDrillDownLevel.AD, MarketingAnalyticsDrillDownLevel.AD_GROUP):+ raise ValidationError("Conversion recordings are not available at ad or ad group level.")++ goals, _ = self._filter_invalid_conversion_goals(self._get_team_conversion_goals())+ processors = self._create_conversion_goal_processors(goals)+ processor = next((p for p in processors if p.goal.conversion_goal_id == goal_id), None)+ if processor is None:+ raise ValidationError("This conversion goal is no longer available. Refresh the table and try again.")+ if isinstance(processor.goal, ConversionGoalFilter3):+ raise ValidationError("Conversion recordings are only available for event and action goals.")+ processor.include_session_ids = True++ # Resolve through the table's own joins: the displayed campaign can come from costs, not its UTM.+ table = self.to_query()+ key_fields = [self.config.campaign_field]+ if level in (MarketingAnalyticsDrillDownLevel.CAMPAIGN, MarketingAnalyticsDrillDownLevel.CHANNEL_SOURCE):+ key_fields.append(self.config.source_field)+ if level == MarketingAnalyticsDrillDownLevel.CAMPAIGN:+ key_fields.append(self.config.id_field)+ table.select.extend(+ ast.Alias(+ alias=f"_conversion_{field}",+ expr=ast.Field(chain=self.config.get_unified_conversion_field_chain(field)),+ )+ for field in key_fields+ )+ row_conditions = [+ parse_expr(+ "{field} = {value}",+ {+ "field": ast.Field(chain=[self.config.get_campaign_column_alias()]),+ "value": ast.Constant(value=group),+ },+ )+ ]+ if level in (MarketingAnalyticsDrillDownLevel.CAMPAIGN, MarketingAnalyticsDrillDownLevel.CHANNEL_SOURCE):+ row_conditions.append(parse_expr("Source = {source}", {"source": ast.Constant(value=source)}))+ if level == MarketingAnalyticsDrillDownLevel.CAMPAIGN and not (+ self.query.compareFilter and self.query.compareFilter.compare+ ):+ row_conditions.append(parse_expr("ID = {id}", {"id": ast.Constant(value=campaign_id or "-")}))+ selected_keys = ast.SelectQuery(+ select=[ast.Tuple(exprs=[ast.Field(chain=[f"_conversion_{field}"]) for field in key_fields])],+ select_from=ast.JoinExpr(table=table, alias="table_rows"),+ where=ast.And(exprs=row_conditions),+ )++ conversions = processor.generate_cte_query(+ self._get_where_conditions(+ date_range=self.query_date_range,+ include_date_range=True,+ date_field=processor.get_date_field(),+ use_date_not_datetime=True,+ ),+ date_from=self.query_date_range.date_from(),+ date_to=self.query_date_range.date_to(),+ )+ grouping_fields = {self.config.campaign_field, self.config.id_field, self.config.source_field}+ conversions.select = [+ col for col in conversions.select if isinstance(col, ast.Alias) and col.alias in grouping_fields+ ]+ conversions.group_by = None+ session_id = (+ ast.Field(chain=["session_id"])+ if processor.uses_attribution_pipeline+ else parse_expr("toString(ifNull(events.properties.$session_id, ''))")+ )+ conversions.select.append(ast.Alias(alias="conversion_session_id", expr=session_id))++ mapped_fields: dict[str, ast.Expr] = {field: ast.Field(chain=[field]) for field in grouping_fields}+ if level == MarketingAnalyticsDrillDownLevel.CAMPAIGN:+ mapped_fields[self.config.campaign_field], mapped_fields[self.config.id_field] = ConversionGoalsAggregator(+ [processor], self.config+ )._apply_campaign_name_mappings(+ mapped_fields[self.config.campaign_field],+ mapped_fields[self.config.id_field],+ mapped_fields[self.config.source_field],+ )+ sessions = parse_select(+ "SELECT DISTINCT conversion_session_id FROM {conversions} WHERE {key} IN {keys}"+ " AND notEmpty(conversion_session_id) AND conversion_session_id != '00000000-0000-0000-0000-000000000000'",+ {+ "conversions": conversions,+ "key": ast.Tuple(exprs=[mapped_fields[field] for field in key_fields]),+ "keys": selected_keys,+ },+ )+ assert isinstance(sessions, ast.SelectQuery)+ return sessions++ def sessions(+ self, goal_id: str, group: str, source: str, campaign_id: str | None, after: str | None, limit: int+ ) -> ConversionRecordingsResponse:+ try:+ query = self.sessions_query(goal_id, group, source, campaign_id)+ except MarketingPrecomputeNotReady as not_ready:+ handle_not_ready(team=self.team, query=not_ready.query or self.query)+ return {"session_ids": [], "has_more": False, "preparing": True}++ paginator = HogQLHasMorePaginator(limit=limit)+ sessions = parse_select(+ "SELECT conversion_session_id FROM {conversions} WHERE conversion_session_id > {after} ORDER BY conversion_session_id",+ {"conversions": query, "after": ast.Constant(value=after or "")},+ )+ paginator.execute_hogql_query(+ query=sessions,+ query_type="marketing_analytics_conversion_recordings",+ team=self.team,+ user=self.user,+ modifiers=self.modifiers,+ context=self._shared_hogql_context,+ # The row selection embeds the full table query, which groups by high-cardinality campaign+ # dimensions. Let the GROUP BY spill to disk, as the table runner does, rather than hit the memory limit.+ settings=HogQLGlobalSettings(max_bytes_before_external_group_by=MARKETING_SPILL_AFTER_BYTES),+ )+ return {+ "session_ids": [str(row[0]) for row in paginator.results],+ "has_more": paginator.has_more(),+ "preparing": False,+ }diff --git a/products/marketing_analytics/backend/services/test_conversion_recordings.py b/products/marketing_analytics/backend/services/test_conversion_recordings.pynew file mode 100644index 000000000000..ce52d17d2780--- /dev/null+++ b/products/marketing_analytics/backend/services/test_conversion_recordings.py@@ -0,0 +1,417 @@+from datetime import UTC, datetime+from pathlib import Path+from uuid import uuid4++import time_machine+from posthog.test.base import APIBaseTest, ClickhouseTestMixin, _create_event, _create_person, flush_persons_and_events+from unittest.mock import patch++from parameterized import parameterized+from rest_framework.exceptions import ValidationError++from posthog.schema import (+ AttributionMode,+ CompareFilter,+ DateRange,+ MarketingAnalyticsDrillDownLevel,+ MarketingAnalyticsTableQuery,+)++from posthog.clickhouse.client.execute import sync_execute, validated_client_query_id+from posthog.clickhouse.client.limit import ConcurrencyLimitExceeded+from posthog.clickhouse.preaggregation.marketing_conversions_sql import TRUNCATE_MARKETING_CONVERSIONS_TABLE_SQL+from posthog.clickhouse.preaggregation.marketing_touchpoints_sql import TRUNCATE_MARKETING_TOUCHPOINTS_TABLE_SQL+from posthog.clickhouse.query_tagging import get_query_tag_value, tags_context++from products.actions.backend.models.action import Action+from products.analytics_platform.backend.lazy_computation.lazy_computation_executor import LazyComputationResult+from products.analytics_platform.backend.models.preaggregation_job import PreaggregationJob+from products.marketing_analytics.backend.hogql_queries.errors import MarketingPrecomputeNotReady+from products.marketing_analytics.backend.hogql_queries.marketing_analytics_table_query_runner import (+ MarketingAnalyticsTableQueryRunner,+)+from products.marketing_analytics.backend.services.conversion_recordings import ConversionRecordingsQuery+from products.warehouse_sources.backend.facade.testing import create_data_warehouse_table_from_csv+++@time_machine.travel("2026-09-20T12:00:00Z", tick=False)+class TestConversionRecordings(ClickhouseTestMixin, APIBaseTest):+ CLASS_DATA_LEVEL_SETUP = False++ def setUp(self) -> None:+ super().setUp()+ config = self.team.marketing_analytics_config+ config.conversion_goals = [+ {+ "kind": "EventsNode",+ "event": "purchase",+ "name": "purchase",+ "math": "total",+ "conversion_goal_id": "purchase",+ "conversion_goal_name": "Purchases",+ "schema_map": {"utm_campaign_name": "utm_campaign", "utm_source_name": "utm_source"},+ }+ ]+ config.attribution_window_days = 7+ config.save()+ self.source = MarketingAnalyticsTableQuery(+ properties=[],+ dateRange=DateRange(date_from="2026-09-15", date_to="2026-09-20"),+ select=["Campaign", "Source", "ID", "Purchases"],+ )+ self.flags = patch(+ "products.marketing_analytics.backend.hogql_queries.marketing_analytics_config.feature_enabled_or_false",+ return_value=False,+ )+ self.flags.start()+ self.addCleanup(self.flags.stop)+ for index, (person, campaign) in enumerate(+ [("alex", "winter-sale"), ("sam", "winter-sale"), ("other", "other-sale")], start=1+ ):+ _create_person(team=self.team, distinct_ids=[person], properties={"email": f"{person}@example.com"})+ _create_event(+ team=self.team,+ distinct_id=person,+ event="$pageview",+ timestamp="2026-09-16T10:00:00Z",+ properties={+ "utm_campaign": campaign,+ "utm_source": "google",+ "utm_medium": "cpc",+ "$session_id": f"01994530-9000-7000-8000-00000000001{index}",+ },+ )+ for hour in [11, 12]:+ _create_event(+ team=self.team,+ distinct_id=person,+ event="purchase",+ timestamp=f"2026-09-16T{hour}:00:00Z",+ properties={"$session_id": f"01994530-9000-7000-8000-00000000000{index}"},+ )+ flush_persons_and_events()++ @parameterized.expand(+ [+ (MarketingAnalyticsDrillDownLevel.CAMPAIGN, "winter-sale", "google", 2),+ (MarketingAnalyticsDrillDownLevel.SOURCE, "google", "", 3),+ (MarketingAnalyticsDrillDownLevel.MEDIUM, "cpc", "", 3),+ ]+ )+ def test_sessions_match_the_table_attribution(+ self, level: MarketingAnalyticsDrillDownLevel, group: str, source: str, count: int+ ) -> None:+ self.source.drillDownLevel = level+ self.source.select = None+ table = MarketingAnalyticsTableQueryRunner(query=self.source, team=self.team, user=self.user).calculate()+ self.assertTrue(table.results)+ result = ConversionRecordingsQuery(query=self.source, team=self.team, user=self.user).sessions(+ "purchase", group, source, None, None, 50+ )+ self.assertEqual(+ result["session_ids"], [f"01994530-9000-7000-8000-00000000000{i}" for i in range(1, count + 1)]+ )+ self.assertFalse(result["has_more"])+ self.assertFalse(result["preparing"])++ def test_endpoint_pagination_and_exact_row_keys(self) -> None:+ _create_person(team=self.team, distinct_ids=["pat"], properties={"email": "[email protected]"})+ _create_event(+ team=self.team,+ distinct_id="pat",+ event="$pageview",+ timestamp="2026-09-16T10:00:00Z",+ properties={"utm_campaign": "winter-sale ", "utm_source": "google", "utm_medium": "cpc"},+ )+ _create_event(+ team=self.team,+ distinct_id="pat",+ event="purchase",+ timestamp="2026-09-16T11:00:00Z",+ properties={"$session_id": "01994530-9000-7000-8000-000000000004"},+ )+ flush_persons_and_events()+ url = f"/api/projects/{self.team.pk}/marketing_analytics/conversion_recordings/"+ payload = {+ "client_query_id": "01994530-9000-7000-8000-000000000021",+ "source": self.source.model_dump(mode="json"),+ "goal_id": "purchase",+ "group": "winter-sale",+ "source_name": "google",+ "limit": 1,+ }+ query_ids: list[str | None] = []++ def capture_query_id() -> str | None:+ query_ids.append(get_query_tag_value("client_query_id"))+ return validated_client_query_id()++ with (+ tags_context(product=None, feature=None, client_query_id=None),+ patch("posthog.clickhouse.client.execute.DEBUG", True),+ patch("posthog.clickhouse.client.execute.TEST", False),+ patch("posthog.clickhouse.client.execute.validated_client_query_id", side_effect=capture_query_id),+ ):+ first = self.client.post(url, payload, format="json")+ self.assertEqual(first.status_code, 200, first.content)+ self.assertIn(payload["client_query_id"], query_ids)+ self.assertTrue(first.json()["has_more"])+ second = self.client.post(url, {**payload, "after": first.json()["session_ids"][-1]}, format="json")+ self.assertEqual(second.status_code, 200, second.content)+ self.assertFalse(second.json()["has_more"])+ self.assertNotEqual(first.json()["session_ids"][0], second.json()["session_ids"][0])+ exhausted = self.client.post(url, {**payload, "after": second.json()["session_ids"][-1]}, format="json")+ self.assertEqual(exhausted.json()["session_ids"], [])+ self.assertFalse(exhausted.json()["has_more"])+ padded = self.client.post(url, {**payload, "group": "winter-sale ", "limit": 50}, format="json")+ self.assertEqual(padded.json()["session_ids"], ["01994530-9000-7000-8000-000000000004"])+ invalid_requests: list[dict[str, object]] = [+ {"source": {"kind": "ActorsQuery"}},+ {"goal_id": "removed-goal"},+ {"source": {**self.source.model_dump(mode="json"), "drillDownLevel": "ad"}},+ ]+ for invalid_fields in invalid_requests:+ with self.subTest(invalid_fields=invalid_fields):+ invalid = self.client.post(url, {**payload, **invalid_fields}, format="json")+ self.assertEqual(invalid.status_code, 400)+ for limiter in ("get_app_org_rate_limiter", "get_api_team_rate_limiter"):+ with self.subTest(limiter=limiter), patch(f"products.marketing_analytics.backend.api.{limiter}") as mock:+ mock.return_value.run.side_effect = ConcurrencyLimitExceeded("internal limiter detail")+ throttled = self.client.post(url, payload, format="json")+ self.assertEqual(throttled.status_code, 429)+ self.assertNotIn("internal limiter detail", throttled.json()["detail"])++ def test_campaign_mapping_and_missing_row(self) -> None:+ config = self.team.marketing_analytics_config+ config.campaign_name_mappings = {"GoogleAds": {"Winter campaign": ["winter-sale"]}}+ config.save()+ for group, campaign_id, expected in [+ ("Winter campaign", None, 2),+ ("winter-sale", None, 0),+ ("Winter campaign", "another-campaign-id", 0),+ ]:+ result = ConversionRecordingsQuery(query=self.source, team=self.team, user=self.user).sessions(+ "purchase", group, "google", campaign_id, None, 50+ )+ self.assertEqual(len(result["session_ids"]), expected)++ config.campaign_field_preferences = {"GoogleAds": {"match_field": "campaign_id"}}+ config.campaign_name_mappings = {"GoogleAds": {"mapped-id": ["winter-sale"]}}+ config.save()+ for compare, campaign_id, expected in [+ (False, None, 0),+ (False, "", 0),+ (False, "-", 0),+ (False, "mapped-id", 2),+ (True, None, 2),+ (True, "mapped-id", 2),+ ]:+ with self.subTest(compare=compare, campaign_id=campaign_id):+ self.source.compareFilter = CompareFilter(compare=compare)+ result = ConversionRecordingsQuery(query=self.source, team=self.team, user=self.user).sessions(+ "purchase", "winter-sale", "google", campaign_id, None, 50+ )+ self.assertEqual(len(result["session_ids"]), expected)++ def test_cold_precompute_is_retryable(self) -> None:+ runner = ConversionRecordingsQuery(query=self.source, team=self.team, user=self.user)+ with (+ patch.object(runner, "sessions_query", side_effect=MarketingPrecomputeNotReady("purchase")),+ patch("products.marketing_analytics.backend.services.conversion_recordings.handle_not_ready") as warm,+ ):+ self.assertEqual(+ runner.sessions("purchase", "winter-sale", "google", None, None, 50),+ {"session_ids": [], "has_more": False, "preparing": True},+ )+ warm.assert_called_once_with(team=self.team, query=self.source)+ result = runner.sessions("purchase", "winter-sale", "google", None, None, 50)+ self.assertEqual(len(result["session_ids"]), 2)+ self.assertFalse(result["preparing"])++ def test_precomputed_session_metadata_does_not_split_the_table_conversion(self) -> None:+ job_ids = [uuid4(), uuid4()]+ person_id = uuid4()+ session_ids = ["01994530-9000-7000-8000-000000000051", "01994530-9000-7000-8000-000000000052"]+ self.addCleanup(sync_execute, TRUNCATE_MARKETING_CONVERSIONS_TABLE_SQL())+ sync_execute(+ "INSERT INTO sharded_marketing_conversions_preaggregated "+ "(team_id, job_id, person_id, conversion_timestamp, conversion_math_value, session_id, "+ "campaign_name, source_name, computed_at, expires_at) VALUES",+ [+ (+ self.team.pk,+ job_id,+ person_id,+ datetime(2026, 9, 16, 11, tzinfo=UTC),+ 1,+ session_ids[index],+ "winter-sale",+ "google",+ datetime(2026, 9, 20, index, tzinfo=UTC),+ datetime(2100, 1, 1, tzinfo=UTC),+ )+ for index, job_id in enumerate(job_ids)+ ],+ )+ table_runner = MarketingAnalyticsTableQueryRunner(query=self.source, team=self.team, user=self.user)+ table_runner.config.conversion_goal_precomputation_enabled = True+ recordings_runner = ConversionRecordingsQuery(query=self.source, team=self.team, user=self.user)+ recordings_runner.config.conversion_goal_precomputation_enabled = True+ with patch(+ "products.marketing_analytics.backend.hogql_queries.conversion_goal_processor.marketing_ensure_precomputed",+ return_value=LazyComputationResult(ready=True, job_ids=job_ids),+ ):+ table = table_runner.calculate()+ assert table.columns is not None+ self.assertEqual(len(table.results), 1)+ self.assertEqual(table.results[0][table.columns.index("Purchases")].value, 1)+ result = recordings_runner.sessions("purchase", "winter-sale", "google", None, None, 50)+ self.assertEqual(result["session_ids"], [session_ids[1]])++ @parameterized.expand(+ [+ (False, AttributionMode.LAST_TOUCH, 7),+ (True, AttributionMode.LAST_TOUCH, 7),+ (False, AttributionMode.LINEAR, 7),+ (True, AttributionMode.LINEAR, 7),+ (False, AttributionMode.LAST_TOUCH, 0),+ (False, AttributionMode.LAST_TOUCH, 7, True),+ (True, AttributionMode.LAST_TOUCH, 7, True),+ ]+ )+ def test_returns_conversion_sessions_not_other_sessions_of_the_same_person(+ self, precompute: bool, mode: AttributionMode, window_days: int, action_goal: bool = False+ ) -> None:+ if precompute:+ sync_execute(TRUNCATE_MARKETING_TOUCHPOINTS_TABLE_SQL())+ sync_execute(TRUNCATE_MARKETING_CONVERSIONS_TABLE_SQL())+ PreaggregationJob.objects.all().delete()+ self.addCleanup(sync_execute, TRUNCATE_MARKETING_TOUCHPOINTS_TABLE_SQL())+ self.addCleanup(sync_execute, TRUNCATE_MARKETING_CONVERSIONS_TABLE_SQL())+ if action_goal:+ action = Action.objects.create(team=self.team, name="Purchases", steps_json=[{"event": "purchase"}])+ config = self.team.marketing_analytics_config+ config.conversion_goals[0].update(kind="ActionsNode", id=action.id)+ config.conversion_goals[0].pop("event")+ config.save()+ for hour, properties in [+ (13, {}),+ (14, {"$session_id": "00000000-0000-0000-0000-000000000000"}),+ (+ 15,+ {+ "$session_id": "01994530-9000-7000-8000-000000000006",+ **({"utm_campaign": "later-sale", "utm_source": "google"} if window_days == 0 else {}),+ },+ ),+ ]:+ _create_event(+ team=self.team,+ distinct_id="alex",+ event="purchase",+ timestamp=f"2026-09-16T{hour}:00:00Z",+ properties=properties,+ )+ _create_event(+ team=self.team,+ distinct_id="alex",+ event="$pageview",+ timestamp="2026-09-16T14:30:00Z",+ properties={+ "$session_id": "01994530-9000-7000-8000-000000000008",+ "utm_campaign": "later-sale",+ "utm_source": "google",+ },+ )+ _create_event(+ team=self.team,+ distinct_id="alex",+ event="purchase",+ timestamp="2026-09-01T10:00:00Z",+ properties={+ "$session_id": "01994530-9000-7000-8000-000000000007",+ "utm_campaign": "later-sale",+ "utm_source": "google",+ },+ )+ flush_persons_and_events()+ runner = ConversionRecordingsQuery(query=self.source, team=self.team, user=self.user)+ runner.config.conversion_goal_precomputation_enabled = precompute+ runner.config.attribution_mode = mode+ runner.config.attribution_window_days = window_days+ with (+ patch(+ "products.marketing_analytics.backend.hogql_queries.marketing_lazy_precompute.is_background_warming_request",+ return_value=True,+ ),+ patch(+ "products.analytics_platform.backend.lazy_computation.lazy_computation_executor._get_ch_expires_at",+ return_value=datetime(2100, 1, 1, tzinfo=UTC),+ ),+ ):+ result = runner.sessions("purchase", "later-sale", "google", None, None, 50)+ self.assertEqual(+ result, {"session_ids": ["01994530-9000-7000-8000-000000000006"], "has_more": False, "preparing": False}+ )+++class TestWarehouseConversionRecordings(ClickhouseTestMixin, APIBaseTest):+ CLASS_DATA_LEVEL_SETUP = False++ def setUp(self) -> None:+ super().setUp()+ flags = patch(+ "products.marketing_analytics.backend.hogql_queries.marketing_analytics_config.feature_enabled_or_false",+ return_value=False,+ )+ flags.start()+ self.addCleanup(flags.stop)++ def test_warehouse_goal_without_conversion_sessions_is_rejected(self) -> None:+ table, *_rest, cleanup = create_data_warehouse_table_from_csv(+ Path(__file__).parents[1] / "hogql_queries/test/external/warehouse_conversions_empty_utm.csv",+ "conversion_recordings_warehouse",+ {+ "user_id": "String",+ "event_timestamp": "DateTime",+ "campaign_name": "String",+ "source_name": "String",+ "revenue": "Int64",+ },+ "test_storage_bucket-posthog.marketing_analytics.conversion_recordings",+ self.team,+ )+ self.addCleanup(cleanup)+ _create_person(team=self.team, distinct_ids=["dw_user_2"], properties={"email": "[email protected]"})+ flush_persons_and_events()+ config = self.team.marketing_analytics_config+ config.conversion_goals = [+ {+ "kind": "DataWarehouseNode",+ "id": table.name,+ "table_name": table.name,+ "name": "Warehouse purchases",+ "math": "total",+ "conversion_goal_id": "warehouse",+ "conversion_goal_name": "Warehouse purchases",+ "distinct_id_field": "user_id",+ "id_field": "user_id",+ "timestamp_field": "event_timestamp",+ "schema_map": {+ "utm_campaign_name": "campaign_name",+ "utm_source_name": "source_name",+ "timestamp_field": "event_timestamp",+ },+ }+ ]+ config.save()+ source = MarketingAnalyticsTableQuery(+ properties=[], dateRange=DateRange(date_from="2023-01-01", date_to="2023-01-31")+ )+ with (+ time_machine.travel("2023-02-01T12:00:00Z", tick=False),+ self.assertRaisesMessage(ValidationError, "only available for event and action goals"),+ ):+ ConversionRecordingsQuery(query=source, team=self.team, user=self.user).sessions(+ "warehouse", "summer_sale", "google", None, None, 50+ )diff --git a/products/marketing_analytics/conversion-recordings.md b/products/marketing_analytics/conversion-recordings.mdnew file mode 100644index 000000000000..2944bfd83a97--- /dev/null+++ b/products/marketing_analytics/conversion-recordings.md@@ -0,0 +1,24 @@+# Conversion recordings++Behind `marketing-analytics-conversion-recordings`, positive event and action conversion cells open the existing Replay playlist in Ad performance and the legacy dashboard.+Ad and ad group rows, warehouse goals, and shared dashboards do not expose the action.++## Session selection++The product endpoint reuses the table's attribution query and campaign mappings to resolve the selected row.+It preserves the current period, filters, and conversion goal, and returns the session of the conversion event, not the attributed touchpoint.+Hidden grouping columns remain available as row keys without changing the saved column selection.+A missing campaign ID selects only the table's missing-ID row; comparison rows combine campaign IDs as the table does.+Multiple conversions in one session produce one session ID.+Pagination uses the last session ID as a cursor.+The modal sends at most 100 session IDs to Replay at a time; Previous and Next select the conversion session page.++## Availability and errors++Missing attribution precomputes return a preparing state with a retry action.+Failed requests show a query ID for tracing the request in ClickHouse query logs; each attempt uses a new ID.+Replay receives the selected session IDs and handles recording availability, permissions, and playback.+Conversions without session IDs have no replay, and a session may have no recording because it was not recorded or has expired.+The playlist does not apply an additional start-date or minimum-duration filter, because a conversion session can start before the selected conversion period.+Replay retains its native controls, including **Show all**, which can clear the session filter.+There is no intermediate people list, and the shared Replay components, query registry, and query cache are unchanged.diff --git a/products/marketing_analytics/frontend/ConversionRecordingsModal.stories.tsx b/products/marketing_analytics/frontend/ConversionRecordingsModal.stories.tsxnew file mode 100644index 000000000000..2945665d2546--- /dev/null+++ b/products/marketing_analytics/frontend/ConversionRecordingsModal.stories.tsx@@ -0,0 +1,156 @@+import { Meta, StoryObj } from '@storybook/react'++import recordingEventsJson from 'scenes/session-recordings/__mocks__/recording_events_query'+import { recordingMetaJson } from 'scenes/session-recordings/__mocks__/recording_meta'+import { snapshotsAsJSONLines } from 'scenes/session-recordings/__mocks__/recording_snapshots'+import { recordings } from 'scenes/session-recordings/__mocks__/recordings'++import { useStorybookMocks } from '~/mocks/browser'++import { ConversionRecordingsModal } from './ConversionRecordingsModal'+import { ConversionRecordingsRequestApi, ConversionRecordingsResponseApi } from './generated/api.schemas'++const meta: Meta<typeof ConversionRecordingsModal> = {+ title: 'Marketing Analytics/Conversion recordings',+ component: ConversionRecordingsModal,+ args: {+ goalName: 'Purchases',+ request: {+ source: { kind: 'MarketingAnalyticsTableQuery', properties: [], dateRange: { date_from: '-7d' } },+ goal_id: 'purchase',+ group: 'winter-sale',+ source_name: 'google',+ },+ onClose: () => {},+ },+ parameters: {+ mockDate: '2023-08-11T12:05:00Z',+ testOptions: { waitForSelector: '.LemonModal', snapshotTargetSelector: '.LemonModal' },+ },+}+export default meta+type Story = StoryObj<typeof meta>++const sessions: ConversionRecordingsResponseApi = {+ session_ids: recordings.map(({ id }) => id),+ has_more: false,+ preparing: false,+}++export const WithRecordings: Story = {+ render: (args) => {+ useStorybookMocks({+ post: {+ '/api/projects/:team_id/marketing_analytics/conversion_recordings/': async ({ request }) => {+ const { after } = (await request.json()) as ConversionRecordingsRequestApi+ return {+ ...sessions,+ session_ids: after ? sessions.session_ids.slice(1) : sessions.session_ids.slice(0, 1),+ has_more: !after,+ }+ },+ '/api/environments/:team_id/query/:kind': async ({ request }) => {+ const body = (await request.json()) as { query: { kind: string } }+ return body.query.kind === 'EventsQuery'+ ? recordingEventsJson+ : {+ columns: ['session_id', '$geoip_country_code', '$browser', '$device_type', '$os'],+ results: recordings.map(({ id }) => [id, 'GB', 'Chrome', 'Desktop', 'Mac OS X']),+ }+ },+ },+ get: {+ '/api/environments/:team_id/session_recordings': ({ request }) => {+ const ids = JSON.parse(new URL(request.url).searchParams.get('session_ids') || '[]') as string[]+ return { has_next: false, results: recordings.filter(({ id }) => ids.includes(id)), version: 1 }+ },+ '/api/environments/:team_id/session_recordings/:id': ({ params }) => ({+ ...recordingMetaJson,+ id: params.id,+ }),+ '/api/environments/:team_id/session_recordings/:id/snapshots': ({ request }) =>+ new URL(request.url).searchParams.get('source') === 'blob_v2'+ ? new Response(snapshotsAsJSONLines())+ : {+ sources: [+ {+ source: 'blob_v2',+ start_timestamp: '2023-08-11T12:03:36.097000Z',+ end_timestamp: '2023-08-11T12:04:52.268000Z',+ blob_key: '0',+ },+ ],+ },+ },+ })+ return <ConversionRecordingsModal {...args} />+ },+ play: async ({ canvasElement }) => {+ let recording: HTMLElement | null = null+ for (let frame = 0; frame < 120 && !recording; frame++) {+ recording = canvasElement.ownerDocument.querySelector('.Playlist__list .ph-no-capture span.truncate')+ if (!recording) {+ await new Promise<void>((resolve) => requestAnimationFrame(() => resolve()))+ }+ }+ if (!recording) {+ throw new Error('The conversion recording list did not load')+ }+ recording.click()+ },+ parameters: {+ testOptions: {+ waitForSelector: 'iframe.PlayerFrame__document >>> .PlayerFrame__content .replayer-wrapper iframe',+ },+ },+}++export const NoRecordings: Story = {+ render: (args) => {+ useStorybookMocks({+ post: { '/api/projects/:team_id/marketing_analytics/conversion_recordings/': sessions },+ get: { '/api/environments/:team_id/session_recordings': { has_next: false, results: [], version: 1 } },+ })+ return <ConversionRecordingsModal {...args} />+ },+}++export const Preparing: Story = {+ render: (args) => {+ useStorybookMocks({+ post: {+ '/api/projects/:team_id/marketing_analytics/conversion_recordings/': {+ ...sessions,+ session_ids: [],+ preparing: true,+ },+ },+ })+ return <ConversionRecordingsModal {...args} />+ },+}++export const Empty: Story = {+ render: (args) => {+ useStorybookMocks({+ post: {+ '/api/projects/:team_id/marketing_analytics/conversion_recordings/': { ...sessions, session_ids: [] },+ },+ })+ return <ConversionRecordingsModal {...args} />+ },+}++export const QueryError: Story = {+ render: (args) => {+ useStorybookMocks({+ post: {+ '/api/projects/:team_id/marketing_analytics/conversion_recordings/': [+ 500,+ { detail: 'Could not load conversion recordings.' },+ ],+ },+ })+ return <ConversionRecordingsModal {...args} />+ },+}diff --git a/products/marketing_analytics/frontend/ConversionRecordingsModal.tsx b/products/marketing_analytics/frontend/ConversionRecordingsModal.tsxnew file mode 100644index 000000000000..1ae73bae471b--- /dev/null+++ b/products/marketing_analytics/frontend/ConversionRecordingsModal.tsx@@ -0,0 +1,117 @@+import { useActions, useValues } from 'kea'++import { LemonBanner, LemonButton, LemonModal, Spinner } from '@posthog/lemon-ui'++import { SessionRecordingsPlaylist } from 'scenes/session-recordings/playlist/SessionRecordingsPlaylist'+import { DEFAULT_RECORDING_FILTERS } from 'scenes/session-recordings/playlist/sessionRecordingsPlaylistLogic'++import { conversionRecordingsLogic } from './conversionRecordingsLogic'+import { MarketingQueryError } from './dashboard/MarketingQueryError'+import { ConversionRecordingsRequestApi } from './generated/api.schemas'++export function ConversionRecordingsModal({+ request,+ goalName,+ onClose,+}: {+ request: ConversionRecordingsRequestApi+ goalName: string+ onClose: () => void+}): JSX.Element {+ const logic = conversionRecordingsLogic({ request })+ const { page, pageLoading } = useValues(logic)+ const { loadSessions } = useActions(logic)++ return (+ <LemonModal+ isOpen+ onClose={onClose}+ title={`${goalName}: conversion recordings for ${request.group || '(not set)'}`}+ width="90vw"+ footer={+ (page.pageIndex > 0 || page.has_more) && (+ <>+ <span className="text-secondary">Conversion sessions, page {page.pageIndex + 1}</span>+ <LemonButton+ type="secondary"+ disabledReason={page.pageIndex === 0 ? 'You are on the first page' : undefined}+ loading={pageLoading}+ onClick={() => loadSessions({ pageIndex: page.pageIndex - 1 })}+ >+ Previous+ </LemonButton>+ <LemonButton+ type="secondary"+ disabledReason={!page.has_more ? 'You are on the last page' : undefined}+ loading={pageLoading}+ onClick={() => loadSessions({ pageIndex: page.pageIndex + 1 })}+ >+ Next+ </LemonButton>+ </>+ )+ }+ >+ <div className="flex flex-col gap-4">+ <p className="text-secondary m-0">+ Recordings from sessions where these conversions happened. Not every conversion has a recording.+ </p>+ {pageLoading && !page.session_ids.length && <Spinner />}+ {page.preparing && (+ <LemonBanner type="info">+ Conversion details are being prepared. Try again in a few minutes.+ </LemonBanner>+ )}+ {page.errorMessage && (+ <MarketingQueryError+ message={page.errorMessage}+ queryId={page.queryId}+ onRetry={() => loadSessions({ pageIndex: page.retryPage })}+ loading={pageLoading}+ />+ )}+ {page.session_ids.length > 0 ? (+ <div className="h-[60vh] min-h-96 overflow-auto">+ <SessionRecordingsPlaylist+ key={page.pageIndex}+ logicKey={`marketing-conversions-${JSON.stringify(request)}-${page.pageIndex}`}+ analyticsSource="marketing-analytics-conversions"+ autoPlay={false}+ filters={{+ ...DEFAULT_RECORDING_FILTERS,+ session_ids: page.session_ids,+ date_from: 'all',+ date_to: null,+ duration: [],+ filter_test_accounts: false,+ }}+ resetToCallerFilters+ updateSearchParams={false}+ listEmptyState={+ <p className="p-4">+ No recordings are available for these conversion sessions. Try another date range or+ conversion goal.+ </p>+ }+ />+ </div>+ ) : !pageLoading && !page.preparing && !page.errorMessage ? (+ <LemonBanner type="info">+ These conversions have no session IDs. Try another date range or conversion goal.+ </LemonBanner>+ ) : null}+ {page.preparing && (+ <LemonButton+ type="secondary"+ loading={pageLoading}+ onClick={() => loadSessions({ pageIndex: page.retryPage })}+ center+ fullWidth+ >+ Try again+ </LemonButton>+ )}+ </div>+ </LemonModal>+ )+}diff --git a/products/marketing_analytics/frontend/conversionRecordingsLogic.test.ts b/products/marketing_analytics/frontend/conversionRecordingsLogic.test.tsnew file mode 100644index 000000000000..7fab069c0a8b--- /dev/null+++ b/products/marketing_analytics/frontend/conversionRecordingsLogic.test.ts@@ -0,0 +1,100 @@+import { expectLogic, partial } from 'kea-test-utils'++import { useMocks } from '~/mocks/jest'+import { initKeaTests } from '~/test/init'++import { conversionRecordingsLogic } from './conversionRecordingsLogic'+import { ConversionRecordingsRequestApi } from './generated/api.schemas'++describe('conversionRecordingsLogic', () => {+ let logic: ReturnType<typeof conversionRecordingsLogic.build>+ const request: ConversionRecordingsRequestApi = {+ source: { kind: 'MarketingAnalyticsTableQuery', properties: [] },+ goal_id: 'purchase',+ group: 'winter-sale',+ }+ const first = '00000000-0000-4000-8000-000000000001'+ const second = '00000000-0000-4000-8000-000000000002'+ let requests: ConversionRecordingsRequestApi[]++ beforeEach(() => {+ initKeaTests()+ requests = []+ useMocks({+ post: {+ '/api/projects/:team_id/marketing_analytics/conversion_recordings/': async ({ request }) => {+ const body = (await request.json()) as ConversionRecordingsRequestApi+ requests.push(body)+ return {+ session_ids: body.after ? [second] : [first],+ has_more: !body.after,+ preparing: false,+ }+ },+ },+ })+ logic = conversionRecordingsLogic({ request })+ })+ afterEach(() => logic.unmount())++ it('replaces the session page and navigates back with the matching cursor', async () => {+ await expectLogic(logic, () => {+ logic.mount()+ }).toFinishAllListeners()+ expect(requests[0].client_query_id).toEqual(expect.any(String))+ await expectLogic(logic, () => logic.actions.loadSessions({ pageIndex: 1 }))+ .toFinishAllListeners()+ .toMatchValues({ page: partial({ session_ids: [second], pageIndex: 1, has_more: false }) })+ expect(requests[1]).toMatchObject({ ...request, after: first })+ await expectLogic(logic, () => logic.actions.loadSessions({ pageIndex: 0 }))+ .toFinishAllListeners()+ .toMatchValues({ page: partial({ session_ids: [first], has_more: true, pageIndex: 0 }) })+ expect(requests[2]).not.toHaveProperty('after')+ await expectLogic(logic, () => logic.actions.loadSessions({ pageIndex: 1 })).toFinishAllListeners()+ expect(requests[3].after).toBe(first)+ })++ it.each(['failed', 'preparing'] as const)('preserves the current page and retries the %s page', async (state) => {+ await expectLogic(logic, () => {+ logic.mount()+ }).toFinishAllListeners()+ useMocks({+ post: {+ '/api/projects/:team_id/marketing_analytics/conversion_recordings/': async ({ request }) => {+ requests.push((await request.json()) as ConversionRecordingsRequestApi)+ return state === 'failed'+ ? [500, { detail: 'Failed' }]+ : { session_ids: [], has_more: false, preparing: true }+ },+ },+ })+ await expectLogic(logic, () => {+ logic.actions.loadSessions({ pageIndex: 1 })+ })+ .toFinishAllListeners()+ .toMatchValues({+ page: partial({ preparing: state === 'preparing', session_ids: [first], has_more: true, pageIndex: 0 }),+ pageLoading: false,+ })+ expect(logic.values.page.queryId).toBe(requests.at(-1)?.client_query_id)+ expect(logic.values.page.queryId).not.toBe(requests[0].client_query_id)+ expect(logic.values.page.errorMessage).toBe(state === 'failed' ? 'Failed' : undefined)+ useMocks({+ post: {+ '/api/projects/:team_id/marketing_analytics/conversion_recordings/': async ({ request }) => {+ requests.push((await request.json()) as ConversionRecordingsRequestApi)+ return { session_ids: [second], preparing: false, has_more: false }+ },+ },+ })+ await expectLogic(logic, () => logic.actions.loadSessions({ pageIndex: logic.values.page.retryPage }))+ .toFinishAllListeners()+ .toMatchValues({+ page: partial({ session_ids: [second], preparing: false, pageIndex: 1 }),+ pageLoading: false,+ })+ expect(logic.values.page.errorMessage).toBeUndefined()+ expect(logic.values.page.queryId).toBeUndefined()+ expect(requests.at(-1)?.after).toBe(first)+ })+})diff --git a/products/marketing_analytics/frontend/conversionRecordingsLogic.ts b/products/marketing_analytics/frontend/conversionRecordingsLogic.tsnew file mode 100644index 000000000000..84df776a46ff--- /dev/null+++ b/products/marketing_analytics/frontend/conversionRecordingsLogic.ts@@ -0,0 +1,135 @@+import { MakeLogicType, afterMount, connect, kea, key, path, props } from 'kea'+import { loaders } from 'kea-loaders'++import { ApiError } from 'lib/api'+import { inStorybook, inStorybookTestRunner, uuid } from 'lib/utils/dom'+import { teamLogic } from 'scenes/teamLogic'++import * as api from './generated/api'+import { ConversionRecordingsRequestApi, ConversionRecordingsResponseApi } from './generated/api.schemas'++export interface ConversionRecordingsLogicProps {+ request: ConversionRecordingsRequestApi+}++export interface ConversionRecordingsPage extends ConversionRecordingsResponseApi {+ pageIndex: number+ cursors: string[]+ retryPage?: number+ errorMessage?: string+ queryId?: string+}++const emptyPage: ConversionRecordingsPage = {+ session_ids: [],+ has_more: false,+ preparing: false,+ pageIndex: 0,+ cursors: [],+}++// Generated by kea-typegen. Update if you're an agent, ignore if you're human.+export interface conversionRecordingsLogicValues {+ currentTeamId: number | null // teamLogic+ page: ConversionRecordingsPage+ pageLoading: boolean+}++// Generated by kea-typegen. Update if you're an agent, ignore if you're human.+export interface conversionRecordingsLogicActions {+ loadSessions: (payload: { pageIndex?: number }) => {+ pageIndex?: number+ }+ loadSessionsFailure: (+ error: string,+ errorObject?: any+ ) => {+ error: string+ errorObject?: any+ }+ loadSessionsSuccess: (+ page: ConversionRecordingsPage,+ payload?: {+ pageIndex?: number+ }+ ) => {+ page: ConversionRecordingsPage+ payload?: {+ pageIndex?: number+ }+ }+}++// Generated by kea-typegen. Update if you're an agent, ignore if you're human.+export interface conversionRecordingsLogicMeta {+ key: string+}++export type conversionRecordingsLogicType = MakeLogicType<+ conversionRecordingsLogicValues,+ conversionRecordingsLogicActions,+ ConversionRecordingsLogicProps,+ conversionRecordingsLogicMeta+>++export const conversionRecordingsLogic = kea<conversionRecordingsLogicType>([+ props({} as ConversionRecordingsLogicProps),+ key(({ request }) => JSON.stringify(request)),+ path((key) => ['products', 'marketing_analytics', 'conversionRecordingsLogic', key]),+ connect({ values: [teamLogic, ['currentTeamId']] }),+ loaders(({ props, values }) => ({+ page: [+ emptyPage,+ {+ loadSessions: async (+ payload: { pageIndex?: number },+ breakpoint+ ): Promise<ConversionRecordingsPage> => {+ await breakpoint(250)+ const pageIndex = payload.pageIndex ?? 0+ const queryId =+ inStorybook() || inStorybookTestRunner() ? '00000000-0000-4000-8000-000000000000' : uuid()+ let response: ConversionRecordingsResponseApi+ try {+ response = await api.marketingAnalyticsConversionRecordingsList(String(values.currentTeamId), {+ ...props.request,+ client_query_id: queryId,+ after: pageIndex > 0 ? values.page.cursors[pageIndex - 1] : undefined,+ limit: 100,+ })+ } catch (error) {+ breakpoint()+ return {+ ...values.page,+ errorMessage:+ (error instanceof ApiError && error.detail) ||+ "Couldn't load conversion recordings. Try again.",+ preparing: false,+ queryId,+ retryPage: pageIndex,+ }+ }+ breakpoint()+ if (response.preparing) {+ return {+ ...values.page,+ preparing: true,+ errorMessage: undefined,+ queryId,+ retryPage: pageIndex,+ }+ }+ return {+ ...response,+ pageIndex,+ cursors: [+ ...values.page.cursors.slice(0, pageIndex),+ ...(response.has_more ? response.session_ids.slice(-1) : []),+ ],+ }+ },+ },+ ],+ })),+ afterMount(({ actions }) => actions.loadSessions({})),+])diff --git a/products/marketing_analytics/frontend/conversionRecordingsRequest.test.ts b/products/marketing_analytics/frontend/conversionRecordingsRequest.test.tsnew file mode 100644index 000000000000..f17030e5c030--- /dev/null+++ b/products/marketing_analytics/frontend/conversionRecordingsRequest.test.ts@@ -0,0 +1,94 @@+import {+ DataTableNode,+ MarketingAnalyticsDrillDownLevel,+ MarketingAnalyticsTableQuery,+ NodeKind,+} from '~/queries/schema/schema-general'++import {+ conversionRecordingsRequest,+ conversionRecordingsTableQuery,+ restoreConversionRecordingsColumns,+} from './conversionRecordingsRequest'++describe('conversion recordings row selection', () => {+ const source: MarketingAnalyticsTableQuery = {+ kind: NodeKind.MarketingAnalyticsTableQuery,+ properties: [],+ select: ['Purchases'],+ }+ const query: DataTableNode = { kind: NodeKind.DataTableNode, source }++ it.each([+ [MarketingAnalyticsDrillDownLevel.Campaign, ['Campaign', 'Source', 'ID']],+ [MarketingAnalyticsDrillDownLevel.ChannelSource, ['Channel', 'Source']],+ [MarketingAnalyticsDrillDownLevel.Source, ['Source']],+ [MarketingAnalyticsDrillDownLevel.Medium, ['Medium']],+ ])('keeps hidden row keys available at %s level without saving them', (level, columns) => {+ const original: DataTableNode = {+ ...query,+ source: { ...source, drillDownLevel: level },+ hiddenColumns: ['Cost'],+ }+ const prepared = conversionRecordingsTableQuery(original, true)+ expect((prepared.source as MarketingAnalyticsTableQuery).select).toEqual(['Purchases', ...columns])+ expect(prepared.hiddenColumns).toEqual(['Cost', ...columns])++ const record = columns.map((key) => ({ key, value: `${key} value` }))+ const request = conversionRecordingsRequest(prepared.source as MarketingAnalyticsTableQuery, record, 'purchase')+ expect(request).toMatchObject({ goal_id: 'purchase', group: `${columns[0]} value` })+ if (columns.includes('ID')) {+ expect(request).toMatchObject({ campaign_id: 'ID value', source_name: 'Source value' })+ }++ const sorted: DataTableNode = {+ ...prepared,+ source: { ...(prepared.source as MarketingAnalyticsTableQuery), orderBy: [['Purchases', 'DESC']] },+ }+ expect(restoreConversionRecordingsColumns(sorted, original)).toEqual({+ ...original,+ source: { ...original.source, orderBy: [['Purchases', 'DESC']] },+ })+ })++ it.each([+ [false, 'campaign-id', 'campaign-id'],+ [false, null, '-'],+ [false, '', '-'],+ [true, 'campaign-id', undefined],+ [true, null, undefined],+ ])('selects the campaign ID %s/%s without splitting comparison rows', (compare, id, expected) => {+ const prepared = conversionRecordingsTableQuery(+ { ...query, source: { ...source, compareFilter: { compare } } },+ true+ )+ expect((prepared.source as MarketingAnalyticsTableQuery).select).toEqual([+ 'Purchases',+ 'Campaign',+ 'Source',+ ...(compare ? [] : ['ID']),+ ])+ expect(+ conversionRecordingsRequest(+ prepared.source as MarketingAnalyticsTableQuery,+ [+ { key: 'Campaign', value: 'winter-sale' },+ { key: 'Source', value: 'google' },+ { key: 'ID', value: id },+ ],+ 'purchase'+ )?.campaign_id+ ).toBe(expected)+ })++ it.each([false, true])('leaves complete queries unchanged (enabled: %s)', (enabled) => {+ const complete: DataTableNode = {+ ...query,+ source: { ...source, select: ['Campaign', 'Source', 'ID', 'Purchases'] },+ }+ expect(conversionRecordingsTableQuery(complete, enabled)).toBe(complete)+ if (!enabled) {+ expect(conversionRecordingsTableQuery(query, enabled)).toBe(query)+ }+ })+})diff --git a/products/marketing_analytics/frontend/conversionRecordingsRequest.ts b/products/marketing_analytics/frontend/conversionRecordingsRequest.tsnew file mode 100644index 000000000000..dc8fde080753--- /dev/null+++ b/products/marketing_analytics/frontend/conversionRecordingsRequest.ts@@ -0,0 +1,99 @@+import {+ DataTableNode,+ MARKETING_ANALYTICS_DRILL_DOWN_CONFIG,+ MarketingAnalyticsDrillDownLevel,+ MarketingAnalyticsItem,+ MarketingAnalyticsTableQuery,+} from '~/queries/schema/schema-general'++import { ConversionRecordingsRequestApi } from './generated/api.schemas'++export interface ConversionRecordingsSelection {+ tableKey: string+ request: ConversionRecordingsRequestApi+ goalName: string+}++function rowColumns(source: MarketingAnalyticsTableQuery): string[] {+ const level = source.drillDownLevel ?? MarketingAnalyticsDrillDownLevel.Campaign+ if (level === MarketingAnalyticsDrillDownLevel.Ad || level === MarketingAnalyticsDrillDownLevel.AdGroup) {+ return []+ }+ const columns = [MARKETING_ANALYTICS_DRILL_DOWN_CONFIG[level].columnAlias]+ if (+ level === MarketingAnalyticsDrillDownLevel.Campaign ||+ level === MarketingAnalyticsDrillDownLevel.ChannelSource+ ) {+ columns.push('Source')+ }+ if (level === MarketingAnalyticsDrillDownLevel.Campaign && !source.compareFilter?.compare) {+ columns.push('ID')+ }+ return columns+}++export function conversionRecordingsTableQuery(query: DataTableNode, enabled: boolean): DataTableNode {+ const source = query.source as MarketingAnalyticsTableQuery+ if (!enabled || !source.select?.length) {+ return query+ }+ const hidden = rowColumns(source).filter((column) => !source.select?.includes(column))+ if (!hidden.length) {+ return query+ }+ return {+ ...query,+ source: { ...source, select: [...source.select, ...hidden] },+ hiddenColumns: [...(query.hiddenColumns ?? []), ...hidden],+ }+}++export function restoreConversionRecordingsColumns(updated: DataTableNode, original: DataTableNode): DataTableNode {+ const source = original.source as MarketingAnalyticsTableQuery+ if (!source.select?.length) {+ return updated+ }+ const hidden = rowColumns(source).filter((column) => !source.select?.includes(column))+ const updatedSource = updated.source as MarketingAnalyticsTableQuery+ return {+ ...updated,+ source: { ...updatedSource, select: updatedSource.select?.filter((column) => !hidden.includes(column)) },+ hiddenColumns: original.hiddenColumns,+ }+}++function rowValue(record: unknown, column: string): string | undefined {+ if (!Array.isArray(record)) {+ return undefined+ }+ const cell = record.find((item): item is MarketingAnalyticsItem => item?.key === column)+ return cell?.value == null ? undefined : String(cell.value)+}++export function conversionRecordingsRequest(+ source: MarketingAnalyticsTableQuery,+ record: unknown,+ goalId: string+): ConversionRecordingsRequestApi | null {+ const level = source.drillDownLevel ?? MarketingAnalyticsDrillDownLevel.Campaign+ if (level === MarketingAnalyticsDrillDownLevel.Ad || level === MarketingAnalyticsDrillDownLevel.AdGroup) {+ return null+ }+ const group = rowValue(record, MARKETING_ANALYTICS_DRILL_DOWN_CONFIG[level].columnAlias)+ const sourceName = rowValue(record, 'Source')+ const needsSource =+ level === MarketingAnalyticsDrillDownLevel.Campaign || level === MarketingAnalyticsDrillDownLevel.ChannelSource+ if (group === undefined || (needsSource && sourceName === undefined)) {+ return null+ }+ return {+ source: source as ConversionRecordingsRequestApi['source'],+ goal_id: goalId,+ group,+ source_name: needsSource ? sourceName : '',+ campaign_id:+ level === MarketingAnalyticsDrillDownLevel.Campaign && !source.compareFilter?.compare+ ? rowValue(record, 'ID') || '-'+ : undefined,+ }+}diff --git a/products/marketing_analytics/frontend/generated/api.schemas.ts b/products/marketing_analytics/frontend/generated/api.schemas.tsindex a4731def1e73..038d2e5b5d76 100644--- a/products/marketing_analytics/frontend/generated/api.schemas.ts+++ b/products/marketing_analytics/frontend/generated/api.schemas.ts@@ -1318,6 +1318,655 @@ export interface ConversionGoalWriteApi {goal: ConversionGoalApi}+export interface CompareFilterApi {+ /** Whether to compare the current date range to a previous date range. */+ compare?: boolean | null+ /** The date range to compare to. The value is a relative date. Examples of relative dates are: `-1y` for 1 year ago, `-14m` for 14 months ago, `-100w` for 100 weeks ago, `-14d` for 14 days ago, `-30h` for 30 hours ago. */+ compare_to?: string | null+}++export interface ActionConversionGoalApi {+ actionId: number+ properties?:+ | (EventPropertyFilterApi | PersonPropertyFilterApi | SessionPropertyFilterApi | CohortPropertyFilterApi)[]+ | null+}++export interface CustomEventConversionGoalApi {+ customEventName: string+ properties?:+ | (EventPropertyFilterApi | PersonPropertyFilterApi | SessionPropertyFilterApi | CohortPropertyFilterApi)[]+ | null+}++export type DaysOfWeekEnumApi = (typeof DaysOfWeekEnumApi)[keyof typeof DaysOfWeekEnumApi]++export const DaysOfWeekEnumApi = {+ Number1: 1,+ Number2: 2,+ Number3: 3,+ Number4: 4,+ Number5: 5,+ Number6: 6,+ Number7: 7,+} as const++export interface DateRangeApi {+ /** Start of the date range. Accepts ISO 8601 timestamps (e.g., 2024-01-15T00:00:00Z) or relative formats: -7d (7 days ago), -2w (2 weeks ago), -1m (1 month ago),+ * -1h (1 hour ago), -1mStart (start of last month), -1yStart (start of last year). */+ date_from?: string | null+ /** End of the date range. Same format as date_from. Omit or null for "now". A calendar day without a time (2024-01-15) is inclusive: it rounds to the last moment of that day in the project timezone, unless explicitDate is set. */+ date_to?: string | null+ /** Restrict the query to events occurring on these ISO days of week (1=Monday to 7=Sunday), evaluated in the project timezone. Omit or empty for all days. Only applied by insight queries. */+ daysOfWeek?: DaysOfWeekEnumApi[] | null+ /** Exclude the current, still-collecting period by clipping date_to to the end of the last complete interval (evaluated in the project timezone). No-op when the range contains no complete interval. Only applied by insight queries. */+ excludeIncompletePeriods?: boolean | null+ /** Whether the date_from and date_to should be used verbatim. Disables rounding to the start and end of period. */+ explicitDate?: boolean | null+}++export type MarketingAnalyticsDrillDownLevelApi =+ (typeof MarketingAnalyticsDrillDownLevelApi)[keyof typeof MarketingAnalyticsDrillDownLevelApi]++export const MarketingAnalyticsDrillDownLevelApi = {+ Channel: 'channel',+ ChannelSource: 'channel_source',+ Source: 'source',+ Campaign: 'campaign',+ AdGroup: 'ad_group',+ Ad: 'ad',+ Medium: 'medium',+ Content: 'content',+ Term: 'term',+} as const++export interface IntegrationFilterApi {+ /** Keep rows that no integration reports cost for, such as organic, email or an unmapped source. Defaults to true. */+ includeNonIntegrated?: boolean | null+ /** Selected integration source IDs to filter by (e.g., table IDs or source map IDs) */+ integrationSourceIds?: string[] | null+}++export type IntervalTypeApi = (typeof IntervalTypeApi)[keyof typeof IntervalTypeApi]++export const IntervalTypeApi = {+ Second: 'second',+ Minute: 'minute',+ Hour: 'hour',+ Day: 'day',+ Week: 'week',+ Month: 'month',+ Quarter: 'quarter',+ Year: 'year',+} as const++export type BounceRatePageViewModeApi = (typeof BounceRatePageViewModeApi)[keyof typeof BounceRatePageViewModeApi]++export const BounceRatePageViewModeApi = {+ CountPageviews: 'count_pageviews',+ UniqUrls: 'uniq_urls',+ UniqPageScreenAutocaptures: 'uniq_page_screen_autocaptures',+} as const++export type FilterLogicalOperatorApi = (typeof FilterLogicalOperatorApi)[keyof typeof FilterLogicalOperatorApi]++export const FilterLogicalOperatorApi = {+ And: 'AND',+ Or: 'OR',+} as const++export type CustomBotFieldApi = (typeof CustomBotFieldApi)[keyof typeof CustomBotFieldApi]++export const CustomBotFieldApi = {+ RawUserAgent: '$raw_user_agent',+ Ip: '$ip',+ Lib: '$lib',+ Host: '$host',+ Pathname: '$pathname',+ CurrentUrl: '$current_url',+ Browser: '$browser',+ Os: '$os',+ BrowserLanguage: '$browser_language',+ ScreenWidth: '$screen_width',+ ScreenHeight: '$screen_height',+ GeoipCountryCode: '$geoip_country_code',+ Referrer: '$referrer',+ ReferringDomain: '$referring_domain',+} as const++export type CustomBotMatcherApi = (typeof CustomBotMatcherApi)[keyof typeof CustomBotMatcherApi]++export const CustomBotMatcherApi = {+ Contains: 'contains',+ Regex: 'regex',+ Exact: 'exact',+ Cidr: 'cidr',+} as const++export interface CustomBotConditionApi {+ id: string+ /** The event property this condition reads. */+ key: CustomBotFieldApi+ matcher: CustomBotMatcherApi+ /** Matched against the property named by `key`. */+ pattern: string+}++export interface CustomBotRuleApi {+ /** Reported by `$virt_traffic_category`. Defaults to `custom`. */+ category?: string | null+ /** Whether every condition must match (AND) or any one of them (OR). */+ combiner: FilterLogicalOperatorApi+ id: string+ items: CustomBotConditionApi[]+ /** Reported by `$virt_bot_name` and `$virt_bot_operator` when the rule matches. */+ name: string+}++export type CustomChannelFieldApi = (typeof CustomChannelFieldApi)[keyof typeof CustomChannelFieldApi]++export const CustomChannelFieldApi = {+ UtmSource: 'utm_source',+ UtmMedium: 'utm_medium',+ UtmCampaign: 'utm_campaign',+ ReferringDomain: 'referring_domain',+ Url: 'url',+ Pathname: 'pathname',+ Hostname: 'hostname',+} as const++export type CustomChannelOperatorApi = (typeof CustomChannelOperatorApi)[keyof typeof CustomChannelOperatorApi]++export const CustomChannelOperatorApi = {+ Exact: 'exact',+ IsNot: 'is_not',+ IsSet: 'is_set',+ IsNotSet: 'is_not_set',+ Icontains: 'icontains',+ NotIcontains: 'not_icontains',+ Regex: 'regex',+ NotRegex: 'not_regex',+} as const++export interface CustomChannelConditionApi {+ id: string+ key: CustomChannelFieldApi+ op: CustomChannelOperatorApi+ value?: string | string[] | null+}++export interface CustomChannelRuleApi {+ channel_type: string+ combiner: FilterLogicalOperatorApi+ id: string+ items: CustomChannelConditionApi[]+}++export interface DataWarehouseEventsModifierApi {+ distinct_id_field: string+ id_field: string+ table_name: string+ timestamp_field: string+}++export type InCohortViaApi = (typeof InCohortViaApi)[keyof typeof InCohortViaApi]++export const InCohortViaApi = {+ Auto: 'auto',+ Leftjoin: 'leftjoin',+ Subquery: 'subquery',+ LeftjoinConjoined: 'leftjoin_conjoined',+} as const++export type InlineCohortCalculationApi = (typeof InlineCohortCalculationApi)[keyof typeof InlineCohortCalculationApi]++export const InlineCohortCalculationApi = {+ Off: 'off',+ Auto: 'auto',+ Always: 'always',+} as const++export type MaterializationModeApi = (typeof MaterializationModeApi)[keyof typeof MaterializationModeApi]++export const MaterializationModeApi = {+ Auto: 'auto',+ LegacyNullAsString: 'legacy_null_as_string',+ LegacyNullAsNull: 'legacy_null_as_null',+ Disabled: 'disabled',+} as const++export type MaterializedColumnsOptimizationModeApi =+ (typeof MaterializedColumnsOptimizationModeApi)[keyof typeof MaterializedColumnsOptimizationModeApi]++export const MaterializedColumnsOptimizationModeApi = {+ Disabled: 'disabled',+ Optimized: 'optimized',+} as const++export type ParserModeApi = (typeof ParserModeApi)[keyof typeof ParserModeApi]++export const ParserModeApi = {+ CppOnly: 'cpp_only',+ CppWithRustShadow: 'cpp_with_rust_shadow',+ CppWithRustPyShadow: 'cpp_with_rust_py_shadow',+ RustWithCppShadow: 'rust_with_cpp_shadow',+ RustOnly: 'rust_only',+ RustPyOnly: 'rust_py_only',+ RustPyWithCppShadow: 'rust_py_with_cpp_shadow',+} as const++export type PersonsArgMaxVersionApi = (typeof PersonsArgMaxVersionApi)[keyof typeof PersonsArgMaxVersionApi]++export const PersonsArgMaxVersionApi = {+ Auto: 'auto',+ V1: 'v1',+ V2: 'v2',+} as const++export type PersonsJoinModeApi = (typeof PersonsJoinModeApi)[keyof typeof PersonsJoinModeApi]++export const PersonsJoinModeApi = {+ Inner: 'inner',+ Left: 'left',+} as const++export type PersonsOnEventsModeApi = (typeof PersonsOnEventsModeApi)[keyof typeof PersonsOnEventsModeApi]++export const PersonsOnEventsModeApi = {+ Disabled: 'disabled',+ PersonIdNoOverridePropertiesOnEvents: 'person_id_no_override_properties_on_events',+ PersonIdOverridePropertiesOnEvents: 'person_id_override_properties_on_events',+ PersonIdOverridePropertiesJoined: 'person_id_override_properties_joined',+} as const++export type PropertyGroupsModeApi = (typeof PropertyGroupsModeApi)[keyof typeof PropertyGroupsModeApi]++export const PropertyGroupsModeApi = {+ Enabled: 'enabled',+ Disabled: 'disabled',+ Optimized: 'optimized',+} as const++export type SessionTableVersionApi = (typeof SessionTableVersionApi)[keyof typeof SessionTableVersionApi]++export const SessionTableVersionApi = {+ Auto: 'auto',+ V1: 'v1',+ V2: 'v2',+ V3: 'v3',+} as const++export type SessionsV2JoinModeApi = (typeof SessionsV2JoinModeApi)[keyof typeof SessionsV2JoinModeApi]++export const SessionsV2JoinModeApi = {+ String: 'string',+ Uuid: 'uuid',+} as const++export interface HogQLQueryModifiersApi {+ bounceRateDurationSeconds?: number | null+ bounceRatePageViewMode?: BounceRatePageViewModeApi | null+ convertToProjectTimezone?: boolean | null+ /** Do not treat a missing user agent as automation on cookieless events. Positive bot signals and custom project rules still apply. Resolved server-side; not intended to be set by clients. */+ cookielessTrafficIsRegular?: boolean | null+ customBotDefinitions?: CustomBotRuleApi[] | null+ customChannelTypeRules?: CustomChannelRuleApi[] | null+ dataWarehouseEventsModifiers?: DataWarehouseEventsModifierApi[] | null+ debug?: boolean | null+ /** If these are provided, the query will fail if these skip indexes are not used */+ forceClickhouseDataSkippingIndexes?: string[] | null+ formatCsvAllowDoubleQuotes?: boolean | null+ inCohortVia?: InCohortViaApi | null+ inlineCohortCalculation?: InlineCohortCalculationApi | null+ materializationMode?: MaterializationModeApi | null+ materializedColumnsOptimizationMode?: MaterializedColumnsOptimizationModeApi | null+ /** Merge sibling aggregating LEFT JOINs over federated Postgres tables into one UNION ALL join, so their scans overlap */+ mergeFederatedAggregateJoins?: boolean | null+ optimizeJoinedFilters?: boolean | null+ optimizeProjections?: boolean | null+ /** HogQL parser backend; absent → `rust_py_with_cpp_shadow` (rust-py is primary, cpp runs as a sampled shadow). `*_shadow` modes return the primary result and sample-compare against the other parser, reporting divergences without failing the request. The `rust_py_*` modes drive the same hand-rolled Rust parser as `rust_*` but build `posthog.hogql.ast` dataclass instances directly via PyO3, skipping the JSON round-trip. */+ parserMode?: ParserModeApi | null+ /** Push an `id IN (SELECT person_id FROM <left table> WHERE …)` predicate into the joined persons subquery, so the latest-version lookup only reads persons that the outer query's left-table filters can reach. Applies only to a persons join from the query's own FROM table. */+ personIdPushdown?: boolean | null+ personsArgMaxVersion?: PersonsArgMaxVersionApi | null+ personsJoinMode?: PersonsJoinModeApi | null+ personsOnEventsMode?: PersonsOnEventsModeApi | null+ propertyGroupsMode?: PropertyGroupsModeApi | null+ pushDownPredicates?: boolean | null+ s3TableUseInvalidColumns?: boolean | null+ /** Push a `session_id_v7 IN (SELECT … FROM events WHERE …)` predicate into the raw_sessions subquery to limit aggregation to sessions that participate in the outer events filter. */+ sessionIdPushdown?: boolean | null+ /** Pre-filter raw_sessions aggregation by `session_id_v7 IN (cheap pre-aggregation that only materializes the columns referenced by the outer-WHERE session predicate)`. Useful when the breakdown/SELECT pulls in many session columns (e.g. `$channel_type`) but the filter only references one (e.g. `$entry_current_url`). */+ sessionPropertyPreAggregation?: boolean | null+ sessionTableVersion?: SessionTableVersionApi | null+ sessionsV2JoinMode?: SessionsV2JoinModeApi | null+ timings?: boolean | null+ /** Remove provably redundant casts and nullability wrappers (e.g. `toString(String)`, `assumeNotNull(non_nullable)`, dead `ifNull` fallbacks) using inferred expression types */+ typeAwareCastSimplification?: boolean | null+ useMaterializedViews?: boolean | null+ /** Read events from the native JSON events table (`true`) or the legacy events table (`false`). When unset, the project's stored value applies, then the `CLICKHOUSE_HOGQL_USE_NEW_EVENTS_SCHEMA` instance settings. This is an internal rollout switch. PostHog staff set the project value in Django admin and the project settings API ignores it. */+ useNewEventsSchema?: boolean | null+ usePreaggregatedIntermediateResults?: boolean | null+ /** Try to automatically convert HogQL queries to use preaggregated tables at the AST level * */+ usePreaggregatedTableTransforms?: boolean | null+ useWebAnalyticsPreAggregatedTables?: boolean | null+ /** Serve filters on the stored session-entry attribution properties (`$channel_type`, `$entry_utm_*`, `$entry_referring_domain`) by recomputing the value from the session's first pageview. Resolved server-side; not intended to be set by clients. */+ webAnalyticsFirstPageviewFilters?: boolean | null+}++export type MarketingAnalyticsOrderByEnumApi =+ (typeof MarketingAnalyticsOrderByEnumApi)[keyof typeof MarketingAnalyticsOrderByEnumApi]++export const MarketingAnalyticsOrderByEnumApi = {+ Asc: 'ASC',+ Desc: 'DESC',+} as const++export interface ClickhouseQueryProgressApi {+ active_cpu_time: number+ bytes_read: number+ estimated_rows_total: number+ rows_read: number+ time_elapsed: number+}++export type QueryScanFixLocationApi = (typeof QueryScanFixLocationApi)[keyof typeof QueryScanFixLocationApi]++export const QueryScanFixLocationApi = {+ Query: 'query',+ Subquery: 'subquery',+ View: 'view',+ InsightDateRange: 'insight_date_range',+ DashboardDateFilter: 'dashboard_date_filter',+} as const++export type QueryScanFindingKindApi = (typeof QueryScanFindingKindApi)[keyof typeof QueryScanFindingKindApi]++export const QueryScanFindingKindApi = {+ NoEventFilter: 'no_event_filter',+ NoStartDate: 'no_start_date',+ PersonsJoin: 'persons_join',+} as const++export interface QueryScanWarningApi {+ /** Whether the person can change the query so it reads less and still answers the same question. Surfaces show the full advice and "Fix with AI" only when a finding is actionable. */+ actionable: boolean+ /** True when the query reads this much on purpose, so reading less would change the answer. Absent means no. */+ by_design?: boolean | null+ /** A label for what in the query text kept the read wide, such as `in_or`. Only analytics and the assistant read it, and the labels can change. */+ cause?: string | null+ /** The one fact the finding rests on. */+ evidence?: string | null+ /** What "Fix with AI" and the assistant are told to do. */+ fix: string+ /** Where the change goes. Absent means the query itself. */+ fix_location?: QueryScanFixLocationApi | null+ kind: QueryScanFindingKindApi+ /** Shown to the person: what happened and what to do. */+ message: string+}++export interface QueryScanAnalysisApi {+ /** The message the Fix with AI button sends to the assistant. Absent when no finding can be fixed in the query. */+ assistant_prompt?: string | null+ /** Every finding, fixable or not. Empty when the analysis found none. */+ findings: QueryScanWarningApi[]+ /** How much of all the project's events the query read, 0 to 1. */+ project_share?: number | null+ /** How much of the project's events in the query's date range the query read, 0 to 1. */+ range_share?: number | null+}++export interface QueryScanSummaryApi {+ /** The stored analysis, put on the response when it is served. Absent while the analysis runs, and when none was requested. */+ analysis?: QueryScanAnalysisApi | null+ /** True when the run asked for an analysis, or found one stored. While `analysis` is absent, poll `GET /query/scan/{cache_key}` for it. */+ analysis_requested?: boolean | null+ /** ClickHouse time for the last fresh run, summed over its ClickHouse queries. */+ duration_ms: number+ /** True when ClickHouse stopped the run instead of finishing it. */+ killed?: boolean | null+ /** Rows ClickHouse read for the last fresh run, all tables included. */+ rows_read: number+}++export interface QueryStatusApi {+ budget_remaining_bytes?: number | null+ bytes_read?: number | null+ /** Cache key of the run that failed, so clients can ask for its query scan. */+ cache_key?: string | null+ /** Whether the query is still running. Will be true if the query is complete, even if it errored. Either result or error will be set. */+ complete?: boolean | null+ dashboard_id?: number | null+ /** When did the query execution task finish (whether successfully or not). */+ end_time?: string | null+ /** If the query failed, this will be set to true. More information can be found in the error_message field. */+ error?: boolean | null+ /** Stable machine-readable code for the error (the DRF exception code), when known. */+ error_code?: string | null+ error_message?: string | null+ expiration_time?: string | null+ id: string+ insight_id?: number | null+ labels?: string[] | null+ /** When was the query execution task picked up by a worker. */+ pickup_time?: string | null+ /** ONLY async queries use QueryStatus. */+ query_async?: true+ query_progress?: ClickhouseQueryProgressApi | null+ query_scan?: QueryScanSummaryApi | null+ results?: unknown+ /** When was query execution task enqueued. */+ start_time?: string | null+ task_id?: string | null+ team_id: number+}++export interface ResolvedDateRangeResponseApi {+ date_from: string+ date_to: string+}++export type WebAnalyticsItemKindApi = (typeof WebAnalyticsItemKindApi)[keyof typeof WebAnalyticsItemKindApi]++export const WebAnalyticsItemKindApi = {+ Unit: 'unit',+ DurationS: 'duration_s',+ Percentage: 'percentage',+ Currency: 'currency',+} as const++export interface MarketingAnalyticsItemApi {+ changeFromPreviousPct?: number | null+ hasComparison?: boolean | null+ isIncreaseBad?: boolean | null+ key: string+ kind: WebAnalyticsItemKindApi+ previous?: number | string | null+ value?: number | string | null+}++export interface SamplingRateApi {+ denominator?: number | null+ numerator: number+}++export interface QueryTimingApi {+ /** Key. Shortened to 'k' to save on data. */+ k: string+ /** Time in seconds. Shortened to 't' to save on data. */+ t: number+}++export interface DataWarehouseSourceUsageApi {+ /** ExternalDataSource id */+ id: string+ /** Connector type of the source (e.g. Stripe, Postgres), if known */+ source_type?: string | null+ /** Warehouse table name that was referenced */+ table_name: string+}++export interface DataWarehouseSyncWarningApi {+ /** Human-readable warning shown to the user */+ message: string+ /** Name of the ExternalDataSchema responsible for syncing the table */+ schema_name: string+ /** ID of the ExternalDataSource, used to link to its management page. Null for self-managed tables. */+ source_id?: string | null+ /** Source type, e.g. "Stripe", "Hubspot" */+ source_type: string+ /** Sync status that triggered the warning, e.g. "Failed", "Paused", "BillingLimitReached" */+ status: string+ /** Name of the warehouse table the warning refers to */+ table_name: string+ /** Tells warning kinds apart in the shared `warnings` list */+ type?: 'warehouse_sync'+}++export interface AccessControlFilterWarningApi {+ /** Human-readable warning shown to the user */+ message: string+ /** Resource types the user has access restrictions on, referenced by the query, e.g. ["insight", "dashboard"] */+ resources: string[]+ /** Tells warning kinds apart in the shared `warnings` list */+ type?: 'access_control'+}++export interface MarketingAnalyticsTableQueryResponseApi {+ columns?: unknown[] | null+ /** ISO timestamp of the oldest precompute window backing this result — surfaced as "data as of X". */+ dataComputedAt?: string | null+ /** Query error. Returned only if 'explain' or `modifiers.debug` is true. Throws an error otherwise. */+ error?: string | null+ hasMore?: boolean | null+ /** Generated HogQL query. */+ hogql?: string | null+ limit?: number | null+ /** Modifiers used when performing the query */+ modifiers?: HogQLQueryModifiersApi | null+ offset?: number | null+ /** True when a conversion goal's precompute has not been warmed for this window yet — the UI shows a "computing" state rather than empty results. Marketing analytics serves exclusively from precompute. */+ precomputeNotReady?: boolean | null+ /** Query status indicates whether next to the provided data, a query is still running. */+ query_status?: QueryStatusApi | null+ /** The resolved previous/comparison period date range, when comparing against another period */+ resolved_compare_date_range?: ResolvedDateRangeResponseApi | null+ /** The date range used for the query */+ resolved_date_range?: ResolvedDateRangeResponseApi | null+ results: MarketingAnalyticsItemApi[][]+ samplingRate?: SamplingRateApi | null+ /** Measured timings for different parts of the query generation process */+ timings?: QueryTimingApi[] | null+ types?: unknown[] | null+ /** Connector-synced data warehouse sources referenced by this query, if any. */+ used_data_warehouse_sources?: DataWarehouseSourceUsageApi[] | null+ /** Warnings about data warehouse sources referenced by the query whose latest sync failed, is paused, hit a billing limit, or is otherwise stale. Results may not reflect current source data. Accumulated across every HogQL execution that contributes to this response — so insights backed by warehouse tables (Trends, Funnels, etc.) receive the same warnings as raw HogQL queries. Also carries access control warnings when a system-table query filters out objects the user can't access. */+ warnings?: (DataWarehouseSyncWarningApi | AccessControlFilterWarningApi)[] | null+}++export interface WebAnalyticsSamplingApi {+ enabled?: boolean | null+ forceSamplingRate?: SamplingRateApi | null+}++export interface QueryLogTagsApi {+ /** Name of the query, preferably unique. For example web_analytics_vitals */+ name?: string | null+ /** Short id of the saved Web analytics filter preset this query was run under, if any. */+ presetId?: string | null+ /** Product responsible for this query. Use string, there's no need to churn the Schema when we add a new product * */+ productKey?: string | null+ /** Scene where this query is shown in the UI. Use string, there's no need to churn the Schema when we add a new Scene * */+ scene?: string | null+}++export interface MarketingAnalyticsTableQueryApi {+ /** Groups aggregation - not used in Web Analytics but required for type compatibility */+ aggregation_group_type_index?: number | null+ /** Compare to date range */+ compareFilter?: CompareFilterApi | null+ conversionGoal?: ActionConversionGoalApi | CustomEventConversionGoalApi | null+ /** Colors used in the insight's visualization - not used in Web Analytics but required for type compatibility */+ dataColorTheme?: number | null+ dateRange?: DateRangeApi | null+ doPathCleaning?: boolean | null+ /** Draft conversion goal that can be set in the UI without saving */+ draftConversionGoal?: ConversionGoalFilter1Api | ConversionGoalFilter2Api | ConversionGoalFilter3Api | null+ /** Drill-down hierarchy level: channel, source, or campaign (default) */+ drillDownLevel?: MarketingAnalyticsDrillDownLevelApi | null+ /** Filter test accounts */+ filterTestAccounts?: boolean | null+ includeRevenue?: boolean | null+ /** Filter by integration type */+ integrationFilter?: IntegrationFilterApi | null+ /** Interval for date range calculation (affects date_to rounding for hour vs day ranges) */+ interval?: IntervalTypeApi | null+ kind?: 'MarketingAnalyticsTableQuery'+ /** Number of rows to return */+ limit?: number | null+ /** Modifiers used when performing the query */+ modifiers?: HogQLQueryModifiersApi | null+ /** Number of rows to skip before returning rows */+ offset?: number | null+ /** Columns to order by - similar to EventsQuery format */+ orderBy?: (string | MarketingAnalyticsOrderByEnumApi)[][] | null+ properties: (+ | EventPropertyFilterApi+ | PersonPropertyFilterApi+ | SessionPropertyFilterApi+ | CohortPropertyFilterApi+ )[]+ response?: MarketingAnalyticsTableQueryResponseApi | null+ sampling?: WebAnalyticsSamplingApi | null+ /** Sampling rate */+ samplingFactor?: number | null+ /** Return a limited set of data. Will use default columns if empty. */+ select?: string[] | null+ tags?: QueryLogTagsApi | null+ useSessionsTable?: boolean | null+ /** version of the node, used for schema migrations */+ version?: number | null+}++export interface ConversionRecordingsRequestApi {+ /** A unique query ID for tracing this request in query logs. */+ client_query_id?: string+ /** The table query whose conversion cell was selected. */+ source: MarketingAnalyticsTableQueryApi+ /** The selected conversion goal ID. */+ goal_id: string+ /** The displayed row grouping value. */+ group: string+ /** The displayed row source. */+ source_name?: string+ /**+ * The displayed campaign ID, omitted for comparison rows.+ * @nullable+ */+ campaign_id?: string | null+ /**+ * The last session ID returned by the previous page. Omit for the first page.+ * @maxLength 200+ */+ after?: string+ /**+ * The maximum number of conversion session IDs to return.+ * @minimum 1+ * @maximum 100+ */+ limit?: number+}++export interface ConversionRecordingsResponseApi {+ /** Sessions in which the attributed conversions occurred. A session might not have a recording. */+ session_ids: string[]+ /** Whether another page of conversion sessions is available. */+ has_more: boolean+ /** Whether the conversion data is still being prepared. */+ preparing: boolean+}+export interface RequiredTableStatusApi {/** Name of the required source table (e.g. 'campaign', 'campaign_stats') */table_name: stringdiff --git a/products/marketing_analytics/frontend/generated/api.ts b/products/marketing_analytics/frontend/generated/api.tsindex 1c618f7589ab..f33257e2d53d 100644--- a/products/marketing_analytics/frontend/generated/api.ts+++ b/products/marketing_analytics/frontend/generated/api.ts@@ -14,6 +14,8 @@ import type {ConversionGoalWriteApi,ConversionGoalWriteResponseApi,ConversionGoalsListResponseApi,+ ConversionRecordingsRequestApi,+ ConversionRecordingsResponseApi,DataSourceHealthResponseApi,EventSuggestionsResponseApi,GoalExplanationApi,@@ -142,6 +144,23 @@ export const marketingAnalyticsConversionGoalsCreateCreate = async (})}+export const getMarketingAnalyticsConversionRecordingsListUrl = (projectId: string) => {+ return `/api/projects/${projectId}/marketing_analytics/conversion_recordings/`+}++export const marketingAnalyticsConversionRecordingsList = async (+ projectId: string,+ conversionRecordingsRequestApi: ConversionRecordingsRequestApi,+ options?: RequestInit+): Promise<ConversionRecordingsResponseApi> => {+ return apiMutator<ConversionRecordingsResponseApi>(getMarketingAnalyticsConversionRecordingsListUrl(projectId), {+ ...options,+ method: 'POST',+ headers: { 'Content-Type': 'application/json', ...options?.headers },+ body: JSON.stringify(conversionRecordingsRequestApi),+ })+}+export const getMarketingAnalyticsDataSourcesRetrieveUrl = (projectId: string,params?: MarketingAnalyticsDataSourcesRetrieveParamsdiff --git a/products/marketing_analytics/frontend/generated/api.zod.ts b/products/marketing_analytics/frontend/generated/api.zod.tsindex 69fe3bf8b1f6..a81d920281fa 100644--- a/products/marketing_analytics/frontend/generated/api.zod.ts+++ b/products/marketing_analytics/frontend/generated/api.zod.ts@@ -45,3 +45,7 @@ export const MarketingAnalyticsConversionGoalsUpdatePartialUpdateBody = /* @__PUexport const MarketingAnalyticsConversionGoalsCreateCreateBody = /* @__PURE__ */ zod.record(zod.string(), zod.unknown()).describe('Deep\/recursive schema (opaque in Zod — use TypeScript types for full shape)')++export const MarketingAnalyticsConversionRecordingsListBody = /* @__PURE__ */ zod+ .record(zod.string(), zod.unknown())+ .describe('Deep\/recursive schema (opaque in Zod — use TypeScript types for full shape)')diff --git a/products/marketing_analytics/mcp/tools.yaml b/products/marketing_analytics/mcp/tools.yamlindex d8226f9a5198..cfd01d355201 100644--- a/products/marketing_analytics/mcp/tools.yaml+++ b/products/marketing_analytics/mcp/tools.yaml@@ -30,6 +30,9 @@ tools:events_with_unmatched_utm_source (add a custom source mapping). is_approximate is true when the 30d countmay differ from the dashboard's attribution-windowed number.feature_flag: marketing-analytics-mcp+ marketing-analytics-conversion-recordings-list:+ operation: marketing_analytics_conversion_recordings_list+ enabled: falsemarketing-analytics-create-conversion-goal:operation: marketing_analytics_conversion_goals_create_createenabled: truediff --git a/products/marketing_analytics/package.json b/products/marketing_analytics/package.jsonindex e2992c47e3fa..cf09ef590ffd 100644--- a/products/marketing_analytics/package.json+++ b/products/marketing_analytics/package.json@@ -6,8 +6,12 @@"dependencies": {"@posthog/quill-charts": "workspace:*","kea": "catalog:",+ "kea-loaders": "catalog:","kea-subscriptions": "catalog:"},+ "devDependencies": {+ "kea-test-utils": "catalog:"+ },"peerDependencies": {"@posthog/brand": "catalog:","@posthog/icons": "catalog:",diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.tsindex 4fca1f346e31..560cf1c91ce9 100644--- a/services/mcp/src/api/generated.ts+++ b/services/mcp/src/api/generated.ts@@ -24750,6 +24750,44 @@ export namespace Schemas {Automatic: 'automatic',} as const;+ export interface ConversionRecordingsRequest {+ /** A unique query ID for tracing this request in query logs. */+ client_query_id?: string;+ /** The table query whose conversion cell was selected. */+ source: MarketingAnalyticsTableQuery;+ /** The selected conversion goal ID. */+ goal_id: string;+ /** The displayed row grouping value. */+ group: string;+ /** The displayed row source. */+ source_name?: string;+ /**+ * The displayed campaign ID, omitted for comparison rows.+ * @nullable+ */+ campaign_id?: string | null;+ /**+ * The last session ID returned by the previous page. Omit for the first page.+ * @maxLength 200+ */+ after?: string;+ /**+ * The maximum number of conversion session IDs to return.+ * @minimum 1+ * @maximum 100+ */+ limit?: number;+ }++ export interface ConversionRecordingsResponse {+ /** Sessions in which the attributed conversions occurred. A session might not have a recording. */+ session_ids: string[];+ /** Whether another page of conversion sessions is available. */+ has_more: boolean;+ /** Whether the conversion data is still being prepared. */+ preparing: boolean;+ }+/*** * `0` - Disabled* * `1` - Stateless