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): improve uxui of id matching (#65497)

Fernando Gomes1e8bf23f26e0
diff --git a/frontend/snapshots.yml b/frontend/snapshots.yml
index 20c0a8418068..afdec4f00fcd 100644
--- a/frontend/snapshots.yml
+++ b/frontend/snapshots.yml
@@ -5437,13 +5437,25 @@ snapshots:
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
+ hash: v1.k794b7964.6fe23365f987396077c452f3dfe38f692c874ff0ee6142597f74d6feefe211db.XlTl5tDjFGmMkDDx1J6Houa_mxqS-4GpWrPaf_hs2Xk
scenes-app-identitymatching--identity-matching-empty--light:
- hash: v1.k794b7964.f9926a29648e70aaefabb52cc8f2873645d10ff68c5b35a86b53301649c3fc76._-1oLavqCmpFtryme0wGVYBvA6caczdWrxatH__KCb8
+ hash: v1.k794b7964.576678cc5f15af3cc6788cbcf8092cb4633e40e728407cc0a7897d78f689cb24.OBfXIvCDfEkuEdvmsp6ZmSN8fepujeyo8aEArhdMmzo
+ scenes-app-identitymatching--identity-matching-high-confidence-only--dark:
+ hash: v1.k794b7964.ec2acacb457e0dd239efa1fc735e6becd1452e0b0b9ee9abf629dd3c4cba74a3.K_w3T9Vi0ScNB6LK_rIMzBx9qms9sDmKYbFXOWFnW70
+ scenes-app-identitymatching--identity-matching-high-confidence-only--light:
+ hash: v1.k794b7964.4d3b2361bc470388be7c04dd4c875cc658c5edb251ba36c938f332c2a01ff21b.cnCApLSXv9h7_2D3W50s_Gic0QUzROCZi9WlI7JbL7c
scenes-app-identitymatching--identity-matching-links--dark:
- hash: v1.k794b7964.29928880970e5313fd6c9f06c85ee39905703aa53ec5c8c2eb021a53cb050227.4YKf3mh2oPrqZtVLiELhmpjM9LuLnOIh91axiijwv2o
+ hash: v1.k794b7964.40b0a32c1387c37a7b2214e41f79e10917eeffa1a55af4c21c0f26bcf8c6b5cc.CRnmP-09m0Dn2tPcIv1xKmn853YFxVXBnTdEQo1wvs8
scenes-app-identitymatching--identity-matching-links--light:
- hash: v1.k794b7964.2c62a943d44f752fa95427494501ad9f279c7fae50fbb668b48c9117e8c65bea.rIglwzOhQ9f_LwJY6srygYhwZEJuvhY94RN4rDix7WQ
+ hash: v1.k794b7964.b321e83e3f181efe7da556741fcd0e64364497369809acd7519e3c522104f796.yvslAXwxCUNOWrAWU27bpU20wi3o-Ra9zyS7H-ghekQ
+ scenes-app-identitymatching--identity-matching-logreg-only--dark:
+ hash: v1.k794b7964.863c302d816a58e0cb86571349fbd12050a6c9dbde66e03b5dc67d336d007830.GS85npWWijWnNotS3e2x-Q-o37Nh63galgG-tQfycNM
+ scenes-app-identitymatching--identity-matching-logreg-only--light:
+ hash: v1.k794b7964.28a5f63c45e499b868923277f259c10ac1a7633704f5a5e92b958afca86cc5e3._MSe3INWCRthr3bOXT9t9tL-gGJxDXy8UUrUeQqGz2w
+ scenes-app-identitymatching--identity-matching-paid-attribution--dark:
+ hash: v1.k794b7964.ec2acacb457e0dd239efa1fc735e6becd1452e0b0b9ee9abf629dd3c4cba74a3.2NRQm195Pnr0tiN-SqmECg5GjLL4JZFq4yugnYiGhZc
+ scenes-app-identitymatching--identity-matching-paid-attribution--light:
+ hash: v1.k794b7964.4d3b2361bc470388be7c04dd4c875cc658c5edb251ba36c938f332c2a01ff21b._ojUVhjnh-D6MFt_1IvN7KxuZ76IXepPLsNFy8aveX0
scenes-app-inbox-badges--all-badges--dark:
hash: v1.k794b7964.51fa6006ad07b02e6f11a352d76e9c401efd4445bd42d873081e7e7689aa14e0.okUTzDeF87AijpmaUtUxy65qKVS502E1-Eo1nXh10XE
scenes-app-inbox-badges--all-badges--light:
diff --git a/products/growth/backend/api/identity_matching.py b/products/growth/backend/api/identity_matching.py
index 422dec589aae..52fcf8600544 100644
--- a/products/growth/backend/api/identity_matching.py
+++ b/products/growth/backend/api/identity_matching.py
@@ -20,6 +20,7 @@ from rest_framework.response import Response
from posthog.api.routing import TeamAndOrgViewSetMixin
from posthog.clickhouse.client import sync_execute
+from posthog.clickhouse.query_tagging import Feature, Product, tags_context
from posthog.permissions import IsStaffUser
from products.growth.backend.constants import (
@@ -118,12 +119,22 @@ class IdentityMatchingLinksResponseSerializer(serializers.Serializer):
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.")
+ high_confidence = serializers.IntegerField(help_text="Links from this model in the 'high' tier.")
+ medium_confidence = serializers.IntegerField(help_text="Links from this model in the 'medium' tier.")
+ low_confidence = serializers.IntegerField(help_text="Links from this model in the 'low' tier.")
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.")
+ total_links = serializers.IntegerField(help_text="Total links across all models in this run.")
+ unique_orphans = serializers.IntegerField(help_text="Distinct anonymous visitors that were linked.")
+ paid_touches = serializers.IntegerField(
+ help_text="Links where a paid ad click was recovered for an anonymous visitor."
+ )
+ first_link_at = serializers.DateTimeField(help_text="Earliest link computed_at in the run (UTC).")
+ last_link_at = serializers.DateTimeField(help_text="Latest link computed_at in the run (UTC).")
class IdentityMatchingRunsResponseSerializer(serializers.Serializer):
@@ -174,14 +185,24 @@ class IdentityMatchingLinkViewSet(TeamAndOrgViewSetMixin, viewsets.ViewSet):
self.team.pk, _ALL_RUNS, IDENTITY_MATCHING_LINKS_DATASET, IDENTITY_MATCHING_LINKS_STRUCTURE
)
+ def _all_runs_candidate_pairs_read_args(self) -> str:
+ """`s3(...)` args globbing every run's candidate_pairs objects for this team."""
+ return identity_matching_dataset_read_args(
+ self.team.pk,
+ _ALL_RUNS,
+ IDENTITY_MATCHING_CANDIDATE_PAIRS_DATASET,
+ IDENTITY_MATCHING_CANDIDATE_PAIRS_STRUCTURE,
+ )
+
def _latest_job_id(self) -> str | None:
# argMax over an empty glob returns one row with the column's default (''); treat as no run.
- result = sync_execute( # nosemgrep: clickhouse-injection-taint,clickhouse-fstring-param-audit — only the constant s3() structure/format and a team_id-derived path are interpolated; team_id is an int from the URL, all values parameterized
- f"SELECT argMax(job_id, computed_at) FROM s3({self._all_runs_links_read_args()}) WHERE team_id = %(team_id)s",
- {"team_id": self.team.pk},
- settings=_S3_READ_SETTINGS,
- team_id=self.team.pk,
- )
+ with tags_context(product=Product.GROWTH, feature=Feature.QUERY):
+ result = sync_execute( # nosemgrep: clickhouse-injection-taint,clickhouse-fstring-param-audit — only the constant s3() structure/format and a team_id-derived path are interpolated; team_id is an int from the URL, all values parameterized
+ f"SELECT argMax(job_id, computed_at) FROM s3({self._all_runs_links_read_args()}) WHERE team_id = %(team_id)s",
+ {"team_id": self.team.pk},
+ settings=_S3_READ_SETTINGS,
+ team_id=self.team.pk,
+ )
job_id = result[0][0]
return str(job_id) if job_id else None
@@ -229,49 +250,50 @@ class IdentityMatchingLinkViewSet(TeamAndOrgViewSetMixin, viewsets.ViewSet):
links_s3 = self._links_read_args(job_id)
candidate_pairs_s3 = self._candidate_pairs_read_args(job_id)
- count_result = sync_execute( # nosemgrep: clickhouse-injection-taint,clickhouse-fstring-param-audit — s3 path from team_id (int) and validated job_id UUID; WHERE built from literals, values parameterized
- f"SELECT count() FROM s3({links_s3}) AS lk WHERE {where}",
- query_params,
- settings=_S3_READ_SETTINGS,
- team_id=self.team.pk,
- )
- count = count_result[0][0]
- rows = sync_execute( # nosemgrep: clickhouse-injection-taint,clickhouse-fstring-param-audit — s3 path from team_id (int) and validated job_id UUID; WHERE built from 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 s3({links_s3}) AS lk
- LEFT JOIN s3({candidate_pairs_s3}) AS p
- ON 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,
- settings=_S3_READ_SETTINGS,
- team_id=self.team.pk,
- )
+ with tags_context(product=Product.GROWTH, feature=Feature.QUERY):
+ count_result = sync_execute( # nosemgrep: clickhouse-injection-taint,clickhouse-fstring-param-audit — s3 path from team_id (int) and validated job_id UUID; WHERE built from literals, values parameterized
+ f"SELECT count() FROM s3({links_s3}) AS lk WHERE {where}",
+ query_params,
+ settings=_S3_READ_SETTINGS,
+ team_id=self.team.pk,
+ )
+ count = count_result[0][0]
+ rows = sync_execute( # nosemgrep: clickhouse-injection-taint,clickhouse-fstring-param-audit — s3 path from team_id (int) and validated job_id UUID; WHERE built from 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 s3({links_s3}) AS lk
+ LEFT JOIN s3({candidate_pairs_s3}) AS p
+ ON 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,
+ settings=_S3_READ_SETTINGS,
+ team_id=self.team.pk,
+ )
field_names = [
"job_id",
"model_version",
@@ -301,30 +323,81 @@ class IdentityMatchingLinkViewSet(TeamAndOrgViewSetMixin, viewsets.ViewSet):
@extend_schema(
summary="List identity matching runs",
- description="Recent identity matching runs for this project with link counts per scoring "
- "model, most recent first.",
+ description="Recent identity matching runs for this project with link counts, tier "
+ "breakdowns, and paid attribution stats per scoring model, most recent first.",
responses={200: IdentityMatchingRunsResponseSerializer, 503: _STORAGE_UNAVAILABLE_RESPONSE},
)
@action(detail=False, methods=["GET"])
def runs(self, request: Request, **kwargs: Any) -> Response:
self._assert_storage_configured()
- rows = sync_execute( # nosemgrep: clickhouse-injection-taint,clickhouse-fstring-param-audit — s3 path from team_id (int); values parameterized
- f"""
- SELECT job_id, max(computed_at) AS computed_at, model_version, count() AS link_count
- FROM s3({self._all_runs_links_read_args()})
- WHERE team_id = %(team_id)s
- GROUP BY job_id, model_version
- ORDER BY computed_at DESC
- """,
- {"team_id": self.team.pk},
- settings=_S3_READ_SETTINGS,
- team_id=self.team.pk,
- )
+ with tags_context(product=Product.GROWTH, feature=Feature.QUERY):
+ links_rows = sync_execute( # nosemgrep: clickhouse-injection-taint,clickhouse-fstring-param-audit — s3 path from team_id (int); values parameterized
+ f"""
+ SELECT
+ job_id,
+ max(computed_at) AS latest_computed_at,
+ min(computed_at) AS earliest_computed_at,
+ model_version,
+ count() AS link_count,
+ countIf(tier = 'high') AS high_count,
+ countIf(tier = 'medium') AS medium_count,
+ countIf(tier = 'low') AS low_count,
+ groupUniqArray(orphan_distinct_id) AS orphans
+ FROM s3({self._all_runs_links_read_args()})
+ WHERE team_id = %(team_id)s
+ GROUP BY job_id, model_version
+ ORDER BY latest_computed_at DESC
+ """,
+ {"team_id": self.team.pk},
+ settings=_S3_READ_SETTINGS,
+ team_id=self.team.pk,
+ )
+ # Paid touch counts come from candidate_pairs (links Parquet has no paid-touch columns).
+ pairs_rows = sync_execute( # nosemgrep: clickhouse-injection-taint,clickhouse-fstring-param-audit — s3 path from team_id (int); values parameterized
+ f"""
+ SELECT job_id, count(DISTINCT orphan_distinct_id) AS paid_touches
+ FROM s3({self._all_runs_candidate_pairs_read_args()})
+ WHERE team_id = %(team_id)s AND orphan_paid_touch = 1 AND anchor_paid_touch = 0
+ GROUP BY job_id
+ """,
+ {"team_id": self.team.pk},
+ settings=_S3_READ_SETTINGS,
+ team_id=self.team.pk,
+ )
+ paid_touches_by_run: dict[str, int] = {str(job_id): count for job_id, count in pairs_rows}
+
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})
+ for row in links_rows:
+ job_id, latest_at, earliest_at, model_version, link_count, high, medium, low, orphans = row
+ run = runs.setdefault(
+ str(job_id),
+ {
+ "job_id": job_id,
+ "computed_at": latest_at,
+ "first_link_at": earliest_at,
+ "last_link_at": latest_at,
+ "models": [],
+ "total_links": 0,
+ "unique_orphans": 0,
+ "paid_touches": paid_touches_by_run.get(str(job_id), 0),
+ },
+ )
+ run["computed_at"] = max(run["computed_at"], latest_at)
+ run["last_link_at"] = max(run["last_link_at"], latest_at)
+ run["first_link_at"] = min(run["first_link_at"], earliest_at)
+ run["models"].append(
+ {
+ "model_version": model_version,
+ "link_count": link_count,
+ "high_confidence": high,
+ "medium_confidence": medium,
+ "low_confidence": low,
+ }
+ )
+ run["total_links"] += link_count
+ orphan_set = run.setdefault("_orphan_set", set())
+ orphan_set.update(orphans)
+ run["unique_orphans"] = len(orphan_set)
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
index cd1c90441186..0b5b59112847 100644
--- a/products/growth/backend/api/test_identity_matching.py
+++ b/products/growth/backend/api/test_identity_matching.py
@@ -211,3 +211,13 @@ class TestIdentityMatchingLinksAPI(APIBaseTest):
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}
+ run_a = results[0]
+ assert run_a["total_links"] == 3
+ assert run_a["unique_orphans"] == 2
+ assert run_a["paid_touches"] == 1 # phone-2 has orphan_paid_touch=1
+ assert run_a["first_link_at"] is not None
+ assert run_a["last_link_at"] is not None
+ run_a_rules = {m["model_version"]: m for m in run_a["models"]}["rules_v1"]
+ assert run_a_rules["high_confidence"] == 1
+ assert run_a_rules["medium_confidence"] == 1
+ assert run_a_rules["low_confidence"] == 0
diff --git a/products/growth/frontend/IdentityMatchingDetail.tsx b/products/growth/frontend/IdentityMatchingDetail.tsx
new file mode 100644
index 000000000000..40577a890405
--- /dev/null
+++ b/products/growth/frontend/IdentityMatchingDetail.tsx
@@ -0,0 +1,194 @@
+import { IconArrowRight, IconBrowser, IconExternal, IconGlobe, IconLaptop, IconTarget } from '@posthog/icons'
+import { LemonButton, LemonTag, Tooltip } from '@posthog/lemon-ui'
+
+import { dayjs } from 'lib/dayjs'
+import { PersonDisplay } from 'scenes/persons/PersonDisplay'
+import { urls } from 'scenes/urls'
+
+import type { IdentityMatchingLinkApi } from './generated/api.schemas'
+import {
+ CATEGORY_DESCRIPTIONS,
+ CATEGORY_LABELS,
+ CATEGORY_ORDER,
+ type Signal,
+ type SignalCategory,
+ extractEmail,
+ extractSignals,
+ normalizedScore,
+ personFromDistinctId,
+} from './identityMatchingUtils'
+
+const CATEGORY_ICON: Record<SignalCategory, JSX.Element> = {
+ network: <IconGlobe />,
+ device: <IconLaptop />,
+ behavior: <IconBrowser />,
+ attribution: <IconTarget />,
+}
+
+const STRENGTH_LABELS: Record<number, string> = {
+ 1: 'Weak signal',
+ 2: 'Moderate signal',
+ 3: 'Strong signal',
+}
+
+function matchSummary(link: IdentityMatchingLinkApi, confidence: number): string {
+ const signals = extractSignals(link)
+ const topSignals = signals.filter((s) => s.strength >= 2).slice(0, 2)
+ const reasons = topSignals.map((s) => s.label.toLowerCase()).join(' and ')
+ const pct = Math.round(confidence * 100)
+ const personLabel = extractEmail(link.anchor_person_key) ?? 'this identified person'
+ if (reasons) {
+ return `We're ${pct}% confident this anonymous visitor is ${personLabel}, because they ${reasons}.`
+ }
+ return `We're ${pct}% confident this anonymous visitor is ${personLabel}.`
+}
+
+function SignalRow({ signal }: { signal: Signal }): JSX.Element {
+ return (
+ <div className="flex items-start gap-2 py-1.5">
+ <Tooltip title={STRENGTH_LABELS[signal.strength]}>
+ <div className="flex shrink-0 pt-0.5">
+ {Array.from({ length: 3 }, (_, i) => (
+ <div
+ key={i}
+ className={`size-1.5 rounded-full mr-0.5 ${
+ i < signal.strength ? 'bg-accent' : 'bg-border'
+ }`}
+ />
+ ))}
+ </div>
+ </Tooltip>
+ <div className="min-w-0">
+ <span className="text-sm font-medium">{signal.label}</span>
+ <p className="text-xs text-tertiary mt-0.5">{signal.description}</p>
+ </div>
+ </div>
+ )
+}
+
+function EvidenceSection({ category, signals }: { category: SignalCategory; signals: Signal[] }): JSX.Element | null {
+ if (signals.length === 0) {
+ return null
+ }
+ return (
+ <div>
+ <div className="flex items-center gap-2 mb-2">
+ <span className="text-base text-secondary">{CATEGORY_ICON[category]}</span>
+ <h4 className="text-sm font-semibold">{CATEGORY_LABELS[category]}</h4>
+ </div>
+ <p className="text-xs text-tertiary mb-2">{CATEGORY_DESCRIPTIONS[category]}</p>
+ <div className="divide-y divide-border">
+ {signals.map((signal, i) => (
+ <SignalRow key={i} signal={signal} />
+ ))}
+ </div>
+ </div>
+ )
+}
+
+export function IdentityMatchingDetail({ link }: { link: IdentityMatchingLinkApi }): JSX.Element {
+ const confidence = normalizedScore(link)
+ const signals = extractSignals(link)
+ const orphanEmail = extractEmail(link.orphan_distinct_id)
+ const anchorEmail = extractEmail(link.anchor_person_key)
+ const pct = Math.round(confidence * 100)
+
+ return (
+ <div className="space-y-6">
+ {/* The match */}
+ <div>
+ <div className="flex items-center gap-4 mb-3">
+ <div className="flex-1 rounded-lg border border-primary p-3">
+ <div className="text-xs text-tertiary mb-1">Anonymous visitor</div>
+ <PersonDisplay person={personFromDistinctId(link.orphan_distinct_id)} noPopover withIcon="sm" />
+ {!orphanEmail && (
+ <div className="font-mono text-xs text-muted mt-1">{link.orphan_distinct_id}</div>
+ )}
+ </div>
+ <IconArrowRight className="text-xl text-tertiary shrink-0" />
+ <div className="flex-1 rounded-lg border border-primary p-3">
+ <div className="text-xs text-tertiary mb-1">Identified person</div>
+ <PersonDisplay person={personFromDistinctId(link.anchor_person_key)} noPopover withIcon="sm" />
+ {!anchorEmail && (
+ <div className="font-mono text-xs text-muted mt-1">{link.anchor_person_key}</div>
+ )}
+ </div>
+ </div>
+ <p className="text-sm text-secondary">{matchSummary(link, confidence)}</p>
+ </div>
+
+ {/* Confidence */}
+ <div className="rounded-lg border border-primary p-4">
+ <div className="flex items-center justify-between mb-2">
+ <h4 className="text-sm font-semibold">Confidence assessment</h4>
+ <LemonTag
+ type={pct >= 70 ? 'success' : pct >= 40 ? 'warning' : 'default'}
+ >{`${pct}% confident`}</LemonTag>
+ </div>
+ <div className="flex items-center gap-2 mb-3">
+ <div className="flex-1 h-2 rounded-full bg-bg-light overflow-hidden">
+ <div
+ className={`h-full rounded-full ${
+ pct >= 70 ? 'bg-success' : pct >= 40 ? 'bg-warning' : 'bg-muted'
+ }`}
+ style={{ width: `${pct}%` }}
+ />
+ </div>
+ </div>
+ <div className="grid grid-cols-2 gap-2 text-xs">
+ <div>
+ <span className="text-tertiary">Model</span>
+ <div className="mt-0.5">
+ <LemonTag>{link.model_version}</LemonTag>
+ </div>
+ </div>
+ <div>
+ <span className="text-tertiary">Confidence gap</span>
+ <Tooltip title="How much this score exceeds the next-best candidate. A larger gap means fewer competing matches.">
+ <div className="mt-0.5 font-mono">{link.margin.toFixed(2)}</div>
+ </Tooltip>
+ </div>
+ <div>
+ <span className="text-tertiary">Raw score</span>
+ <Tooltip title="The model's unnormalized score. For rules_v1 this is a weighted point sum; for logreg_v1 it's a 0–1 probability.">
+ <div className="mt-0.5 font-mono">{link.score.toFixed(2)}</div>
+ </Tooltip>
+ </div>
+ <div>
+ <span className="text-tertiary">Computed</span>
+ <div className="mt-0.5">{dayjs(link.computed_at).format('MMM D, YYYY HH:mm')}</div>
+ </div>
+ </div>
+ </div>
+
+ {/* Evidence by category */}
+ <div className="space-y-5">
+ <h4 className="text-sm font-semibold">Why we matched them</h4>
+ {CATEGORY_ORDER.map((category) => {
+ const catSignals = signals.filter((s) => s.category === category)
+ return <EvidenceSection key={category} category={category} signals={catSignals} />
+ })}
+ </div>
+
+ {/* Actions */}
+ <div className="flex items-center gap-2 pt-2 border-t border-border">
+ <LemonButton
+ size="small"
+ type="secondary"
+ icon={<IconExternal />}
+ to={urls.personByDistinctId(link.orphan_distinct_id)}
+ >
+ View anonymous visitor
+ </LemonButton>
+ <LemonButton
+ size="small"
+ type="secondary"
+ icon={<IconExternal />}
+ to={urls.personByDistinctId(link.anchor_person_key)}
+ >
+ View identified person
+ </LemonButton>
+ </div>
+ </div>
+ )
+}
diff --git a/products/growth/frontend/IdentityMatchingScene.stories.tsx b/products/growth/frontend/IdentityMatchingScene.stories.tsx
index 42ff0b1a61a9..b1e90c78d7b7 100644
--- a/products/growth/frontend/IdentityMatchingScene.stories.tsx
+++ b/products/growth/frontend/IdentityMatchingScene.stories.tsx
@@ -126,21 +126,56 @@ const LINKS_RESULT: IdentityMatchingLinkApi[] = [
orphan_paid_touch: false,
anchor_paid_touch: true,
},
+ {
+ job_id: RUN_A,
+ model_version: 'logreg_v1',
+ orphan_distinct_id: '0190a1b2-anon-3c4d-5e6f-eve0000000001',
+ anchor_person_key: '0190a1b2-user-3c4d-5e6f-eve0000000002',
+ score: 0.42,
+ margin: 0.15,
+ tier: 'low',
+ computed_at: '2023-02-01T09:30:00Z',
+ shared_ip_days: 1,
+ shared_ips: 2,
+ min_ip_block_size: 15,
+ geo_city_match: false,
+ timezone_match: false,
+ 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: false,
+ },
]
const RUNS_RESULT: IdentityMatchingRunApi[] = [
{
job_id: RUN_A,
computed_at: '2023-02-01T09:30:00Z',
+ first_link_at: '2023-02-01T09:28:00Z',
+ last_link_at: '2023-02-01T09:31:00Z',
+ total_links: 6,
+ unique_orphans: 4,
+ paid_touches: 2,
models: [
- { model_version: 'rules_v1', link_count: 4 },
- { model_version: 'logreg_v1', link_count: 1 },
+ { model_version: 'rules_v1', link_count: 4, high_confidence: 2, medium_confidence: 1, low_confidence: 1 },
+ { model_version: 'logreg_v1', link_count: 2, high_confidence: 1, medium_confidence: 0, low_confidence: 1 },
],
},
{
job_id: RUN_B,
computed_at: '2023-01-25T09:30:00Z',
- models: [{ model_version: 'rules_v1', link_count: 2 }],
+ first_link_at: '2023-01-25T09:29:00Z',
+ last_link_at: '2023-01-25T09:30:30Z',
+ total_links: 2,
+ unique_orphans: 2,
+ paid_touches: 0,
+ models: [
+ { model_version: 'rules_v1', link_count: 2, high_confidence: 1, medium_confidence: 1, low_confidence: 0 },
+ ],
},
]
@@ -182,3 +217,51 @@ export const IdentityMatchingEmpty: Story = {
}),
],
}
+
+export const IdentityMatchingHighConfidenceOnly: Story = {
+ decorators: [
+ mswDecorator({
+ get: {
+ '/api/projects/:team_id/identity_matching_links/': {
+ results: LINKS_RESULT.filter((l) => l.tier === 'high'),
+ count: LINKS_RESULT.filter((l) => l.tier === 'high').length,
+ },
+ '/api/projects/:team_id/identity_matching_links/runs/': {
+ results: RUNS_RESULT,
+ },
+ },
+ }),
+ ],
+}
+
+export const IdentityMatchingLogregOnly: Story = {
+ decorators: [
+ mswDecorator({
+ get: {
+ '/api/projects/:team_id/identity_matching_links/': {
+ results: LINKS_RESULT.filter((l) => l.model_version === 'logreg_v1'),
+ count: LINKS_RESULT.filter((l) => l.model_version === 'logreg_v1').length,
+ },
+ '/api/projects/:team_id/identity_matching_links/runs/': {
+ results: RUNS_RESULT,
+ },
+ },
+ }),
+ ],
+}
+
+export const IdentityMatchingPaidAttribution: Story = {
+ decorators: [
+ mswDecorator({
+ get: {
+ '/api/projects/:team_id/identity_matching_links/': {
+ results: LINKS_RESULT.filter((l) => l.orphan_paid_touch),
+ count: LINKS_RESULT.filter((l) => l.orphan_paid_touch).length,
+ },
+ '/api/projects/:team_id/identity_matching_links/runs/': {
+ results: RUNS_RESULT,
+ },
+ },
+ }),
+ ],
+}
diff --git a/products/growth/frontend/IdentityMatchingScene.tsx b/products/growth/frontend/IdentityMatchingScene.tsx
index 15053bb554db..ad8df0ab528f 100644
--- a/products/growth/frontend/IdentityMatchingScene.tsx
+++ b/products/growth/frontend/IdentityMatchingScene.tsx
@@ -1,61 +1,244 @@
import { useActions, useValues } from 'kea'
+import { useState } from 'react'
-import { LemonBanner, LemonInput, LemonSelect, LemonTable, LemonTag, Link } from '@posthog/lemon-ui'
+import { IconDownload, IconInfo, IconPerson } from '@posthog/icons'
+import {
+ LemonBanner,
+ LemonButton,
+ LemonInput,
+ LemonSegmentedButton,
+ LemonSelect,
+ LemonTab,
+ LemonTable,
+ LemonTableColumns,
+ LemonTabs,
+ LemonTag,
+ Tooltip,
+ Link,
+} from '@posthog/lemon-ui'
+import api from 'lib/api'
import { AccessDenied } from 'lib/components/AccessDenied'
+import { downloadBlob } from 'lib/components/ExportButton/exporter'
import { dayjs } from 'lib/dayjs'
-import { LemonTableColumns } from 'lib/lemon-ui/LemonTable'
+import { LemonDialog } from 'lib/lemon-ui/LemonDialog'
+import { LemonDrawer } from 'lib/lemon-ui/LemonDrawer/LemonDrawer'
+import { LemonField } from 'lib/lemon-ui/LemonField'
+import { lemonToast } from 'lib/lemon-ui/LemonToast'
+import { PersonDisplay } from 'scenes/persons/PersonDisplay'
import { SceneExport } from 'scenes/sceneTypes'
import { urls } from 'scenes/urls'
import { userLogic } from 'scenes/userLogic'
+import { SceneContent } from '~/layout/scenes/components/SceneContent'
+
import type { IdentityMatchingLinkApi } from './generated/api.schemas'
-import { identityMatchingLogic } from './identityMatchingLogic'
+import { IdentityMatchingDetail } from './IdentityMatchingDetail'
+import { LINKS_PAGE_SIZE, identityMatchingLogic } from './identityMatchingLogic'
+import {
+ CATEGORY_LABELS,
+ CATEGORY_ORDER,
+ type SignalCategory,
+ computeTierStats,
+ extractSignals,
+ normalizedScore,
+ personFromDistinctId,
+} from './identityMatchingUtils'
+import { PaidAttributionTimeline } from './PaidAttributionTimeline'
+import { RunsHistory } from './RunsHistory'
export const scene: SceneExport = {
component: IdentityMatchingScene,
logic: identityMatchingLogic,
}
-const TIER_TAG_TYPE = {
+type ModelPreference = 'all' | 'logreg_v1' | 'rules_v1'
+
+const TIER_TAG_TYPE: Record<string, 'success' | 'warning' | 'default'> = {
high: 'success',
medium: 'warning',
low: 'default',
-} as const
+}
+
+const CATEGORY_TAG_TYPE: Record<SignalCategory, 'default' | 'highlight' | 'completion'> = {
+ network: 'highlight',
+ device: 'highlight',
+ behavior: 'default',
+ attribution: 'completion',
+}
+
+function buildLinksCsv(links: IdentityMatchingLinkApi[]): string {
+ const headers = [
+ 'orphan_distinct_id',
+ 'anchor_person_key',
+ 'model_version',
+ 'score',
+ 'margin',
+ 'tier',
+ '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',
+ 'computed_at',
+ ]
+ const rows = links.map((l) =>
+ [
+ l.orphan_distinct_id,
+ l.anchor_person_key,
+ l.model_version,
+ l.score,
+ l.margin,
+ l.tier,
+ l.shared_ip_days,
+ l.shared_ips,
+ l.min_ip_block_size,
+ l.geo_city_match,
+ l.timezone_match,
+ l.language_match,
+ l.ua_exact_match,
+ l.orphan_is_webview,
+ l.device_type_complement,
+ l.days_overlap,
+ l.avg_path_jaccard,
+ l.orphan_paid_touch,
+ l.anchor_paid_touch,
+ l.computed_at,
+ ]
+ .map((v) => {
+ let s = String(v)
+ if (/^\s*[=+\-@]/.test(s)) {
+ s = `'${s}`
+ }
+ return s.includes(',') || s.includes('"') ? `"${s.replace(/"/g, '""')}"` : s
+ })
+ .join(',')
+ )
+ return [headers.join(','), ...rows].join('\n')
+}
+
+function exportLinks(links: IdentityMatchingLinkApi[], totalCount: number): void {
+ const csv = buildLinksCsv(links)
+ const blob = new Blob([csv], { type: 'text/csv' })
+ downloadBlob(blob, `identity_matching_links_${dayjs().format('YYYY-MM-DD')}.csv`)
+ if (totalCount > links.length) {
+ lemonToast.warning(
+ `Exported ${links.length} of ${totalCount} links (current page only). Navigate to other pages to export remaining links.`
+ )
+ } else {
+ lemonToast.success(`Exported ${links.length} links`)
+ }
+}
+
+function createCohortFromLinks(links: IdentityMatchingLinkApi[], modelPreference: ModelPreference): void {
+ const distinctIds = new Set<string>()
+ for (const link of links) {
+ if (modelPreference === 'all' || link.model_version === modelPreference) {
+ distinctIds.add(link.orphan_distinct_id)
+ distinctIds.add(link.anchor_person_key)
+ }
+ }
+ const ids = Array.from(distinctIds)
+
+ LemonDialog.openForm({
+ title: 'Create cohort from identity matches',
+ initialValues: { name: `Identity matches (${dayjs().format('YYYY-MM-DD')})` },
+ content: (
+ <LemonField name="name">
+ <LemonInput placeholder="Cohort name" autoFocus />
+ </LemonField>
+ ),
+ errors: { name: (name: string) => (!name ? 'You must enter a name' : undefined) },
+ onSubmit: async ({ name }: Record<string, any>) => {
+ try {
+ const csvContent = ids
+ .map((id) =>
+ String(id)
+ .replace(/[\n\r]/g, ' ')
+ .replace(/[\s]*[=+\-@]/, "'$&")
+ )
+ .join('\n')
+ const csvFile = new File([csvContent], 'distinct_ids.csv', { type: 'text/csv' })
+ const formData = new FormData()
+ formData.append('name', name)
+ formData.append('description', `Created from identity matching links (${ids.length} distinct IDs)`)
+ formData.append('is_static', 'true')
+ formData.append('csv', csvFile)
+ formData.append('filters', JSON.stringify({ properties: {} }))
+ await api.cohorts.create(formData as unknown as Record<string, unknown>)
+ lemonToast.success(`Created cohort "${name}" with ${ids.length} persons`)
+ } catch {
+ lemonToast.error('Failed to create cohort')
+ }
+ },
+ })
+}
+
+function KpiBar({ links, loading }: { links: IdentityMatchingLinkApi[]; loading: boolean }): JSX.Element {
+ const stats = computeTierStats(links)
+ const highPct = stats.total > 0 ? Math.round((stats.high / stats.total) * 100) : 0
+ const paidPct = stats.total > 0 ? Math.round((stats.paidTouches / stats.total) * 100) : 0
+
+ if (loading) {
+ return <div className="text-sm text-muted">Loading…</div>
+ }
-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 className="flex flex-wrap items-center gap-2 text-sm">
+ <span className="font-semibold text-primary">{stats.total.toLocaleString()}</span>
+ <span className="text-tertiary">links</span>
+ <span className="text-border">·</span>
+ <LemonTag type="success">{stats.high.toLocaleString()} high</LemonTag>
+ <span className="text-tertiary">{highPct}%</span>
+ <span className="text-border">·</span>
+ <LemonTag type="warning">{stats.medium.toLocaleString()} medium</LemonTag>
+ <span className="text-border">·</span>
+ <LemonTag>{stats.low.toLocaleString()} low</LemonTag>
+ <span className="text-border">·</span>
+ <LemonTag type="completion">{stats.paidTouches.toLocaleString()} paid touches</LemonTag>
+ <span className="text-tertiary">{paidPct}%</span>
</div>
)
}
export function IdentityMatchingScene(): JSX.Element {
const { user } = useValues(userLogic)
- const { filters, links, linksCount, linksResponseLoading, runs, modelVersions } = useValues(identityMatchingLogic)
- const { setFilters } = useActions(identityMatchingLogic)
+ const {
+ filters,
+ links,
+ linksCount,
+ linksResponseLoading,
+ runs,
+ modelVersions,
+ runsResponseLoading,
+ page,
+ activeTab,
+ } = useValues(identityMatchingLogic)
+ const { setFilters, setPage, setActiveTab } = useActions(identityMatchingLogic)
+
+ const [drawerLink, setDrawerLink] = useState<IdentityMatchingLinkApi | null>(null)
if (!user?.is_staff) {
return <AccessDenied object="page" reason="Identity matching is limited to staff users while in development." />
}
+ const tierStats = computeTierStats(links)
+
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 to={urls.personByDistinctId(link.orphan_distinct_id)}>
+ <PersonDisplay person={personFromDistinctId(link.orphan_distinct_id)} noPopover withIcon="sm" />
</Link>
),
},
@@ -63,113 +246,258 @@ export function IdentityMatchingScene(): JSX.Element {
title: 'Matched person',
dataIndex: 'anchor_person_key',
render: (_, link) => (
- <Link to={urls.personByDistinctId(link.anchor_person_key)}>{link.anchor_person_key}</Link>
+ <Link to={urls.personByDistinctId(link.anchor_person_key)}>
+ <PersonDisplay person={personFromDistinctId(link.anchor_person_key)} noPopover withIcon="sm" />
+ </Link>
),
},
{
title: 'Model',
dataIndex: 'model_version',
render: (_, link) => <LemonTag>{link.model_version}</LemonTag>,
+ width: 110,
},
{
- title: 'Score',
- dataIndex: 'score',
+ title: (
+ <span className="flex items-center gap-1">
+ Confidence
+ <Tooltip title="Normalized confidence score combining the model's score, tier, and margin over the runner-up candidate.">
+ <IconInfo className="text-xs text-tertiary" />
+ </Tooltip>
+ </span>
+ ),
+ key: 'confidence',
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>,
+ render: (_, link) => {
+ const confidence = normalizedScore(link)
+ const pct = Math.round(confidence * 100)
+ return (
+ <div className="flex flex-col gap-1 min-w-28">
+ <div className="flex items-center gap-2">
+ <div className="flex-1 h-2 rounded-full bg-bg-light overflow-hidden">
+ <div
+ className={`h-full rounded-full ${
+ pct >= 70 ? 'bg-success' : pct >= 40 ? 'bg-warning' : 'bg-muted'
+ }`}
+ style={{ width: `${pct}%` }}
+ />
+ </div>
+ <Tooltip title={`Raw score: ${link.score.toFixed(2)} (${link.model_version})`}>
+ <span className="text-xs font-mono text-secondary tabular-nums">{pct}%</span>
+ </Tooltip>
+ </div>
+ <div className="flex items-center gap-1.5">
+ <LemonTag type={TIER_TAG_TYPE[link.tier]}>{link.tier}</LemonTag>
+ <Tooltip title="Confidence gap over the runner-up candidate">
+ <span className="text-xs text-tertiary">gap {link.margin.toFixed(2)}</span>
+ </Tooltip>
+ </div>
+ </div>
+ )
+ },
+ width: 180,
},
{
title: 'Evidence',
- render: (_, link) => <EvidenceCell link={link} />,
+ key: 'evidence',
+ render: (_, link) => {
+ const signals = extractSignals(link)
+ return (
+ <div className="flex flex-col gap-1">
+ {CATEGORY_ORDER.map((cat) => {
+ const catSignals = signals.filter((s) => s.category === cat)
+ if (catSignals.length === 0) {
+ return null
+ }
+ return (
+ <div key={cat} className="flex items-center gap-1">
+ <Tooltip title={CATEGORY_LABELS[cat]}>
+ <span className="text-xs text-tertiary w-16 shrink-0">
+ {CATEGORY_LABELS[cat]}
+ </span>
+ </Tooltip>
+ <div className="flex flex-wrap gap-1">
+ {catSignals.map((signal, i) => (
+ <LemonTag key={`${cat}-${i}`} type={CATEGORY_TAG_TYPE[cat]}>
+ {signal.label}
+ </LemonTag>
+ ))}
+ </div>
+ </div>
+ )
+ })}
+ </div>
+ )
+ },
},
{
title: 'Computed',
dataIndex: 'computed_at',
render: (_, link) => dayjs(link.computed_at).format('MMM D, YYYY HH:mm'),
+ width: 140,
},
]
- 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'}`}
+ const tabs: LemonTab<string>[] = [
+ {
+ key: 'links',
+ label: (
+ <span className="flex items-center gap-1.5">
+ Links
+ {linksCount > 0 && <LemonTag className="ml-1">{linksCount.toLocaleString()}</LemonTag>}
+ </span>
+ ),
+ content: (
+ <div className="space-y-4">
+ <KpiBar links={links} loading={linksResponseLoading} />
+ <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.total_links} links`,
+ })),
+ ]}
+ size="small"
+ />
+ <LemonSegmentedButton
+ value={filters.modelVersion ?? 'all'}
+ onChange={(modelVersion) =>
+ setFilters({ modelVersion: modelVersion === 'all' ? null : modelVersion })
+ }
+ options={[
+ { value: 'all' as const, label: 'All models' },
+ ...modelVersions.map((version) => ({ value: version, label: version })),
+ ]}
+ size="small"
+ />
+ <LemonInput
+ type="search"
+ placeholder="Search distinct IDs or emails"
+ value={filters.search}
+ onChange={(search) => setFilters({ search })}
+ size="small"
+ />
+ <div className="flex gap-2 ml-auto">
+ <LemonButton
+ size="small"
+ type="secondary"
+ icon={<IconDownload />}
+ disabled={links.length === 0}
+ onClick={() => exportLinks(links, linksCount)}
+ >
+ Export CSV
+ </LemonButton>
+ <LemonButton
+ size="small"
+ type="secondary"
+ icon={<IconPerson />}
+ disabled={links.length === 0}
+ onClick={() =>
+ createCohortFromLinks(links, (filters.modelVersion as ModelPreference) ?? 'all')
+ }
+ >
+ Create cohort
+ </LemonButton>
+ </div>
+ </div>
+ {!linksResponseLoading && links.length === 0 ? (
+ <LemonBanner
+ type="info"
+ action={{
+ to: 'https://posthog.com/docs',
+ targetBlank: true,
+ children: 'Learn more',
+ }}
+ >
+ No identity matching links yet. Links appear after the identity matching Dagster job has run
+ for this project. The job runs periodically — contact your growth team if you need to
+ trigger a run manually.
+ </LemonBanner>
+ ) : (
+ <LemonTable
+ dataSource={links}
+ columns={columns}
+ loading={linksResponseLoading}
+ rowKey={(link) => `${link.model_version}:${link.orphan_distinct_id}`}
+ pagination={{
+ controlled: true,
+ pageSize: LINKS_PAGE_SIZE,
+ currentPage: page,
+ entryCount: linksCount,
+ onBackward: page > 1 ? () => setPage(page - 1) : undefined,
+ onForward: page * LINKS_PAGE_SIZE < linksCount ? () => setPage(page + 1) : undefined,
+ }}
+ nouns={['link', 'links']}
+ onRow={(link) => ({
+ onClick: () => setDrawerLink(link),
+ className: 'cursor-pointer',
+ })}
+ />
+ )}
</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 }}
+ ),
+ },
+ {
+ key: 'paid_attribution',
+ label: (
+ <span className="flex items-center gap-1.5">
+ Paid attribution
+ {tierStats.paidTouches > 0 && (
+ <LemonTag type="completion" className="ml-1">
+ {tierStats.paidTouches}
+ </LemonTag>
+ )}
+ </span>
+ ),
+ content: <PaidAttributionTimeline links={links} />,
+ },
+ {
+ key: 'runs',
+ label: 'Run history',
+ content: (
+ <RunsHistory
+ runs={runs}
+ selectedJobId={filters.jobId}
+ onSelect={(jobId) => setFilters({ jobId })}
+ loading={runsResponseLoading}
/>
- )}
- </div>
+ ),
+ },
+ ]
+
+ return (
+ <SceneContent className="pt-4">
+ <div>
+ <h1 className="text-xl font-bold">Identity matching</h1>
+ <p className="text-sm text-secondary mt-1">
+ Probable links between anonymous visitors and identified persons, recovered from first-party
+ signals. Links are analytics-only suggestions — nothing is merged.
+ </p>
+ </div>
+ <LemonTabs
+ activeKey={activeTab}
+ onChange={(key: string) => setActiveTab(key as typeof activeTab)}
+ tabs={tabs}
+ sceneInset
+ />
+ <LemonDrawer
+ isOpen={drawerLink !== null}
+ onClose={() => setDrawerLink(null)}
+ width="60vw"
+ title={
+ <div className="flex items-center gap-2">
+ <IconPerson className="text-lg" />
+ <span>Identity match detail</span>
+ </div>
+ }
+ >
+ {drawerLink && <IdentityMatchingDetail link={drawerLink} />}
+ </LemonDrawer>
+ </SceneContent>
)
}
diff --git a/products/growth/frontend/PaidAttributionTimeline.tsx b/products/growth/frontend/PaidAttributionTimeline.tsx
new file mode 100644
index 000000000000..56fb585e972e
--- /dev/null
+++ b/products/growth/frontend/PaidAttributionTimeline.tsx
@@ -0,0 +1,292 @@
+import { IconArrowRight, IconExternal, IconTarget } from '@posthog/icons'
+import { LemonButton, LemonTable, LemonTableColumns, LemonTag, Tooltip } from '@posthog/lemon-ui'
+
+import { dayjs } from 'lib/dayjs'
+import { PersonDisplay } from 'scenes/persons/PersonDisplay'
+import { urls } from 'scenes/urls'
+
+import type { IdentityMatchingLinkApi } from './generated/api.schemas'
+import { normalizedScore, personFromDistinctId } from './identityMatchingUtils'
+
+interface TimelineStep {
+ label: string
+ description: string
+ tone: 'completion' | 'highlight' | 'muted'
+}
+
+function buildTimeline(link: IdentityMatchingLinkApi): TimelineStep[] {
+ const steps: TimelineStep[] = []
+
+ if (link.orphan_paid_touch) {
+ steps.push({
+ label: 'Paid ad click',
+ description: 'The anonymous visitor arrived via a paid ad click (e.g. Google Ads, LinkedIn, TikTok).',
+ tone: 'completion',
+ })
+ }
+
+ steps.push({
+ label: 'Shared network',
+ description: `Both identities were seen on the same IP address on ${link.shared_ip_days} day${link.shared_ip_days === 1 ? '' : 's'}, suggesting the same person on the same network.`,
+ tone: 'highlight',
+ })
+
+ if (link.ua_exact_match) {
+ steps.push({
+ label: 'Same device',
+ description:
+ 'An identical browser user agent was seen on both identities — likely the same physical device.',
+ tone: 'highlight',
+ })
+ }
+
+ if (link.avg_path_jaccard > 0) {
+ steps.push({
+ label: 'Browsed same pages',
+ description: `${Math.round(link.avg_path_jaccard * 100)}% overlap in pages visited on shared IP days.`,
+ tone: 'muted',
+ })
+ }
+
+ steps.push({
+ label: 'Identified person',
+ description: link.anchor_paid_touch
+ ? 'The visitor was already identified — both the ad click and the identification belong to the same person.'
+ : 'The visitor later identified themselves (e.g. signed up). This match links the earlier anonymous ad click to them.',
+ tone: 'completion',
+ })
+
+ return steps
+}
+
+const DOT_CLASS: Record<TimelineStep['tone'], string> = {
+ completion: 'bg-success border-success',
+ highlight: 'bg-accent border-accent',
+ muted: 'bg-surface-secondary border-border',
+}
+
+function PaidTimelineCard({ link }: { link: IdentityMatchingLinkApi }): JSX.Element {
+ const steps = buildTimeline(link)
+ const confidence = normalizedScore(link)
+ const pct = Math.round(confidence * 100)
+
+ return (
+ <div className="rounded-lg border border-primary bg-surface-secondary p-4 space-y-3">
+ {/* Identity pair */}
+ <div className="flex items-center gap-3">
+ <div className="flex-1 min-w-0">
+ <div className="text-xs text-tertiary mb-0.5">Anonymous visitor</div>
+ <PersonDisplay person={personFromDistinctId(link.orphan_distinct_id)} noPopover withIcon="sm" />
+ </div>
+ <IconArrowRight className="text-lg text-tertiary shrink-0" />
+ <div className="flex-1 min-w-0">
+ <div className="text-xs text-tertiary mb-0.5">Identified person</div>
+ <PersonDisplay person={personFromDistinctId(link.anchor_person_key)} noPopover withIcon="sm" />
+ </div>
+ <div className="shrink-0 text-right">
+ <LemonTag type={pct >= 70 ? 'success' : pct >= 40 ? 'warning' : 'default'}>{pct}%</LemonTag>
+ <div className="text-xs text-tertiary mt-1">{link.model_version}</div>
+ </div>
+ </div>
+
+ {/* Timeline */}
+ <div className="pl-1">
+ <div className="relative">
+ {/* Vertical line — sits behind the dots, centered on them */}
+ <div className="absolute left-[7px] top-3 bottom-3 w-px bg-border" />
+ <div className="space-y-3">
+ {steps.map((step, i) => (
+ <div key={i} className="flex items-start gap-3">
+ <div
+ className={`size-3.5 rounded-full border-2 shrink-0 mt-0.5 ${DOT_CLASS[step.tone]}`}
+ />
+ <div className="min-w-0 flex-1">
+ <div className="text-sm font-medium">{step.label}</div>
+ <p className="text-xs text-tertiary">{step.description}</p>
+ </div>
+ </div>
+ ))}
+ </div>
+ </div>
+ </div>
+
+ {/* Footer */}
+ <div className="flex items-center justify-between pt-2 border-t border-border">
+ <span className="text-xs text-tertiary">
+ Computed {dayjs(link.computed_at).format('MMM D, YYYY HH:mm')}
+ </span>
+ <div className="flex gap-1">
+ <LemonButton
+ size="xsmall"
+ type="tertiary"
+ icon={<IconExternal />}
+ to={urls.personByDistinctId(link.orphan_distinct_id)}
+ >
+ Visitor
+ </LemonButton>
+ <LemonButton
+ size="xsmall"
+ type="tertiary"
+ icon={<IconExternal />}
+ to={urls.personByDistinctId(link.anchor_person_key)}
+ >
+ Person
+ </LemonButton>
+ </div>
+ </div>
+ </div>
+ )
+}
+
+function PaidAttributionTable({ links }: { links: IdentityMatchingLinkApi[] }): JSX.Element {
+ const columns: LemonTableColumns<IdentityMatchingLinkApi> = [
+ {
+ title: 'Anonymous visitor',
+ dataIndex: 'orphan_distinct_id',
+ render: (_, link) => (
+ <PersonDisplay person={personFromDistinctId(link.orphan_distinct_id)} noPopover withIcon="sm" />
+ ),
+ },
+ {
+ title: 'Identified person',
+ dataIndex: 'anchor_person_key',
+ render: (_, link) => (
+ <PersonDisplay person={personFromDistinctId(link.anchor_person_key)} noPopover withIcon="sm" />
+ ),
+ },
+ {
+ title: 'Confidence',
+ key: 'confidence',
+ render: (_, link) => {
+ const pct = Math.round(normalizedScore(link) * 100)
+ return <LemonTag type={pct >= 70 ? 'success' : pct >= 40 ? 'warning' : 'default'}>{pct}%</LemonTag>
+ },
+ width: 100,
+ },
+ {
+ title: 'IP days',
+ dataIndex: 'shared_ip_days',
+ width: 80,
+ render: (_, link) => <span className="font-mono tabular-nums">{link.shared_ip_days}</span>,
+ },
+ {
+ title: 'Same UA',
+ dataIndex: 'ua_exact_match',
+ width: 80,
+ render: (_, link) => (link.ua_exact_match ? <LemonTag type="highlight">Yes</LemonTag> : '—'),
+ },
+ {
+ title: 'Type',
+ key: 'type',
+ width: 110,
+ render: (_, link) =>
+ link.anchor_paid_touch ? (
+ <LemonTag type="highlight">Confirmed</LemonTag>
+ ) : (
+ <LemonTag type="completion">Recovered</LemonTag>
+ ),
+ },
+ {
+ title: 'Computed',
+ dataIndex: 'computed_at',
+ width: 140,
+ render: (_, link) => dayjs(link.computed_at).format('MMM D, HH:mm'),
+ },
+ ]
+
+ return (
+ <LemonTable
+ dataSource={links}
+ columns={columns}
+ rowKey={(link) => `${link.model_version}:${link.orphan_distinct_id}`}
+ pagination={{ pageSize: 50 }}
+ size="small"
+ nouns={['attribution', 'attributions']}
+ />
+ )
+}
+
+export function PaidAttributionTimeline({ links }: { links: IdentityMatchingLinkApi[] }): JSX.Element {
+ const paidLinks = links.filter((l) => l.orphan_paid_touch && !l.anchor_paid_touch)
+ const continuityLinks = links.filter((l) => l.orphan_paid_touch && l.anchor_paid_touch)
+ const allPaid = [...paidLinks, ...continuityLinks]
+
+ return (
+ <div className="space-y-4">
+ <div className="flex items-center gap-2">
+ <IconTarget className="text-lg" />
+ <h3 className="text-base font-semibold">Paid attribution</h3>
+ <Tooltip title="Links where an anonymous visitor arrived via a paid ad click, and the match recovers attribution to the identified person. 'Recovered' means the ad click was on the anonymous identity; 'Confirmed' means both sides had the paid click.">
+ <span className="text-xs text-tertiary underline decoration-dotted cursor-help">
+ How this works
+ </span>
+ </Tooltip>
+ </div>
+ {allPaid.length === 0 ? (
+ <p className="text-sm text-tertiary">
+ No paid ad touches found in the current results. When the identity matching job links an anonymous
+ visitor who clicked a paid ad to an identified person, they will appear here as a recovered
+ attribution timeline.
+ </p>
+ ) : (
+ <>
+ {/* Summary stats */}
+ <div className="flex items-center gap-3 text-sm">
+ <span className="text-secondary">
+ <LemonTag type="completion">{paidLinks.length}</LemonTag> recovered
+ </span>
+ <span className="text-secondary">
+ <LemonTag type="highlight">{continuityLinks.length}</LemonTag> confirmed
+ </span>
+ <span className="text-tertiary">· {allPaid.length} total</span>
+ </div>
+
+ {/* Compact table view when there are many attributions, card timeline when few */}
+ {allPaid.length > 20 ? (
+ <PaidAttributionTable links={allPaid} />
+ ) : (
+ <>
+ {paidLinks.length > 0 && (
+ <div className="space-y-3">
+ <div className="flex items-center gap-2">
+ <span className="text-sm font-medium">Recovered</span>
+ <span className="text-xs text-tertiary">
+ Ad clicks on anonymous visitors, now linked to known users
+ </span>
+ </div>
+ <div className="grid grid-cols-1 gap-3 xl:grid-cols-2">
+ {paidLinks.map((link) => (
+ <PaidTimelineCard
+ key={`${link.model_version}:${link.orphan_distinct_id}`}
+ link={link}
+ />
+ ))}
+ </div>
+ </div>
+ )}
+ {continuityLinks.length > 0 && (
+ <div className="space-y-3">
+ <div className="flex items-center gap-2">
+ <span className="text-sm font-medium">Confirmed</span>
+ <span className="text-xs text-tertiary">
+ Both identities had paid ad clicks — match confirms same person across the
+ journey
+ </span>
+ </div>
+ <div className="grid grid-cols-1 gap-3 xl:grid-cols-2">
+ {continuityLinks.map((link) => (
+ <PaidTimelineCard
+ key={`${link.model_version}:${link.orphan_distinct_id}`}
+ link={link}
+ />
+ ))}
+ </div>
+ </div>
+ )}
+ </>
+ )}
+ </>
+ )}
+ </div>
+ )
+}
diff --git a/products/growth/frontend/RunsHistory.tsx b/products/growth/frontend/RunsHistory.tsx
new file mode 100644
index 000000000000..c264d3ffd6aa
--- /dev/null
+++ b/products/growth/frontend/RunsHistory.tsx
@@ -0,0 +1,137 @@
+import { IconClock, IconPerson, IconTarget } from '@posthog/icons'
+import { LemonTable, LemonTableColumns, LemonTag, Tooltip } from '@posthog/lemon-ui'
+
+import { dayjs } from 'lib/dayjs'
+
+import type { IdentityMatchingRunApi } from './generated/api.schemas'
+
+function durationLabel(start: string, end: string): string {
+ const diff = dayjs(end).diff(dayjs(start), 'second')
+ if (diff < 60) {
+ return `${diff}s`
+ }
+ if (diff < 3600) {
+ return `${Math.round(diff / 60)}m`
+ }
+ return `${Math.round(diff / 3600)}h ${Math.round((diff % 3600) / 60)}m`
+}
+
+export function RunsHistory({
+ runs,
+ selectedJobId,
+ onSelect,
+ loading,
+}: {
+ runs: IdentityMatchingRunApi[]
+ selectedJobId: string | null
+ onSelect: (jobId: string | null) => void
+ loading: boolean
+}): JSX.Element {
+ const columns: LemonTableColumns<IdentityMatchingRunApi> = [
+ {
+ title: (
+ <span className="flex items-center gap-1">
+ <IconClock className="text-sm" />
+ Computed
+ </span>
+ ),
+ dataIndex: 'computed_at',
+ render: (_, run) => (
+ <div>
+ <div className="font-medium">{dayjs(run.computed_at).format('MMM D, YYYY HH:mm')}</div>
+ <div className="text-xs text-tertiary">
+ {run.first_link_at && run.last_link_at
+ ? durationLabel(run.first_link_at, run.last_link_at)
+ : ''}
+ </div>
+ </div>
+ ),
+ width: 160,
+ },
+ {
+ title: 'Models',
+ dataIndex: 'models',
+ render: (_, run) => (
+ <div className="flex flex-wrap gap-1">
+ {run.models.map((model) => (
+ <Tooltip
+ key={model.model_version}
+ title={`${model.high_confidence} high · ${model.medium_confidence} medium · ${model.low_confidence} low`}
+ >
+ <LemonTag>
+ {model.model_version}: {model.link_count}
+ </LemonTag>
+ </Tooltip>
+ ))}
+ </div>
+ ),
+ },
+ {
+ title: (
+ <span className="flex items-center gap-1">
+ <IconPerson className="text-sm" />
+ Visitors
+ </span>
+ ),
+ dataIndex: 'unique_orphans',
+ render: (_, run) => <span className="font-mono tabular-nums">{run.unique_orphans}</span>,
+ width: 100,
+ sorter: (a, b) => a.unique_orphans - b.unique_orphans,
+ },
+ {
+ title: 'Tier breakdown',
+ key: 'tiers',
+ render: (_, run) => {
+ const high = run.models.reduce((sum, m) => sum + m.high_confidence, 0)
+ const medium = run.models.reduce((sum, m) => sum + m.medium_confidence, 0)
+ const low = run.models.reduce((sum, m) => sum + m.low_confidence, 0)
+ return (
+ <div className="flex items-center gap-1.5">
+ <LemonTag type="success">{high} high</LemonTag>
+ <LemonTag type="warning">{medium} med</LemonTag>
+ <LemonTag>{low} low</LemonTag>
+ </div>
+ )
+ },
+ width: 200,
+ },
+ {
+ title: (
+ <span className="flex items-center gap-1">
+ <IconTarget className="text-sm" />
+ Paid touches
+ </span>
+ ),
+ dataIndex: 'paid_touches',
+ render: (_, run) => (
+ <span className="font-mono tabular-nums">
+ {run.paid_touches > 0 ? <span className="text-success">{run.paid_touches}</span> : '—'}
+ </span>
+ ),
+ width: 120,
+ sorter: (a, b) => a.paid_touches - b.paid_touches,
+ },
+ {
+ title: 'Total',
+ dataIndex: 'total_links',
+ render: (_, run) => <span className="font-mono tabular-nums font-semibold">{run.total_links}</span>,
+ width: 80,
+ sorter: (a, b) => a.total_links - b.total_links,
+ },
+ ]
+
+ return (
+ <LemonTable
+ dataSource={runs}
+ columns={columns}
+ loading={loading}
+ rowKey="job_id"
+ size="small"
+ onRow={(run) => ({
+ onClick: () => onSelect(selectedJobId === run.job_id ? null : run.job_id),
+ className: selectedJobId === run.job_id ? 'bg-accent-highlight-secondary' : 'cursor-pointer',
+ })}
+ emptyState="No runs yet. The identity matching Dagster job hasn't produced any results for this project."
+ />
+ )
+}
diff --git a/products/growth/frontend/generated/api.schemas.ts b/products/growth/frontend/generated/api.schemas.ts
index 6f97504fdf09..21ef31a6984a 100644
--- a/products/growth/frontend/generated/api.schemas.ts
+++ b/products/growth/frontend/generated/api.schemas.ts
@@ -86,6 +86,12 @@ export interface IdentityMatchingRunModelCountApi {
model_version: string
/** Number of links this model produced in the run. */
link_count: number
+ /** Links from this model in the 'high' tier. */
+ high_confidence: number
+ /** Links from this model in the 'medium' tier. */
+ medium_confidence: number
+ /** Links from this model in the 'low' tier. */
+ low_confidence: number
}
export interface IdentityMatchingRunApi {
@@ -95,6 +101,16 @@ export interface IdentityMatchingRunApi {
computed_at: string
/** Link counts per scoring model in this run. */
models: IdentityMatchingRunModelCountApi[]
+ /** Total links across all models in this run. */
+ total_links: number
+ /** Distinct anonymous visitors that were linked. */
+ unique_orphans: number
+ /** Links where a paid ad click was recovered for an anonymous visitor. */
+ paid_touches: number
+ /** Earliest link computed_at in the run (UTC). */
+ first_link_at: string
+ /** Latest link computed_at in the run (UTC). */
+ last_link_at: string
}
export interface IdentityMatchingRunsResponseApi {
diff --git a/products/growth/frontend/generated/api.ts b/products/growth/frontend/generated/api.ts
index aef7f93af88c..8f63b5dff333 100644
--- a/products/growth/frontend/generated/api.ts
+++ b/products/growth/frontend/generated/api.ts
@@ -50,7 +50,7 @@ export const getIdentityMatchingLinksRunsRetrieveUrl = (projectId: string) => {
}
/**
- * Recent identity matching runs for this project with link counts per scoring model, most recent first.
+ * Recent identity matching runs for this project with link counts, tier breakdowns, and paid attribution stats per scoring model, most recent first.
* @summary List identity matching runs
*/
export const identityMatchingLinksRunsRetrieve = async (
diff --git a/products/growth/frontend/generated/api.zod.schemas.ts b/products/growth/frontend/generated/api.zod.schemas.ts
index 8c18a14a90c6..7a254e2d99b7 100644
--- a/products/growth/frontend/generated/api.zod.schemas.ts
+++ b/products/growth/frontend/generated/api.zod.schemas.ts
@@ -121,6 +121,9 @@ export type IdentityMatchingErrorApiOutput = zod.output<typeof IdentityMatchingE
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.'),
+ high_confidence: zod.number().describe("Links from this model in the 'high' tier."),
+ medium_confidence: zod.number().describe("Links from this model in the 'medium' tier."),
+ low_confidence: zod.number().describe("Links from this model in the 'low' tier."),
})
export type IdentityMatchingRunModelCountApi = zod.input<typeof IdentityMatchingRunModelCountApi>
@@ -134,9 +137,17 @@ export const IdentityMatchingRunApi = zod.object({
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.'),
+ high_confidence: zod.number().describe("Links from this model in the 'high' tier."),
+ medium_confidence: zod.number().describe("Links from this model in the 'medium' tier."),
+ low_confidence: zod.number().describe("Links from this model in the 'low' tier."),
})
)
.describe('Link counts per scoring model in this run.'),
+ total_links: zod.number().describe('Total links across all models in this run.'),
+ unique_orphans: zod.number().describe('Distinct anonymous visitors that were linked.'),
+ paid_touches: zod.number().describe('Links where a paid ad click was recovered for an anonymous visitor.'),
+ first_link_at: zod.iso.datetime({ offset: true }).describe('Earliest link computed_at in the run (UTC).'),
+ last_link_at: zod.iso.datetime({ offset: true }).describe('Latest link computed_at in the run (UTC).'),
})
export type IdentityMatchingRunApi = zod.input<typeof IdentityMatchingRunApi>
@@ -153,9 +164,21 @@ export const IdentityMatchingRunsResponseApi = zod.object({
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.'),
+ high_confidence: zod.number().describe("Links from this model in the 'high' tier."),
+ medium_confidence: zod.number().describe("Links from this model in the 'medium' tier."),
+ low_confidence: zod.number().describe("Links from this model in the 'low' tier."),
})
)
.describe('Link counts per scoring model in this run.'),
+ total_links: zod.number().describe('Total links across all models in this run.'),
+ unique_orphans: zod.number().describe('Distinct anonymous visitors that were linked.'),
+ paid_touches: zod
+ .number()
+ .describe('Links where a paid ad click was recovered for an anonymous visitor.'),
+ first_link_at: zod.iso
+ .datetime({ offset: true })
+ .describe('Earliest link computed_at in the run (UTC).'),
+ last_link_at: zod.iso.datetime({ offset: true }).describe('Latest link computed_at in the run (UTC).'),
})
)
.describe('Runs ordered by recency, most recent first.'),
diff --git a/products/growth/frontend/identityMatchingLogic.ts b/products/growth/frontend/identityMatchingLogic.ts
index 15d0264a205a..0dac9048aa16 100644
--- a/products/growth/frontend/identityMatchingLogic.ts
+++ b/products/growth/frontend/identityMatchingLogic.ts
@@ -33,14 +33,18 @@ const DEFAULT_FILTERS: IdentityMatchingFilters = {
search: '',
}
-const LINKS_PAGE_SIZE = 500
+export const LINKS_PAGE_SIZE = 50
+
+export type IdentityMatchingTab = 'links' | 'paid_attribution' | 'runs'
export const identityMatchingLogic = kea<identityMatchingLogicType>([
path(['products', 'growth', 'frontend', 'identityMatchingLogic']),
actions({
setFilters: (filters: Partial<IdentityMatchingFilters>) => ({ filters }),
+ setPage: (page: number) => ({ page }),
+ setActiveTab: (tab: IdentityMatchingTab) => ({ tab }),
}),
- loaders(({ values }) => ({
+ loaders(({ values, cache }) => ({
runsResponse: {
__default: null as IdentityMatchingRunsResponseApi | null,
loadRuns: async () => {
@@ -54,7 +58,8 @@ export const identityMatchingLogic = kea<identityMatchingLogicType>([
await breakpoint(300)
const projectId = String(teamLogic.values.currentTeamId)
const { jobId, modelVersion, tier, minScore, search } = values.filters
- const params: IdentityMatchingLinksListParams = { limit: LINKS_PAGE_SIZE }
+ const offset = (values.page - 1) * LINKS_PAGE_SIZE
+ const params: IdentityMatchingLinksListParams = { limit: LINKS_PAGE_SIZE, offset }
if (jobId) {
params.job_id = jobId
}
@@ -70,8 +75,12 @@ export const identityMatchingLogic = kea<identityMatchingLogicType>([
if (search.trim()) {
params.search = search.trim()
}
+ const requestId = (cache.loadLinksSeq = (cache.loadLinksSeq ?? 0) + 1)
const response = await identityMatchingLinksList(projectId, params)
breakpoint()
+ if (requestId !== cache.loadLinksSeq) {
+ return values.linksResponse
+ }
return response
},
},
@@ -83,6 +92,19 @@ export const identityMatchingLogic = kea<identityMatchingLogicType>([
setFilters: (state, { filters }) => ({ ...state, ...filters }),
},
],
+ page: [
+ 1,
+ {
+ setPage: (_, { page }) => page,
+ setFilters: () => 1,
+ },
+ ],
+ activeTab: [
+ 'links' as IdentityMatchingTab,
+ {
+ setActiveTab: (_, { tab }) => tab,
+ },
+ ],
}),
selectors({
links: [(s) => [s.linksResponse], (linksResponse): IdentityMatchingLinkApi[] => linksResponse?.results ?? []],
@@ -116,6 +138,9 @@ export const identityMatchingLogic = kea<identityMatchingLogicType>([
setFilters: () => {
actions.loadLinks(null)
},
+ setPage: () => {
+ actions.loadLinks(null)
+ },
})),
afterMount(({ actions }) => {
actions.loadRuns()
diff --git a/products/growth/frontend/identityMatchingUtils.ts b/products/growth/frontend/identityMatchingUtils.ts
new file mode 100644
index 000000000000..71dd726d3af5
--- /dev/null
+++ b/products/growth/frontend/identityMatchingUtils.ts
@@ -0,0 +1,209 @@
+import type { IdentityMatchingLinkApi } from './generated/api.schemas'
+
+/** Very permissive email format — matches the person-utils pattern. */
+const EMAIL_REGEX = /.+@.+\..+/i
+
+/** Returns an email if the identifier looks like one, otherwise null. */
+export function extractEmail(identifier: string): string | null {
+ return EMAIL_REGEX.test(identifier) ? identifier : null
+}
+
+/** Build a PersonPropType-shaped object from a distinct ID, attaching email when it looks like one. */
+export function personFromDistinctId(distinctId: string): {
+ properties?: Record<string, unknown>
+ distinct_id: string
+} {
+ const email = extractEmail(distinctId)
+ return email ? { properties: { email }, distinct_id: distinctId } : { distinct_id: distinctId }
+}
+
+export type Tier = 'high' | 'medium' | 'low'
+
+export type SignalCategory = 'network' | 'device' | 'behavior' | 'attribution'
+
+export interface Signal {
+ category: SignalCategory
+ label: string
+ /** Plain-English explanation of what this signal means and why it matters. */
+ description: string
+ /** How much this signal contributes to confidence: 1 (weak) to 3 (strong). */
+ strength: number
+}
+
+export const CATEGORY_ORDER: SignalCategory[] = ['network', 'device', 'behavior', 'attribution']
+
+export const CATEGORY_LABELS: Record<SignalCategory, string> = {
+ network: 'Shared network',
+ device: 'Matching devices',
+ behavior: 'Browsing patterns',
+ attribution: 'Paid attribution',
+}
+
+export const CATEGORY_DESCRIPTIONS: Record<SignalCategory, string> = {
+ network: 'Both identities were seen on the same network — the strongest indicator they are the same person.',
+ device: 'Both identities used similar hardware or software, suggesting the same physical device or user.',
+ behavior: 'Both identities visited similar pages at similar times, suggesting the same browsing session.',
+ attribution:
+ 'A paid ad click by the anonymous visitor can now be attributed to the identified person — recovering lost attribution data.',
+}
+
+/**
+ * Decompose a link's evidence fields into categorized, weighted signals.
+ * Signal strengths are based on how predictive each signal is in the scoring models.
+ */
+export function extractSignals(link: IdentityMatchingLinkApi): Signal[] {
+ const signals: Signal[] = [
+ {
+ category: 'network',
+ label: `${link.shared_ip_days} shared IP-day${link.shared_ip_days === 1 ? '' : 's'}`,
+ description:
+ 'Both identities were seen on the same IP address on the same day(s). This is the strongest signal — it means they were likely on the same network (home, office, or mobile).',
+ strength: 3,
+ },
+ {
+ category: 'network',
+ label: `${link.shared_ips} shared IP${link.shared_ips === 1 ? '' : 's'}`,
+ description: 'They shared multiple distinct IP addresses, further reinforcing the connection.',
+ strength: 2,
+ },
+ {
+ category: 'network',
+ label: 'Small IP block (household)',
+ description:
+ 'The shared IP had very few other devices on it, suggesting a household or personal network rather than a shared office or VPN.',
+ strength: 2,
+ },
+ {
+ category: 'network',
+ label: 'Same city',
+ description: 'Both identities were geolocated to the same city.',
+ strength: 1,
+ },
+ {
+ category: 'device',
+ label: 'Same user agent',
+ description:
+ 'Both identities sent an identical browser user agent string — same browser version, OS, and device. This strongly suggests the same device.',
+ strength: 3,
+ },
+ {
+ category: 'device',
+ label: 'Webview + same UA',
+ description:
+ 'The anonymous visitor came from an in-app webview, and the user agent matches the identified person — common when someone clicks a link inside an app.',
+ strength: 2,
+ },
+ {
+ category: 'device',
+ label: 'Mobile + desktop pair',
+ description:
+ 'One identity is mobile and the other is desktop — a common pattern for the same person using multiple devices on the same network.',
+ strength: 1,
+ },
+ {
+ category: 'device',
+ label: 'Same timezone',
+ description: 'Both identities reported the same browser timezone.',
+ strength: 1,
+ },
+ {
+ category: 'device',
+ label: 'Same language',
+ description: 'Both identities had the same browser language setting.',
+ strength: 1,
+ },
+ {
+ category: 'behavior',
+ label: `${Math.round(link.avg_path_jaccard * 100)}% path overlap`,
+ description:
+ 'On the days they shared an IP, both identities visited many of the same pages — suggesting the same person browsing across devices.',
+ strength: 2,
+ },
+ {
+ category: 'behavior',
+ label: `${link.days_overlap} day${link.days_overlap === 1 ? '' : 's'} of overlap`,
+ description: 'They were seen on the same network on multiple distinct days.',
+ strength: 1,
+ },
+ {
+ category: 'attribution',
+ label: 'New paid touch recovered',
+ description:
+ 'The anonymous visitor arrived via a paid ad click (e.g., Google Ads). This match links that ad spend to the identified person, recovering attribution that would otherwise be lost.',
+ strength: 3,
+ },
+ {
+ category: 'attribution',
+ label: 'Paid continuity',
+ description:
+ 'Both the anonymous visitor and the identified person had paid ad click IDs — the match confirms they are the same person across the ad journey.',
+ strength: 2,
+ },
+ ]
+
+ const isActive = (s: Signal): boolean => {
+ switch (s.label) {
+ case `${link.shared_ip_days} shared IP-day${link.shared_ip_days === 1 ? '' : 's'}`:
+ return link.shared_ip_days > 0
+ case `${link.shared_ips} shared IP${link.shared_ips === 1 ? '' : 's'}`:
+ return link.shared_ips > 1
+ case 'Small IP block (household)':
+ return link.min_ip_block_size <= 3 && link.shared_ip_days > 0
+ case 'Same city':
+ return link.geo_city_match
+ case 'Same user agent':
+ return link.ua_exact_match
+ case 'Webview + same UA':
+ return link.orphan_is_webview && link.ua_exact_match
+ case 'Mobile + desktop pair':
+ return link.device_type_complement
+ case 'Same timezone':
+ return link.timezone_match
+ case 'Same language':
+ return link.language_match
+ case `${Math.round(link.avg_path_jaccard * 100)}% path overlap`:
+ return link.avg_path_jaccard > 0
+ case `${link.days_overlap} day${link.days_overlap === 1 ? '' : 's'} of overlap`:
+ return link.days_overlap > 0
+ case 'New paid touch recovered':
+ return link.orphan_paid_touch && !link.anchor_paid_touch
+ case 'Paid continuity':
+ return link.orphan_paid_touch && link.anchor_paid_touch
+ default:
+ return false
+ }
+ }
+
+ return signals.filter(isActive)
+}
+
+/**
+ * Normalize a score to a 0-1 confidence value.
+ * - logreg_v1: already 0-1
+ * - rules_v1: unbounded weighted sum — normalize against a practical max of ~10
+ */
+export function normalizedScore(link: IdentityMatchingLinkApi): number {
+ if (link.model_version === 'logreg_v1') {
+ return Math.min(link.score, 1)
+ }
+ return Math.min(link.score / 10, 1)
+}
+
+export interface TierStats {
+ high: number
+ medium: number
+ low: number
+ total: number
+ paidTouches: number
+}
+
+export function computeTierStats(links: IdentityMatchingLinkApi[]): TierStats {
+ const stats: TierStats = { high: 0, medium: 0, low: 0, total: links.length, paidTouches: 0 }
+ for (const link of links) {
+ stats[link.tier as Tier]++
+ if (link.orphan_paid_touch && !link.anchor_paid_touch) {
+ stats.paidTouches++
+ }
+ }
+ return stats
+}
diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.ts
index 835c56495704..31b09428ed68 100644
--- a/services/mcp/src/api/generated.ts
+++ b/services/mcp/src/api/generated.ts
@@ -26107,6 +26107,12 @@ export namespace Schemas {
model_version: string;
/** Number of links this model produced in the run. */
link_count: number;
+ /** Links from this model in the 'high' tier. */
+ high_confidence: number;
+ /** Links from this model in the 'medium' tier. */
+ medium_confidence: number;
+ /** Links from this model in the 'low' tier. */
+ low_confidence: number;
}
export interface IdentityMatchingRun {
@@ -26116,6 +26122,16 @@ export namespace Schemas {
computed_at: string;
/** Link counts per scoring model in this run. */
models: IdentityMatchingRunModelCount[];
+ /** Total links across all models in this run. */
+ total_links: number;
+ /** Distinct anonymous visitors that were linked. */
+ unique_orphans: number;
+ /** Links where a paid ad click was recovered for an anonymous visitor. */
+ paid_touches: number;
+ /** Earliest link computed_at in the run (UTC). */
+ first_link_at: string;
+ /** Latest link computed_at in the run (UTC). */
+ last_link_at: string;
}
export interface IdentityMatchingRunsResponse {