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.

refactor(growth): move identity matching off clickhouse tables onto s3 parquet (#64861)

Fernando Gomesc6fdc7fca9de
diff --git a/posthog/settings/object_storage.py b/posthog/settings/object_storage.py
index 9c29ac1daf48..380888467a6f 100644
--- a/posthog/settings/object_storage.py
+++ b/posthog/settings/object_storage.py
@@ -51,3 +51,30 @@ BILLING_USAGE_REPORTS_S3_BUCKET = os.getenv("BILLING_USAGE_REPORTS_S3_BUCKET") o
# expire non-`ready` bundles after a grace period (handled by infra). Falls
# back to the general bucket in dev / self-hosted.
AGENT_BUNDLES_S3_BUCKET = os.getenv("AGENT_BUNDLES_S3_BUCKET") or OBJECT_STORAGE_BUCKET
+
+# Identity matching scratch storage (products/growth `identity_matching_job`). The job writes
+# per-run Parquet objects via ClickHouse `INSERT INTO FUNCTION s3(...)` and the read API globs
+# them back with `s3(...)`, so only the ClickHouse cluster needs bucket access — the Dagster
+# process and the web process never touch boto3. Retention is owned by the bucket lifecycle
+# policy (there is no MergeTree TTL on S3); infra must expire the prefix (≥ the eval horizon so
+# a run's inputs survive until evaluation). Prod bucket names are infra-provided via env and
+# never committed; local/dev/test reuse the object-storage service (SeaweedFS).
+IDENTITY_MATCHING_S3_BUCKET = os.getenv("IDENTITY_MATCHING_S3_BUCKET") or OBJECT_STORAGE_BUCKET
+IDENTITY_MATCHING_S3_PREFIX = os.getenv("IDENTITY_MATCHING_S3_PREFIX", "identity_matching")
+IDENTITY_MATCHING_S3_REGION = os.getenv("IDENTITY_MATCHING_S3_REGION") or OBJECT_STORAGE_REGION
+# Endpoint is set for S3-compatible object storage (local/dev/test); empty on prod, where the
+# cluster reaches the bucket over AWS S3 via its attached IAM role (so no endpoint and no keys
+# — the credential question is owned by infra, mirroring events_backfill_to_duckling).
+#
+# This must be the endpoint the ClickHouse *cluster* can reach, which is not always
+# OBJECT_STORAGE_ENDPOINT: CI points OBJECT_STORAGE_ENDPOINT at `localhost:19000` for the test
+# process, but ClickHouse runs in docker-compose and reaches object storage by its service name
+# (`objectstorage:19000`) — using `localhost` there makes the cluster connect to itself and the
+# s3() call hangs. So in TEST/DEBUG default to the cluster-reachable host (matching the
+# `objectstorage:19000` convention in data_warehouse / web_analytics_s3); on prod it stays empty.
+if TEST or DEBUG:
+ IDENTITY_MATCHING_S3_ENDPOINT: Optional[str] = (
+ os.getenv("IDENTITY_MATCHING_S3_ENDPOINT", "http://objectstorage:19000") or None
+ )
+else:
+ IDENTITY_MATCHING_S3_ENDPOINT = os.getenv("IDENTITY_MATCHING_S3_ENDPOINT", "") or None
diff --git a/products/growth/backend/api/identity_matching.py b/products/growth/backend/api/identity_matching.py
index 89659be57071..c6bf8c211658 100644
--- a/products/growth/backend/api/identity_matching.py
+++ b/products/growth/backend/api/identity_matching.py
@@ -1,8 +1,12 @@
-"""Read-only API over the identity matching link tables.
+"""Read-only API over the identity matching links.
-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.
+Each run of the `identity_matching_job` Dagster job (products/growth/dags/identity_matching.py)
+writes its links and candidate pairs as Parquet to a per-run S3 prefix
+(`<prefix>/team_<team_id>/<job_id>/...`); nothing is persisted on the ClickHouse cluster. Every
+query reads those objects back through the `s3(...)` table function and degrades to an empty
+result set when the team has no objects yet (a glob matching no files returns zero rows under
+`s3_throw_on_zero_files_match=0`). Cross-team isolation is enforced by the `team_<team_id>` path
+segment: a job_id belonging to another team resolves to a prefix this team never wrote.
"""
from typing import Any
@@ -18,13 +22,23 @@ 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_CANDIDATE_PAIRS_DATASET,
+ IDENTITY_MATCHING_CANDIDATE_PAIRS_STRUCTURE,
+ IDENTITY_MATCHING_LINKS_DATASET,
+ IDENTITY_MATCHING_LINKS_STRUCTURE,
IDENTITY_MATCHING_TIERS,
+ identity_matching_dataset_read_args,
)
MAX_RUNS_LISTED = 50
+# Let a glob matching no objects return zero rows (the "no run yet" path) instead of erroring.
+_S3_READ_SETTINGS = {"s3_throw_on_zero_files_match": "0"}
+
+# All-runs glob for one team: `<prefix>/team_<team_id>/*/links/*.parquet`. links is the smallest
+# dataset, so enumerating every run of a team this way is cheap.
+_ALL_RUNS = "*"
+
class IdentityMatchingLinkSerializer(serializers.Serializer):
job_id = serializers.UUIDField(help_text="Identity matching run that produced this link.")
@@ -118,22 +132,33 @@ class IdentityMatchingLinkViewSet(TeamAndOrgViewSetMixin, viewsets.ViewSet):
# 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 _links_read_args(self, job_id: str) -> str:
+ """`s3(...)` args for one run's links objects (`job_id` is a validated UUID string)."""
+ return identity_matching_dataset_read_args(
+ self.team.pk, job_id, IDENTITY_MATCHING_LINKS_DATASET, IDENTITY_MATCHING_LINKS_STRUCTURE
+ )
+
+ def _candidate_pairs_read_args(self, job_id: str) -> str:
+ return identity_matching_dataset_read_args(
+ self.team.pk, job_id, IDENTITY_MATCHING_CANDIDATE_PAIRS_DATASET, IDENTITY_MATCHING_CANDIDATE_PAIRS_STRUCTURE
+ )
+
+ def _all_runs_links_read_args(self) -> str:
+ """`s3(...)` args globbing every run's links objects for this team."""
+ return identity_matching_dataset_read_args(
+ self.team.pk, _ALL_RUNS, IDENTITY_MATCHING_LINKS_DATASET, IDENTITY_MATCHING_LINKS_STRUCTURE
+ )
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
- """,
+ # 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,
)
- return str(rows[0][0]) if rows else None
+ job_id = result[0][0]
+ return str(job_id) if job_id else None
@extend_schema(
summary="List identity matching links",
@@ -148,17 +173,14 @@ class IdentityMatchingLinkViewSet(TeamAndOrgViewSetMixin, viewsets.ViewSet):
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"]
+ # job_id scopes the run via the S3 path; team_id stays as a defensive predicate.
+ conditions = ["lk.team_id = %(team_id)s"]
query_params: dict[str, Any] = {
"team_id": self.team.pk,
- "job_id": job_id,
"limit": params["limit"],
"offset": params["offset"],
}
@@ -178,14 +200,17 @@ class IdentityMatchingLinkViewSet(TeamAndOrgViewSetMixin, viewsets.ViewSet):
)
query_params["search"] = params["search"]
where = " AND ".join(conditions)
+ links_s3 = self._links_read_args(job_id)
+ candidate_pairs_s3 = self._candidate_pairs_read_args(job_id)
- [[count]] = ( # nosemgrep: clickhouse-fstring-param-audit
- sync_execute(
- f"SELECT count() FROM {IDENTITY_MATCHING_LINKS_TABLE} AS lk WHERE {where}",
- query_params,
- )
+ 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,
)
- rows = sync_execute( # nosemgrep: clickhouse-fstring-param-audit — constant table names, WHERE built from string literals, values parameterized
+ 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,
@@ -209,17 +234,17 @@ class IdentityMatchingLinkViewSet(TeamAndOrgViewSetMixin, viewsets.ViewSet):
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
+ 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",
@@ -256,18 +281,17 @@ class IdentityMatchingLinkViewSet(TeamAndOrgViewSetMixin, viewsets.ViewSet):
)
@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(
+ 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 {IDENTITY_MATCHING_LINKS_TABLE}
+ 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,
)
runs: dict[str, dict[str, Any]] = {}
for job_id, computed_at, model_version, link_count in rows:
diff --git a/products/growth/backend/api/test_identity_matching.py b/products/growth/backend/api/test_identity_matching.py
index 66015a6765a1..495436e9e886 100644
--- a/products/growth/backend/api/test_identity_matching.py
+++ b/products/growth/backend/api/test_identity_matching.py
@@ -1,16 +1,24 @@
+import hashlib
from datetime import UTC, datetime, timedelta
from typing import Any
from uuid import uuid4
from posthog.test.base import APIBaseTest
+from django.test import override_settings
+
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
+from products.growth.backend.constants import (
+ IDENTITY_MATCHING_CANDIDATE_PAIRS_DATASET,
+ IDENTITY_MATCHING_CANDIDATE_PAIRS_STRUCTURE,
+ IDENTITY_MATCHING_LINKS_DATASET,
+ IDENTITY_MATCHING_LINKS_STRUCTURE,
+ identity_matching_s3_args,
+)
OTHER_TEAM_ID = 909_090_909
@@ -18,18 +26,26 @@ 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.
+# computed_at controls run recency (latest run wins by default, runs() orders by it).
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)
+_S3_WRITE_SETTINGS = {"s3_truncate_on_insert": "1"}
+
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)
+ # S3 objects are not transactional, so a per-test prefix isolates fixtures across tests
+ # (and from prod data). The object store is ephemeral, so no explicit teardown is needed.
+ self._prefix_override = override_settings(IDENTITY_MATCHING_S3_PREFIX=f"identity_matching_test_{uuid4().hex}")
+ self._prefix_override.enable()
+
+ def tearDown(self) -> None:
+ self._prefix_override.disable()
+ super().tearDown()
def _insert_link(
self,
@@ -44,11 +60,19 @@ class TestIdentityMatchingLinksAPI(APIBaseTest):
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
+ # Each link/pair is its own Parquet part object, matching how the job writes per-run S3
+ # datasets. The pair key is deterministic so the rules and logreg links for one orphan
+ # share a single candidate_pairs row (truncate-on-insert), avoiding a join fan-out.
+ pair_key = hashlib.sha256(f"{orphan}|{anchor}".encode()).hexdigest()[:12]
+ links_args = identity_matching_s3_args(
+ team_id,
+ job_id,
+ f"{IDENTITY_MATCHING_LINKS_DATASET}/{model_version}_{pair_key}.parquet",
+ IDENTITY_MATCHING_LINKS_STRUCTURE,
+ )
+ sync_execute( # nosemgrep: clickhouse-fstring-param-audit — test fixture; s3 args from constants, 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)
+ INSERT INTO FUNCTION s3({links_args})
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)
""",
@@ -62,17 +86,19 @@ class TestIdentityMatchingLinksAPI(APIBaseTest):
"tier": tier,
"computed_at": computed_at,
},
+ settings=_S3_WRITE_SETTINGS,
+ )
+ pairs_args = identity_matching_s3_args(
+ team_id,
+ job_id,
+ f"{IDENTITY_MATCHING_CANDIDATE_PAIRS_DATASET}/{pair_key}.parquet",
+ IDENTITY_MATCHING_CANDIDATE_PAIRS_STRUCTURE,
)
- sync_execute( # nosemgrep: clickhouse-fstring-param-audit — test fixture; constant table name, all values parameterized
+ sync_execute( # nosemgrep: clickhouse-fstring-param-audit — test fixture; s3 args from constants, 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)
+ INSERT INTO FUNCTION s3({pairs_args})
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)
+ 3600, 0.5, %(orphan_paid_touch)s, 0, 10, 20, -1)
""",
{
"job_id": job_id,
@@ -80,8 +106,8 @@ class TestIdentityMatchingLinksAPI(APIBaseTest):
"orphan": orphan,
"anchor": anchor,
"orphan_paid_touch": orphan_paid_touch,
- "computed_at": computed_at,
},
+ settings=_S3_WRITE_SETTINGS,
)
def _seed(self) -> None:
@@ -159,12 +185,7 @@ class TestIdentityMatchingLinksAPI(APIBaseTest):
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")
+ # No objects written for this team: both endpoints glob an empty prefix and degrade cleanly.
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}
diff --git a/products/growth/backend/constants.py b/products/growth/backend/constants.py
index 3e9db4b62fe9..bcb8d7317e23 100644
--- a/products/growth/backend/constants.py
+++ b/products/growth/backend/constants.py
@@ -1,5 +1,7 @@
from typing import Literal, TypedDict
+from django.conf import settings
+
SDK_CACHE_EXPIRY = 60 * 60 * 24 * 7 # 7 days — used by the GitHub `latestVersion` cache (hourly Dagster job)
# Team-events snapshot TTL — sized to self-heal one missed daily cron run.
@@ -52,17 +54,150 @@ 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 no longer persists tables on the ClickHouse cluster. Each run of
+# products/growth/dags/identity_matching.py writes its datasets as Parquet to a pre-provisioned
+# ClickHouse "scratch" S3 bucket, namespaced per team and run:
+#
+# <prefix>/team_<team_id>/<job_id>/device_days/data.parquet
+# <prefix>/team_<team_id>/<job_id>/person_timeline/part_<n>.parquet
+# <prefix>/team_<team_id>/<job_id>/candidate_pairs/data.parquet
+# <prefix>/team_<team_id>/<job_id>/links/rules_v1.parquet
+# <prefix>/team_<team_id>/<job_id>/links/logreg_v1_part_<n>.parquet
+#
+# The job_id segment gives per-run isolation; the team_<team_id> segment lets the read API
+# enumerate a team's runs with a glob without reading other teams' objects. All S3 I/O is
+# mediated by ClickHouse (`INSERT INTO FUNCTION s3` / `FROM s3`); the dataset path-segment
+# constants, Parquet schemas, and the `s3(...)` argument builder live here (not in the Dagster
+# module) so the read API can build identical URLs without importing Dagster.
+IDENTITY_MATCHING_DEVICE_DAYS_DATASET = "device_days"
+IDENTITY_MATCHING_PERSON_TIMELINE_DATASET = "person_timeline"
+IDENTITY_MATCHING_CANDIDATE_PAIRS_DATASET = "candidate_pairs"
+IDENTITY_MATCHING_LINKS_DATASET = "links"
IDENTITY_MATCHING_RULES_MODEL_VERSION = "rules_v1"
IDENTITY_MATCHING_LOGREG_MODEL_VERSION = "logreg_v1"
IDENTITY_MATCHING_TIERS = ["high", "medium", "low"]
+# Parquet column schemas, passed as the explicit `structure` argument to `s3(...)`. They are
+# *required* for the VALUES-based writes (person_timeline, logreg links) and used on every read
+# so that a glob matching no objects returns zero rows instead of failing schema inference (the
+# "no run yet" path). `job_id` is `String` because ClickHouse cannot write `UUID` to Parquet;
+# `model_version`/`tier` are plain `String` because `LowCardinality` is a MergeTree-only
+# optimisation. On writes the structure also drives ClickHouse's cast of the projection, exactly
+# as the old `INSERT INTO <table>` did against the column types — so the column order here must
+# match each op's SELECT/VALUES projection order.
+IDENTITY_MATCHING_DEVICE_DAYS_STRUCTURE = """
+ job_id String,
+ 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')
+"""
+
+IDENTITY_MATCHING_PERSON_TIMELINE_STRUCTURE = """
+ job_id String,
+ 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')
+"""
+
+IDENTITY_MATCHING_CANDIDATE_PAIRS_STRUCTURE = """
+ job_id String,
+ 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
+"""
+
+IDENTITY_MATCHING_LINKS_STRUCTURE = """
+ job_id String,
+ team_id Int64,
+ model_version String,
+ orphan_distinct_id String,
+ anchor_person_key String,
+ score Float64,
+ runner_up_score Float64,
+ margin Float64,
+ tier String,
+ computed_at DateTime
+"""
+
+
+def identity_matching_run_prefix(team_id: int, job_id: str) -> str:
+ """S3 key prefix for one run: `<prefix>/team_<team_id>/<job_id>`.
+
+ `job_id` is either a run UUID (string) or the glob `*` to enumerate every run of a team.
+ """
+ return f"{settings.IDENTITY_MATCHING_S3_PREFIX}/team_{team_id}/{job_id}"
+
+
+def identity_matching_s3_args(team_id: int, job_id: str, relative_path: str, structure: str) -> str:
+ """Build the argument list for a ClickHouse `s3(...)` call: ``url[, key, secret], 'Parquet', structure``.
+
+ Credentials are emitted only when an endpoint is configured (local/dev/test object storage);
+ on prod the endpoint is empty and the cluster reaches the bucket via its attached IAM role, so
+ no secret is ever interpolated into SQL. ``team_id`` (int), ``job_id`` (run UUID or ``*``) and
+ ``relative_path`` (constant dataset segments) are all trusted, never request input.
+ """
+ key = f"{identity_matching_run_prefix(team_id, job_id)}/{relative_path}"
+ endpoint = settings.IDENTITY_MATCHING_S3_ENDPOINT
+ if endpoint:
+ # Local/dev/test S3-compatible storage (SeaweedFS/MinIO): path-style URL including bucket.
+ url = f"{endpoint}/{settings.IDENTITY_MATCHING_S3_BUCKET}/{key}"
+ creds = f"'{settings.OBJECT_STORAGE_ACCESS_KEY_ID}', '{settings.OBJECT_STORAGE_SECRET_ACCESS_KEY}', "
+ else:
+ # Prod AWS S3: virtual-hosted-style HTTPS URL; the cluster authenticates via its IAM role.
+ url = f"https://{settings.IDENTITY_MATCHING_S3_BUCKET}.s3.{settings.IDENTITY_MATCHING_S3_REGION}.amazonaws.com/{key}"
+ creds = ""
+ # The structure is wrapped in a single-quoted SQL literal, so escape the single quotes inside
+ # column types like DateTime64(6, 'UTC') — otherwise they terminate the literal early.
+ compact_structure = " ".join(structure.split()).replace("'", "\\'")
+ return f"'{url}', {creds}'Parquet', '{compact_structure}'"
+
+
+def identity_matching_dataset_read_args(team_id: int, job_id: str, dataset: str, structure: str) -> str:
+ """`s3(...)` args reading every Parquet part of a dataset under a run (or all runs when job_id=``*``)."""
+ return identity_matching_s3_args(team_id, job_id, f"{dataset}/*.parquet", structure)
+
def github_sdk_versions_key(sdk_type: str) -> str:
return f"github:sdk_versions:{sdk_type}"
diff --git a/products/growth/dags/identity_matching.py b/products/growth/dags/identity_matching.py
index be546018c655..fa4d7067d151 100644
--- a/products/growth/dags/identity_matching.py
+++ b/products/growth/dags/identity_matching.py
@@ -11,9 +11,11 @@ Ground truth comes from retroactive merges: an orphan that merges into a person
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.
+The job persists nothing on the ClickHouse cluster: each stage writes its output as Parquet
+to a pre-provisioned "scratch" S3 bucket via `INSERT INTO FUNCTION s3(...)`, namespaced per
+run (`<prefix>/team_<team_id>/<job_id>/<dataset>/`), and reads it back with the `s3(...)` table
+function. Retention is the bucket lifecycle policy's job — there is no MergeTree 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
@@ -24,10 +26,10 @@ Known limitations:
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.
+- The Parquet objects store raw IPs; they are internal-only and expire via the scratch
+ bucket's lifecycle policy.
"""
-import uuid
import hashlib
import datetime
from collections.abc import Sequence
@@ -44,12 +46,19 @@ 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_CANDIDATE_PAIRS_DATASET,
+ IDENTITY_MATCHING_CANDIDATE_PAIRS_STRUCTURE,
+ IDENTITY_MATCHING_DEVICE_DAYS_DATASET,
+ IDENTITY_MATCHING_DEVICE_DAYS_STRUCTURE,
+ IDENTITY_MATCHING_LINKS_DATASET,
+ IDENTITY_MATCHING_LINKS_STRUCTURE,
IDENTITY_MATCHING_LOGREG_MODEL_VERSION,
- IDENTITY_MATCHING_PERSON_TIMELINE_TABLE,
+ IDENTITY_MATCHING_PERSON_TIMELINE_DATASET,
+ IDENTITY_MATCHING_PERSON_TIMELINE_STRUCTURE,
IDENTITY_MATCHING_RULES_MODEL_VERSION,
+ identity_matching_dataset_read_args,
+ identity_matching_run_prefix,
+ identity_matching_s3_args,
)
# Click IDs that indicate a paid ad click, a subset of CAMPAIGN_PROPERTIES
@@ -112,11 +121,6 @@ DEFAULT_RULE_WEIGHTS: dict[str, float] = {
"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.
@@ -220,10 +224,6 @@ class MatchingRun:
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
@@ -244,129 +244,86 @@ class MatchingRun:
@dataclass(frozen=True)
-class MatchingTable:
- name: str
- columns_sql: str
- order_by: str
+class MatchingDataset:
+ """A per-run S3 dataset: a folder of one or more Parquet objects under the run prefix.
- @property
- def qualified_name(self) -> str:
- return f"{settings.CLICKHOUSE_DATABASE}.{self.name}"
+ `folder` is the path segment under `<prefix>/team_<team_id>/<job_id>/`; `structure` is the
+ Parquet column schema, passed as the explicit `structure` arg to every `s3(...)` call so that
+ writes cast the projection to fixed column types (replacing the old `INSERT INTO <table>`) and
+ reads stay schema-stable. No DDL: there is no table to create, sync, or drop.
+ """
- @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",
-)
+ folder: str
+ structure: str
-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",
-)
+ def write_args(self, run: "MatchingRun", filename: str) -> str:
+ """`s3(...)` args writing one object `<folder>/<filename>` for this run."""
+ return identity_matching_s3_args(run.config.team_id, run.job_id, f"{self.folder}/{filename}", self.structure)
+
+ def read_args(self, run: "MatchingRun") -> str:
+ """`s3(...)` args globbing every Parquet object in this dataset for this run."""
+ return identity_matching_dataset_read_args(run.config.team_id, run.job_id, self.folder, self.structure)
-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",
+DEVICE_DAYS = MatchingDataset(IDENTITY_MATCHING_DEVICE_DAYS_DATASET, IDENTITY_MATCHING_DEVICE_DAYS_STRUCTURE)
+PERSON_TIMELINE = MatchingDataset(
+ IDENTITY_MATCHING_PERSON_TIMELINE_DATASET, IDENTITY_MATCHING_PERSON_TIMELINE_STRUCTURE
+)
+CANDIDATE_PAIRS = MatchingDataset(
+ IDENTITY_MATCHING_CANDIDATE_PAIRS_DATASET, IDENTITY_MATCHING_CANDIDATE_PAIRS_STRUCTURE
)
+LINKS = MatchingDataset(IDENTITY_MATCHING_LINKS_DATASET, IDENTITY_MATCHING_LINKS_STRUCTURE)
+
+# A single Parquet object per SQL-produced dataset; multi-part datasets append `part_<n>`.
+SINGLE_OBJECT = "data.parquet"
+
+# `s3_truncate_on_insert` makes each write overwrite its own deterministically-named object, so an
+# op retry is idempotent. `s3_throw_on_zero_files_match=0` lets a glob that matches nothing return
+# zero rows instead of erroring (the logreg-skipped and no-data paths).
+
+
+def _write_settings(context: dagster.OpExecutionContext) -> dict[str, str]:
+ return {**settings_with_log_comment(context), "s3_truncate_on_insert": "1"}
+
+
+def _read_settings(context: dagster.OpExecutionContext) -> dict[str, str]:
+ return {**settings_with_log_comment(context), "s3_throw_on_zero_files_match": "0"}
-ALL_TABLES: list[MatchingTable] = [DEVICE_DAYS, PERSON_TIMELINE, CANDIDATE_PAIRS, LINKS]
+
+# Rows the Python ops build (person_timeline, logreg links) are written in small batches as inline
+# VALUES. clickhouse_driver's native-block insert path (`INSERT ... VALUES` with a list of tuples
+# and nothing after VALUES) hangs against `INSERT INTO FUNCTION s3(...)`; embedding the rows as
+# `VALUES (%(..)s), ...` placeholders instead routes through ordinary server-parsed substitution,
+# which writes Parquet to s3 reliably. Batches stay small so each substituted statement stays well
+# under max_query_size (raised here for headroom) and the AST element cap.
+_S3_VALUES_BATCH = 1000
+
+
+def _write_rows_to_s3(
+ context: dagster.OpExecutionContext,
+ cluster: ClickhouseCluster,
+ dataset: "MatchingDataset",
+ run: "MatchingRun",
+ rows: list[tuple[Any, ...]],
+ columns: int,
+ filename_prefix: str = "part",
+) -> None:
+ if not rows:
+ return
+ query_settings = {**_write_settings(context), "max_query_size": "10485760"}
+ for part, offset in enumerate(range(0, len(rows), _S3_VALUES_BATCH)):
+ batch = rows[offset : offset + _S3_VALUES_BATCH]
+ placeholders: list[str] = []
+ parameters: dict[str, Any] = {}
+ for i, row in enumerate(batch):
+ keys = [f"v{i}_{j}" for j in range(columns)]
+ placeholders.append("(" + ", ".join(f"%({key})s" for key in keys) + ")")
+ parameters.update(zip(keys, row, strict=True))
+ query = (
+ f"INSERT INTO FUNCTION s3({dataset.write_args(run, f'{filename_prefix}_{part}.parquet')}) "
+ f"VALUES {', '.join(placeholders)}"
+ )
+ cluster.any_host(partial(_execute, query=query, parameters=parameters, query_settings=query_settings)).result()
def _prop(name: str) -> str:
@@ -387,19 +344,18 @@ def _has_paid_clid_expr() -> str:
@dagster.op
-def setup_tables(
+def prepare_run(
context: dagster.OpExecutionContext,
- cluster: dagster.ResourceParam[ClickhouseCluster],
config: IdentityMatchingConfig,
) -> MatchingRun:
- """Create the job's tables on all hosts and seed the run state."""
+ """Validate the team gate and seed the run state. No tables are created — each stage writes
+ Parquet to its own S3 prefix, and the first real write surfaces any auth/bucket error."""
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}"
+ f"edges from {run.edges_start}, eval until {run.eval_end}; "
+ f"writing to s3 prefix {identity_matching_run_prefix(config.team_id, run.job_id)}/"
)
return run
@@ -413,13 +369,9 @@ def build_device_day_index(
"""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)
+ INSERT INTO FUNCTION s3({DEVICE_DAYS.write_args(run, SINGLE_OBJECT)})
SELECT
- toUUID(%(job_id)s),
+ %(job_id)s,
team_id,
distinct_id,
toDate(timestamp) AS day,
@@ -460,20 +412,18 @@ def build_device_day_index(
"paths_cap": config.paths_per_day_cap,
}
cluster.any_host(
- partial(_execute, query=query, parameters=parameters, query_settings=settings_with_log_comment(context))
+ partial(_execute, query=query, parameters=parameters, query_settings=_write_settings(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)
+ FROM s3({DEVICE_DAYS.read_args(run)})
""",
- parameters={"job_id": run.job_id},
- query_settings=settings_with_log_comment(context),
+ parameters={},
+ query_settings=_read_settings(context),
)
).result()
empty_ip_fraction = (empty_ip_rows / rows) if rows else 0.0
@@ -596,9 +546,8 @@ def extract_person_timeline(
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])
+ (run.job_id, config.team_id, member, 1, person_key, "", "", first_seen_by_id[member])
for member, person_key in person_key_by_id.items()
]
labeled = 0
@@ -616,20 +565,10 @@ def extract_person_timeline(
# 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))
+ rows.append((run.job_id, 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()
+ # Each batch is its own Parquet part object; reads glob `person_timeline/*.parquet`.
+ _write_rows_to_s3(context, cluster, PERSON_TIMELINE, run, rows, columns=8)
anchor_persons = len(set(person_key_by_id.values()))
context.add_output_metadata(
@@ -653,27 +592,21 @@ def build_candidate_pairs(
"""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)
+ INSERT INTO FUNCTION s3({CANDIDATE_PAIRS.write_args(run, SINGLE_OBJECT)})
WITH
anchors AS (
SELECT distinct_id, person_key
- FROM {PERSON_TIMELINE.qualified_name}
- WHERE job_id = toUUID(%(job_id)s) AND is_anchor = 1
+ FROM s3({PERSON_TIMELINE.read_args(run)})
+ WHERE 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 != ''
+ FROM s3({PERSON_TIMELINE.read_args(run)})
+ WHERE is_anchor = 0 AND label_person_key != ''
),
dd AS (
SELECT *
- FROM {DEVICE_DAYS.qualified_name}
- WHERE job_id = toUUID(%(job_id)s)
+ FROM s3({DEVICE_DAYS.read_args(run)})
),
ip_day_blocks AS (
SELECT ip, day, uniqExact(distinct_id) AS block_size
@@ -773,7 +706,7 @@ def build_candidate_pairs(
LIMIT %(max_candidates_per_orphan)s BY orphan_distinct_id
)
SELECT
- toUUID(%(job_id)s),
+ %(job_id)s,
%(team_id)s,
p.orphan_distinct_id,
p.anchor_person_key,
@@ -807,20 +740,18 @@ def build_candidate_pairs(
"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))
+ partial(_execute, query=query, parameters=parameters, query_settings=_write_settings(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)
+ FROM s3({CANDIDATE_PAIRS.read_args(run)})
""",
- parameters={"job_id": run.job_id},
- query_settings=settings_with_log_comment(context),
+ parameters={},
+ query_settings=_read_settings(context),
)
).result()
context.add_output_metadata(
@@ -860,11 +791,9 @@ def score_rule_based(
"""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)
+ INSERT INTO FUNCTION s3({LINKS.write_args(run, f"{RULES_MODEL_VERSION}.parquet")})
SELECT
- toUUID(%(job_id)s),
+ %(job_id)s,
%(team_id)s,
'{RULES_MODEL_VERSION}',
orphan_distinct_id,
@@ -872,7 +801,8 @@ def score_rule_based(
score,
runner_up,
score - runner_up,
- multiIf(score >= %(tier_high)s, 'high', score >= %(tier_medium)s, 'medium', 'low')
+ multiIf(score >= %(tier_high)s, 'high', score >= %(tier_medium)s, 'medium', 'low'),
+ now()
FROM (
SELECT
orphan_distinct_id,
@@ -890,8 +820,7 @@ def score_rule_based(
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
+ FROM s3({CANDIDATE_PAIRS.read_args(run)})
)
)
WHERE rn = 1 AND score >= %(min_score)s AND (score - runner_up) >= %(min_margin)s
@@ -905,20 +834,19 @@ def score_rule_based(
"min_margin": config.rule_min_margin,
}
cluster.any_host(
- partial(_execute, query=query, parameters=parameters, query_settings=settings_with_log_comment(context))
+ partial(_execute, query=query, parameters=parameters, query_settings=_write_settings(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}'
+ FROM s3({LINKS.read_args(run)})
+ WHERE model_version = '{RULES_MODEL_VERSION}'
""",
- parameters={"job_id": run.job_id},
- query_settings=settings_with_log_comment(context),
+ parameters={},
+ query_settings=_read_settings(context),
)
).result()
context.add_output_metadata({"rule_links": dagster.MetadataValue.int(links)})
@@ -956,12 +884,12 @@ def train_logreg_and_score(
_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
+ FROM s3({CANDIDATE_PAIRS.read_args(run)})
+ WHERE 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),
+ parameters={"max_rows": config.max_training_rows},
+ query_settings=_read_settings(context),
)
).result()
positives = sum(1 for row in labeled_rows if row[1] == 1)
@@ -986,13 +914,13 @@ def train_logreg_and_score(
_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
+ FROM s3({CANDIDATE_PAIRS.read_args(run)})
+ WHERE 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),
+ parameters={"limit": weak_negative_count},
+ query_settings=_read_settings(context),
)
).result()
@@ -1046,13 +974,12 @@ def train_logreg_and_score(
_execute,
query=f"""
SELECT orphan_distinct_id, anchor_person_key, {feature_cols}
- FROM {CANDIDATE_PAIRS.qualified_name}
- WHERE job_id = toUUID(%(job_id)s)
+ FROM s3({CANDIDATE_PAIRS.read_args(run)})
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),
+ parameters={"max_rows": config.max_scoring_rows},
+ query_settings=_read_settings(context),
)
).result()
if len(scoring_rows) >= config.max_scoring_rows:
@@ -1071,12 +998,12 @@ def train_logreg_and_score(
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
+ computed_at = datetime.datetime.now(datetime.UTC)
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,
+ run.job_id,
config.team_id,
LOGREG_MODEL_VERSION,
orphan_id,
@@ -1085,22 +1012,15 @@ def train_logreg_and_score(
runner_up,
prob - runner_up,
tier,
+ computed_at,
)
)
- 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()
+ # Winners go to their own `links/logreg_v1_part_<n>.parquet` objects (the rules op already
+ # wrote `links/rules_v1.parquet`); the read side unions them with `links/*.parquet`.
+ _write_rows_to_s3(
+ context, cluster, LINKS, run, link_rows, columns=10, filename_prefix=f"{LOGREG_MODEL_VERSION}_part"
+ )
metadata["logreg_links"] = dagster.MetadataValue.int(len(link_rows))
context.add_output_metadata(metadata)
@@ -1119,22 +1039,20 @@ def evaluate_and_report(
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)
+ ch_settings = _read_settings(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
+ FROM s3({DEVICE_DAYS.read_args(run)}) AS d
LEFT JOIN (
SELECT distinct_id, is_anchor
- FROM {PERSON_TIMELINE.qualified_name}
- WHERE job_id = toUUID(%(job_id)s)
+ FROM s3({PERSON_TIMELINE.read_args(run)})
) AS t ON d.distinct_id = t.distinct_id
- WHERE d.job_id = toUUID(%(job_id)s)
""",
- parameters={"job_id": run.job_id},
+ parameters={},
query_settings=ch_settings,
)
).result()
@@ -1147,15 +1065,14 @@ def evaluate_and_report(
SELECT
uniqExactIf(t.distinct_id, t.label_person_key != ''),
uniqExactIf(t.distinct_id, t.label_person_key = '')
- FROM {PERSON_TIMELINE.qualified_name} AS t
+ FROM s3({PERSON_TIMELINE.read_args(run)}) AS t
INNER JOIN (
SELECT DISTINCT distinct_id
- FROM {DEVICE_DAYS.qualified_name}
- WHERE job_id = toUUID(%(job_id)s)
+ FROM s3({DEVICE_DAYS.read_args(run)})
) AS d ON t.distinct_id = d.distinct_id
- WHERE t.job_id = toUUID(%(job_id)s) AND t.is_anchor = 0
+ WHERE t.is_anchor = 0
""",
- parameters={"job_id": run.job_id},
+ parameters={},
query_settings=ch_settings,
)
).result()
@@ -1165,10 +1082,9 @@ def evaluate_and_report(
_execute,
query=f"""
SELECT uniqExact(orphan_distinct_id)
- FROM {CANDIDATE_PAIRS.qualified_name}
- WHERE job_id = toUUID(%(job_id)s)
+ FROM s3({CANDIDATE_PAIRS.read_args(run)})
""",
- parameters={"job_id": run.job_id},
+ parameters={},
query_settings=ch_settings,
)
).result()
@@ -1203,19 +1119,18 @@ def evaluate_and_report(
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
+ FROM s3({LINKS.read_args(run)}) AS lk
+ INNER JOIN s3({CANDIDATE_PAIRS.read_args(run)}) AS p
+ ON 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 != ''
+ FROM s3({PERSON_TIMELINE.read_args(run)})
+ WHERE 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
+ WHERE lk.model_version = %(model_version)s
""",
- parameters={"job_id": run.job_id, "model_version": model_version},
+ parameters={"model_version": model_version},
query_settings=ch_settings,
)
).result()
@@ -1261,7 +1176,7 @@ def _execute(
@dagster.job(tags={"owner": JobOwners.TEAM_GROWTH.value, "disable_slack_notifications": "true"})
def identity_matching_job():
- run = setup_tables()
+ run = prepare_run()
run = build_device_day_index(run)
run = extract_person_timeline(run)
run = build_candidate_pairs(run)
diff --git a/products/growth/dags/tests/test_identity_matching.py b/products/growth/dags/tests/test_identity_matching.py
index ea7cf7899118..982017112c0c 100644
--- a/products/growth/dags/tests/test_identity_matching.py
+++ b/products/growth/dags/tests/test_identity_matching.py
@@ -11,6 +11,7 @@ from clickhouse_driver import Client
from posthog.clickhouse.cluster import ClickhouseCluster
+from products.growth.backend.constants import identity_matching_dataset_read_args
from products.growth.dags import identity_matching
from products.growth.dags.identity_matching import (
CANDIDATE_PAIRS,
@@ -20,6 +21,7 @@ from products.growth.dags.identity_matching import (
PERSON_TIMELINE,
RULES_MODEL_VERSION,
IdentityMatchingConfig,
+ MatchingDataset,
identity_matching_job,
is_identity_matching_registered,
validate_team_allowed,
@@ -27,6 +29,17 @@ from products.growth.dags.identity_matching import (
TEAM_ID = 99
+# Each stage writes Parquet to a per-run S3 prefix; reads glob it back via `s3(...)`.
+_S3_READ_SETTINGS = {"s3_throw_on_zero_files_match": "0"}
+
+
+def _read_dataset(
+ client: Client, dataset: MatchingDataset, job_id: UUID, columns: str, suffix: str = ""
+) -> list[tuple[Any, ...]]:
+ args = identity_matching_dataset_read_args(TEAM_ID, str(job_id), dataset.folder, dataset.structure)
+ return client.execute(f"SELECT {columns} FROM s3({args}) {suffix}", settings=_S3_READ_SETTINGS)
+
+
HOUSEHOLD_IP = "10.0.0.1"
BOB_IP = "10.0.0.2"
CARA_IP = "10.0.0.9"
@@ -174,7 +187,7 @@ def _run_job(cluster: ClickhouseCluster, **config_overrides: Any) -> tuple[dagst
}
config = IdentityMatchingConfig(**config_kwargs)
result = identity_matching_job.execute_in_process(
- run_config=dagster.RunConfig({"setup_tables": config}),
+ run_config=dagster.RunConfig({"prepare_run": config}),
resources={"cluster": cluster},
)
return result, UUID(result.dagster_run.run_id)
@@ -187,22 +200,14 @@ def test_identity_matching_job(cluster: ClickhouseCluster) -> None:
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},
- )
+ return _read_dataset(client, DEVICE_DAYS, job_id, "day, ips", "WHERE distinct_id = 'phone-anna' ORDER BY day")
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},
- )
+ rows = _read_dataset(client, PERSON_TIMELINE, job_id, "distinct_id, is_anchor, person_key, label_person_key")
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()
@@ -219,10 +224,11 @@ def test_identity_matching_job(cluster: ClickhouseCluster) -> None:
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},
+ rows = _read_dataset(
+ client,
+ CANDIDATE_PAIRS,
+ job_id,
+ "orphan_distinct_id, anchor_person_key, shared_ip_days, label, ua_exact_match, orphan_is_webview",
)
return {(orphan, anchor): tuple(rest) for orphan, anchor, *rest in rows}
@@ -237,11 +243,7 @@ def test_identity_matching_job(cluster: ClickhouseCluster) -> None:
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},
- )
+ rows = _read_dataset(client, LINKS, job_id, "model_version, orphan_distinct_id, anchor_person_key")
return {(model_version, orphan): anchor for model_version, orphan, anchor in rows}
links = cluster.any_host(get_links).result()
@@ -260,11 +262,7 @@ def test_logreg_skips_without_labels(cluster: ClickhouseCluster) -> None:
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},
- )
+ [[count]] = _read_dataset(client, LINKS, job_id, "count()", f"WHERE model_version = '{LOGREG_MODEL_VERSION}'")
return count
assert cluster.any_host(get_logreg_link_count).result() == 0