Skip to content

:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.

feat(growth): add identity matching job and review screen (#62815)

Fernando Gomes9ff4c00c1140
diff --git a/frontend/package.json b/frontend/package.json
index 421e1c2bcf34..eaa4504d7a06 100644
--- a/frontend/package.json
+++ b/frontend/package.json
@@ -93,6 +93,7 @@
"@posthog/products-feature-flags": "workspace:*",
"@posthog/products-games": "workspace:*",
"@posthog/products-groups": "workspace:*",
+ "@posthog/products-growth": "workspace:*",
"@posthog/products-legal-documents": "workspace:*",
"@posthog/products-links": "workspace:*",
"@posthog/products-live-debugger": "workspace:*",
diff --git a/frontend/snapshots.yml b/frontend/snapshots.yml
index a9ed39e64299..3bffe66f9e80 100644
--- a/frontend/snapshots.yml
+++ b/frontend/snapshots.yml
@@ -5280,6 +5280,14 @@ snapshots:
hash: v1.k794b7964.ccbdd94e59c1029a025b82b148e055fc0f95bbf3d9b22c2e9ec0f6056d573e5b.NZwaV6bkwoSS9a6zSlfpSKp-RCZwNns1fXt5iZawOgI
scenes-app-hogfunctions-destination--runs-with-data--light:
hash: v1.k794b7964.0096a479368226c8e814746b035ce360a9345b27a081ffc2083cf6e855489432.jMrGy2vE-erlaH_1tAskw0DDuKX-SdTXXjE32rc2uI0
+ scenes-app-identitymatching--identity-matching-empty--dark:
+ hash: v1.k794b7964.b5481dc731aaa83da41edb92da53e26a902347717ef2cdc767b04947b135ba5e.dqnfFqc3D6LKMjv4l5njc7rEoB7lVHmoVCwLA2QG3m0
+ scenes-app-identitymatching--identity-matching-empty--light:
+ hash: v1.k794b7964.f9926a29648e70aaefabb52cc8f2873645d10ff68c5b35a86b53301649c3fc76._-1oLavqCmpFtryme0wGVYBvA6caczdWrxatH__KCb8
+ scenes-app-identitymatching--identity-matching-links--dark:
+ hash: v1.k794b7964.29928880970e5313fd6c9f06c85ee39905703aa53ec5c8c2eb021a53cb050227.4YKf3mh2oPrqZtVLiELhmpjM9LuLnOIh91axiijwv2o
+ scenes-app-identitymatching--identity-matching-links--light:
+ hash: v1.k794b7964.2c62a943d44f752fa95427494501ad9f279c7fae50fbb668b48c9117e8c65bea.rIglwzOhQ9f_LwJY6srygYhwZEJuvhY94RN4rDix7WQ
scenes-app-inbox-badges--all-badges--dark:
hash: v1.k794b7964.51fa6006ad07b02e6f11a352d76e9c401efd4445bd42d873081e7e7689aa14e0.okUTzDeF87AijpmaUtUxy65qKVS502E1-Eo1nXh10XE
scenes-app-inbox-badges--all-badges--light:
diff --git a/frontend/src/lib/constants.tsx b/frontend/src/lib/constants.tsx
index 35bc26fe47ff..18e4d63cdc18 100644
--- a/frontend/src/lib/constants.tsx
+++ b/frontend/src/lib/constants.tsx
@@ -321,6 +321,8 @@ export const FEATURE_FLAGS = {
HACKATHONS_SUBSCRIPTIONS: 'hackathons_subscriptions', // owner: #team-analytics-platform, gates listing subscription delivery history and AI change summaries
HEALTH_ALERTS: 'health-alerts', // owner: #team-growth, gates the central /health/alerts scene and per-page Alerts buttons
HEALTH_ASK_AI: 'health-ask-ai', // owner: @jordanm-posthog #team-web-analytics, gates the "Ask PostHog AI" buttons on the Health overview
+ IDENTITY_MATCHING: 'identity-matching', // owner: #team-growth
+ INSIGHT_SUBSCRIBE_PROMINENT_BUTTON: 'insight-subscribe-prominent-button', // owner: @mattp #team-analytics-platform multivariate=control,test
INTER_PROJECT_TRANSFERS: 'inter-project-transfers', // owner: @reecejones #team-platform-features
JS_SNIPPET_VERSIONING: 'js-snippet-versioning', // owner: #team-client-libraries
LEGAL_DOCUMENTS: 'legal-documents', // owner: @rafaeelaudibert #team-growth
diff --git a/frontend/src/products.json b/frontend/src/products.json
index 19b18d91e254..7bd8d848c51e 100644
--- a/frontend/src/products.json
+++ b/frontend/src/products.json
@@ -140,6 +140,13 @@
"type": "feature_flag",
"intents": ["feature_flags", "experiments", "early_access_features"]
},
+ {
+ "path": "Identity matching",
+ "category": "Unreleased",
+ "iconType": "persons",
+ "type": null,
+ "intents": ["marketing_analytics"]
+ },
{ "path": "Links", "category": "Unreleased", "iconType": null, "type": "link", "intents": ["links"] },
{
"path": "Live Debugger",
diff --git a/frontend/src/products.tsx b/frontend/src/products.tsx
index a9cfed57648e..ab6fc12757cb 100644
--- a/frontend/src/products.tsx
+++ b/frontend/src/products.tsx
@@ -117,6 +117,7 @@ export const productScenes: Record<string, () => Promise<any>> = {
FeatureFlagTemplates: () => import('../../products/feature_flags/frontend/FeatureFlagTemplatesScene'),
Game368Hedgehogs: () => import('../../products/games/368Hedgehogs/368Hedgehogs'),
FlappyHog: () => import('../../products/games/FlappyHog/FlappyHog'),
+ IdentityMatching: () => import('../../products/growth/frontend/IdentityMatchingScene'),
LegalDocuments: () => import('../../products/legal_documents/frontend/scenes/LegalDocumentsScene'),
LegalDocumentNew: () => import('../../products/legal_documents/frontend/scenes/LegalDocumentNewScene'),
Links: () => import('../../products/links/frontend/LinksScene'),
@@ -248,6 +249,7 @@ export const productRoutes: Record<string, [string, string]> = {
'/feature_flags/templates': ['FeatureFlagTemplates', 'featureFlagTemplates'],
'/games/368hedgehogs': ['Game368Hedgehogs', 'game368Hedgehogs'],
'/games/flappyhog': ['FlappyHog', 'flappyHog'],
+ '/identity-matching': ['IdentityMatching', 'identityMatching'],
'/legal': ['LegalDocuments', 'legalDocuments'],
'/legal/new/:type': ['LegalDocumentNew', 'legalDocumentNew'],
'/links': ['Links', 'links'],
@@ -658,6 +660,14 @@ export const productConfiguration: Record<string, any> = {
FeatureFlagTemplates: { projectBased: true, name: 'Feature flag templates' },
Game368Hedgehogs: { name: '368Hedgehogs', projectBased: true, activityScope: 'Games' },
FlappyHog: { name: 'FlappyHog', projectBased: true, activityScope: 'Games' },
+ IdentityMatching: {
+ name: 'Identity matching',
+ projectBased: true,
+ activityScope: 'IdentityMatching',
+ description:
+ 'Review probable links between anonymous visitors and identified persons, recovered from first-party signals.',
+ iconType: 'persons',
+ },
LegalDocuments: {
name: 'Legal documents',
organizationBased: true,
@@ -1080,6 +1090,7 @@ export const productUrls = {
groupsNew: (groupTypeIndex: string | number): string => `/groups/${groupTypeIndex}/new`,
group: (groupTypeIndex: string | number, groupKey: string, encode: boolean = true, tab?: string | null): string =>
`/groups/${groupTypeIndex}/${encode ? encodeURIComponent(groupKey) : groupKey}${tab ? `/${tab}` : ''}`,
+ identityMatching: (): string => '/identity-matching',
legalDocuments: (): string => '/legal',
legalDocumentNew: (type: 'BAA' | 'DPA'): string => `/legal/new/${type.toLowerCase()}`,
links: (): string => '/links',
@@ -1788,6 +1799,17 @@ export const getTreeItemsProducts = (): FileSystemImport[] => [
sceneKey: 'Heatmaps',
sceneKeys: ['Heatmaps'],
},
+ {
+ path: 'Identity matching',
+ intents: [ProductKey.MARKETING_ANALYTICS],
+ category: ProductItemCategory.UNRELEASED,
+ href: urls.identityMatching(),
+ flag: FEATURE_FLAGS.IDENTITY_MATCHING,
+ tags: ['alpha'],
+ iconType: 'persons',
+ sceneKey: 'IdentityMatching',
+ sceneKeys: ['IdentityMatching'],
+ },
{
path: 'LLM analytics',
displayLabel: 'AI observability',
diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml
index 9ebf7b805271..2e0f2e689c84 100644
--- a/pnpm-lock.yaml
+++ b/pnpm-lock.yaml
@@ -363,7 +363,7 @@ importers:
version: 0.25.12
jest:
specifier: ^29.7.0
puppeteer:
specifier: 19.0.0
version: 19.0.0([email protected])
@@ -678,6 +678,9 @@ importers:
'@posthog/products-groups':
specifier: workspace:*
version: link:../products/groups
+ '@posthog/products-growth':
+ specifier: workspace:*
+ version: link:../products/growth
'@posthog/products-legal-documents':
specifier: workspace:*
version: link:../products/legal_documents
@@ -2561,7 +2564,7 @@ importers:
version: 8.57.0
jest:
specifier: '*'
kea:
specifier: 'catalog:'
version: 4.0.0-pre.5([email protected])
@@ -3291,7 +3294,35 @@ importers:
specifier: 18.3.1
version: 18.3.1
- products/growth: {}
+ products/growth:
+ dependencies:
+ '@posthog/icons':
+ specifier: '*'
+ '@storybook/react':
+ specifier: 'catalog:'
+ '@types/react':
+ specifier: 18.3.27
+ version: 18.3.27
+ clsx:
+ specifier: '*'
+ version: 2.1.1
+ jest:
+ specifier: '*'
+ kea:
+ specifier: 'catalog:'
+ version: 4.0.0-pre.5([email protected])
+ kea-loaders:
+ specifier: 'catalog:'
+ react:
+ specifier: 18.3.1
+ version: 18.3.1
+ typescript:
+ specifier: 6.0.3
+ version: 6.0.3
products/legal_documents:
dependencies:
@@ -4064,7 +4095,7 @@ importers:
version: 1.2.1
jest:
specifier: '*'
kea:
specifier: 'catalog:'
version: 4.0.0-pre.5([email protected])
@@ -26951,6 +26982,41 @@ snapshots:
- ts-node
- utf-8-validate
+ dependencies:
+ '@jest/console': 29.7.0
+ '@jest/reporters': 29.7.0
+ '@jest/test-result': 29.7.0
+ '@jest/transform': 29.7.0
+ '@jest/types': 29.6.3
+ '@types/node': 22.18.8
+ ansi-escapes: 4.3.2
+ chalk: 4.1.2
+ ci-info: 3.8.0
+ exit: 0.1.2
+ graceful-fs: 4.2.11
+ jest-changed-files: 29.7.0
+ jest-config: 29.7.0(@types/[email protected])
+ jest-haste-map: 29.7.0
+ jest-message-util: 29.7.0
+ jest-regex-util: 29.6.3
+ jest-resolve: 29.7.0
+ jest-resolve-dependencies: 29.7.0
+ jest-runner: 29.7.0
+ jest-runtime: 29.7.0
+ jest-snapshot: 29.7.0
+ jest-util: 29.7.0
+ jest-validate: 29.7.0
+ jest-watcher: 29.7.0
+ micromatch: 4.0.8
+ pretty-format: 29.7.0
+ slash: 3.0.0
+ strip-ansi: 6.0.1
+ transitivePeerDependencies:
+ - babel-plugin-macros
+ - supports-color
+ - ts-node
+
dependencies:
'@jest/console': 29.7.0
@@ -27092,6 +27158,42 @@ snapshots:
- supports-color
- ts-node
+ dependencies:
+ '@jest/console': 30.0.5
+ '@jest/pattern': 30.0.1
+ '@jest/reporters': 30.0.5
+ '@jest/test-result': 30.0.5
+ '@jest/transform': 30.0.5
+ '@jest/types': 30.0.5
+ '@types/node': 22.18.8
+ ansi-escapes: 4.3.2
+ chalk: 4.1.2
+ ci-info: 4.3.0
+ exit-x: 0.2.2
+ graceful-fs: 4.2.11
+ jest-changed-files: 30.0.5
+ jest-haste-map: 30.0.5
+ jest-message-util: 30.0.5
+ jest-regex-util: 30.0.1
+ jest-resolve: 30.0.5
+ jest-resolve-dependencies: 30.0.5
+ jest-runner: 30.0.5
+ jest-runtime: 30.0.5
+ jest-snapshot: 30.0.5
+ jest-util: 30.0.5
+ jest-validate: 30.0.5
+ jest-watcher: 30.0.5
+ micromatch: 4.0.8
+ pretty-format: 30.0.5
+ slash: 3.0.0
+ transitivePeerDependencies:
+ - babel-plugin-macros
+ - esbuild-register
+ - supports-color
+ - ts-node
+
dependencies:
'@jest/types': 29.6.3
@@ -35270,6 +35372,21 @@ snapshots:
safe-buffer: 5.2.1
sha.js: 2.4.12
+ dependencies:
+ '@jest/types': 29.6.3
+ chalk: 4.1.2
+ exit: 0.1.2
+ graceful-fs: 4.2.11
+ jest-config: 29.7.0
+ jest-util: 29.7.0
+ prompts: 2.4.2
+ transitivePeerDependencies:
+ - '@types/node'
+ - babel-plugin-macros
+ - supports-color
+ - ts-node
+
dependencies:
'@jest/types': 29.6.3
@@ -38511,14 +38628,14 @@ snapshots:
dependencies:
+ '@jest/core': 29.7.0
'@jest/test-result': 29.7.0
'@jest/types': 29.6.3
chalk: 4.1.2
+ create-jest: 29.7.0
exit: 0.1.2
import-local: 3.2.0
+ jest-config: 29.7.0
jest-util: 29.7.0
jest-validate: 29.7.0
yargs: 17.7.2
@@ -38604,6 +38721,25 @@ snapshots:
- supports-color
- ts-node
+ dependencies:
+ '@jest/test-result': 30.0.5
+ '@jest/types': 30.0.5
+ chalk: 4.1.2
+ exit-x: 0.2.2
+ import-local: 3.2.0
+ jest-util: 30.0.5
+ jest-validate: 30.0.5
+ yargs: 17.7.2
+ transitivePeerDependencies:
+ - '@types/node'
+ - babel-plugin-macros
+ - esbuild-register
+ - supports-color
+ - ts-node
+
dependencies:
'@babel/core': 7.29.0
@@ -38638,6 +38774,64 @@ snapshots:
- supports-color
- utf-8-validate
+ dependencies:
+ '@babel/core': 7.29.0
+ '@jest/test-sequencer': 29.7.0
+ '@jest/types': 29.6.3
+ babel-jest: 29.7.0(@babel/[email protected])
+ chalk: 4.1.2
+ ci-info: 3.8.0
+ deepmerge: 4.3.1
+ glob: 7.2.3
+ graceful-fs: 4.2.11
+ jest-circus: 29.7.0
+ jest-environment-node: 29.7.0
+ jest-get-type: 29.6.3
+ jest-regex-util: 29.6.3
+ jest-resolve: 29.7.0
+ jest-runner: 29.7.0
+ jest-util: 29.7.0
+ jest-validate: 29.7.0
+ micromatch: 4.0.8
+ parse-json: 5.2.0
+ pretty-format: 29.7.0
+ slash: 3.0.0
+ strip-json-comments: 3.1.1
+ transitivePeerDependencies:
+ - babel-plugin-macros
+ - supports-color
+
+ dependencies:
+ '@babel/core': 7.29.0
+ '@jest/test-sequencer': 29.7.0
+ '@jest/types': 29.6.3
+ babel-jest: 29.7.0(@babel/[email protected])
+ chalk: 4.1.2
+ ci-info: 3.8.0
+ deepmerge: 4.3.1
+ glob: 7.2.3
+ graceful-fs: 4.2.11
+ jest-circus: 29.7.0
+ jest-environment-node: 29.7.0
+ jest-get-type: 29.6.3
+ jest-regex-util: 29.6.3
+ jest-resolve: 29.7.0
+ jest-runner: 29.7.0
+ jest-util: 29.7.0
+ jest-validate: 29.7.0
+ micromatch: 4.0.8
+ parse-json: 5.2.0
+ pretty-format: 29.7.0
+ slash: 3.0.0
+ strip-json-comments: 3.1.1
+ optionalDependencies:
+ '@types/node': 22.18.8
+ transitivePeerDependencies:
+ - babel-plugin-macros
+ - supports-color
+
dependencies:
'@babel/core': 7.29.0
@@ -38796,6 +38990,74 @@ snapshots:
- babel-plugin-macros
- supports-color
+ dependencies:
+ '@babel/core': 7.29.0
+ '@jest/get-type': 30.0.1
+ '@jest/pattern': 30.0.1
+ '@jest/test-sequencer': 30.0.5
+ '@jest/types': 30.0.5
+ babel-jest: 30.0.5(@babel/[email protected])
+ chalk: 4.1.2
+ ci-info: 4.3.0
+ deepmerge: 4.3.1
+ glob: 10.5.0
+ graceful-fs: 4.2.11
+ jest-circus: 30.0.5
+ jest-docblock: 30.0.1
+ jest-environment-node: 30.0.5
+ jest-regex-util: 30.0.1
+ jest-resolve: 30.0.5
+ jest-runner: 30.0.5
+ jest-util: 30.0.5
+ jest-validate: 30.0.5
+ micromatch: 4.0.8
+ parse-json: 5.2.0
+ pretty-format: 30.0.5
+ slash: 3.0.0
+ strip-json-comments: 3.1.1
+ optionalDependencies:
+ '@types/node': 22.18.8
+ esbuild-register: 3.6.0([email protected])
+ transitivePeerDependencies:
+ - babel-plugin-macros
+ - supports-color
+
+ dependencies:
+ '@babel/core': 7.29.0
+ '@jest/get-type': 30.0.1
+ '@jest/pattern': 30.0.1
+ '@jest/test-sequencer': 30.0.5
+ '@jest/types': 30.0.5
+ babel-jest: 30.0.5(@babel/[email protected])
+ chalk: 4.1.2
+ ci-info: 4.3.0
+ deepmerge: 4.3.1
+ glob: 10.5.0
+ graceful-fs: 4.2.11
+ jest-circus: 30.0.5
+ jest-docblock: 30.0.1
+ jest-environment-node: 30.0.5
+ jest-regex-util: 30.0.1
+ jest-resolve: 30.0.5
+ jest-runner: 30.0.5
+ jest-util: 30.0.5
+ jest-validate: 30.0.5
+ micromatch: 4.0.8
+ parse-json: 5.2.0
+ pretty-format: 30.0.5
+ slash: 3.0.0
+ strip-json-comments: 3.1.1
+ optionalDependencies:
+ '@types/node': 25.8.0
+ esbuild-register: 3.6.0([email protected])
+ transitivePeerDependencies:
+ - babel-plugin-macros
+ - supports-color
+
dependencies:
chalk: 4.1.2
@@ -39679,7 +39941,7 @@ snapshots:
dependencies:
+ '@jest/core': 29.7.0
'@jest/types': 29.6.3
import-local: 3.2.0
jest-cli: 29.7.0
@@ -39738,6 +40000,19 @@ snapshots:
- supports-color
- ts-node
+ dependencies:
+ '@jest/types': 30.0.5
+ import-local: 3.2.0
+ transitivePeerDependencies:
+ - '@types/node'
+ - babel-plugin-macros
+ - esbuild-register
+ - supports-color
+ - ts-node
+
diff --git a/posthog/dags/locations/growth.py b/posthog/dags/locations/growth.py
index 9605fe18d8bc..e11c4f417747 100644
--- a/posthog/dags/locations/growth.py
+++ b/posthog/dags/locations/growth.py
@@ -1,18 +1,30 @@
import dagster
-from products.growth.dags import github_sdk_versions, oauth, team_production_event_activation, user_product_list
+from products.growth.dags import (
+ github_sdk_versions,
+ identity_matching,
+ oauth,
+ team_production_event_activation,
+ user_product_list,
+)
from . import loggers, resources
+jobs = [
+ oauth.oauth_clear_expired_oauth_tokens_job,
+ github_sdk_versions.cache_github_sdk_versions_job,
+ user_product_list.populate_user_product_list_job,
+ user_product_list.sync_colleagues_products_monthly_job,
+ user_product_list.sync_cross_sell_products_monthly_job,
+ team_production_event_activation.detect_first_team_production_event_job,
+]
+# Identity matching processes internal PostHog data that only exists on Cloud US (team 2),
+# so the job is not registered on Cloud EU.
+if identity_matching.is_identity_matching_registered():
+ jobs.append(identity_matching.identity_matching_job)
+
defs = dagster.Definitions(
- jobs=[
- oauth.oauth_clear_expired_oauth_tokens_job,
- github_sdk_versions.cache_github_sdk_versions_job,
- user_product_list.populate_user_product_list_job,
- user_product_list.sync_colleagues_products_monthly_job,
- user_product_list.sync_cross_sell_products_monthly_job,
- team_production_event_activation.detect_first_team_production_event_job,
- ],
+ jobs=jobs,
schedules=[
oauth.oauth_clear_expired_oauth_tokens_schedule,
github_sdk_versions.cache_github_sdk_versions_schedule,
diff --git a/posthog/settings/web.py b/posthog/settings/web.py
index 2d0d80d9190a..096f1d72a589 100644
--- a/posthog/settings/web.py
+++ b/posthog/settings/web.py
@@ -92,6 +92,7 @@ PRODUCTS_APPS = [
"products.managed_migrations.backend.apps.ManagedMigrationsConfig",
"products.replay.backend.apps.ReplayConfig",
"products.cohorts.backend.apps.CohortsConfig",
+ "products.growth.backend.apps.GrowthConfig",
"products.reminders.backend.apps.RemindersConfig",
]
diff --git a/products/growth/backend/api/__init__.py b/products/growth/backend/api/__init__.py
new file mode 100644
index 000000000000..97c1508cda7d
--- /dev/null
+++ b/products/growth/backend/api/__init__.py
@@ -0,0 +1,3 @@
+from products.growth.backend.api.identity_matching import IdentityMatchingLinkViewSet
+
+__all__ = ["IdentityMatchingLinkViewSet"]
diff --git a/products/growth/backend/api/identity_matching.py b/products/growth/backend/api/identity_matching.py
new file mode 100644
index 000000000000..89659be57071
--- /dev/null
+++ b/products/growth/backend/api/identity_matching.py
@@ -0,0 +1,279 @@
+"""Read-only API over the identity matching link tables.
+
+The tables are written by the `identity_matching_job` Dagster job
+(products/growth/dags/identity_matching.py) and only exist once that job has run, so every
+query first checks table existence and degrades to an empty result set.
+"""
+
+from typing import Any
+
+from drf_spectacular.utils import extend_schema, extend_schema_serializer
+from rest_framework import serializers, viewsets
+from rest_framework.decorators import action
+from rest_framework.request import Request
+from rest_framework.response import Response
+
+from posthog.api.routing import TeamAndOrgViewSetMixin
+from posthog.clickhouse.client import sync_execute
+from posthog.permissions import IsStaffUser
+
+from products.growth.backend.constants import (
+ IDENTITY_MATCHING_CANDIDATE_PAIRS_TABLE,
+ IDENTITY_MATCHING_LINKS_TABLE,
+ IDENTITY_MATCHING_TIERS,
+)
+
+MAX_RUNS_LISTED = 50
+
+
+class IdentityMatchingLinkSerializer(serializers.Serializer):
+ job_id = serializers.UUIDField(help_text="Identity matching run that produced this link.")
+ model_version = serializers.CharField(
+ help_text="Scoring model that produced the link, e.g. 'rules_v1' or 'logreg_v1'."
+ )
+ orphan_distinct_id = serializers.CharField(
+ help_text="Anonymous distinct ID that the model linked to an identified person."
+ )
+ anchor_person_key = serializers.CharField(
+ help_text="Canonical distinct ID representing the matched identified person."
+ )
+ score = serializers.FloatField(
+ help_text="Link score: weighted rule points for 'rules_v1', a 0-1 probability for 'logreg_v1'."
+ )
+ margin = serializers.FloatField(help_text="Score margin over the runner-up candidate person for this orphan.")
+ tier = serializers.ChoiceField(
+ choices=IDENTITY_MATCHING_TIERS, help_text="Confidence tier derived from score thresholds."
+ )
+ computed_at = serializers.DateTimeField(help_text="When the link was computed (UTC).")
+ shared_ip_days = serializers.IntegerField(help_text="Distinct (IP, day) combinations both sides were seen on.")
+ shared_ips = serializers.IntegerField(help_text="Distinct IPs both sides were seen on.")
+ min_ip_block_size = serializers.IntegerField(
+ help_text="Device count on the least crowded shared IP-day; small values suggest a household IP."
+ )
+ geo_city_match = serializers.BooleanField(help_text="Both sides were seen in the same city.")
+ timezone_match = serializers.BooleanField(help_text="Both sides reported the same timezone.")
+ language_match = serializers.BooleanField(help_text="Both sides reported the same browser language.")
+ ua_exact_match = serializers.BooleanField(help_text="A byte-identical user agent was seen on both sides.")
+ orphan_is_webview = serializers.BooleanField(
+ help_text="The orphan's traffic came from an in-app browser or webview."
+ )
+ device_type_complement = serializers.BooleanField(help_text="The sides form a mobile + desktop device pair.")
+ days_overlap = serializers.IntegerField(help_text="Number of days on which the two sides shared an IP.")
+ avg_path_jaccard = serializers.FloatField(
+ help_text="Average overlap (0-1) of pages visited by the two sides on shared IP-days."
+ )
+ orphan_paid_touch = serializers.BooleanField(
+ help_text="The orphan arrived via a paid click ID (gclid, li_fat_id, ...) inside the window."
+ )
+ anchor_paid_touch = serializers.BooleanField(
+ help_text="The matched person already had a paid click ID inside the window."
+ )
+
+
+class IdentityMatchingLinksFilterSerializer(serializers.Serializer):
+ job_id = serializers.UUIDField(
+ required=False, help_text="Identity matching run to read. Defaults to the team's most recent run."
+ )
+ model_version = serializers.CharField(
+ required=False, help_text="Only return links produced by this scoring model, e.g. 'rules_v1'."
+ )
+ tier = serializers.ChoiceField(
+ choices=IDENTITY_MATCHING_TIERS, required=False, help_text="Only return links in this confidence tier."
+ )
+ min_score = serializers.FloatField(required=False, help_text="Only return links with a score at or above this.")
+ search = serializers.CharField(
+ required=False,
+ help_text="Case-insensitive substring match on the orphan distinct ID or the matched person key.",
+ )
+ limit = serializers.IntegerField(
+ required=False, default=100, min_value=1, max_value=500, help_text="Page size, at most 500."
+ )
+ offset = serializers.IntegerField(required=False, default=0, min_value=0, help_text="Pagination offset.")
+
+
+# many=False stops drf-spectacular from array-wrapping the list action's envelope response.
+@extend_schema_serializer(many=False)
+class IdentityMatchingLinksResponseSerializer(serializers.Serializer):
+ results = IdentityMatchingLinkSerializer(many=True, help_text="Links ordered by score, descending.")
+ count = serializers.IntegerField(help_text="Total links matching the filters, ignoring pagination.")
+
+
+class IdentityMatchingRunModelCountSerializer(serializers.Serializer):
+ model_version = serializers.CharField(help_text="Scoring model, e.g. 'rules_v1' or 'logreg_v1'.")
+ link_count = serializers.IntegerField(help_text="Number of links this model produced in the run.")
+
+
+class IdentityMatchingRunSerializer(serializers.Serializer):
+ job_id = serializers.UUIDField(help_text="Identity matching run identifier (the Dagster run ID).")
+ computed_at = serializers.DateTimeField(help_text="When the run wrote its links (UTC).")
+ models = IdentityMatchingRunModelCountSerializer(many=True, help_text="Link counts per scoring model in this run.")
+
+
+class IdentityMatchingRunsResponseSerializer(serializers.Serializer):
+ results = IdentityMatchingRunSerializer(many=True, help_text="Runs ordered by recency, most recent first.")
+
+
+class IdentityMatchingLinkViewSet(TeamAndOrgViewSetMixin, viewsets.ViewSet):
+ scope_object = "INTERNAL"
+ # Staff-only while identity matching is under development.
+ permission_classes = [IsStaffUser]
+
+ def _links_table_exists(self) -> bool:
+ [[exists]] = sync_execute(f"EXISTS TABLE {IDENTITY_MATCHING_LINKS_TABLE}")
+ return bool(exists)
+
+ def _latest_job_id(self) -> str | None:
+ rows = sync_execute(
+ f"""
+ SELECT job_id
+ FROM {IDENTITY_MATCHING_LINKS_TABLE}
+ WHERE team_id = %(team_id)s
+ ORDER BY computed_at DESC
+ LIMIT 1
+ """,
+ {"team_id": self.team.pk},
+ )
+ return str(rows[0][0]) if rows else None
+
+ @extend_schema(
+ summary="List identity matching links",
+ description="Scored links between anonymous distinct IDs and identified persons, with the "
+ "evidence behind each link. Produced by the identity matching Dagster job; empty until that "
+ "job has run for this project.",
+ parameters=[IdentityMatchingLinksFilterSerializer],
+ responses={200: IdentityMatchingLinksResponseSerializer},
+ )
+ def list(self, request: Request, **kwargs: Any) -> Response:
+ filters = IdentityMatchingLinksFilterSerializer(data=request.query_params)
+ filters.is_valid(raise_exception=True)
+ params = filters.validated_data
+
+ if not self._links_table_exists():
+ return Response({"results": [], "count": 0})
+
+ job_id = str(params["job_id"]) if params.get("job_id") else self._latest_job_id()
+ if job_id is None:
+ return Response({"results": [], "count": 0})
+
+ conditions = ["lk.team_id = %(team_id)s", "lk.job_id = %(job_id)s"]
+ query_params: dict[str, Any] = {
+ "team_id": self.team.pk,
+ "job_id": job_id,
+ "limit": params["limit"],
+ "offset": params["offset"],
+ }
+ if params.get("model_version"):
+ conditions.append("lk.model_version = %(model_version)s")
+ query_params["model_version"] = params["model_version"]
+ if params.get("tier"):
+ conditions.append("lk.tier = %(tier)s")
+ query_params["tier"] = params["tier"]
+ if params.get("min_score") is not None:
+ conditions.append("lk.score >= %(min_score)s")
+ query_params["min_score"] = params["min_score"]
+ if params.get("search"):
+ conditions.append(
+ "(positionCaseInsensitive(lk.orphan_distinct_id, %(search)s) > 0"
+ " OR positionCaseInsensitive(lk.anchor_person_key, %(search)s) > 0)"
+ )
+ query_params["search"] = params["search"]
+ where = " AND ".join(conditions)
+
+ [[count]] = ( # nosemgrep: clickhouse-fstring-param-audit
+ sync_execute(
+ f"SELECT count() FROM {IDENTITY_MATCHING_LINKS_TABLE} AS lk WHERE {where}",
+ query_params,
+ )
+ )
+ rows = sync_execute( # nosemgrep: clickhouse-fstring-param-audit — constant table names, WHERE built from string literals, values parameterized
+ f"""
+ SELECT
+ lk.job_id,
+ lk.model_version,
+ lk.orphan_distinct_id,
+ lk.anchor_person_key,
+ lk.score,
+ lk.margin,
+ lk.tier,
+ lk.computed_at,
+ p.shared_ip_days,
+ p.shared_ips,
+ p.min_ip_block_size,
+ p.geo_city_match,
+ p.timezone_match,
+ p.language_match,
+ p.ua_exact_match,
+ p.orphan_is_webview,
+ p.device_type_complement,
+ p.days_overlap,
+ p.avg_path_jaccard,
+ p.orphan_paid_touch,
+ p.anchor_paid_touch
+ FROM {IDENTITY_MATCHING_LINKS_TABLE} AS lk
+ LEFT JOIN {IDENTITY_MATCHING_CANDIDATE_PAIRS_TABLE} AS p
+ ON lk.job_id = p.job_id
+ AND lk.team_id = p.team_id
+ AND lk.orphan_distinct_id = p.orphan_distinct_id
+ AND lk.anchor_person_key = p.anchor_person_key
+ WHERE {where}
+ ORDER BY lk.score DESC, lk.orphan_distinct_id, lk.model_version
+ LIMIT %(limit)s OFFSET %(offset)s
+ """,
+ query_params,
+ )
+ field_names = [
+ "job_id",
+ "model_version",
+ "orphan_distinct_id",
+ "anchor_person_key",
+ "score",
+ "margin",
+ "tier",
+ "computed_at",
+ "shared_ip_days",
+ "shared_ips",
+ "min_ip_block_size",
+ "geo_city_match",
+ "timezone_match",
+ "language_match",
+ "ua_exact_match",
+ "orphan_is_webview",
+ "device_type_complement",
+ "days_overlap",
+ "avg_path_jaccard",
+ "orphan_paid_touch",
+ "anchor_paid_touch",
+ ]
+ results = [dict(zip(field_names, row, strict=True)) for row in rows]
+ response = IdentityMatchingLinksResponseSerializer({"results": results, "count": count})
+ return Response(response.data)
+
+ @extend_schema(
+ summary="List identity matching runs",
+ description="Recent identity matching runs for this project with link counts per scoring "
+ "model, most recent first.",
+ responses={200: IdentityMatchingRunsResponseSerializer},
+ )
+ @action(detail=False, methods=["GET"])
+ def runs(self, request: Request, **kwargs: Any) -> Response:
+ if not self._links_table_exists():
+ return Response({"results": []})
+
+ rows = sync_execute(
+ f"""
+ SELECT job_id, max(computed_at) AS computed_at, model_version, count() AS link_count
+ FROM {IDENTITY_MATCHING_LINKS_TABLE}
+ WHERE team_id = %(team_id)s
+ GROUP BY job_id, model_version
+ ORDER BY computed_at DESC
+ """,
+ {"team_id": self.team.pk},
+ )
+ runs: dict[str, dict[str, Any]] = {}
+ for job_id, computed_at, model_version, link_count in rows:
+ run = runs.setdefault(str(job_id), {"job_id": job_id, "computed_at": computed_at, "models": []})
+ run["computed_at"] = max(run["computed_at"], computed_at)
+ run["models"].append({"model_version": model_version, "link_count": link_count})
+ results = list(runs.values())[:MAX_RUNS_LISTED]
+ response = IdentityMatchingRunsResponseSerializer({"results": results})
+ return Response(response.data)
diff --git a/products/growth/backend/api/test_identity_matching.py b/products/growth/backend/api/test_identity_matching.py
new file mode 100644
index 000000000000..66015a6765a1
--- /dev/null
+++ b/products/growth/backend/api/test_identity_matching.py
@@ -0,0 +1,182 @@
+from datetime import UTC, datetime, timedelta
+from typing import Any
+from uuid import uuid4
+
+from posthog.test.base import APIBaseTest
+
+from parameterized import parameterized
+from rest_framework import status
+
+from posthog.clickhouse.client import sync_execute
+
+from products.growth.backend.constants import IDENTITY_MATCHING_CANDIDATE_PAIRS_TABLE, IDENTITY_MATCHING_LINKS_TABLE
+from products.growth.dags.identity_matching import CANDIDATE_PAIRS, LINKS
+
+OTHER_TEAM_ID = 909_090_909
+
+RUN_A = str(uuid4())
+RUN_B = str(uuid4())
+RUN_OTHER_TEAM = str(uuid4())
+
+# Within the tables' 30-day TTL on computed_at; expired rows are dropped by ClickHouse.
+RUN_A_COMPUTED_AT = datetime.now(UTC).replace(microsecond=0) - timedelta(hours=1)
+RUN_B_COMPUTED_AT = datetime.now(UTC).replace(microsecond=0) - timedelta(days=2)
+
+
+class TestIdentityMatchingLinksAPI(APIBaseTest):
+ def setUp(self) -> None:
+ super().setUp()
+ self.user.is_staff = True
+ self.user.save()
+ sync_execute(LINKS.create_sql)
+ sync_execute(CANDIDATE_PAIRS.create_sql)
+
+ def _insert_link(
+ self,
+ team_id: int,
+ job_id: str,
+ orphan: str,
+ anchor: str,
+ score: float = 5.0,
+ tier: str = "high",
+ model_version: str = "rules_v1",
+ computed_at: datetime | None = None,
+ orphan_paid_touch: int = 0,
+ ) -> None:
+ computed_at = computed_at or RUN_A_COMPUTED_AT
+ sync_execute( # nosemgrep: clickhouse-fstring-param-audit — test fixture; constant table name, all values parameterized
+ f"""
+ INSERT INTO {IDENTITY_MATCHING_LINKS_TABLE}
+ (job_id, team_id, model_version, orphan_distinct_id, anchor_person_key, score,
+ runner_up_score, margin, tier, computed_at)
+ VALUES (%(job_id)s, %(team_id)s, %(model_version)s, %(orphan)s, %(anchor)s,
+ %(score)s, 0.0, %(score)s, %(tier)s, %(computed_at)s)
+ """,
+ {
+ "job_id": job_id,
+ "team_id": team_id,
+ "model_version": model_version,
+ "orphan": orphan,
+ "anchor": anchor,
+ "score": score,
+ "tier": tier,
+ "computed_at": computed_at,
+ },
+ )
+ sync_execute( # nosemgrep: clickhouse-fstring-param-audit — test fixture; constant table name, all values parameterized
+ f"""
+ INSERT INTO {IDENTITY_MATCHING_CANDIDATE_PAIRS_TABLE}
+ (job_id, team_id, orphan_distinct_id, anchor_person_key, shared_ip_days, shared_ips,
+ min_ip_block_size, geo_city_match, timezone_match, language_match, ua_exact_match,
+ orphan_is_webview, device_type_complement, days_overlap, orphan_last_to_anchor_first_s,
+ avg_path_jaccard, orphan_paid_touch, anchor_paid_touch, orphan_event_count,
+ anchor_event_count, label, computed_at)
+ VALUES (%(job_id)s, %(team_id)s, %(orphan)s, %(anchor)s, 3, 1, 2, 1, 1, 1, 0, 0, 1, 3,
+ 3600, 0.5, %(orphan_paid_touch)s, 0, 10, 20, -1, %(computed_at)s)
+ """,
+ {
+ "job_id": job_id,
+ "team_id": team_id,
+ "orphan": orphan,
+ "anchor": anchor,
+ "orphan_paid_touch": orphan_paid_touch,
+ "computed_at": computed_at,
+ },
+ )
+
+ def _seed(self) -> None:
+ self._insert_link(self.team.pk, RUN_A, "phone-1", "[email protected]", score=7.0, tier="high")
+ self._insert_link(self.team.pk, RUN_A, "phone-2", "[email protected]", score=4.5, tier="medium", orphan_paid_touch=1)
+ self._insert_link(
+ self.team.pk, RUN_A, "phone-1", "[email protected]", score=0.92, tier="high", model_version="logreg_v1"
+ )
+ # An older run for the same team: must not be returned by default.
+ self._insert_link(
+ self.team.pk,
+ RUN_B,
+ "phone-old",
+ score=3.0,
+ tier="low",
+ computed_at=RUN_B_COMPUTED_AT,
+ )
+ # Another team's rows: must never be visible.
+ self._insert_link(OTHER_TEAM_ID, RUN_OTHER_TEAM, "phone-other-team", "[email protected]", score=9.0)
+
+ def test_lists_latest_run_for_own_team_only(self) -> None:
+ self._seed()
+ response = self.client.get(f"/api/projects/{self.team.pk}/identity_matching_links/")
+ assert response.status_code == status.HTTP_200_OK
+ data = response.json()
+ assert data["count"] == 3
+ orphans = {row["orphan_distinct_id"] for row in data["results"]}
+ assert orphans == {"phone-1", "phone-2"}
+ assert "phone-other-team" not in orphans
+ assert "phone-old" not in orphans
+ assert data["results"][0]["score"] == 7.0 # ordered by score, descending
+ assert data["results"][0]["shared_ip_days"] == 3
+ assert data["results"][0]["geo_city_match"] is True
+ assert data["results"][0]["ua_exact_match"] is False
+
+ def test_specific_run_selectable_via_job_id(self) -> None:
+ self._seed()
+ response = self.client.get(f"/api/projects/{self.team.pk}/identity_matching_links/", {"job_id": RUN_B})
+ assert response.status_code == status.HTTP_200_OK
+ assert {row["orphan_distinct_id"] for row in response.json()["results"]} == {"phone-old"}
+
+ def test_other_team_rows_are_not_reachable_via_job_id(self) -> None:
+ self._seed()
+ response = self.client.get(f"/api/projects/{self.team.pk}/identity_matching_links/", {"job_id": RUN_OTHER_TEAM})
+ assert response.status_code == status.HTTP_200_OK
+ assert response.json() == {"results": [], "count": 0}
+
+ @parameterized.expand(
+ [
+ ({"model_version": "logreg_v1"}, {"phone-1"}),
+ ({"tier": "medium"}, {"phone-2"}),
+ ({"min_score": 5.0}, {"phone-1"}),
+ ({"search": "PHONE-2"}, {"phone-2"}),
+ ({"search": "anna"}, {"phone-1"}),
+ ({"limit": 1}, {"phone-1"}),
+ ]
+ )
+ def test_list_filters(self, params: dict[str, Any], expected_orphans: set[str]) -> None:
+ self._seed()
+ response = self.client.get(f"/api/projects/{self.team.pk}/identity_matching_links/", params)
+ assert response.status_code == status.HTTP_200_OK
+ assert {row["orphan_distinct_id"] for row in response.json()["results"]} == expected_orphans
+
+ def test_invalid_filter_is_rejected(self) -> None:
+ response = self.client.get(f"/api/projects/{self.team.pk}/identity_matching_links/", {"tier": "huge"})
+ assert response.status_code == status.HTTP_400_BAD_REQUEST
+
+ def test_non_staff_user_is_denied(self) -> None:
+ self.user.is_staff = False
+ self.user.save()
+ response = self.client.get(f"/api/projects/{self.team.pk}/identity_matching_links/")
+ assert response.status_code == status.HTTP_403_FORBIDDEN
+ runs_response = self.client.get(f"/api/projects/{self.team.pk}/identity_matching_links/runs/")
+ assert runs_response.status_code == status.HTTP_403_FORBIDDEN
+
+ def test_empty_when_no_runs_exist(self) -> None:
+ response = self.client.get(f"/api/projects/{self.team.pk}/identity_matching_links/")
+ assert response.status_code == status.HTTP_200_OK
+ assert response.json() == {"results": [], "count": 0}
+
+ def test_empty_when_tables_missing(self) -> None:
+ sync_execute(f"DROP TABLE IF EXISTS {IDENTITY_MATCHING_LINKS_TABLE} SYNC")
+ response = self.client.get(f"/api/projects/{self.team.pk}/identity_matching_links/")
+ assert response.status_code == status.HTTP_200_OK
+ assert response.json() == {"results": [], "count": 0}
+ runs_response = self.client.get(f"/api/projects/{self.team.pk}/identity_matching_links/runs/")
+ assert runs_response.status_code == status.HTTP_200_OK
+ assert runs_response.json() == {"results": []}
+
+ def test_runs_lists_link_counts_per_model(self) -> None:
+ self._seed()
+ response = self.client.get(f"/api/projects/{self.team.pk}/identity_matching_links/runs/")
+ assert response.status_code == status.HTTP_200_OK
+ results = response.json()["results"]
+ assert [run["job_id"] for run in results] == [RUN_A, RUN_B]
+ run_a_models = {model["model_version"]: model["link_count"] for model in results[0]["models"]}
+ assert run_a_models == {"rules_v1": 2, "logreg_v1": 1}
diff --git a/products/growth/backend/apps.py b/products/growth/backend/apps.py
new file mode 100644
index 000000000000..843b853fc72d
--- /dev/null
+++ b/products/growth/backend/apps.py
@@ -0,0 +1,7 @@
+from django.apps import AppConfig
+
+
+class GrowthConfig(AppConfig):
+ default_auto_field = "django.db.models.BigAutoField"
+ name = "products.growth.backend"
+ label = "growth"
diff --git a/products/growth/backend/constants.py b/products/growth/backend/constants.py
index 4151d16d5d93..3e9db4b62fe9 100644
--- a/products/growth/backend/constants.py
+++ b/products/growth/backend/constants.py
@@ -52,6 +52,18 @@ class SdkVersionEntry(TypedDict):
count: int
+# Identity matching ClickHouse tables, written by products/growth/dags/identity_matching.py.
+# Live here so the API view doesn't need to import from a Dagster module.
+IDENTITY_MATCHING_DEVICE_DAYS_TABLE = "identity_matching_device_days"
+IDENTITY_MATCHING_PERSON_TIMELINE_TABLE = "identity_matching_person_timeline"
+IDENTITY_MATCHING_CANDIDATE_PAIRS_TABLE = "identity_matching_candidate_pairs"
+IDENTITY_MATCHING_LINKS_TABLE = "identity_matching_links"
+
+IDENTITY_MATCHING_RULES_MODEL_VERSION = "rules_v1"
+IDENTITY_MATCHING_LOGREG_MODEL_VERSION = "logreg_v1"
+IDENTITY_MATCHING_TIERS = ["high", "medium", "low"]
+
+
def github_sdk_versions_key(sdk_type: str) -> str:
return f"github:sdk_versions:{sdk_type}"
diff --git a/products/growth/backend/routes.py b/products/growth/backend/routes.py
new file mode 100644
index 000000000000..3eddb1e05ab1
--- /dev/null
+++ b/products/growth/backend/routes.py
@@ -0,0 +1,9 @@
+from posthog.api.routing import RouterRegistry
+
+from products.growth.backend.api.identity_matching import IdentityMatchingLinkViewSet
+
+
+def register_routes(routers: RouterRegistry) -> None:
+ routers.projects.register(
+ r"identity_matching_links", IdentityMatchingLinkViewSet, "project_identity_matching_links", ["team_id"]
+ )
diff --git a/products/growth/dags/identity_matching.py b/products/growth/dags/identity_matching.py
new file mode 100644
index 000000000000..be546018c655
--- /dev/null
+++ b/products/growth/dags/identity_matching.py
@@ -0,0 +1,1270 @@
+"""Identity matching: link anonymous distinct_ids to identified persons using first-party signals.
+
+Visits from the same human on different devices/browsers produce unlinked anonymous
+distinct_ids, so pre-signup marketing touchpoints (e.g. a paid click on a phone) cannot
+be attributed to the signup that happens on another device. This job scores candidate
+(orphan distinct_id, identified person) links from signals we already store: shared
+IP-days, geo/locale agreement, user-agent and webview signatures, temporal patterns,
+path overlap, and campaign continuity.
+
+Ground truth comes from retroactive merges: an orphan that merges into a person *after*
+the feature window is, at window end, indistinguishable from a permanent orphan, so those
+merges provide labels for training and for precision/recall evaluation without leakage.
+
+The job writes scored links to its own ClickHouse tables (keyed by job_id, 30-day TTL).
+It never writes to the person store: merges are irreversible, links stay reversible and
+analytics-only.
+
+Environment restrictions: the job processes internal PostHog data that only exists on
+Cloud US (team 2). It is not registered on Cloud EU, and on Cloud US it only accepts the
+allowed internal teams; local, dev, and self-hosted environments are unrestricted.
+
+Known limitations:
+- Merges older than `identity_lookback_days` before the window are not visible, so a
+ long-dormant merged distinct_id that reactivates in-window is classified as an orphan.
+- IP-based features require `$ip` on events; teams with IP anonymization enabled will
+ produce empty IP coverage (surfaced loudly in the run report).
+- Tables store raw IPs; they are internal-only and expire via TTL.
+"""
+
+import uuid
+import hashlib
+import datetime
+from collections.abc import Sequence
+from dataclasses import dataclass
+from functools import partial
+from typing import Any
+
+import dagster
+import pydantic
+from clickhouse_driver import Client
+
+from posthog import settings
+from posthog.clickhouse.cluster import ClickhouseCluster
+from posthog.dags.common import JobOwners, settings_with_log_comment
+
+from products.growth.backend.constants import (
+ IDENTITY_MATCHING_CANDIDATE_PAIRS_TABLE,
+ IDENTITY_MATCHING_DEVICE_DAYS_TABLE,
+ IDENTITY_MATCHING_LINKS_TABLE,
+ IDENTITY_MATCHING_LOGREG_MODEL_VERSION,
+ IDENTITY_MATCHING_PERSON_TIMELINE_TABLE,
+ IDENTITY_MATCHING_RULES_MODEL_VERSION,
+)
+
+# Click IDs that indicate a paid ad click, a subset of CAMPAIGN_PROPERTIES
+# (posthog/taxonomy/taxonomy.py) excluding organic/email params like igshid or mc_cid.
+PAID_CLICK_IDS: list[str] = [
+ "gclid",
+ "gad_source",
+ "gclsrc",
+ "dclid",
+ "gbraid",
+ "wbraid",
+ "fbclid",
+ "msclkid",
+ "twclid",
+ "li_fat_id",
+ "ttclid",
+ "rdt_cid",
+ "sccid",
+]
+
+IDENTITY_EVENTS: list[str] = ["$identify", "$create_alias", "$merge_dangerously"]
+
+# In-app browsers and webviews keep their own cookie jar, so ad clicks that open in them
+# are orphaned even on a single device. Byte-identical UA + shared IP is a strong signal.
+# Double backslash: ClickHouse string literals unescape \\ to \, yielding the regex wv\).
+WEBVIEW_UA_REGEX = r"wv\\)|FBAN|FBAV|Instagram|Line/|MicroMessenger|GSA/"
+
+RULES_MODEL_VERSION = IDENTITY_MATCHING_RULES_MODEL_VERSION
+LOGREG_MODEL_VERSION = IDENTITY_MATCHING_LOGREG_MODEL_VERSION
+
+# Numeric pair features, in the column order used for both training and scoring.
+PAIR_FEATURE_COLUMNS: list[str] = [
+ "shared_ip_days",
+ "shared_ips",
+ "min_ip_block_size",
+ "geo_city_match",
+ "timezone_match",
+ "language_match",
+ "ua_exact_match",
+ "orphan_is_webview",
+ "device_type_complement",
+ "days_overlap",
+ "orphan_last_to_anchor_first_s",
+ "avg_path_jaccard",
+ "orphan_paid_touch",
+ "anchor_paid_touch",
+]
+
+DEFAULT_RULE_WEIGHTS: dict[str, float] = {
+ "shared_ip_day": 1.0,
+ "multi_ip": 1.5,
+ "small_block": 1.0,
+ "geo_city": 0.5,
+ "timezone": 0.25,
+ "language": 0.25,
+ "ua_exact": 2.0,
+ "webview_same_ua": 1.5,
+ "device_complement": 0.5,
+ "path_jaccard": 2.0,
+ "paid_continuity": 0.75,
+}
+
+DEVICE_DAYS_TABLE = IDENTITY_MATCHING_DEVICE_DAYS_TABLE
+PERSON_TIMELINE_TABLE = IDENTITY_MATCHING_PERSON_TIMELINE_TABLE
+CANDIDATE_PAIRS_TABLE = IDENTITY_MATCHING_CANDIDATE_PAIRS_TABLE
+LINKS_TABLE = IDENTITY_MATCHING_LINKS_TABLE
+
+# Internal-only data-safety guardrails: the training data lives in the PostHog Cloud US
+# internal project (team 2). The job is not registered on Cloud EU at all, and on Cloud US
+# it refuses to process any other team. Local, dev, and self-hosted are unrestricted.
+PROD_US_ALLOWED_TEAM_IDS: frozenset[int] = frozenset({2})
+
+
+def is_identity_matching_registered() -> bool:
+ return settings.CLOUD_DEPLOYMENT != "EU"
+
+
+def validate_team_allowed(team_id: int) -> None:
+ if settings.CLOUD_DEPLOYMENT == "EU":
+ raise dagster.Failure("Identity matching does not run on PostHog Cloud EU")
+ if settings.CLOUD_DEPLOYMENT == "US" and team_id not in PROD_US_ALLOWED_TEAM_IDS:
+ raise dagster.Failure(
+ f"On PostHog Cloud US identity matching may only process teams "
+ f"{sorted(PROD_US_ALLOWED_TEAM_IDS)}, got team {team_id}"
+ )
+
+
+class IdentityMatchingConfig(dagster.Config):
+ team_id: int = pydantic.Field(description="Team whose events are matched.")
+ date_start: str = pydantic.Field(description="Feature window start (inclusive), YYYY-MM-DD.")
+ date_end: str = pydantic.Field(description="Feature window end (exclusive), YYYY-MM-DD.")
+ eval_horizon_days: int = pydantic.Field(
+ default=14,
+ description="Days after date_end in which merges are used as evaluation labels.",
+ )
+ identity_lookback_days: int = pydantic.Field(
+ default=90,
+ description="Days before date_start to scan identity events for anchor classification.",
+ )
+ included_events: list[str] = pydantic.Field(
+ default=["$pageview", "$screen", "$identify"],
+ description="Events scanned for the device-day index. $identify is included because it "
+ "carries the anchor device's IP at the identification moment.",
+ )
+ ips_per_day_cap: int = pydantic.Field(default=10, description="Max distinct IPs kept per device-day.")
+ paths_per_day_cap: int = pydantic.Field(default=50, description="Max distinct pathnames kept per device-day.")
+ ip_day_block_cap: int = pydantic.Field(
+ default=25,
+ description="(ip, day) blocks with more devices than this are excluded from candidate generation.",
+ )
+ ip_window_device_cap: int = pydantic.Field(
+ default=100,
+ description="IPs seen with more devices than this over the whole window are excluded "
+ "(corporate NAT / CGNAT guard).",
+ )
+ max_candidates_per_orphan: int = pydantic.Field(default=20, description="Max anchor candidates kept per orphan.")
+ max_identity_edges: int = pydantic.Field(default=2_000_000, description="Max identity edges pulled into memory.")
+ rule_weights: dict[str, float] = pydantic.Field(
+ default=DEFAULT_RULE_WEIGHTS,
+ description="Per-signal weights for the rule-based score.",
+ )
+ rule_min_score: float = pydantic.Field(default=3.0, description="Minimum rule score for a link to be kept.")
+ rule_min_margin: float = pydantic.Field(
+ default=1.0,
+ description="Minimum rule-score margin over the runner-up anchor for a link to be kept.",
+ )
+ rule_tier_high: float = pydantic.Field(default=6.0, description="Rule score at or above which tier is 'high'.")
+ rule_tier_medium: float = pydantic.Field(default=4.0, description="Rule score at or above which tier is 'medium'.")
+ rule_thresholds: list[float] = pydantic.Field(
+ default=[2.0, 3.0, 4.0, 5.0, 6.0, 8.0],
+ description="Rule-score thresholds for the evaluation sweep.",
+ )
+ min_training_positives: int = pydantic.Field(
+ default=50,
+ description="Minimum positive labels required to train the logistic regression.",
+ )
+ min_training_negatives: int = pydantic.Field(
+ default=20,
+ description="Minimum hard-negative labels required to train the logistic regression.",
+ )
+ max_training_rows: int = pydantic.Field(default=500_000, description="Max labeled rows pulled for training.")
+ max_scoring_rows: int = pydantic.Field(default=2_000_000, description="Max candidate rows pulled for scoring.")
+ weak_negative_sample_ratio: float = pydantic.Field(
+ default=3.0,
+ description="Unlabeled pairs sampled as weak negatives, per labeled row.",
+ )
+ prob_thresholds: list[float] = pydantic.Field(
+ default=[0.5, 0.6, 0.7, 0.8, 0.9, 0.95],
+ description="Probability thresholds for the evaluation sweep.",
+ )
+ prob_tier_high: float = pydantic.Field(default=0.9, description="Probability at or above which tier is 'high'.")
+ prob_tier_medium: float = pydantic.Field(default=0.7, description="Probability at or above which tier is 'medium'.")
+
+ @pydantic.model_validator(mode="after")
+ def check_window(self) -> "IdentityMatchingConfig":
+ if datetime.date.fromisoformat(self.date_start) >= datetime.date.fromisoformat(self.date_end):
+ raise ValueError("date_start must be before date_end")
+ unknown_weights = set(self.rule_weights) - set(DEFAULT_RULE_WEIGHTS)
+ if unknown_weights:
+ raise ValueError(f"Unknown rule weights: {sorted(unknown_weights)}")
+ return self
+
+
+@dataclass(frozen=True)
+class MatchingRun:
+ """Run state threaded through ops: the run's job_id plus the parsed config."""
+
+ job_id: str
+ config: IdentityMatchingConfig
+
+ @property
+ def job_uuid(self) -> uuid.UUID:
+ return uuid.UUID(self.job_id)
+
+ @property
+ def date_start(self) -> str:
+ return self.config.date_start
+
+ @property
+ def date_end(self) -> str:
+ return self.config.date_end
+
+ @property
+ def edges_start(self) -> str:
+ start = datetime.date.fromisoformat(self.config.date_start)
+ return (start - datetime.timedelta(days=self.config.identity_lookback_days)).isoformat()
+
+ @property
+ def eval_end(self) -> str:
+ end = datetime.date.fromisoformat(self.config.date_end)
+ return (end + datetime.timedelta(days=self.config.eval_horizon_days)).isoformat()
+
+
+@dataclass(frozen=True)
+class MatchingTable:
+ name: str
+ columns_sql: str
+ order_by: str
+
+ @property
+ def qualified_name(self) -> str:
+ return f"{settings.CLICKHOUSE_DATABASE}.{self.name}"
+
+ @property
+ def create_sql(self) -> str:
+ return f"""
+ CREATE TABLE IF NOT EXISTS {self.qualified_name}
+ (
+ {self.columns_sql}
+ )
+ ENGINE = ReplicatedReplacingMergeTree('/clickhouse/tables/noshard/{self.qualified_name}', '{{replica}}-{{shard}}', computed_at)
+ ORDER BY ({self.order_by})
+ TTL computed_at + INTERVAL 30 DAY DELETE
+ """
+
+ def create(self, client: Client) -> None:
+ client.execute(self.create_sql)
+
+ def sync(self, client: Client) -> None:
+ client.execute(f"SYSTEM SYNC REPLICA {self.qualified_name} STRICT")
+
+
+DEVICE_DAYS = MatchingTable(
+ name=DEVICE_DAYS_TABLE,
+ columns_sql="""
+ job_id UUID,
+ team_id Int64,
+ distinct_id String,
+ day Date,
+ ips Array(String),
+ browser String,
+ os String,
+ device_type String,
+ timezone String,
+ browser_language String,
+ raw_user_agent String,
+ geo_city String,
+ geo_subdivision String,
+ geo_postal String,
+ paths Array(String),
+ referring_domain String,
+ utm_source String,
+ utm_medium String,
+ utm_campaign String,
+ has_paid_clid UInt8,
+ first_clid_kind String,
+ event_count UInt64,
+ first_ts DateTime64(6, 'UTC'),
+ last_ts DateTime64(6, 'UTC'),
+ computed_at DateTime DEFAULT now()
+ """,
+ order_by="job_id, team_id, distinct_id, day",
+)
+
+PERSON_TIMELINE = MatchingTable(
+ name=PERSON_TIMELINE_TABLE,
+ columns_sql="""
+ job_id UUID,
+ team_id Int64,
+ distinct_id String,
+ is_anchor UInt8,
+ person_key String,
+ label_person_key String,
+ label_target_id String,
+ first_seen DateTime64(6, 'UTC'),
+ computed_at DateTime DEFAULT now()
+ """,
+ order_by="job_id, team_id, distinct_id",
+)
+
+CANDIDATE_PAIRS = MatchingTable(
+ name=CANDIDATE_PAIRS_TABLE,
+ columns_sql="""
+ job_id UUID,
+ team_id Int64,
+ orphan_distinct_id String,
+ anchor_person_key String,
+ shared_ip_days UInt32,
+ shared_ips UInt32,
+ min_ip_block_size UInt32,
+ geo_city_match UInt8,
+ timezone_match UInt8,
+ language_match UInt8,
+ ua_exact_match UInt8,
+ orphan_is_webview UInt8,
+ device_type_complement UInt8,
+ days_overlap UInt32,
+ orphan_last_to_anchor_first_s Int64,
+ avg_path_jaccard Float32,
+ orphan_paid_touch UInt8,
+ anchor_paid_touch UInt8,
+ orphan_event_count UInt64,
+ anchor_event_count UInt64,
+ label Int8,
+ computed_at DateTime DEFAULT now()
+ """,
+ order_by="job_id, team_id, orphan_distinct_id, anchor_person_key",
+)
+
+LINKS = MatchingTable(
+ name=LINKS_TABLE,
+ columns_sql="""
+ job_id UUID,
+ team_id Int64,
+ model_version LowCardinality(String),
+ orphan_distinct_id String,
+ anchor_person_key String,
+ score Float64,
+ runner_up_score Float64,
+ margin Float64,
+ tier LowCardinality(String),
+ computed_at DateTime DEFAULT now()
+ """,
+ order_by="job_id, team_id, model_version, orphan_distinct_id",
+)
+
+ALL_TABLES: list[MatchingTable] = [DEVICE_DAYS, PERSON_TIMELINE, CANDIDATE_PAIRS, LINKS]
+
+
+def _prop(name: str) -> str:
+ return f"JSONExtractString(properties, '{name}')"
+
+
+def _any_nonempty(expr: str) -> str:
+ return f"anyIf({expr}, {expr} != '')"
+
+
+def _first_clid_kind_expr() -> str:
+ branches = ", ".join(f"{_prop(clid)} != '', '{clid}'" for clid in PAID_CLICK_IDS)
+ return f"multiIf({branches}, '')"
+
+
+def _has_paid_clid_expr() -> str:
+ return " OR ".join(f"{_prop(clid)} != ''" for clid in PAID_CLICK_IDS)
+
+
+def setup_tables(
+ context: dagster.OpExecutionContext,
+ cluster: dagster.ResourceParam[ClickhouseCluster],
+ config: IdentityMatchingConfig,
+) -> MatchingRun:
+ """Create the job's tables on all hosts and seed the run state."""
+ validate_team_allowed(config.team_id)
+ for table in ALL_TABLES:
+ cluster.map_all_hosts(table.create).result()
+ run = MatchingRun(job_id=context.run.run_id, config=config)
+ context.log.info(
+ f"Run {run.job_id}: team {config.team_id}, window [{run.date_start}, {run.date_end}), "
+ f"edges from {run.edges_start}, eval until {run.eval_end}"
+ )
+ return run
+
+
+def build_device_day_index(
+ context: dagster.OpExecutionContext,
+ cluster: dagster.ResourceParam[ClickhouseCluster],
+ run: MatchingRun,
+) -> MatchingRun:
+ """Aggregate per-(distinct_id, day) signals from events into the device-day index."""
+ config = run.config
+ query = f"""
+ INSERT INTO {DEVICE_DAYS.qualified_name}
+ (job_id, team_id, distinct_id, day, ips, browser, os, device_type, timezone,
+ browser_language, raw_user_agent, geo_city, geo_subdivision, geo_postal, paths,
+ referring_domain, utm_source, utm_medium, utm_campaign, has_paid_clid,
+ first_clid_kind, event_count, first_ts, last_ts)
+ SELECT
+ toUUID(%(job_id)s),
+ team_id,
+ distinct_id,
+ toDate(timestamp) AS day,
+ groupUniqArrayIf(%(ips_cap)s)({_prop("$ip")}, {_prop("$ip")} != ''),
+ {_any_nonempty(_prop("$browser"))},
+ {_any_nonempty(_prop("$os"))},
+ {_any_nonempty(_prop("$device_type"))},
+ {_any_nonempty(_prop("$timezone"))},
+ {_any_nonempty(_prop("$browser_language"))},
+ {_any_nonempty(_prop("$raw_user_agent"))},
+ {_any_nonempty(_prop("$geoip_city_name"))},
+ {_any_nonempty(_prop("$geoip_subdivision_1_code"))},
+ {_any_nonempty(_prop("$geoip_postal_code"))},
+ groupUniqArrayIf(%(paths_cap)s)({_prop("$pathname")}, event = '$pageview' AND {_prop("$pathname")} != ''),
+ argMinIf({_prop("$referring_domain")}, timestamp, {_prop("$referring_domain")} != ''),
+ argMinIf({_prop("utm_source")}, timestamp, {_prop("utm_source")} != ''),
+ argMinIf({_prop("utm_medium")}, timestamp, {_prop("utm_medium")} != ''),
+ argMinIf({_prop("utm_campaign")}, timestamp, {_prop("utm_campaign")} != ''),
+ max(toUInt8({_has_paid_clid_expr()})),
+ argMinIf({_first_clid_kind_expr()}, timestamp, {_has_paid_clid_expr()}),
+ count(),
+ min(timestamp),
+ max(timestamp)
+ FROM {settings.CLICKHOUSE_DATABASE}.events
+ WHERE team_id = %(team_id)s
+ AND timestamp >= toDateTime(%(date_start)s)
+ AND timestamp < toDateTime(%(date_end)s)
+ AND event IN %(included_events)s
+ GROUP BY team_id, distinct_id, day
+ """
+ parameters = {
+ "job_id": run.job_id,
+ "team_id": config.team_id,
+ "date_start": run.date_start,
+ "date_end": run.date_end,
+ "included_events": tuple(config.included_events),
+ "ips_cap": config.ips_per_day_cap,
+ "paths_cap": config.paths_per_day_cap,
+ }
+ cluster.any_host(
+ partial(_execute, query=query, parameters=parameters, query_settings=settings_with_log_comment(context))
+ ).result()
+ cluster.map_all_hosts(DEVICE_DAYS.sync).result()
+
+ [[rows, devices, empty_ip_rows]] = cluster.any_host(
+ partial(
+ _execute,
+ query=f"""
+ SELECT count(), uniqExact(distinct_id), countIf(empty(ips))
+ FROM {DEVICE_DAYS.qualified_name}
+ WHERE job_id = toUUID(%(job_id)s)
+ """,
+ parameters={"job_id": run.job_id},
+ query_settings=settings_with_log_comment(context),
+ )
+ ).result()
+ empty_ip_fraction = (empty_ip_rows / rows) if rows else 0.0
+ if rows == 0:
+ context.log.warning("Device-day index is empty: no matching events in the window")
+ elif empty_ip_fraction > 0.5:
+ context.log.warning(
+ f"{empty_ip_fraction:.0%} of device-days have no $ip — the team likely has IP "
+ "anonymization enabled, so IP-based matching will not work"
+ )
+ context.add_output_metadata(
+ {
+ "device_day_rows": dagster.MetadataValue.int(rows),
+ "distinct_devices": dagster.MetadataValue.int(devices),
+ "empty_ip_fraction": dagster.MetadataValue.float(round(empty_ip_fraction, 4)),
+ }
+ )
+ return run
+
+
+class _UnionFind:
+ def __init__(self) -> None:
+ self.parent: dict[str, str] = {}
+
+ def find(self, item: str) -> str:
+ # Iterative with path compression: edge chains can exceed the recursion limit.
+ root = self.parent.setdefault(item, item)
+ while self.parent[root] != root:
+ root = self.parent[root]
+ while self.parent[item] != root:
+ self.parent[item], item = root, self.parent[item]
+ return root
+
+ def union(self, a: str, b: str) -> None:
+ root_a, root_b = self.find(a), self.find(b)
+ if root_a != root_b:
+ self.parent[root_b] = root_a
+
+ def components(self) -> dict[str, list[str]]:
+ groups: dict[str, list[str]] = {}
+ for item in self.parent:
+ groups.setdefault(self.find(item), []).append(item)
+ return groups
+
+
+def extract_person_timeline(
+ context: dagster.OpExecutionContext,
+ cluster: dagster.ResourceParam[ClickhouseCluster],
+ run: MatchingRun,
+) -> MatchingRun:
+ """Classify distinct_ids as anchors (identified as of window end) and extract evaluation labels.
+
+ The timeline is derived entirely from identity events so it can be evaluated "as of" the
+ window end; state tables (person.is_identified, overrides) have no time-travel semantics.
+ """
+ config = run.config
+ edges_query = f"""
+ SELECT other_id, target_id, min(ts) AS first_seen
+ FROM (
+ SELECT
+ if(
+ event = '$identify',
+ {_prop("$anon_distinct_id")},
+ {_prop("alias")}
+ ) AS other_id,
+ distinct_id AS target_id,
+ timestamp AS ts
+ FROM {settings.CLICKHOUSE_DATABASE}.events
+ WHERE team_id = %(team_id)s
+ AND event IN %(identity_events)s
+ AND timestamp >= toDateTime(%(edges_start)s)
+ AND timestamp < toDateTime(%(eval_end)s)
+ )
+ WHERE other_id != '' AND other_id != target_id
+ GROUP BY other_id, target_id
+ ORDER BY first_seen
+ LIMIT %(max_edges)s
+ """
+ edges: list[tuple[str, str, datetime.datetime]] = cluster.any_host(
+ partial(
+ _execute,
+ query=edges_query,
+ parameters={
+ "team_id": config.team_id,
+ "identity_events": tuple(IDENTITY_EVENTS),
+ "edges_start": run.edges_start,
+ "eval_end": run.eval_end,
+ "max_edges": config.max_identity_edges,
+ },
+ query_settings=settings_with_log_comment(context),
+ )
+ ).result()
+ if len(edges) >= config.max_identity_edges:
+ context.log.warning(f"Identity edges truncated at {len(edges)}; anchor classification is incomplete")
+
+ # ClickHouse returns timezone-aware datetimes for DateTime64(..., 'UTC') columns.
+ window_end = datetime.datetime.fromisoformat(run.date_end).replace(tzinfo=datetime.UTC)
+ union_find = _UnionFind()
+ first_seen_by_id: dict[str, datetime.datetime] = {}
+ eval_edges: list[tuple[str, str, datetime.datetime]] = []
+ identified_ids: set[str] = set()
+ for other_id, target_id, first_seen in edges:
+ if first_seen < window_end:
+ union_find.union(target_id, other_id)
+ identified_ids.add(target_id)
+ for member in (other_id, target_id):
+ if member not in first_seen_by_id or first_seen < first_seen_by_id[member]:
+ first_seen_by_id[member] = first_seen
+ else:
+ eval_edges.append((other_id, target_id, first_seen))
+
+ # The canonical key prefers identified-side ids (merge targets): a bare lexicographic
+ # minimum could crown an anonymous device id, which then surfaces as the matched person
+ # in the API and UI.
+ person_key_by_id: dict[str, str] = {}
+ for members in union_find.components().values():
+ identified_members = [member for member in members if member in identified_ids]
+ person_key = min(identified_members) if identified_members else min(members)
+ for member in members:
+ person_key_by_id[member] = person_key
+
+ job_uuid = run.job_uuid
+ rows: list[tuple[Any, ...]] = [
+ (job_uuid, config.team_id, member, 1, person_key, "", "", first_seen_by_id[member])
+ for member, person_key in person_key_by_id.items()
+ ]
+ labeled = 0
+ unrecoverable = 0
+ seen_eval_orphans: set[str] = set()
+ for other_id, target_id, first_seen in eval_edges:
+ # An id already identified as of window end is an anchor, not a gradable orphan.
+ if other_id in person_key_by_id or other_id in seen_eval_orphans:
+ continue
+ seen_eval_orphans.add(other_id)
+ label_person_key = person_key_by_id.get(target_id, "")
+ if label_person_key:
+ labeled += 1
+ else:
+ # The orphan merged into a person that was not an anchor in the window, so no
+ # candidate pair could ever have linked it; counted separately in evaluation.
+ unrecoverable += 1
+ rows.append((job_uuid, config.team_id, other_id, 0, "", label_person_key, target_id, first_seen))
+
+ insert_query = f"""
+ INSERT INTO {PERSON_TIMELINE.qualified_name}
+ (job_id, team_id, distinct_id, is_anchor, person_key, label_person_key, label_target_id, first_seen)
+ VALUES
+ """
+ batch_size = 100_000
+ for offset in range(0, len(rows), batch_size):
+ batch = rows[offset : offset + batch_size]
+ cluster.any_host(
+ partial(_execute, query=insert_query, parameters=batch, query_settings=settings_with_log_comment(context))
+ ).result()
+ cluster.map_all_hosts(PERSON_TIMELINE.sync).result()
+
+ anchor_persons = len(set(person_key_by_id.values()))
+ context.add_output_metadata(
+ {
+ "identity_edges": dagster.MetadataValue.int(len(edges)),
+ "anchor_distinct_ids": dagster.MetadataValue.int(len(person_key_by_id)),
+ "anchor_persons": dagster.MetadataValue.int(anchor_persons),
+ "eval_labeled_orphans": dagster.MetadataValue.int(labeled),
+ "unrecoverable_eval_orphans": dagster.MetadataValue.int(unrecoverable),
+ }
+ )
+ return run
+
+
+def build_candidate_pairs(
+ context: dagster.OpExecutionContext,
+ cluster: dagster.ResourceParam[ClickhouseCluster],
+ run: MatchingRun,
+) -> MatchingRun:
+ """Generate (orphan, anchor person) candidate pairs from IP-day co-location and compute pair features."""
+ config = run.config
+ query = f"""
+ INSERT INTO {CANDIDATE_PAIRS.qualified_name}
+ (job_id, team_id, orphan_distinct_id, anchor_person_key, shared_ip_days, shared_ips,
+ min_ip_block_size, geo_city_match, timezone_match, language_match, ua_exact_match,
+ orphan_is_webview, device_type_complement, days_overlap, orphan_last_to_anchor_first_s,
+ avg_path_jaccard, orphan_paid_touch, anchor_paid_touch, orphan_event_count,
+ anchor_event_count, label)
+ WITH
+ anchors AS (
+ SELECT distinct_id, person_key
+ FROM {PERSON_TIMELINE.qualified_name}
+ WHERE job_id = toUUID(%(job_id)s) AND is_anchor = 1
+ ),
+ labels AS (
+ SELECT distinct_id, label_person_key
+ FROM {PERSON_TIMELINE.qualified_name}
+ WHERE job_id = toUUID(%(job_id)s) AND is_anchor = 0 AND label_person_key != ''
+ ),
+ dd AS (
+ SELECT *
+ FROM {DEVICE_DAYS.qualified_name}
+ WHERE job_id = toUUID(%(job_id)s)
+ ),
+ ip_day_blocks AS (
+ SELECT ip, day, uniqExact(distinct_id) AS block_size
+ FROM dd
+ ARRAY JOIN ips AS ip
+ GROUP BY ip, day
+ HAVING block_size <= %(ip_day_block_cap)s
+ ),
+ ip_window AS (
+ SELECT ip
+ FROM dd
+ ARRAY JOIN ips AS ip
+ GROUP BY ip
+ HAVING uniqExact(distinct_id) <= %(ip_window_device_cap)s
+ ),
+ orphan_days AS (
+ SELECT
+ dd.distinct_id AS distinct_id,
+ dd.day AS day,
+ ip,
+ b.block_size AS block_size,
+ dd.geo_city AS geo_city,
+ dd.timezone AS timezone,
+ dd.browser_language AS browser_language,
+ dd.raw_user_agent AS raw_user_agent,
+ dd.device_type AS device_type,
+ dd.paths AS paths
+ FROM dd
+ ARRAY JOIN ips AS ip
+ INNER JOIN ip_day_blocks AS b USING (ip, day)
+ WHERE ip IN (SELECT ip FROM ip_window)
+ AND dd.distinct_id NOT IN (SELECT distinct_id FROM anchors)
+ ),
+ anchor_days AS (
+ SELECT
+ a.person_key AS person_key,
+ dd.day AS day,
+ ip,
+ dd.geo_city AS geo_city,
+ dd.timezone AS timezone,
+ dd.browser_language AS browser_language,
+ dd.raw_user_agent AS raw_user_agent,
+ dd.device_type AS device_type,
+ dd.paths AS paths
+ FROM dd
+ ARRAY JOIN ips AS ip
+ INNER JOIN anchors AS a ON dd.distinct_id = a.distinct_id
+ WHERE ip IN (SELECT ip FROM ip_window)
+ ),
+ orphan_totals AS (
+ SELECT
+ distinct_id,
+ min(first_ts) AS o_first,
+ max(last_ts) AS o_last,
+ sum(event_count) AS o_events,
+ max(has_paid_clid) AS o_paid
+ FROM dd
+ WHERE distinct_id NOT IN (SELECT distinct_id FROM anchors)
+ GROUP BY distinct_id
+ ),
+ anchor_totals AS (
+ SELECT
+ a.person_key AS person_key,
+ min(dd.first_ts) AS a_first,
+ max(dd.last_ts) AS a_last,
+ sum(dd.event_count) AS a_events,
+ max(dd.has_paid_clid) AS a_paid
+ FROM dd
+ INNER JOIN anchors AS a ON dd.distinct_id = a.distinct_id
+ GROUP BY a.person_key
+ ),
+ pair_core AS (
+ SELECT
+ o.distinct_id AS orphan_distinct_id,
+ a.person_key AS anchor_person_key,
+ uniqExact((o.ip, o.day)) AS shared_ip_days,
+ uniqExact(o.ip) AS shared_ips,
+ min(o.block_size) AS min_ip_block_size,
+ max(o.geo_city != '' AND o.geo_city = a.geo_city) AS geo_city_match,
+ max(o.timezone != '' AND o.timezone = a.timezone) AS timezone_match,
+ max(o.browser_language != '' AND o.browser_language = a.browser_language) AS language_match,
+ max(o.raw_user_agent != '' AND o.raw_user_agent = a.raw_user_agent) AS ua_exact_match,
+ max(match(o.raw_user_agent, '{WEBVIEW_UA_REGEX}')) AS orphan_is_webview,
+ max(
+ (o.device_type = 'Mobile' AND a.device_type = 'Desktop')
+ OR (o.device_type = 'Desktop' AND a.device_type = 'Mobile')
+ ) AS device_type_complement,
+ uniqExact(o.day) AS days_overlap,
+ avg(
+ length(arrayIntersect(o.paths, a.paths))
+ / greatest(length(arrayDistinct(arrayConcat(o.paths, a.paths))), 1)
+ ) AS avg_path_jaccard
+ FROM orphan_days AS o
+ INNER JOIN anchor_days AS a ON o.ip = a.ip AND o.day = a.day
+ GROUP BY orphan_distinct_id, anchor_person_key
+ ORDER BY orphan_distinct_id, shared_ip_days DESC, shared_ips DESC
+ LIMIT %(max_candidates_per_orphan)s BY orphan_distinct_id
+ )
+ SELECT
+ toUUID(%(job_id)s),
+ %(team_id)s,
+ p.orphan_distinct_id,
+ p.anchor_person_key,
+ p.shared_ip_days,
+ p.shared_ips,
+ p.min_ip_block_size,
+ p.geo_city_match,
+ p.timezone_match,
+ p.language_match,
+ p.ua_exact_match,
+ p.orphan_is_webview,
+ p.device_type_complement,
+ p.days_overlap,
+ dateDiff('second', o_tot.o_last, a_tot.a_first),
+ p.avg_path_jaccard,
+ o_tot.o_paid,
+ a_tot.a_paid,
+ o_tot.o_events,
+ a_tot.a_events,
+ multiIf(l.distinct_id = '', toInt8(-1), l.label_person_key = p.anchor_person_key, toInt8(1), toInt8(0))
+ FROM pair_core AS p
+ INNER JOIN orphan_totals AS o_tot ON p.orphan_distinct_id = o_tot.distinct_id
+ INNER JOIN anchor_totals AS a_tot ON p.anchor_person_key = a_tot.person_key
+ LEFT JOIN labels AS l ON p.orphan_distinct_id = l.distinct_id
+ """
+ parameters = {
+ "job_id": run.job_id,
+ "team_id": config.team_id,
+ "ip_day_block_cap": config.ip_day_block_cap,
+ "ip_window_device_cap": config.ip_window_device_cap,
+ "max_candidates_per_orphan": config.max_candidates_per_orphan,
+ }
+ cluster.any_host(
+ partial(_execute, query=query, parameters=parameters, query_settings=settings_with_log_comment(context))
+ ).result()
+ cluster.map_all_hosts(CANDIDATE_PAIRS.sync).result()
+
+ [[pair_rows, orphans_with_candidates, positives, negatives]] = cluster.any_host(
+ partial(
+ _execute,
+ query=f"""
+ SELECT count(), uniqExact(orphan_distinct_id), countIf(label = 1), countIf(label = 0)
+ FROM {CANDIDATE_PAIRS.qualified_name}
+ WHERE job_id = toUUID(%(job_id)s)
+ """,
+ parameters={"job_id": run.job_id},
+ query_settings=settings_with_log_comment(context),
+ )
+ ).result()
+ context.add_output_metadata(
+ {
+ "pair_rows": dagster.MetadataValue.int(pair_rows),
+ "orphans_with_candidates": dagster.MetadataValue.int(orphans_with_candidates),
+ "labeled_positive_pairs": dagster.MetadataValue.int(positives),
+ "labeled_negative_pairs": dagster.MetadataValue.int(negatives),
+ }
+ )
+ return run
+
+
+def _rule_score_expr(weights: dict[str, float]) -> str:
+ w = {**DEFAULT_RULE_WEIGHTS, **weights}
+ return f"""
+ {float(w["shared_ip_day"])} * least(shared_ip_days, 5)
+ + {float(w["multi_ip"])} * (shared_ips >= 2)
+ + {float(w["small_block"])} * (min_ip_block_size <= 3)
+ + {float(w["geo_city"])} * geo_city_match
+ + {float(w["timezone"])} * timezone_match
+ + {float(w["language"])} * language_match
+ + {float(w["ua_exact"])} * ua_exact_match
+ + {float(w["webview_same_ua"])} * (orphan_is_webview AND ua_exact_match)
+ + {float(w["device_complement"])} * device_type_complement
+ + {float(w["path_jaccard"])} * avg_path_jaccard
+ + {float(w["paid_continuity"])} * (orphan_paid_touch AND NOT anchor_paid_touch)
+ """
+
+
+def score_rule_based(
+ context: dagster.OpExecutionContext,
+ cluster: dagster.ResourceParam[ClickhouseCluster],
+ run: MatchingRun,
+) -> MatchingRun:
+ """Score candidate pairs with the weighted rules and keep the best anchor per orphan."""
+ config = run.config
+ query = f"""
+ INSERT INTO {LINKS.qualified_name}
+ (job_id, team_id, model_version, orphan_distinct_id, anchor_person_key, score,
+ runner_up_score, margin, tier)
+ SELECT
+ toUUID(%(job_id)s),
+ %(team_id)s,
+ '{RULES_MODEL_VERSION}',
+ orphan_distinct_id,
+ anchor_person_key,
+ score,
+ runner_up,
+ score - runner_up,
+ multiIf(score >= %(tier_high)s, 'high', score >= %(tier_medium)s, 'medium', 'low')
+ FROM (
+ SELECT
+ orphan_distinct_id,
+ anchor_person_key,
+ score,
+ row_number() OVER (
+ PARTITION BY orphan_distinct_id ORDER BY score DESC, anchor_person_key
+ ) AS rn,
+ leadInFrame(score) OVER (
+ PARTITION BY orphan_distinct_id ORDER BY score DESC, anchor_person_key
+ ROWS BETWEEN CURRENT ROW AND UNBOUNDED FOLLOWING
+ ) AS runner_up
+ FROM (
+ SELECT
+ orphan_distinct_id,
+ anchor_person_key,
+ ({_rule_score_expr(config.rule_weights)}) AS score
+ FROM {CANDIDATE_PAIRS.qualified_name}
+ WHERE job_id = toUUID(%(job_id)s) AND team_id = %(team_id)s
+ )
+ )
+ WHERE rn = 1 AND score >= %(min_score)s AND (score - runner_up) >= %(min_margin)s
+ """
+ parameters = {
+ "job_id": run.job_id,
+ "team_id": config.team_id,
+ "tier_high": config.rule_tier_high,
+ "tier_medium": config.rule_tier_medium,
+ "min_score": config.rule_min_score,
+ "min_margin": config.rule_min_margin,
+ }
+ cluster.any_host(
+ partial(_execute, query=query, parameters=parameters, query_settings=settings_with_log_comment(context))
+ ).result()
+ cluster.map_all_hosts(LINKS.sync).result()
+
+ [[links]] = cluster.any_host(
+ partial(
+ _execute,
+ query=f"""
+ SELECT count()
+ FROM {LINKS.qualified_name}
+ WHERE job_id = toUUID(%(job_id)s) AND model_version = '{RULES_MODEL_VERSION}'
+ """,
+ parameters={"job_id": run.job_id},
+ query_settings=settings_with_log_comment(context),
+ )
+ ).result()
+ context.add_output_metadata({"rule_links": dagster.MetadataValue.int(links)})
+ return run
+
+
+def _deterministic_test_split(key: str, modulo: int = 5) -> bool:
+ """Stable orphan-level holdout assignment so an orphan's pairs never straddle train/test."""
+ return int.from_bytes(hashlib.sha256(key.encode()).digest()[:8], "big") % modulo == 0
+
+
+def train_logreg_and_score(
+ context: dagster.OpExecutionContext,
+ cluster: dagster.ResourceParam[ClickhouseCluster],
+ run: MatchingRun,
+) -> MatchingRun:
+ """Train a logistic regression on merge-derived labels and score all candidate pairs.
+
+ Skips gracefully (no links inserted) when there are too few labels to train, so the job
+ stays usable on small teams and in local development.
+ """
+ # numpy/sklearn are deferred to keep the heavy dependency off the Dagster code-location
+ # import path; this op is the only consumer.
+ import numpy as np # noqa: PLC0415
+ from sklearn.linear_model import LogisticRegression # noqa: PLC0415
+ from sklearn.metrics import roc_auc_score # noqa: PLC0415
+ from sklearn.pipeline import make_pipeline # noqa: PLC0415
+ from sklearn.preprocessing import StandardScaler # noqa: PLC0415
+
+ config = run.config
+ feature_cols = ", ".join(PAIR_FEATURE_COLUMNS)
+ labeled_rows: list[tuple[Any, ...]] = cluster.any_host(
+ partial(
+ _execute,
+ query=f"""
+ SELECT orphan_distinct_id, label, {feature_cols}
+ FROM {CANDIDATE_PAIRS.qualified_name}
+ WHERE job_id = toUUID(%(job_id)s) AND label != -1
+ LIMIT %(max_rows)s
+ """,
+ parameters={"job_id": run.job_id, "max_rows": config.max_training_rows},
+ query_settings=settings_with_log_comment(context),
+ )
+ ).result()
+ positives = sum(1 for row in labeled_rows if row[1] == 1)
+ negatives = len(labeled_rows) - positives
+ if positives < config.min_training_positives or negatives < config.min_training_negatives:
+ context.log.warning(
+ f"Skipping logistic regression: {positives} positives / {negatives} negatives, "
+ f"need at least {config.min_training_positives} / {config.min_training_negatives}"
+ )
+ context.add_output_metadata(
+ {
+ "trained": dagster.MetadataValue.bool(False),
+ "labeled_positives": dagster.MetadataValue.int(positives),
+ "labeled_negatives": dagster.MetadataValue.int(negatives),
+ }
+ )
+ return run
+
+ weak_negative_count = int(config.weak_negative_sample_ratio * len(labeled_rows))
+ weak_rows: list[tuple[Any, ...]] = cluster.any_host(
+ partial(
+ _execute,
+ query=f"""
+ SELECT orphan_distinct_id, label, {feature_cols}
+ FROM {CANDIDATE_PAIRS.qualified_name}
+ WHERE job_id = toUUID(%(job_id)s) AND label = -1
+ ORDER BY cityHash64(orphan_distinct_id, anchor_person_key)
+ LIMIT %(limit)s
+ """,
+ parameters={"job_id": run.job_id, "limit": weak_negative_count},
+ query_settings=settings_with_log_comment(context),
+ )
+ ).result()
+
+ train_x: list[Sequence[float]] = []
+ train_y: list[int] = []
+ train_weights: list[float] = []
+ test_x: list[Sequence[float]] = []
+ test_y: list[int] = []
+ for orphan_id, label, *features in labeled_rows:
+ if _deterministic_test_split(orphan_id):
+ test_x.append(features)
+ test_y.append(label)
+ else:
+ train_x.append(features)
+ train_y.append(label)
+ train_weights.append(1.0)
+ # Unlabeled pairs are weak negatives: the absence of a later merge does not prove the
+ # link is wrong, so they get a reduced sample weight and never enter the holdout.
+ for _orphan_id, _label, *features in weak_rows:
+ train_x.append(features)
+ train_y.append(0)
+ train_weights.append(0.3)
+
+ if len(set(train_y)) < 2:
+ context.log.warning("Skipping logistic regression: training data has a single class")
+ context.add_output_metadata({"trained": dagster.MetadataValue.bool(False)})
+ return run
+
+ model = make_pipeline(StandardScaler(), LogisticRegression(class_weight="balanced", max_iter=1000))
+ model.fit(np.array(train_x, dtype=np.float64), np.array(train_y), logisticregression__sample_weight=train_weights)
+
+ coefficients = dict(
+ zip(PAIR_FEATURE_COLUMNS, model.named_steps["logisticregression"].coef_[0].round(4).tolist(), strict=True)
+ )
+ metadata: dict[str, Any] = {
+ "trained": dagster.MetadataValue.bool(True),
+ "labeled_positives": dagster.MetadataValue.int(positives),
+ "labeled_negatives": dagster.MetadataValue.int(negatives),
+ "weak_negatives": dagster.MetadataValue.int(len(weak_rows)),
+ "coefficients": dagster.MetadataValue.json(coefficients),
+ }
+ if test_x and len(set(test_y)) == 2:
+ test_probs = model.predict_proba(np.array(test_x, dtype=np.float64))[:, 1]
+ metadata["holdout_rows"] = dagster.MetadataValue.int(len(test_y))
+ metadata["holdout_auc"] = dagster.MetadataValue.float(round(float(roc_auc_score(test_y, test_probs)), 4))
+ else:
+ context.log.warning("Holdout slice lacks both classes; skipping holdout metrics")
+
+ scoring_rows: list[tuple[Any, ...]] = cluster.any_host(
+ partial(
+ _execute,
+ query=f"""
+ SELECT orphan_distinct_id, anchor_person_key, {feature_cols}
+ FROM {CANDIDATE_PAIRS.qualified_name}
+ WHERE job_id = toUUID(%(job_id)s)
+ ORDER BY orphan_distinct_id, anchor_person_key
+ LIMIT %(max_rows)s
+ """,
+ parameters={"job_id": run.job_id, "max_rows": config.max_scoring_rows},
+ query_settings=settings_with_log_comment(context),
+ )
+ ).result()
+ if len(scoring_rows) >= config.max_scoring_rows:
+ context.log.warning(f"Candidate pairs truncated at {len(scoring_rows)} for scoring")
+
+ link_rows: list[tuple[Any, ...]] = []
+ if scoring_rows:
+ probs = model.predict_proba(np.array([row[2:] for row in scoring_rows], dtype=np.float64))[:, 1]
+ best_by_orphan: dict[str, tuple[float, str, float]] = {}
+ for (orphan_id, anchor_key, *_features), prob in zip(scoring_rows, probs, strict=True):
+ prob = float(prob)
+ best = best_by_orphan.get(orphan_id)
+ if best is None:
+ best_by_orphan[orphan_id] = (prob, anchor_key, 0.0)
+ elif prob > best[0]:
+ best_by_orphan[orphan_id] = (prob, anchor_key, best[0])
+ elif prob > best[2]:
+ best_by_orphan[orphan_id] = (best[0], best[1], prob)
+ job_uuid = run.job_uuid
+ for orphan_id, (prob, anchor_key, runner_up) in best_by_orphan.items():
+ tier = "high" if prob >= config.prob_tier_high else "medium" if prob >= config.prob_tier_medium else "low"
+ link_rows.append(
+ (
+ job_uuid,
+ config.team_id,
+ LOGREG_MODEL_VERSION,
+ orphan_id,
+ anchor_key,
+ prob,
+ runner_up,
+ prob - runner_up,
+ tier,
+ )
+ )
+
+ insert_query = f"""
+ INSERT INTO {LINKS.qualified_name}
+ (job_id, team_id, model_version, orphan_distinct_id, anchor_person_key, score,
+ runner_up_score, margin, tier)
+ VALUES
+ """
+ batch_size = 100_000
+ for offset in range(0, len(link_rows), batch_size):
+ batch = link_rows[offset : offset + batch_size]
+ cluster.any_host(
+ partial(_execute, query=insert_query, parameters=batch, query_settings=settings_with_log_comment(context))
+ ).result()
+ cluster.map_all_hosts(LINKS.sync).result()
+
+ metadata["logreg_links"] = dagster.MetadataValue.int(len(link_rows))
+ context.add_output_metadata(metadata)
+ return run
+
+
+def evaluate_and_report(
+ context: dagster.OpExecutionContext,
+ cluster: dagster.ResourceParam[ClickhouseCluster],
+ rules_run: MatchingRun,
+ logreg_run: MatchingRun,
+) -> None:
+ """Grade links against held-out merge labels and report coverage and marketing impact."""
+ if rules_run.job_id != logreg_run.job_id:
+ raise ValueError(f"Mismatched runs: {rules_run.job_id!r} vs {logreg_run.job_id!r}")
+ run = rules_run
+ config = run.config
+ ch_settings = settings_with_log_comment(context)
+
+ [[devices, anchor_devices]] = cluster.any_host(
+ partial(
+ _execute,
+ query=f"""
+ SELECT uniqExact(d.distinct_id), uniqExactIf(d.distinct_id, t.is_anchor = 1)
+ FROM {DEVICE_DAYS.qualified_name} AS d
+ LEFT JOIN (
+ SELECT distinct_id, is_anchor
+ FROM {PERSON_TIMELINE.qualified_name}
+ WHERE job_id = toUUID(%(job_id)s)
+ ) AS t ON d.distinct_id = t.distinct_id
+ WHERE d.job_id = toUUID(%(job_id)s)
+ """,
+ parameters={"job_id": run.job_id},
+ query_settings=ch_settings,
+ )
+ ).result()
+ orphan_devices = devices - anchor_devices
+
+ [[gradable_orphans, unrecoverable_orphans]] = cluster.any_host(
+ partial(
+ _execute,
+ query=f"""
+ SELECT
+ uniqExactIf(t.distinct_id, t.label_person_key != ''),
+ uniqExactIf(t.distinct_id, t.label_person_key = '')
+ FROM {PERSON_TIMELINE.qualified_name} AS t
+ INNER JOIN (
+ SELECT DISTINCT distinct_id
+ FROM {DEVICE_DAYS.qualified_name}
+ WHERE job_id = toUUID(%(job_id)s)
+ ) AS d ON t.distinct_id = d.distinct_id
+ WHERE t.job_id = toUUID(%(job_id)s) AND t.is_anchor = 0
+ """,
+ parameters={"job_id": run.job_id},
+ query_settings=ch_settings,
+ )
+ ).result()
+
+ [[orphans_with_candidates]] = cluster.any_host(
+ partial(
+ _execute,
+ query=f"""
+ SELECT uniqExact(orphan_distinct_id)
+ FROM {CANDIDATE_PAIRS.qualified_name}
+ WHERE job_id = toUUID(%(job_id)s)
+ """,
+ parameters={"job_id": run.job_id},
+ query_settings=ch_settings,
+ )
+ ).result()
+
+ summary_lines = [
+ f"Window [{run.date_start}, {run.date_end}), eval horizon until {run.eval_end}",
+ f"Orphan devices: {orphan_devices} (of {devices} active devices; {anchor_devices} anchor devices)",
+ f"Orphans with at least one candidate: {orphans_with_candidates}",
+ f"Gradable labeled orphans (active in window): {gradable_orphans}",
+ f"Unrecoverable labeled orphans (merge target not an anchor in window): {unrecoverable_orphans}",
+ ]
+
+ metadata: dict[str, Any] = {
+ "orphan_devices": dagster.MetadataValue.int(orphan_devices),
+ "orphans_with_candidates": dagster.MetadataValue.int(orphans_with_candidates),
+ "gradable_orphans": dagster.MetadataValue.int(gradable_orphans),
+ "unrecoverable_orphans": dagster.MetadataValue.int(unrecoverable_orphans),
+ }
+
+ sweeps = {
+ RULES_MODEL_VERSION: [float(t) for t in config.rule_thresholds],
+ LOGREG_MODEL_VERSION: [float(t) for t in config.prob_thresholds],
+ }
+ for model_version, thresholds in sweeps.items():
+ link_rows: list[tuple[float, str, str, int, int]] = cluster.any_host(
+ partial(
+ _execute,
+ query=f"""
+ SELECT
+ lk.score,
+ lk.anchor_person_key,
+ t.label_person_key,
+ p.orphan_paid_touch,
+ p.anchor_paid_touch
+ FROM {LINKS.qualified_name} AS lk
+ INNER JOIN {CANDIDATE_PAIRS.qualified_name} AS p
+ ON lk.job_id = p.job_id
+ AND lk.orphan_distinct_id = p.orphan_distinct_id
+ AND lk.anchor_person_key = p.anchor_person_key
+ LEFT JOIN (
+ SELECT distinct_id, label_person_key
+ FROM {PERSON_TIMELINE.qualified_name}
+ WHERE job_id = toUUID(%(job_id)s) AND is_anchor = 0 AND label_person_key != ''
+ ) AS t ON lk.orphan_distinct_id = t.distinct_id
+ WHERE lk.job_id = toUUID(%(job_id)s) AND lk.model_version = %(model_version)s
+ """,
+ parameters={"job_id": run.job_id, "model_version": model_version},
+ query_settings=ch_settings,
+ )
+ ).result()
+
+ if not link_rows:
+ summary_lines.append(f"\n{model_version}: no links")
+ continue
+
+ table_lines = [
+ f"\n{model_version} ({len(link_rows)} links):",
+ "| threshold | links | graded | precision | recall | new paid touches |",
+ "|---|---|---|---|---|---|",
+ ]
+ for threshold in thresholds:
+ at_t = [row for row in link_rows if row[0] >= threshold]
+ graded = [row for row in at_t if row[2] != ""]
+ correct = sum(1 for row in graded if row[1] == row[2])
+ precision = (correct / len(graded)) if graded else None
+ recall = (correct / gradable_orphans) if gradable_orphans else None
+ paid_gain = sum(1 for row in at_t if row[3] == 1 and row[4] == 0)
+ table_lines.append(
+ f"| {threshold} | {len(at_t)} | {len(graded)} "
+ f"| {f'{precision:.3f}' if precision is not None else 'n/a'} "
+ f"| {f'{recall:.3f}' if recall is not None else 'n/a'} "
+ f"| {paid_gain} |"
+ )
+ summary_lines.extend(table_lines)
+ metadata[f"{model_version}_sweep"] = dagster.MetadataValue.md("\n".join(table_lines))
+
+ report = "\n".join(summary_lines)
+ context.log.info("Identity matching report:\n%s", report)
+ context.add_output_metadata({**metadata, "report": dagster.MetadataValue.md(report)})
+
+
+def _execute(
+ client: Client,
+ query: str,
+ parameters: dict[str, Any] | list[tuple[Any, ...]] | None = None,
+ query_settings: dict[str, str] | None = None,
+) -> list[tuple[Any, ...]]:
+ return client.execute(query, parameters, settings=query_settings)
+
+
[email protected](tags={"owner": JobOwners.TEAM_GROWTH.value, "disable_slack_notifications": "true"})
+def identity_matching_job():
+ run = setup_tables()
+ run = build_device_day_index(run)
+ run = extract_person_timeline(run)
+ run = build_candidate_pairs(run)
+ rules = score_rule_based(run)
+ logreg = train_logreg_and_score(run)
+ evaluate_and_report(rules, logreg)
diff --git a/products/growth/dags/tests/conftest.py b/products/growth/dags/tests/conftest.py
index d97414d2b0fe..37fc531e783b 100644
--- a/products/growth/dags/tests/conftest.py
+++ b/products/growth/dags/tests/conftest.py
@@ -2,6 +2,7 @@
# calls use PostgreSQL instead of SQLite (avoids locking errors).
# Direct import (rather than pytest_plugins) is required because pytest
# disallows pytest_plugins in non-top-level conftest files.
+from posthog.dags.tests.conftest import cluster, django_db_setup # noqa: F401
from posthog.dags.tests.dagster_pg_fixtures import ( # noqa: F401
_dagster_postgres_instance,
_use_postgres_dagster_instance,
diff --git a/products/growth/dags/tests/test_identity_matching.py b/products/growth/dags/tests/test_identity_matching.py
new file mode 100644
index 000000000000..ea7cf7899118
--- /dev/null
+++ b/products/growth/dags/tests/test_identity_matching.py
@@ -0,0 +1,300 @@
+import json
+from datetime import datetime
+from typing import Any
+from uuid import UUID, uuid4
+
+import pytest
+from unittest.mock import patch
+
+import dagster
+from clickhouse_driver import Client
+
+from posthog.clickhouse.cluster import ClickhouseCluster
+
+from products.growth.dags import identity_matching
+from products.growth.dags.identity_matching import (
+ CANDIDATE_PAIRS,
+ DEVICE_DAYS,
+ LINKS,
+ LOGREG_MODEL_VERSION,
+ PERSON_TIMELINE,
+ RULES_MODEL_VERSION,
+ IdentityMatchingConfig,
+ identity_matching_job,
+ is_identity_matching_registered,
+ validate_team_allowed,
+)
+
+TEAM_ID = 99
+
+HOUSEHOLD_IP = "10.0.0.1"
+BOB_IP = "10.0.0.2"
+CARA_IP = "10.0.0.9"
+CORPORATE_IP = "203.0.113.5"
+
+DESKTOP_UA = "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 Chrome/120.0.0.0 Safari/537.36"
+MOBILE_UA = "Mozilla/5.0 (iPhone; CPU iPhone OS 17_0 like Mac OS X) AppleWebKit/605.1.15 Mobile/15E148 Safari/604.1"
+WEBVIEW_UA = (
+ "Mozilla/5.0 (Linux; Android 14; Pixel 8) AppleWebKit/537.36 Chrome/120.0.0.0 Mobile Safari/537.36 wv) LinkedInApp"
+)
+
+
+def _event(event: str, distinct_id: str, timestamp: datetime, properties: dict[str, Any]) -> tuple[Any, ...]:
+ return (uuid4(), event, json.dumps(properties), timestamp, TEAM_ID, distinct_id)
+
+
+def _device_props(ip: str, ua: str, device_type: str, city: str, language: str, path: str) -> dict[str, Any]:
+ return {
+ "$ip": ip,
+ "$raw_user_agent": ua,
+ "$device_type": device_type,
+ "$browser": "Chrome",
+ "$os": "Mac OS X" if device_type == "Desktop" else "iOS",
+ "$timezone": "Europe/Lisbon",
+ "$browser_language": language,
+ "$geoip_city_name": city,
+ "$geoip_subdivision_1_code": "PT-11",
+ "$geoip_postal_code": "1000",
+ "$pathname": path,
+ }
+
+
+def _fixture_events() -> list[tuple[Any, ...]]:
+ anna_desktop = lambda path: _device_props(HOUSEHOLD_IP, DESKTOP_UA, "Desktop", "Lisbon", "en-GB", path)
+ anna_phone = lambda path: _device_props(HOUSEHOLD_IP, MOBILE_UA, "Mobile", "Lisbon", "en-GB", path)
+ bob_desktop = lambda path: _device_props(BOB_IP, DESKTOP_UA, "Desktop", "Porto", "pt-PT", path)
+ bob_phone = lambda ip, path: _device_props(ip, MOBILE_UA, "Mobile", "Porto", "pt-PT", path)
+ cara_device = lambda path: _device_props(CARA_IP, WEBVIEW_UA, "Mobile", "Faro", "pt-PT", path)
+
+ events = [
+ # Anna researches on her laptop, then identifies on Jan 2.
+ _event("$pageview", "laptop-anna-anon", datetime(2025, 1, 1, 10), anna_desktop("/pricing")),
+ _event("$pageview", "laptop-anna-anon", datetime(2025, 1, 1, 11), anna_desktop("/docs")),
+ _event(
+ "$identify",
+ datetime(2025, 1, 2, 9),
+ {**anna_desktop("/signup"), "$anon_distinct_id": "laptop-anna-anon"},
+ ),
+ _event("$pageview", "[email protected]", datetime(2025, 1, 3, 20), anna_desktop("/pricing")),
+ _event("$pageview", "[email protected]", datetime(2025, 1, 4, 20), anna_desktop("/dashboard")),
+ _event("$pageview", "[email protected]", datetime(2025, 1, 5, 20), anna_desktop("/dashboard")),
+ # Anna's phone browses from the household IP on three evenings; the first touch is a
+ # paid click that her identified history lacks.
+ _event("$pageview", "phone-anna", datetime(2025, 1, 3, 21), {**anna_phone("/pricing"), "gclid": "abc123"}),
+ _event("$pageview", "phone-anna", datetime(2025, 1, 4, 21), anna_phone("/blog/why")),
+ _event("$pageview", "phone-anna", datetime(2025, 1, 5, 21), anna_phone("/pricing")),
+ # Bob (same household one evening — the hard negative) identifies on Jan 2 and
+ # browses from his own IP.
+ _event(
+ "$identify",
+ datetime(2025, 1, 2, 12),
+ {**bob_desktop("/signup"), "$anon_distinct_id": "laptop-bob-anon"},
+ ),
+ _event("$pageview", "[email protected]", datetime(2025, 1, 5, 9), bob_desktop("/integrations")),
+ _event("$pageview", "[email protected]", datetime(2025, 1, 6, 9), bob_desktop("/integrations")),
+ # Bob's phone: one day on the household IP (overlapping Anna's anchors), two days on
+ # Bob's own IP overlapping Bob's anchor activity.
+ _event("$pageview", "phone-bob", datetime(2025, 1, 4, 22), bob_phone(HOUSEHOLD_IP, "/integrations")),
+ _event("$pageview", "phone-bob", datetime(2025, 1, 5, 10), bob_phone(BOB_IP, "/integrations")),
+ _event("$pageview", "phone-bob", datetime(2025, 1, 6, 10), bob_phone(BOB_IP, "/integrations")),
+ # Cara: an ad click opened in an in-app webview shares the IP and the byte-identical
+ # webview UA with her identified device.
+ _event(
+ "$identify",
+ datetime(2025, 1, 2, 15),
+ {**cara_device("/signup"), "$anon_distinct_id": "first-cara"},
+ ),
+ _event("$pageview", "[email protected]", datetime(2025, 1, 3, 15), cara_device("/docs")),
+ _event("$pageview", "webview-cara", datetime(2025, 1, 3, 16), cara_device("/docs")),
+ # Events without $ip must not break the run.
+ _event("$pageview", "no-ip-dave", datetime(2025, 1, 4, 8), {"$pathname": "/pricing"}),
+ # Zed's anonymous id sorts before his identified id: the canonical person key must
+ # still be the identified side.
+ _event(
+ "$identify",
+ datetime(2025, 1, 2, 18),
+ {
+ **_device_props("10.0.0.77", DESKTOP_UA, "Desktop", "Braga", "pt-PT", "/signup"),
+ "$anon_distinct_id": "0-zed-anon",
+ },
+ ),
+ ]
+ # A corporate IP with more devices than the block cap: excluded from candidates.
+ events += [
+ _event(
+ "$pageview",
+ f"corp-{i}",
+ datetime(2025, 1, 3, 9),
+ _device_props(CORPORATE_IP, DESKTOP_UA, "Desktop", "Lisbon", "en-GB", "/enterprise"),
+ )
+ for i in range(30)
+ ]
+ # The retroactive merges that grade the run, both after the feature window ends.
+ events += [
+ _event(
+ "$identify",
+ datetime(2025, 1, 10, 9),
+ {**anna_phone("/login"), "$anon_distinct_id": "phone-anna"},
+ ),
+ _event(
+ "$identify",
+ datetime(2025, 1, 11, 9),
+ {**bob_phone(BOB_IP, "/login"), "$anon_distinct_id": "phone-bob"},
+ ),
+ ]
+ return events
+
+
+def _insert_fixture_events(client: Client) -> None:
+ client.execute(
+ "INSERT INTO writable_events (uuid, event, properties, timestamp, team_id, distinct_id) VALUES",
+ _fixture_events(),
+ )
+
+
+def _run_job(cluster: ClickhouseCluster, **config_overrides: Any) -> tuple[dagster.ExecuteInProcessResult, UUID]:
+ config_kwargs: dict[str, Any] = {
+ "team_id": TEAM_ID,
+ "date_start": "2025-01-01",
+ "date_end": "2025-01-08",
+ "eval_horizon_days": 7,
+ "ip_day_block_cap": 10,
+ "ip_window_device_cap": 20,
+ "rule_min_score": 1.0,
+ "rule_min_margin": 0.0,
+ "min_training_positives": 2,
+ "min_training_negatives": 1,
+ **config_overrides,
+ }
+ config = IdentityMatchingConfig(**config_kwargs)
+ result = identity_matching_job.execute_in_process(
+ run_config=dagster.RunConfig({"setup_tables": config}),
+ resources={"cluster": cluster},
+ )
+ return result, UUID(result.dagster_run.run_id)
+
+
+def test_identity_matching_job(cluster: ClickhouseCluster) -> None:
+ cluster.any_host(_insert_fixture_events).result()
+
+ result, job_id = _run_job(cluster)
+ assert result.success
+
+ def get_phone_anna_device_days(client: Client) -> list[tuple[Any, ...]]:
+ return client.execute(
+ f"SELECT day, ips FROM {DEVICE_DAYS.qualified_name} "
+ "WHERE job_id = %(job_id)s AND distinct_id = 'phone-anna' ORDER BY day",
+ {"job_id": job_id},
+ )
+
+ phone_anna_days = cluster.any_host(get_phone_anna_device_days).result()
+ assert len(phone_anna_days) == 3
+ assert all(ips == [HOUSEHOLD_IP] for _, ips in phone_anna_days)
+
+ def get_timeline(client: Client) -> dict[str, tuple[int, str, str]]:
+ rows = client.execute(
+ f"SELECT distinct_id, is_anchor, person_key, label_person_key FROM {PERSON_TIMELINE.qualified_name} "
+ "WHERE job_id = %(job_id)s",
+ {"job_id": job_id},
+ )
+ return {distinct_id: (is_anchor, person_key, label) for distinct_id, is_anchor, person_key, label in rows}
+
+ timeline = cluster.any_host(get_timeline).result()
+ assert timeline["[email protected]"] == (1, "[email protected]", "")
+ assert timeline["laptop-anna-anon"] == (1, "[email protected]", "")
+ assert timeline["[email protected]"] == (1, "[email protected]", "")
+ assert timeline["[email protected]"] == (1, "[email protected]", "")
+ # The identified side stays canonical even when the anonymous id sorts first.
+ assert timeline["[email protected]"] == (1, "[email protected]", "")
+ assert timeline["0-zed-anon"] == (1, "[email protected]", "")
+ # Post-window merges become evaluation labels, not anchors.
+ assert timeline["phone-anna"] == (0, "", "[email protected]")
+ assert timeline["phone-bob"] == (0, "", "[email protected]")
+ assert "corp-0" not in timeline
+
+ def get_pairs(client: Client) -> dict[tuple[str, str], tuple[int, int, int, int]]:
+ rows = client.execute(
+ f"SELECT orphan_distinct_id, anchor_person_key, shared_ip_days, label, ua_exact_match, orphan_is_webview "
+ f"FROM {CANDIDATE_PAIRS.qualified_name} WHERE job_id = %(job_id)s",
+ {"job_id": job_id},
+ )
+ return {(orphan, anchor): tuple(rest) for orphan, anchor, *rest in rows}
+
+ pairs = cluster.any_host(get_pairs).result()
+ assert pairs[("phone-anna", "[email protected]")][:2] == (3, 1)
+ assert pairs[("phone-bob", "[email protected]")][:2] == (1, 0)
+ assert pairs[("phone-bob", "[email protected]")][:2] == (2, 1)
+ cara_pair = pairs[("webview-cara", "[email protected]")]
+ assert cara_pair[1] == -1
+ assert cara_pair[2] == 1 # byte-identical user agent
+ assert cara_pair[3] == 1 # webview signature
+ assert not any(orphan.startswith("corp-") or anchor.startswith("corp-") for orphan, anchor in pairs)
+
+ def get_links(client: Client) -> dict[tuple[str, str], str]:
+ rows = client.execute(
+ f"SELECT model_version, orphan_distinct_id, anchor_person_key FROM {LINKS.qualified_name} "
+ "WHERE job_id = %(job_id)s",
+ {"job_id": job_id},
+ )
+ return {(model_version, orphan): anchor for model_version, orphan, anchor in rows}
+
+ links = cluster.any_host(get_links).result()
+ assert links[(RULES_MODEL_VERSION, "phone-anna")] == "[email protected]"
+ assert links[(RULES_MODEL_VERSION, "phone-bob")] == "[email protected]"
+ assert links[(RULES_MODEL_VERSION, "webview-cara")] == "[email protected]"
+ # Each orphan with candidates gets exactly one best link per model.
+ logreg_links = {orphan for model_version, orphan in links if model_version == LOGREG_MODEL_VERSION}
+ assert logreg_links == {"phone-anna", "phone-bob", "webview-cara"}
+
+
+def test_logreg_skips_without_labels(cluster: ClickhouseCluster) -> None:
+ cluster.any_host(_insert_fixture_events).result()
+
+ result, job_id = _run_job(cluster, min_training_positives=50)
+ assert result.success
+
+ def get_logreg_link_count(client: Client) -> int:
+ [[count]] = client.execute(
+ f"SELECT count() FROM {LINKS.qualified_name} "
+ "WHERE job_id = %(job_id)s AND model_version = %(model_version)s",
+ {"job_id": job_id, "model_version": LOGREG_MODEL_VERSION},
+ )
+ return count
+
+ assert cluster.any_host(get_logreg_link_count).result() == 0
+
+
+ "cloud_deployment,team_id,allowed",
+ [
+ (None, 999, True),
+ ("LOCAL", 999, True),
+ ("DEV", 999, True),
+ ("US", 2, True),
+ ("US", 999, False),
+ ("EU", 2, False),
+ ("EU", 999, False),
+ ],
+)
+def test_team_guard_per_environment(cloud_deployment: str | None, team_id: int, allowed: bool) -> None:
+ with patch.object(identity_matching.settings, "CLOUD_DEPLOYMENT", cloud_deployment):
+ if allowed:
+ validate_team_allowed(team_id)
+ else:
+ with pytest.raises(dagster.Failure):
+ validate_team_allowed(team_id)
+
+
+ "cloud_deployment,registered",
+ [(None, True), ("LOCAL", True), ("DEV", True), ("US", True), ("EU", False)],
+)
+def test_job_registration_per_environment(cloud_deployment: str | None, registered: bool) -> None:
+ with patch.object(identity_matching.settings, "CLOUD_DEPLOYMENT", cloud_deployment):
+ assert is_identity_matching_registered() is registered
diff --git a/products/growth/frontend/IdentityMatchingScene.stories.tsx b/products/growth/frontend/IdentityMatchingScene.stories.tsx
new file mode 100644
index 000000000000..42ff0b1a61a9
--- /dev/null
+++ b/products/growth/frontend/IdentityMatchingScene.stories.tsx
@@ -0,0 +1,184 @@
+import { Meta, StoryObj } from '@storybook/react'
+
+import { App } from 'scenes/App'
+import { urls } from 'scenes/urls'
+
+import { mswDecorator } from '~/mocks/browser'
+
+import type { IdentityMatchingLinkApi, IdentityMatchingRunApi } from './generated/api.schemas'
+
+const RUN_A = '0197a4a6-06d9-7000-34fe-daa2e2afb501'
+const RUN_B = '0197a4a6-06d9-7000-34fe-daa2e2afb502'
+
+const LINKS_RESULT: IdentityMatchingLinkApi[] = [
+ {
+ job_id: RUN_A,
+ model_version: 'rules_v1',
+ orphan_distinct_id: '0190a1b2-phone-3c4d-5e6f-anna00000001',
+ anchor_person_key: '[email protected]',
+ score: 6.92,
+ margin: 6.92,
+ tier: 'high',
+ computed_at: '2023-02-01T09:30:00Z',
+ shared_ip_days: 3,
+ shared_ips: 1,
+ min_ip_block_size: 2,
+ geo_city_match: true,
+ timezone_match: true,
+ language_match: true,
+ ua_exact_match: false,
+ orphan_is_webview: false,
+ device_type_complement: true,
+ days_overlap: 3,
+ avg_path_jaccard: 0.33,
+ orphan_paid_touch: true,
+ anchor_paid_touch: false,
+ },
+ {
+ job_id: RUN_A,
+ model_version: 'rules_v1',
+ orphan_distinct_id: '0190a1b2-webview-3c4d-5e6f-cara00000001',
+ anchor_person_key: '[email protected]',
+ score: 8.5,
+ margin: 8.5,
+ tier: 'high',
+ computed_at: '2023-02-01T09:30:00Z',
+ shared_ip_days: 1,
+ shared_ips: 1,
+ min_ip_block_size: 2,
+ geo_city_match: true,
+ timezone_match: true,
+ language_match: true,
+ ua_exact_match: true,
+ orphan_is_webview: true,
+ device_type_complement: false,
+ days_overlap: 1,
+ avg_path_jaccard: 1,
+ orphan_paid_touch: true,
+ anchor_paid_touch: true,
+ },
+ {
+ job_id: RUN_A,
+ model_version: 'logreg_v1',
+ orphan_distinct_id: '0190a1b2-phone-3c4d-5e6f-anna00000001',
+ anchor_person_key: '[email protected]',
+ score: 0.94,
+ margin: 0.94,
+ tier: 'high',
+ computed_at: '2023-02-01T09:30:00Z',
+ shared_ip_days: 3,
+ shared_ips: 1,
+ min_ip_block_size: 2,
+ geo_city_match: true,
+ timezone_match: true,
+ language_match: true,
+ ua_exact_match: false,
+ orphan_is_webview: false,
+ device_type_complement: true,
+ days_overlap: 3,
+ avg_path_jaccard: 0.33,
+ orphan_paid_touch: true,
+ anchor_paid_touch: false,
+ },
+ {
+ job_id: RUN_A,
+ model_version: 'rules_v1',
+ orphan_distinct_id: '0190a1b2-phone-3c4d-5e6f-bob000000001',
+ anchor_person_key: '[email protected]',
+ score: 4.5,
+ margin: 1.75,
+ tier: 'medium',
+ computed_at: '2023-02-01T09:30:00Z',
+ shared_ip_days: 2,
+ shared_ips: 1,
+ min_ip_block_size: 3,
+ geo_city_match: true,
+ timezone_match: true,
+ language_match: false,
+ ua_exact_match: false,
+ orphan_is_webview: false,
+ device_type_complement: true,
+ days_overlap: 2,
+ avg_path_jaccard: 0.1,
+ orphan_paid_touch: false,
+ anchor_paid_touch: false,
+ },
+ {
+ job_id: RUN_A,
+ model_version: 'rules_v1',
+ orphan_distinct_id: '0190a1b2-tablet-3c4d-5e6f-dana00000001',
+ anchor_person_key: '[email protected]',
+ score: 3.05,
+ margin: 0.3,
+ tier: 'low',
+ computed_at: '2023-02-01T09:30:00Z',
+ shared_ip_days: 1,
+ shared_ips: 1,
+ min_ip_block_size: 8,
+ geo_city_match: false,
+ timezone_match: true,
+ language_match: true,
+ ua_exact_match: false,
+ orphan_is_webview: false,
+ device_type_complement: false,
+ days_overlap: 1,
+ avg_path_jaccard: 0,
+ orphan_paid_touch: false,
+ anchor_paid_touch: true,
+ },
+]
+
+const RUNS_RESULT: IdentityMatchingRunApi[] = [
+ {
+ job_id: RUN_A,
+ computed_at: '2023-02-01T09:30:00Z',
+ models: [
+ { model_version: 'rules_v1', link_count: 4 },
+ { model_version: 'logreg_v1', link_count: 1 },
+ ],
+ },
+ {
+ job_id: RUN_B,
+ computed_at: '2023-01-25T09:30:00Z',
+ models: [{ model_version: 'rules_v1', link_count: 2 }],
+ },
+]
+
+const meta: Meta = {
+ component: App,
+ title: 'Scenes-App/IdentityMatching',
+ parameters: {
+ layout: 'fullscreen',
+ viewMode: 'story',
+ mockDate: '2023-02-02', // To stabilize relative dates
+ pageUrl: urls.identityMatching(),
+ },
+ decorators: [
+ mswDecorator({
+ get: {
+ '/api/projects/:team_id/identity_matching_links/': {
+ results: LINKS_RESULT,
+ count: LINKS_RESULT.length,
+ },
+ '/api/projects/:team_id/identity_matching_links/runs/': {
+ results: RUNS_RESULT,
+ },
+ },
+ }),
+ ],
+}
+export default meta
+
+type Story = StoryObj<{}>
+export const IdentityMatchingLinks: Story = {}
+
+export const IdentityMatchingEmpty: Story = {
+ decorators: [
+ mswDecorator({
+ get: {
+ '/api/projects/:team_id/identity_matching_links/': { results: [], count: 0 },
+ '/api/projects/:team_id/identity_matching_links/runs/': { results: [] },
+ },
+ }),
+ ],
+}
diff --git a/products/growth/frontend/IdentityMatchingScene.tsx b/products/growth/frontend/IdentityMatchingScene.tsx
new file mode 100644
index 000000000000..15053bb554db
--- /dev/null
+++ b/products/growth/frontend/IdentityMatchingScene.tsx
@@ -0,0 +1,175 @@
+import { useActions, useValues } from 'kea'
+
+import { LemonBanner, LemonInput, LemonSelect, LemonTable, LemonTag, Link } from '@posthog/lemon-ui'
+
+import { AccessDenied } from 'lib/components/AccessDenied'
+import { dayjs } from 'lib/dayjs'
+import { LemonTableColumns } from 'lib/lemon-ui/LemonTable'
+import { SceneExport } from 'scenes/sceneTypes'
+import { urls } from 'scenes/urls'
+import { userLogic } from 'scenes/userLogic'
+
+import type { IdentityMatchingLinkApi } from './generated/api.schemas'
+import { identityMatchingLogic } from './identityMatchingLogic'
+
+export const scene: SceneExport = {
+ component: IdentityMatchingScene,
+ logic: identityMatchingLogic,
+}
+
+const TIER_TAG_TYPE = {
+ high: 'success',
+ medium: 'warning',
+ low: 'default',
+} as const
+
+function EvidenceCell({ link }: { link: IdentityMatchingLinkApi }): JSX.Element {
+ return (
+ <div className="flex flex-wrap gap-1">
+ <LemonTag>
+ {link.shared_ip_days} IP-day{link.shared_ip_days === 1 ? '' : 's'}
+ </LemonTag>
+ {link.shared_ips > 1 && <LemonTag>{link.shared_ips} IPs</LemonTag>}
+ {link.ua_exact_match && <LemonTag type="highlight">Same user agent</LemonTag>}
+ {link.orphan_is_webview && <LemonTag type="highlight">Webview</LemonTag>}
+ {link.device_type_complement && <LemonTag>Mobile + desktop</LemonTag>}
+ {link.geo_city_match && <LemonTag>Same city</LemonTag>}
+ {link.avg_path_jaccard > 0 && <LemonTag>{Math.round(link.avg_path_jaccard * 100)}% path overlap</LemonTag>}
+ {link.orphan_paid_touch && !link.anchor_paid_touch && <LemonTag type="completion">New paid touch</LemonTag>}
+ </div>
+ )
+}
+
+export function IdentityMatchingScene(): JSX.Element {
+ const { user } = useValues(userLogic)
+ const { filters, links, linksCount, linksResponseLoading, runs, modelVersions } = useValues(identityMatchingLogic)
+ const { setFilters } = useActions(identityMatchingLogic)
+
+ if (!user?.is_staff) {
+ return <AccessDenied object="page" reason="Identity matching is limited to staff users while in development." />
+ }
+
+ const columns: LemonTableColumns<IdentityMatchingLinkApi> = [
+ {
+ title: 'Anonymous visitor',
+ dataIndex: 'orphan_distinct_id',
+ render: (_, link) => (
+ <Link to={urls.personByDistinctId(link.orphan_distinct_id)} className="font-mono">
+ {link.orphan_distinct_id}
+ </Link>
+ ),
+ },
+ {
+ title: 'Matched person',
+ dataIndex: 'anchor_person_key',
+ render: (_, link) => (
+ <Link to={urls.personByDistinctId(link.anchor_person_key)}>{link.anchor_person_key}</Link>
+ ),
+ },
+ {
+ title: 'Model',
+ dataIndex: 'model_version',
+ render: (_, link) => <LemonTag>{link.model_version}</LemonTag>,
+ },
+ {
+ title: 'Score',
+ dataIndex: 'score',
+ sorter: (a, b) => a.score - b.score,
+ render: (_, link) => link.score.toFixed(2),
+ },
+ {
+ title: 'Margin',
+ dataIndex: 'margin',
+ render: (_, link) => link.margin.toFixed(2),
+ },
+ {
+ title: 'Tier',
+ dataIndex: 'tier',
+ render: (_, link) => <LemonTag type={TIER_TAG_TYPE[link.tier]}>{link.tier}</LemonTag>,
+ },
+ {
+ title: 'Evidence',
+ render: (_, link) => <EvidenceCell link={link} />,
+ },
+ {
+ title: 'Computed',
+ dataIndex: 'computed_at',
+ render: (_, link) => dayjs(link.computed_at).format('MMM D, YYYY HH:mm'),
+ },
+ ]
+
+ return (
+ <div className="space-y-4">
+ <p className="text-secondary">
+ Probable links between anonymous visitors and identified persons, recovered from first-party signals
+ like shared IPs, device traits, and browsing overlap. Links are analytics-only suggestions — nothing is
+ merged.
+ </p>
+ <div className="flex flex-wrap items-center gap-2">
+ <LemonSelect
+ placeholder="Latest run"
+ value={filters.jobId}
+ onChange={(jobId) => setFilters({ jobId })}
+ options={[
+ { value: null, label: 'Latest run' },
+ ...runs.map((run) => ({
+ value: run.job_id,
+ label: `${dayjs(run.computed_at).format('MMM D, HH:mm')} (${run.models
+ .map((model) => `${model.model_version}: ${model.link_count}`)
+ .join(', ')})`,
+ })),
+ ]}
+ size="small"
+ />
+ <LemonSelect
+ placeholder="All models"
+ value={filters.modelVersion}
+ onChange={(modelVersion) => setFilters({ modelVersion })}
+ options={[
+ { value: null, label: 'All models' },
+ ...modelVersions.map((version) => ({ value: version, label: version })),
+ ]}
+ size="small"
+ />
+ <LemonSelect
+ placeholder="All tiers"
+ value={filters.tier}
+ onChange={(tier) => setFilters({ tier })}
+ options={[
+ { value: null, label: 'All tiers' },
+ { value: 'high' as const, label: 'High' },
+ { value: 'medium' as const, label: 'Medium' },
+ { value: 'low' as const, label: 'Low' },
+ ]}
+ size="small"
+ />
+ <LemonInput
+ type="search"
+ placeholder="Search distinct IDs"
+ value={filters.search}
+ onChange={(search) => setFilters({ search })}
+ size="small"
+ />
+ <div className="ml-auto text-secondary">
+ {links.length < linksCount
+ ? `Showing ${links.length} of ${linksCount} links`
+ : `${linksCount} link${linksCount === 1 ? '' : 's'}`}
+ </div>
+ </div>
+ {!linksResponseLoading && links.length === 0 ? (
+ <LemonBanner type="info">
+ No identity matching links yet. Links appear after the identity matching job has run for this
+ project.
+ </LemonBanner>
+ ) : (
+ <LemonTable
+ dataSource={links}
+ columns={columns}
+ loading={linksResponseLoading}
+ rowKey={(link) => `${link.model_version}:${link.orphan_distinct_id}`}
+ pagination={{ pageSize: 50 }}
+ />
+ )}
+ </div>
+ )
+}
diff --git a/products/growth/frontend/generated/api.schemas.ts b/products/growth/frontend/generated/api.schemas.ts
new file mode 100644
index 000000000000..12dd2d4ce772
--- /dev/null
+++ b/products/growth/frontend/generated/api.schemas.ts
@@ -0,0 +1,148 @@
+/**
+ * Auto-generated from the Django backend OpenAPI schema.
+ * To modify these types, update the Django serializers or views, then run:
+ * hogli build:openapi
+ * Questions or issues? #team-devex on Slack
+ *
+ * PostHog API - generated
+ * OpenAPI spec version: 1.0.0
+ */
+/**
+ * * `high` - high
+ * * `medium` - medium
+ * * `low` - low
+ */
+export type TierEnumApi = (typeof TierEnumApi)[keyof typeof TierEnumApi]
+
+export const TierEnumApi = {
+ High: 'high',
+ Medium: 'medium',
+ Low: 'low',
+} as const
+
+export interface IdentityMatchingLinkApi {
+ /** Identity matching run that produced this link. */
+ job_id: string
+ /** Scoring model that produced the link, e.g. 'rules_v1' or 'logreg_v1'. */
+ model_version: string
+ /** Anonymous distinct ID that the model linked to an identified person. */
+ orphan_distinct_id: string
+ /** Canonical distinct ID representing the matched identified person. */
+ anchor_person_key: string
+ /** Link score: weighted rule points for 'rules_v1', a 0-1 probability for 'logreg_v1'. */
+ score: number
+ /** Score margin over the runner-up candidate person for this orphan. */
+ margin: number
+ /** Confidence tier derived from score thresholds.
+ *
+ * * `high` - high
+ * * `medium` - medium
+ * * `low` - low */
+ tier: TierEnumApi
+ /** When the link was computed (UTC). */
+ computed_at: string
+ /** Distinct (IP, day) combinations both sides were seen on. */
+ shared_ip_days: number
+ /** Distinct IPs both sides were seen on. */
+ shared_ips: number
+ /** Device count on the least crowded shared IP-day; small values suggest a household IP. */
+ min_ip_block_size: number
+ /** Both sides were seen in the same city. */
+ geo_city_match: boolean
+ /** Both sides reported the same timezone. */
+ timezone_match: boolean
+ /** Both sides reported the same browser language. */
+ language_match: boolean
+ /** A byte-identical user agent was seen on both sides. */
+ ua_exact_match: boolean
+ /** The orphan's traffic came from an in-app browser or webview. */
+ orphan_is_webview: boolean
+ /** The sides form a mobile + desktop device pair. */
+ device_type_complement: boolean
+ /** Number of days on which the two sides shared an IP. */
+ days_overlap: number
+ /** Average overlap (0-1) of pages visited by the two sides on shared IP-days. */
+ avg_path_jaccard: number
+ /** The orphan arrived via a paid click ID (gclid, li_fat_id, ...) inside the window. */
+ orphan_paid_touch: boolean
+ /** The matched person already had a paid click ID inside the window. */
+ anchor_paid_touch: boolean
+}
+
+export interface IdentityMatchingLinksResponseApi {
+ /** Links ordered by score, descending. */
+ results: IdentityMatchingLinkApi[]
+ /** Total links matching the filters, ignoring pagination. */
+ count: number
+}
+
+export interface IdentityMatchingRunModelCountApi {
+ /** Scoring model, e.g. 'rules_v1' or 'logreg_v1'. */
+ model_version: string
+ /** Number of links this model produced in the run. */
+ link_count: number
+}
+
+export interface IdentityMatchingRunApi {
+ /** Identity matching run identifier (the Dagster run ID). */
+ job_id: string
+ /** When the run wrote its links (UTC). */
+ computed_at: string
+ /** Link counts per scoring model in this run. */
+ models: IdentityMatchingRunModelCountApi[]
+}
+
+export interface IdentityMatchingRunsResponseApi {
+ /** Runs ordered by recency, most recent first. */
+ results: IdentityMatchingRunApi[]
+}
+
+export type IdentityMatchingLinksListParams = {
+ /**
+ * Identity matching run to read. Defaults to the team's most recent run.
+ */
+ job_id?: string
+ /**
+ * Page size, at most 500.
+ * @minimum 1
+ * @maximum 500
+ */
+ limit?: number
+ /**
+ * Only return links with a score at or above this.
+ */
+ min_score?: number
+ /**
+ * Only return links produced by this scoring model, e.g. 'rules_v1'.
+ * @minLength 1
+ */
+ model_version?: string
+ /**
+ * Pagination offset.
+ * @minimum 0
+ */
+ offset?: number
+ /**
+ * Case-insensitive substring match on the orphan distinct ID or the matched person key.
+ * @minLength 1
+ */
+ search?: string
+ /**
+ * Only return links in this confidence tier.
+ *
+ * * `high` - high
+ * * `medium` - medium
+ * * `low` - low
+ * @minLength 1
+ */
+ tier?: IdentityMatchingLinksListTier
+}
+
+export type IdentityMatchingLinksListTier =
+ (typeof IdentityMatchingLinksListTier)[keyof typeof IdentityMatchingLinksListTier]
+
+export const IdentityMatchingLinksListTier = {
+ High: 'high',
+ Medium: 'medium',
+ Low: 'low',
+} as const
diff --git a/products/growth/frontend/generated/api.ts b/products/growth/frontend/generated/api.ts
new file mode 100644
index 000000000000..aef7f93af88c
--- /dev/null
+++ b/products/growth/frontend/generated/api.ts
@@ -0,0 +1,64 @@
+import { apiMutator } from '../../../../frontend/src/lib/api-orval-mutator'
+/**
+ * Auto-generated from the Django backend OpenAPI schema.
+ * To modify these types, update the Django serializers or views, then run:
+ * hogli build:openapi
+ * Questions or issues? #team-devex on Slack
+ *
+ * PostHog API - generated
+ * OpenAPI spec version: 1.0.0
+ */
+import type {
+ IdentityMatchingLinksListParams,
+ IdentityMatchingLinksResponseApi,
+ IdentityMatchingRunsResponseApi,
+} from './api.schemas'
+
+export const getIdentityMatchingLinksListUrl = (projectId: string, params?: IdentityMatchingLinksListParams) => {
+ const normalizedParams = new URLSearchParams()
+
+ Object.entries(params || {}).forEach(([key, value]) => {
+ if (value !== undefined) {
+ normalizedParams.append(key, value === null ? 'null' : String(value))
+ }
+ })
+
+ const stringifiedParams = normalizedParams.toString()
+
+ return stringifiedParams.length > 0
+ ? `/api/projects/${projectId}/identity_matching_links/?${stringifiedParams}`
+ : `/api/projects/${projectId}/identity_matching_links/`
+}
+
+/**
+ * Scored links between anonymous distinct IDs and identified persons, with the evidence behind each link. Produced by the identity matching Dagster job; empty until that job has run for this project.
+ * @summary List identity matching links
+ */
+export const identityMatchingLinksList = async (
+ projectId: string,
+ params?: IdentityMatchingLinksListParams,
+ options?: RequestInit
+): Promise<IdentityMatchingLinksResponseApi> => {
+ return apiMutator<IdentityMatchingLinksResponseApi>(getIdentityMatchingLinksListUrl(projectId, params), {
+ ...options,
+ method: 'GET',
+ })
+}
+
+export const getIdentityMatchingLinksRunsRetrieveUrl = (projectId: string) => {
+ return `/api/projects/${projectId}/identity_matching_links/runs/`
+}
+
+/**
+ * Recent identity matching runs for this project with link counts per scoring model, most recent first.
+ * @summary List identity matching runs
+ */
+export const identityMatchingLinksRunsRetrieve = async (
+ projectId: string,
+ options?: RequestInit
+): Promise<IdentityMatchingRunsResponseApi> => {
+ return apiMutator<IdentityMatchingRunsResponseApi>(getIdentityMatchingLinksRunsRetrieveUrl(projectId), {
+ ...options,
+ method: 'GET',
+ })
+}
diff --git a/products/growth/frontend/generated/api.zod.schemas.ts b/products/growth/frontend/generated/api.zod.schemas.ts
new file mode 100644
index 000000000000..11d85a9b8514
--- /dev/null
+++ b/products/growth/frontend/generated/api.zod.schemas.ts
@@ -0,0 +1,158 @@
+/**
+ * Auto-generated Zod validation schemas from the Django backend OpenAPI schema.
+ * To modify these schemas, update the Django serializers or views, then run:
+ * hogli build:openapi
+ * Questions or issues? #team-devex on Slack
+ *
+ * PostHog API - generated
+ * OpenAPI spec version: 1.0.0
+ */
+import { z as zod } from 'zod'
+
+export const TierEnumApi = zod
+ .enum(['high', 'medium', 'low'])
+ .describe('\* `high` - high\n\* `medium` - medium\n\* `low` - low')
+
+export type TierEnumApi = zod.input<typeof TierEnumApi>
+export type TierEnumApiOutput = zod.output<typeof TierEnumApi>
+
+export const IdentityMatchingLinkApi = zod.object({
+ job_id: zod.uuid().describe('Identity matching run that produced this link.'),
+ model_version: zod.string().describe("Scoring model that produced the link, e.g. 'rules_v1' or 'logreg_v1'."),
+ orphan_distinct_id: zod.string().describe('Anonymous distinct ID that the model linked to an identified person.'),
+ anchor_person_key: zod.string().describe('Canonical distinct ID representing the matched identified person.'),
+ score: zod.number().describe("Link score: weighted rule points for 'rules_v1', a 0-1 probability for 'logreg_v1'."),
+ margin: zod.number().describe('Score margin over the runner-up candidate person for this orphan.'),
+ tier: zod
+ .enum(['high', 'medium', 'low'])
+ .describe('\* `high` - high\n\* `medium` - medium\n\* `low` - low')
+ .describe(
+ 'Confidence tier derived from score thresholds.\n\n\* `high` - high\n\* `medium` - medium\n\* `low` - low'
+ ),
+ computed_at: zod.iso.datetime({ offset: true }).describe('When the link was computed (UTC).'),
+ shared_ip_days: zod.number().describe('Distinct (IP, day) combinations both sides were seen on.'),
+ shared_ips: zod.number().describe('Distinct IPs both sides were seen on.'),
+ min_ip_block_size: zod
+ .number()
+ .describe('Device count on the least crowded shared IP-day; small values suggest a household IP.'),
+ geo_city_match: zod.boolean().describe('Both sides were seen in the same city.'),
+ timezone_match: zod.boolean().describe('Both sides reported the same timezone.'),
+ language_match: zod.boolean().describe('Both sides reported the same browser language.'),
+ ua_exact_match: zod.boolean().describe('A byte-identical user agent was seen on both sides.'),
+ orphan_is_webview: zod.boolean().describe("The orphan's traffic came from an in-app browser or webview."),
+ device_type_complement: zod.boolean().describe('The sides form a mobile + desktop device pair.'),
+ days_overlap: zod.number().describe('Number of days on which the two sides shared an IP.'),
+ avg_path_jaccard: zod
+ .number()
+ .describe('Average overlap (0-1) of pages visited by the two sides on shared IP-days.'),
+ orphan_paid_touch: zod
+ .boolean()
+ .describe('The orphan arrived via a paid click ID (gclid, li_fat_id, ...) inside the window.'),
+ anchor_paid_touch: zod.boolean().describe('The matched person already had a paid click ID inside the window.'),
+})
+
+export type IdentityMatchingLinkApi = zod.input<typeof IdentityMatchingLinkApi>
+export type IdentityMatchingLinkApiOutput = zod.output<typeof IdentityMatchingLinkApi>
+
+export const IdentityMatchingLinksResponseApi = zod.object({
+ results: zod
+ .array(
+ zod.object({
+ job_id: zod.uuid().describe('Identity matching run that produced this link.'),
+ model_version: zod
+ .string()
+ .describe("Scoring model that produced the link, e.g. 'rules_v1' or 'logreg_v1'."),
+ orphan_distinct_id: zod
+ .string()
+ .describe('Anonymous distinct ID that the model linked to an identified person.'),
+ anchor_person_key: zod
+ .string()
+ .describe('Canonical distinct ID representing the matched identified person.'),
+ score: zod
+ .number()
+ .describe("Link score: weighted rule points for 'rules_v1', a 0-1 probability for 'logreg_v1'."),
+ margin: zod.number().describe('Score margin over the runner-up candidate person for this orphan.'),
+ tier: zod
+ .enum(['high', 'medium', 'low'])
+ .describe('\* `high` - high\n\* `medium` - medium\n\* `low` - low')
+ .describe(
+ 'Confidence tier derived from score thresholds.\n\n\* `high` - high\n\* `medium` - medium\n\* `low` - low'
+ ),
+ computed_at: zod.iso.datetime({ offset: true }).describe('When the link was computed (UTC).'),
+ shared_ip_days: zod.number().describe('Distinct (IP, day) combinations both sides were seen on.'),
+ shared_ips: zod.number().describe('Distinct IPs both sides were seen on.'),
+ min_ip_block_size: zod
+ .number()
+ .describe('Device count on the least crowded shared IP-day; small values suggest a household IP.'),
+ geo_city_match: zod.boolean().describe('Both sides were seen in the same city.'),
+ timezone_match: zod.boolean().describe('Both sides reported the same timezone.'),
+ language_match: zod.boolean().describe('Both sides reported the same browser language.'),
+ ua_exact_match: zod.boolean().describe('A byte-identical user agent was seen on both sides.'),
+ orphan_is_webview: zod
+ .boolean()
+ .describe("The orphan's traffic came from an in-app browser or webview."),
+ device_type_complement: zod.boolean().describe('The sides form a mobile + desktop device pair.'),
+ days_overlap: zod.number().describe('Number of days on which the two sides shared an IP.'),
+ avg_path_jaccard: zod
+ .number()
+ .describe('Average overlap (0-1) of pages visited by the two sides on shared IP-days.'),
+ orphan_paid_touch: zod
+ .boolean()
+ .describe('The orphan arrived via a paid click ID (gclid, li_fat_id, ...) inside the window.'),
+ anchor_paid_touch: zod
+ .boolean()
+ .describe('The matched person already had a paid click ID inside the window.'),
+ })
+ )
+ .describe('Links ordered by score, descending.'),
+ count: zod.number().describe('Total links matching the filters, ignoring pagination.'),
+})
+
+export type IdentityMatchingLinksResponseApi = zod.input<typeof IdentityMatchingLinksResponseApi>
+export type IdentityMatchingLinksResponseApiOutput = zod.output<typeof IdentityMatchingLinksResponseApi>
+
+export const IdentityMatchingRunModelCountApi = zod.object({
+ model_version: zod.string().describe("Scoring model, e.g. 'rules_v1' or 'logreg_v1'."),
+ link_count: zod.number().describe('Number of links this model produced in the run.'),
+})
+
+export type IdentityMatchingRunModelCountApi = zod.input<typeof IdentityMatchingRunModelCountApi>
+export type IdentityMatchingRunModelCountApiOutput = zod.output<typeof IdentityMatchingRunModelCountApi>
+
+export const IdentityMatchingRunApi = zod.object({
+ job_id: zod.uuid().describe('Identity matching run identifier (the Dagster run ID).'),
+ computed_at: zod.iso.datetime({ offset: true }).describe('When the run wrote its links (UTC).'),
+ models: zod
+ .array(
+ zod.object({
+ model_version: zod.string().describe("Scoring model, e.g. 'rules_v1' or 'logreg_v1'."),
+ link_count: zod.number().describe('Number of links this model produced in the run.'),
+ })
+ )
+ .describe('Link counts per scoring model in this run.'),
+})
+
+export type IdentityMatchingRunApi = zod.input<typeof IdentityMatchingRunApi>
+export type IdentityMatchingRunApiOutput = zod.output<typeof IdentityMatchingRunApi>
+
+export const IdentityMatchingRunsResponseApi = zod.object({
+ results: zod
+ .array(
+ zod.object({
+ job_id: zod.uuid().describe('Identity matching run identifier (the Dagster run ID).'),
+ computed_at: zod.iso.datetime({ offset: true }).describe('When the run wrote its links (UTC).'),
+ models: zod
+ .array(
+ zod.object({
+ model_version: zod.string().describe("Scoring model, e.g. 'rules_v1' or 'logreg_v1'."),
+ link_count: zod.number().describe('Number of links this model produced in the run.'),
+ })
+ )
+ .describe('Link counts per scoring model in this run.'),
+ })
+ )
+ .describe('Runs ordered by recency, most recent first.'),
+})
+
+export type IdentityMatchingRunsResponseApi = zod.input<typeof IdentityMatchingRunsResponseApi>
+export type IdentityMatchingRunsResponseApiOutput = zod.output<typeof IdentityMatchingRunsResponseApi>
diff --git a/products/growth/frontend/generated/api.zod.ts b/products/growth/frontend/generated/api.zod.ts
new file mode 100644
index 000000000000..e8a15d4e1b52
--- /dev/null
+++ b/products/growth/frontend/generated/api.zod.ts
@@ -0,0 +1,9 @@
+/**
+ * Auto-generated Zod validation schemas from the Django backend OpenAPI schema.
+ * To modify these schemas, update the Django serializers or views, then run:
+ * hogli build:openapi
+ * Questions or issues? #team-devex on Slack
+ *
+ * PostHog API - generated
+ * OpenAPI spec version: 1.0.0
+ */
diff --git a/products/growth/frontend/identityMatchingLogic.ts b/products/growth/frontend/identityMatchingLogic.ts
new file mode 100644
index 000000000000..15d0264a205a
--- /dev/null
+++ b/products/growth/frontend/identityMatchingLogic.ts
@@ -0,0 +1,124 @@
+import { actions, afterMount, kea, listeners, path, reducers, selectors } from 'kea'
+import { loaders } from 'kea-loaders'
+
+import { teamLogic } from 'scenes/teamLogic'
+import { urls } from 'scenes/urls'
+
+import { Breadcrumb } from '~/types'
+
+import { identityMatchingLinksList, identityMatchingLinksRunsRetrieve } from './generated/api'
+import type {
+ IdentityMatchingLinkApi,
+ IdentityMatchingLinksListParams,
+ IdentityMatchingLinksListTier,
+ IdentityMatchingLinksResponseApi,
+ IdentityMatchingRunApi,
+ IdentityMatchingRunsResponseApi,
+} from './generated/api.schemas'
+import type { identityMatchingLogicType } from './identityMatchingLogicType'
+
+export interface IdentityMatchingFilters {
+ jobId: string | null
+ modelVersion: string | null
+ tier: IdentityMatchingLinksListTier | null
+ minScore: number | null
+ search: string
+}
+
+const DEFAULT_FILTERS: IdentityMatchingFilters = {
+ jobId: null,
+ modelVersion: null,
+ tier: null,
+ minScore: null,
+ search: '',
+}
+
+const LINKS_PAGE_SIZE = 500
+
+export const identityMatchingLogic = kea<identityMatchingLogicType>([
+ path(['products', 'growth', 'frontend', 'identityMatchingLogic']),
+ actions({
+ setFilters: (filters: Partial<IdentityMatchingFilters>) => ({ filters }),
+ }),
+ loaders(({ values }) => ({
+ runsResponse: {
+ __default: null as IdentityMatchingRunsResponseApi | null,
+ loadRuns: async () => {
+ const projectId = String(teamLogic.values.currentTeamId)
+ return await identityMatchingLinksRunsRetrieve(projectId)
+ },
+ },
+ linksResponse: {
+ __default: null as IdentityMatchingLinksResponseApi | null,
+ loadLinks: async (_: unknown, breakpoint) => {
+ await breakpoint(300)
+ const projectId = String(teamLogic.values.currentTeamId)
+ const { jobId, modelVersion, tier, minScore, search } = values.filters
+ const params: IdentityMatchingLinksListParams = { limit: LINKS_PAGE_SIZE }
+ if (jobId) {
+ params.job_id = jobId
+ }
+ if (modelVersion) {
+ params.model_version = modelVersion
+ }
+ if (tier) {
+ params.tier = tier
+ }
+ if (minScore !== null) {
+ params.min_score = minScore
+ }
+ if (search.trim()) {
+ params.search = search.trim()
+ }
+ const response = await identityMatchingLinksList(projectId, params)
+ breakpoint()
+ return response
+ },
+ },
+ })),
+ reducers({
+ filters: [
+ DEFAULT_FILTERS,
+ {
+ setFilters: (state, { filters }) => ({ ...state, ...filters }),
+ },
+ ],
+ }),
+ selectors({
+ links: [(s) => [s.linksResponse], (linksResponse): IdentityMatchingLinkApi[] => linksResponse?.results ?? []],
+ linksCount: [(s) => [s.linksResponse], (linksResponse): number => linksResponse?.count ?? 0],
+ runs: [(s) => [s.runsResponse], (runsResponse): IdentityMatchingRunApi[] => runsResponse?.results ?? []],
+ modelVersions: [
+ (s) => [s.runs],
+ (runs): string[] => {
+ const versions = new Set<string>()
+ for (const run of runs) {
+ for (const model of run.models) {
+ versions.add(model.model_version)
+ }
+ }
+ return Array.from(versions).sort()
+ },
+ ],
+ breadcrumbs: [
+ () => [],
+ (): Breadcrumb[] => [
+ {
+ key: 'IdentityMatching',
+ name: 'Identity matching',
+ path: urls.identityMatching(),
+ iconType: 'persons',
+ },
+ ],
+ ],
+ }),
+ listeners(({ actions }) => ({
+ setFilters: () => {
+ actions.loadLinks(null)
+ },
+ })),
+ afterMount(({ actions }) => {
+ actions.loadRuns()
+ actions.loadLinks(null)
+ }),
+])
diff --git a/products/growth/manifest.tsx b/products/growth/manifest.tsx
new file mode 100644
index 000000000000..1aee2e6aef48
--- /dev/null
+++ b/products/growth/manifest.tsx
@@ -0,0 +1,39 @@
+import { FEATURE_FLAGS } from 'lib/constants'
+import { urls } from 'scenes/urls'
+
+import { ProductItemCategory, ProductKey } from '~/queries/schema/schema-general'
+
+import { ProductManifest } from '../../frontend/src/types'
+
+export const manifest: ProductManifest = {
+ name: 'Growth',
+ scenes: {
+ IdentityMatching: {
+ name: 'Identity matching',
+ import: () => import('./frontend/IdentityMatchingScene'),
+ projectBased: true,
+ activityScope: 'IdentityMatching',
+ description:
+ 'Review probable links between anonymous visitors and identified persons, recovered from first-party signals.',
+ iconType: 'persons',
+ },
+ },
+ routes: {
+ '/identity-matching': ['IdentityMatching', 'identityMatching'],
+ },
+ urls: {
+ identityMatching: (): string => '/identity-matching',
+ },
+ treeItemsProducts: [
+ {
+ path: 'Identity matching',
+ intents: [ProductKey.MARKETING_ANALYTICS],
+ category: ProductItemCategory.UNRELEASED,
+ href: urls.identityMatching(),
+ flag: FEATURE_FLAGS.IDENTITY_MATCHING,
+ tags: ['alpha'],
+ iconType: 'persons',
+ sceneKey: 'IdentityMatching',
+ },
+ ],
+}
diff --git a/products/growth/package.json b/products/growth/package.json
index fa2f6f775d3f..196bfb6b8aa9 100644
--- a/products/growth/package.json
+++ b/products/growth/package.json
@@ -2,5 +2,18 @@
"name": "@posthog/products-growth",
"scripts": {
"backend:test": "pytest -c ../../pytest.ini --rootdir ../.. backend/ -v --tb=short"
+ },
+ "dependencies": {
+ "kea": "catalog:",
+ "kea-loaders": "catalog:"
+ },
+ "peerDependencies": {
+ "@posthog/icons": "*",
+ "@storybook/react": "catalog:",
+ "@types/react": "*",
+ "clsx": "*",
+ "jest": "*",
+ "react": "*",
+ "typescript": "catalog:*"
}
}
diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.ts
index 797a8b602cd2..65ecb9224ef1 100644
--- a/services/mcp/src/api/generated.ts
+++ b/services/mcp/src/api/generated.ts
@@ -25404,6 +25404,97 @@ export namespace Schemas {
tags?: TagDefinition[];
}
+ /**
+ * * `high` - high
+ * * `medium` - medium
+ * * `low` - low
+ */
+ export type TierEnum = typeof TierEnum[keyof typeof TierEnum];
+
+
+ export const TierEnum = {
+ High: 'high',
+ Medium: 'medium',
+ Low: 'low',
+ } as const;
+
+ export interface IdentityMatchingLink {
+ /** Identity matching run that produced this link. */
+ job_id: string;
+ /** Scoring model that produced the link, e.g. 'rules_v1' or 'logreg_v1'. */
+ model_version: string;
+ /** Anonymous distinct ID that the model linked to an identified person. */
+ orphan_distinct_id: string;
+ /** Canonical distinct ID representing the matched identified person. */
+ anchor_person_key: string;
+ /** Link score: weighted rule points for 'rules_v1', a 0-1 probability for 'logreg_v1'. */
+ score: number;
+ /** Score margin over the runner-up candidate person for this orphan. */
+ margin: number;
+ /** Confidence tier derived from score thresholds.
+ *
+ * * `high` - high
+ * * `medium` - medium
+ * * `low` - low */
+ tier: TierEnum;
+ /** When the link was computed (UTC). */
+ computed_at: string;
+ /** Distinct (IP, day) combinations both sides were seen on. */
+ shared_ip_days: number;
+ /** Distinct IPs both sides were seen on. */
+ shared_ips: number;
+ /** Device count on the least crowded shared IP-day; small values suggest a household IP. */
+ min_ip_block_size: number;
+ /** Both sides were seen in the same city. */
+ geo_city_match: boolean;
+ /** Both sides reported the same timezone. */
+ timezone_match: boolean;
+ /** Both sides reported the same browser language. */
+ language_match: boolean;
+ /** A byte-identical user agent was seen on both sides. */
+ ua_exact_match: boolean;
+ /** The orphan's traffic came from an in-app browser or webview. */
+ orphan_is_webview: boolean;
+ /** The sides form a mobile + desktop device pair. */
+ device_type_complement: boolean;
+ /** Number of days on which the two sides shared an IP. */
+ days_overlap: number;
+ /** Average overlap (0-1) of pages visited by the two sides on shared IP-days. */
+ avg_path_jaccard: number;
+ /** The orphan arrived via a paid click ID (gclid, li_fat_id, ...) inside the window. */
+ orphan_paid_touch: boolean;
+ /** The matched person already had a paid click ID inside the window. */
+ anchor_paid_touch: boolean;
+ }
+
+ export interface IdentityMatchingLinksResponse {
+ /** Links ordered by score, descending. */
+ results: IdentityMatchingLink[];
+ /** Total links matching the filters, ignoring pagination. */
+ count: number;
+ }
+
+ export interface IdentityMatchingRunModelCount {
+ /** Scoring model, e.g. 'rules_v1' or 'logreg_v1'. */
+ model_version: string;
+ /** Number of links this model produced in the run. */
+ link_count: number;
+ }
+
+ export interface IdentityMatchingRun {
+ /** Identity matching run identifier (the Dagster run ID). */
+ job_id: string;
+ /** When the run wrote its links (UTC). */
+ computed_at: string;
+ /** Link counts per scoring model in this run. */
+ models: IdentityMatchingRunModelCount[];
+ }
+
+ export interface IdentityMatchingRunsResponse {
+ /** Runs ordered by recency, most recent first. */
+ results: IdentityMatchingRun[];
+ }
+
/**
* * `trends` - trends
* * `funnel` - funnel
@@ -58362,6 +58453,56 @@ export namespace Schemas {
Week: 'week',
} as const;
+ export type IdentityMatchingLinksListParams = {
+ /**
+ * Identity matching run to read. Defaults to the team's most recent run.
+ */
+ job_id?: string;
+ /**
+ * Page size, at most 500.
+ * @minimum 1
+ * @maximum 500
+ */
+ limit?: number;
+ /**
+ * Only return links with a score at or above this.
+ */
+ min_score?: number;
+ /**
+ * Only return links produced by this scoring model, e.g. 'rules_v1'.
+ * @minLength 1
+ */
+ model_version?: string;
+ /**
+ * Pagination offset.
+ * @minimum 0
+ */
+ offset?: number;
+ /**
+ * Case-insensitive substring match on the orphan distinct ID or the matched person key.
+ * @minLength 1
+ */
+ search?: string;
+ /**
+ * Only return links in this confidence tier.
+ *
+ * * `high` - high
+ * * `medium` - medium
+ * * `low` - low
+ * @minLength 1
+ */
+ tier?: IdentityMatchingLinksListTier;
+ };
+
+ export type IdentityMatchingLinksListTier = typeof IdentityMatchingLinksListTier[keyof typeof IdentityMatchingLinksListTier];
+
+
+ export const IdentityMatchingLinksListTier = {
+ High: 'high',
+ Medium: 'medium',
+ Low: 'low',
+ } as const;
+
export type InsightVariablesListParams = {
/**
* A page number within the paginated result set.