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.

fix(growth): harden identity matching storage and speed up the job (#65333)

Fernando Gomes5ac2d5c110d1
diff --git a/products/growth/backend/api/identity_matching.py b/products/growth/backend/api/identity_matching.py
index c6bf8c211658..422dec589aae 100644
--- a/products/growth/backend/api/identity_matching.py
+++ b/products/growth/backend/api/identity_matching.py
@@ -11,9 +11,10 @@ segment: a job_id belonging to another team resolves to a prefix this team never
from typing import Any
-from drf_spectacular.utils import extend_schema, extend_schema_serializer
-from rest_framework import serializers, viewsets
+from drf_spectacular.utils import OpenApiResponse, extend_schema, extend_schema_serializer
+from rest_framework import serializers, status, viewsets
from rest_framework.decorators import action
+from rest_framework.exceptions import APIException
from rest_framework.request import Request
from rest_framework.response import Response
@@ -26,8 +27,10 @@ from products.growth.backend.constants import (
IDENTITY_MATCHING_CANDIDATE_PAIRS_STRUCTURE,
IDENTITY_MATCHING_LINKS_DATASET,
IDENTITY_MATCHING_LINKS_STRUCTURE,
+ IDENTITY_MATCHING_S3_UNCONFIGURED_MESSAGE,
IDENTITY_MATCHING_TIERS,
identity_matching_dataset_read_args,
+ identity_matching_s3_unconfigured,
)
MAX_RUNS_LISTED = 50
@@ -127,11 +130,33 @@ class IdentityMatchingRunsResponseSerializer(serializers.Serializer):
results = IdentityMatchingRunSerializer(many=True, help_text="Runs ordered by recency, most recent first.")
+class IdentityMatchingErrorSerializer(serializers.Serializer):
+ detail = serializers.CharField(help_text="Human-readable explanation of why the request could not be served.")
+
+
+class IdentityMatchingStorageUnavailable(APIException):
+ status_code = status.HTTP_503_SERVICE_UNAVAILABLE
+ default_code = "identity_matching_storage_unavailable"
+ default_detail = IDENTITY_MATCHING_S3_UNCONFIGURED_MESSAGE
+
+
+_STORAGE_UNAVAILABLE_RESPONSE = OpenApiResponse(
+ response=IdentityMatchingErrorSerializer,
+ description="The identity matching scratch bucket is not configured on this deployment.",
+)
+
+
class IdentityMatchingLinkViewSet(TeamAndOrgViewSetMixin, viewsets.ViewSet):
scope_object = "INTERNAL"
# Staff-only while identity matching is under development.
permission_classes = [IsStaffUser]
+ def _assert_storage_configured(self) -> None:
+ """Fail with a clear 503 if the scratch bucket env is missing, rather than letting every
+ s3() read hit the wrong (fallback) bucket and surface an opaque AccessDenied 500."""
+ if identity_matching_s3_unconfigured():
+ raise IdentityMatchingStorageUnavailable()
+
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(
@@ -166,9 +191,10 @@ class IdentityMatchingLinkViewSet(TeamAndOrgViewSetMixin, viewsets.ViewSet):
"evidence behind each link. Produced by the identity matching Dagster job; empty until that "
"job has run for this project.",
parameters=[IdentityMatchingLinksFilterSerializer],
- responses={200: IdentityMatchingLinksResponseSerializer},
+ responses={200: IdentityMatchingLinksResponseSerializer, 503: _STORAGE_UNAVAILABLE_RESPONSE},
)
def list(self, request: Request, **kwargs: Any) -> Response:
+ self._assert_storage_configured()
filters = IdentityMatchingLinksFilterSerializer(data=request.query_params)
filters.is_valid(raise_exception=True)
params = filters.validated_data
@@ -277,10 +303,11 @@ class IdentityMatchingLinkViewSet(TeamAndOrgViewSetMixin, viewsets.ViewSet):
summary="List identity matching runs",
description="Recent identity matching runs for this project with link counts per scoring "
"model, most recent first.",
- responses={200: IdentityMatchingRunsResponseSerializer},
+ 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
diff --git a/products/growth/backend/api/test_identity_matching.py b/products/growth/backend/api/test_identity_matching.py
index 495436e9e886..cd1c90441186 100644
--- a/products/growth/backend/api/test_identity_matching.py
+++ b/products/growth/backend/api/test_identity_matching.py
@@ -193,6 +193,16 @@ class TestIdentityMatchingLinksAPI(APIBaseTest):
assert runs_response.status_code == status.HTTP_200_OK
assert runs_response.json() == {"results": []}
+ @parameterized.expand([("links", ""), ("runs", "runs/")])
+ def test_returns_503_when_scratch_bucket_unconfigured_on_cloud(self, _name: str, suffix: str) -> None:
+ # On Cloud, an unset IDENTITY_MATCHING_S3_BUCKET falls back to OBJECT_STORAGE_BUCKET; both
+ # equal means the env is missing, so the endpoint should fail loudly instead of reading the
+ # wrong bucket. Force equality so the assertion holds regardless of the CI environment.
+ with override_settings(CLOUD_DEPLOYMENT="US", IDENTITY_MATCHING_S3_BUCKET="b", OBJECT_STORAGE_BUCKET="b"):
+ response = self.client.get(f"/api/projects/{self.team.pk}/identity_matching_links/{suffix}")
+ assert response.status_code == status.HTTP_503_SERVICE_UNAVAILABLE
+ assert "IDENTITY_MATCHING_S3_BUCKET" in response.json()["detail"]
+
def test_runs_lists_link_counts_per_model(self) -> None:
self._seed()
response = self.client.get(f"/api/projects/{self.team.pk}/identity_matching_links/runs/")
diff --git a/products/growth/backend/constants.py b/products/growth/backend/constants.py
index bcb8d7317e23..47fa1d4e739e 100644
--- a/products/growth/backend/constants.py
+++ b/products/growth/backend/constants.py
@@ -162,6 +162,25 @@ IDENTITY_MATCHING_LINKS_STRUCTURE = """
"""
+# On a Cloud deployment the scratch bucket must be a dedicated, infra-provided bucket distinct
+# from the general object-storage bucket. IDENTITY_MATCHING_S3_BUCKET falls back to
+# OBJECT_STORAGE_BUCKET when its env var is unset, so equality on Cloud means the var is missing
+# and every s3() call would target the wrong bucket (the app-assets bucket the ClickHouse role
+# cannot access) — a silent AccessDenied. Both the Dagster job and the read API check this so a
+# missing env on either deployment fails loudly instead of 500-ing on AccessDenied.
+IDENTITY_MATCHING_S3_UNCONFIGURED_MESSAGE = (
+ "IDENTITY_MATCHING_S3_BUCKET is not set on this deployment, so identity matching falls back to "
+ "the general object-storage bucket, which the ClickHouse role cannot access. Set it to the "
+ "scratch bucket (the same value as the Dagster deployment) on every deployment that runs the "
+ "identity matching job or its read API."
+)
+
+
+def identity_matching_s3_unconfigured() -> bool:
+ """True when the scratch bucket isn't configured on a Cloud deployment (see message above)."""
+ return bool(settings.CLOUD_DEPLOYMENT) and settings.IDENTITY_MATCHING_S3_BUCKET == settings.OBJECT_STORAGE_BUCKET
+
+
def identity_matching_run_prefix(team_id: int, job_id: str) -> str:
"""S3 key prefix for one run: `<prefix>/team_<team_id>/<job_id>`.
diff --git a/products/growth/dags/identity_matching.py b/products/growth/dags/identity_matching.py
index fa4d7067d151..14b9a65f0df1 100644
--- a/products/growth/dags/identity_matching.py
+++ b/products/growth/dags/identity_matching.py
@@ -33,12 +33,14 @@ Known limitations:
import hashlib
import datetime
from collections.abc import Sequence
+from concurrent.futures import ThreadPoolExecutor, as_completed
from dataclasses import dataclass
from functools import partial
from typing import Any
import dagster
import pydantic
+import dagster_slack
from clickhouse_driver import Client
from posthog import settings
@@ -56,9 +58,11 @@ from products.growth.backend.constants import (
IDENTITY_MATCHING_PERSON_TIMELINE_DATASET,
IDENTITY_MATCHING_PERSON_TIMELINE_STRUCTURE,
IDENTITY_MATCHING_RULES_MODEL_VERSION,
+ IDENTITY_MATCHING_S3_UNCONFIGURED_MESSAGE,
identity_matching_dataset_read_args,
identity_matching_run_prefix,
identity_matching_s3_args,
+ identity_matching_s3_unconfigured,
)
# Click IDs that indicate a paid ad click, a subset of CAMPAIGN_PROPERTIES
@@ -126,6 +130,8 @@ DEFAULT_RULE_WEIGHTS: dict[str, float] = {
# it refuses to process any other team. Local, dev, and self-hosted are unrestricted.
PROD_US_ALLOWED_TEAM_IDS: frozenset[int] = frozenset({2})
+_ONE_GB = 1024**3
+
def is_identity_matching_registered() -> bool:
return settings.CLOUD_DEPLOYMENT != "EU"
@@ -206,6 +212,27 @@ class IdentityMatchingConfig(dagster.Config):
)
prob_tier_high: float = pydantic.Field(default=0.9, description="Probability at or above which tier is 'high'.")
prob_tier_medium: float = pydantic.Field(default=0.7, description="Probability at or above which tier is 'medium'.")
+ query_max_execution_time_seconds: int = pydantic.Field(
+ default=60 * 60,
+ gt=0,
+ description="ClickHouse max_execution_time per query — ceiling that aborts a runaway query.",
+ )
+ query_max_memory_usage_gb: int = pydantic.Field(
+ default=50,
+ gt=0,
+ description="ClickHouse max_memory_usage per query, in GB — per-host cap that guards against OOM.",
+ )
+ query_external_spill_gb: int = pydantic.Field(
+ default=25,
+ gt=0,
+ description="GROUP BY / ORDER BY / JOIN memory in GB past which a query spills to disk "
+ "instead of erroring. Must stay below query_max_memory_usage_gb to take effect before the cap.",
+ )
+ slack_channel: str = pydantic.Field(
+ default="C0BCESDFRLZ",
+ description="Slack channel ID for the success report. Empty disables the notification. The "
+ "Dagster Slack bot must be a member of the channel. Only posts on Cloud deployments.",
+ )
@pydantic.model_validator(mode="after")
def check_window(self) -> "IdentityMatchingConfig":
@@ -214,8 +241,29 @@ class IdentityMatchingConfig(dagster.Config):
unknown_weights = set(self.rule_weights) - set(DEFAULT_RULE_WEIGHTS)
if unknown_weights:
raise ValueError(f"Unknown rule weights: {sorted(unknown_weights)}")
+ if self.query_external_spill_gb >= self.query_max_memory_usage_gb:
+ raise ValueError(
+ f"query_external_spill_gb ({self.query_external_spill_gb}) must be below "
+ f"query_max_memory_usage_gb ({self.query_max_memory_usage_gb}) to spill before the cap"
+ )
return self
+ def query_guards(self) -> dict[str, str]:
+ """ClickHouse per-query guard settings derived from the run config (see _base_settings)."""
+ spill_bytes = str(self.query_external_spill_gb * _ONE_GB)
+ return {
+ "max_execution_time": str(self.query_max_execution_time_seconds),
+ "max_memory_usage": str(self.query_max_memory_usage_gb * _ONE_GB),
+ "max_bytes_before_external_group_by": spill_bytes,
+ "max_bytes_before_external_sort": spill_bytes,
+ "distributed_aggregation_memory_efficient": "1", # memory-efficient GROUP BY over distributed events
+ # Let the candidate_pairs hash join spill to a partial-merge join past the same
+ # threshold instead of erroring at max_memory_usage — without this, a join heavier than
+ # the cap is the one way these guards could break an otherwise-working run.
+ "join_algorithm": "auto",
+ "max_bytes_in_join": spill_bytes,
+ }
+
@dataclass(frozen=True)
class MatchingRun:
@@ -282,21 +330,42 @@ SINGLE_OBJECT = "data.parquet"
# 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"}
+# Per-query guards so a pathological run (e.g. an over-wide window on a large team) degrades or
+# aborts on the single host it runs on, rather than pressuring the cluster. The ceilings are
+# tunable per run from the Dagster launchpad (IdentityMatchingConfig.query_*); the defaults are
+# modeled on the events_backfill_to_duckling job and the working team-2 run sits well under them.
+# The external thresholds make large GROUP BY / ORDER BY spill to disk instead of hitting the
+# memory cap and erroring, so they only change behavior for queries that would otherwise blow up.
+def _base_settings(context: dagster.OpExecutionContext, run: "MatchingRun") -> dict[str, str]:
+ return {**settings_with_log_comment(context), **run.config.query_guards()}
-def _read_settings(context: dagster.OpExecutionContext) -> dict[str, str]:
- return {**settings_with_log_comment(context), "s3_throw_on_zero_files_match": "0"}
+def _write_settings(context: dagster.OpExecutionContext, run: "MatchingRun") -> dict[str, str]:
+ return {**_base_settings(context, run), "s3_truncate_on_insert": "1"}
-# Rows the Python ops build (person_timeline, logreg links) are written in small batches as inline
+def _read_settings(context: dagster.OpExecutionContext, run: "MatchingRun") -> dict[str, str]:
+ return {**_base_settings(context, run), "s3_throw_on_zero_files_match": "0"}
+
+
+# Rows the Python ops build (person_timeline, logreg links) are written in 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
+# which writes Parquet to s3 reliably. Each batch is one serial round-trip writing one Parquet
+# part, so the batch size trades round-trip count (wall-clock) against per-statement size: at 10k
+# rows a substituted statement stays a few MB (well under the max_query_size raised below) and
+# ~100k AST elements (well under the ~500k cap), while cutting round-trips and part files 10x
+# versus 1k. On large teams (team 2) the row count reaches 1-2M, so 1k batches meant thousands of
+# serial inserts dominating the op runtime.
+_S3_VALUES_BATCH = 10000
+
+# Each batch is an independent INSERT INTO FUNCTION s3 round-trip to its own Parquet part, and
+# any_host targets one host, so this many writes run concurrently against that single node. It
+# hides the per-statement round-trip latency that dominated the op (1-2M rows = hundreds of parts)
+# without flooding the host. Distinct part filenames mean concurrent writes never collide, and
+# s3_truncate_on_insert keeps each part idempotent on retry.
+_S3_WRITE_CONCURRENCY = 8
def _write_rows_to_s3(
@@ -310,9 +379,10 @@ def _write_rows_to_s3(
) -> 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]
+ query_settings = {**_write_settings(context, run), "max_query_size": "10485760"}
+ batches = [rows[offset : offset + _S3_VALUES_BATCH] for offset in range(0, len(rows), _S3_VALUES_BATCH)]
+
+ def _write_part(part: int, batch: list[tuple[Any, ...]]) -> None:
placeholders: list[str] = []
parameters: dict[str, Any] = {}
for i, row in enumerate(batch):
@@ -325,6 +395,25 @@ def _write_rows_to_s3(
)
cluster.any_host(partial(_execute, query=query, parameters=parameters, query_settings=query_settings)).result()
+ # Write the first part serially to prime the host connection pool: cluster.any_host creates the
+ # pool lazily on first use (a check-then-set on its host->pool map), so doing one write before
+ # fanning out avoids a creation race when the rest run concurrently.
+ _write_part(0, batches[0])
+ if len(batches) == 1:
+ return
+ with ThreadPoolExecutor(max_workers=_S3_WRITE_CONCURRENCY) as executor:
+ futures = [executor.submit(_write_part, part, batch) for part, batch in enumerate(batches[1:], start=1)]
+ try:
+ for future in as_completed(futures):
+ future.result() # surface the first failure; a retry overwrites parts idempotently
+ except Exception:
+ # Cancel queued (not-yet-started) batches so the op fails fast instead of waiting for
+ # every remaining write — the `with` block's shutdown(wait=True) would otherwise let
+ # all submitted futures run before the exception surfaces.
+ for pending in futures:
+ pending.cancel()
+ raise
+
def _prop(name: str) -> str:
return f"JSONExtractString(properties, '{name}')"
@@ -351,6 +440,10 @@ def prepare_run(
"""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)
+ # Fail before any S3 I/O if the scratch bucket env is missing, rather than writing to the
+ # wrong (fallback) bucket and surfacing an opaque AccessDenied on the first write.
+ if identity_matching_s3_unconfigured():
+ raise dagster.Failure(IDENTITY_MATCHING_S3_UNCONFIGURED_MESSAGE)
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}), "
@@ -412,7 +505,7 @@ def build_device_day_index(
"paths_cap": config.paths_per_day_cap,
}
cluster.any_host(
- partial(_execute, query=query, parameters=parameters, query_settings=_write_settings(context))
+ partial(_execute, query=query, parameters=parameters, query_settings=_write_settings(context, run))
).result()
[[rows, devices, empty_ip_rows]] = cluster.any_host(
@@ -423,7 +516,7 @@ def build_device_day_index(
FROM s3({DEVICE_DAYS.read_args(run)})
""",
parameters={},
- query_settings=_read_settings(context),
+ query_settings=_read_settings(context, run),
)
).result()
empty_ip_fraction = (empty_ip_rows / rows) if rows else 0.0
@@ -514,7 +607,7 @@ def extract_person_timeline(
"eval_end": run.eval_end,
"max_edges": config.max_identity_edges,
},
- query_settings=settings_with_log_comment(context),
+ query_settings=_read_settings(context, run),
)
).result()
if len(edges) >= config.max_identity_edges:
@@ -740,7 +833,7 @@ def build_candidate_pairs(
"max_candidates_per_orphan": config.max_candidates_per_orphan,
}
cluster.any_host(
- partial(_execute, query=query, parameters=parameters, query_settings=_write_settings(context))
+ partial(_execute, query=query, parameters=parameters, query_settings=_write_settings(context, run))
).result()
[[pair_rows, orphans_with_candidates, positives, negatives]] = cluster.any_host(
@@ -751,7 +844,7 @@ def build_candidate_pairs(
FROM s3({CANDIDATE_PAIRS.read_args(run)})
""",
parameters={},
- query_settings=_read_settings(context),
+ query_settings=_read_settings(context, run),
)
).result()
context.add_output_metadata(
@@ -834,7 +927,7 @@ def score_rule_based(
"min_margin": config.rule_min_margin,
}
cluster.any_host(
- partial(_execute, query=query, parameters=parameters, query_settings=_write_settings(context))
+ partial(_execute, query=query, parameters=parameters, query_settings=_write_settings(context, run))
).result()
[[links]] = cluster.any_host(
@@ -846,7 +939,7 @@ def score_rule_based(
WHERE model_version = '{RULES_MODEL_VERSION}'
""",
parameters={},
- query_settings=_read_settings(context),
+ query_settings=_read_settings(context, run),
)
).result()
context.add_output_metadata({"rule_links": dagster.MetadataValue.int(links)})
@@ -889,7 +982,7 @@ def train_logreg_and_score(
LIMIT %(max_rows)s
""",
parameters={"max_rows": config.max_training_rows},
- query_settings=_read_settings(context),
+ query_settings=_read_settings(context, run),
)
).result()
positives = sum(1 for row in labeled_rows if row[1] == 1)
@@ -920,7 +1013,7 @@ def train_logreg_and_score(
LIMIT %(limit)s
""",
parameters={"limit": weak_negative_count},
- query_settings=_read_settings(context),
+ query_settings=_read_settings(context, run),
)
).result()
@@ -979,7 +1072,7 @@ def train_logreg_and_score(
LIMIT %(max_rows)s
""",
parameters={"max_rows": config.max_scoring_rows},
- query_settings=_read_settings(context),
+ query_settings=_read_settings(context, run),
)
).result()
if len(scoring_rows) >= config.max_scoring_rows:
@@ -1027,10 +1120,88 @@ def train_logreg_and_score(
return run
+def _post_run_report_to_slack(
+ context: dagster.OpExecutionContext,
+ slack: dagster_slack.SlackResource,
+ run: "MatchingRun",
+ *,
+ channel: str,
+ report: str,
+ devices: int,
+ orphan_devices: int,
+ anchor_devices: int,
+ orphans_with_candidates: int,
+ gradable_orphans: int,
+ unrecoverable_orphans: int,
+ model_headlines: list[str],
+) -> None:
+ """Post a readable success summary to Slack with the full report attached.
+
+ Only runs on Cloud deployments (the Slack resource is a no-op locally) and never fails the
+ op: the report is already logged and in op metadata, so a Slack outage must not lose a run.
+ """
+ if not settings.CLOUD_DEPLOYMENT:
+ context.log.info("Skipping Slack report in non-prod environment")
+ return
+ if not channel:
+ context.log.info("Skipping Slack report: no slack_channel configured")
+ return
+
+ blocks: list[dict[str, Any]] = [
+ {"type": "header", "text": {"type": "plain_text", "text": "✅ Identity matching run complete", "emoji": True}},
+ {
+ "type": "context",
+ "elements": [
+ {
+ "type": "mrkdwn",
+ "text": f"Env *{settings.CLOUD_DEPLOYMENT}* • team `{run.config.team_id}` • "
+ f"window `[{run.date_start}, {run.date_end})` • eval until `{run.eval_end}`",
+ }
+ ],
+ },
+ {"type": "context", "elements": [{"type": "mrkdwn", "text": f"job_id `{run.job_id}`"}]},
+ {
+ "type": "section",
+ "text": {
+ "type": "mrkdwn",
+ "text": (
+ "*Coverage*\n"
+ f"• Active devices: *{devices:,}* ({orphan_devices:,} orphan / {anchor_devices:,} anchor)\n"
+ f"• Orphans with ≥1 candidate: *{orphans_with_candidates:,}*\n"
+ f"• Gradable labeled orphans: *{gradable_orphans:,}* (+{unrecoverable_orphans:,} unrecoverable)"
+ ),
+ },
+ },
+ ]
+ if model_headlines:
+ blocks.append(
+ {
+ "type": "section",
+ "text": {"type": "mrkdwn", "text": "*Models*\n" + "\n".join(f"• {line}" for line in model_headlines)},
+ }
+ )
+
+ try:
+ client = slack.get_client()
+ # text= is the notification/fallback for clients that don't render blocks.
+ response = client.chat_postMessage(channel=channel, blocks=blocks, text="Identity matching run complete")
+ # files_upload_v2 needs the channel ID, which chat_postMessage returns.
+ client.files_upload_v2(
+ channel=response.get("channel"),
+ content=report,
+ filename=f"identity_matching_{run.job_id}.md",
+ title="Identity matching report",
+ initial_comment="Full evaluation report attached.",
+ )
+ except Exception:
+ context.log.exception("Failed to post identity matching report to Slack")
+
+
@dagster.op
def evaluate_and_report(
context: dagster.OpExecutionContext,
cluster: dagster.ResourceParam[ClickhouseCluster],
+ slack: dagster.ResourceParam[dagster_slack.SlackResource],
rules_run: MatchingRun,
logreg_run: MatchingRun,
) -> None:
@@ -1039,7 +1210,7 @@ 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 = _read_settings(context)
+ ch_settings = _read_settings(context, run)
[[devices, anchor_devices]] = cluster.any_host(
partial(
@@ -1108,6 +1279,7 @@ def evaluate_and_report(
RULES_MODEL_VERSION: [float(t) for t in config.rule_thresholds],
LOGREG_MODEL_VERSION: [float(t) for t in config.prob_thresholds],
}
+ model_headlines: list[str] = [] # one readable line per model for the Slack summary
for model_version, thresholds in sweeps.items():
link_rows: list[tuple[float, str, str, int, int]] = cluster.any_host(
partial(
@@ -1137,6 +1309,7 @@ def evaluate_and_report(
if not link_rows:
summary_lines.append(f"\n{model_version}: no links")
+ model_headlines.append(f"*{model_version}*: no links")
continue
table_lines = [
@@ -1144,6 +1317,7 @@ def evaluate_and_report(
"| threshold | links | graded | precision | recall | new paid touches |",
"|---|---|---|---|---|---|",
]
+ best: tuple[float, float, float, int] | None = None # (precision, threshold, recall, links)
for threshold in thresholds:
at_t = [row for row in link_rows if row[0] >= threshold]
graded = [row for row in at_t if row[2] != ""]
@@ -1151,6 +1325,8 @@ def evaluate_and_report(
precision = (correct / len(graded)) if graded else None
recall = (correct / gradable_orphans) if gradable_orphans else None
paid_gain = sum(1 for row in at_t if row[3] == 1 and row[4] == 0)
+ if precision is not None and (best is None or precision > best[0]):
+ best = (precision, threshold, recall or 0.0, len(at_t))
table_lines.append(
f"| {threshold} | {len(at_t)} | {len(graded)} "
f"| {f'{precision:.3f}' if precision is not None else 'n/a'} "
@@ -1159,10 +1335,31 @@ def evaluate_and_report(
)
summary_lines.extend(table_lines)
metadata[f"{model_version}_sweep"] = dagster.MetadataValue.md("\n".join(table_lines))
+ if best is not None:
+ model_headlines.append(
+ f"*{model_version}*: {len(link_rows)} links · best precision {best[0]:.3f} "
+ f"at score ≥{best[1]} ({best[3]} links, recall {best[2]:.3f})"
+ )
+ else:
+ model_headlines.append(f"*{model_version}*: {len(link_rows)} links (no graded labels)")
report = "\n".join(summary_lines)
context.log.info("Identity matching report:\n%s", report)
context.add_output_metadata({**metadata, "report": dagster.MetadataValue.md(report)})
+ _post_run_report_to_slack(
+ context,
+ slack,
+ run,
+ channel=config.slack_channel,
+ report=report,
+ devices=devices,
+ orphan_devices=orphan_devices,
+ anchor_devices=anchor_devices,
+ orphans_with_candidates=orphans_with_candidates,
+ gradable_orphans=gradable_orphans,
+ unrecoverable_orphans=unrecoverable_orphans,
+ model_headlines=model_headlines,
+ )
def _execute(
@@ -1174,7 +1371,7 @@ def _execute(
return client.execute(query, parameters, settings=query_settings)
[email protected](tags={"owner": JobOwners.TEAM_GROWTH.value, "disable_slack_notifications": "true"})
[email protected](tags={"owner": JobOwners.TEAM_GROWTH.value})
def identity_matching_job():
run = prepare_run()
run = build_device_day_index(run)
diff --git a/products/growth/dags/tests/test_identity_matching.py b/products/growth/dags/tests/test_identity_matching.py
index 982017112c0c..04d8bd501e99 100644
--- a/products/growth/dags/tests/test_identity_matching.py
+++ b/products/growth/dags/tests/test_identity_matching.py
@@ -188,7 +188,8 @@ 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({"prepare_run": config}),
- resources={"cluster": cluster},
+ # Slack posting is skipped off-Cloud, so a no-op resource satisfies the op requirement.
+ resources={"cluster": cluster, "slack": dagster.ResourceDefinition.none_resource()},
)
return result, UUID(result.dagster_run.run_id)
diff --git a/products/growth/frontend/generated/api.schemas.ts b/products/growth/frontend/generated/api.schemas.ts
index 12dd2d4ce772..6f97504fdf09 100644
--- a/products/growth/frontend/generated/api.schemas.ts
+++ b/products/growth/frontend/generated/api.schemas.ts
@@ -76,6 +76,11 @@ export interface IdentityMatchingLinksResponseApi {
count: number
}
+export interface IdentityMatchingErrorApi {
+ /** Human-readable explanation of why the request could not be served. */
+ detail: string
+}
+
export interface IdentityMatchingRunModelCountApi {
/** Scoring model, e.g. 'rules_v1' or 'logreg_v1'. */
model_version: string
diff --git a/products/growth/frontend/generated/api.zod.schemas.ts b/products/growth/frontend/generated/api.zod.schemas.ts
index 11d85a9b8514..8c18a14a90c6 100644
--- a/products/growth/frontend/generated/api.zod.schemas.ts
+++ b/products/growth/frontend/generated/api.zod.schemas.ts
@@ -111,6 +111,13 @@ export const IdentityMatchingLinksResponseApi = zod.object({
export type IdentityMatchingLinksResponseApi = zod.input<typeof IdentityMatchingLinksResponseApi>
export type IdentityMatchingLinksResponseApiOutput = zod.output<typeof IdentityMatchingLinksResponseApi>
+export const IdentityMatchingErrorApi = zod.object({
+ detail: zod.string().describe('Human-readable explanation of why the request could not be served.'),
+})
+
+export type IdentityMatchingErrorApi = zod.input<typeof IdentityMatchingErrorApi>
+export type IdentityMatchingErrorApiOutput = zod.output<typeof IdentityMatchingErrorApi>
+
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.'),
diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.ts
index 2d35d6ebc212..18ff9034a0e3 100644
--- a/services/mcp/src/api/generated.ts
+++ b/services/mcp/src/api/generated.ts
@@ -25744,6 +25744,11 @@ export namespace Schemas {
tags?: TagDefinition[];
}
+ export interface IdentityMatchingError {
+ /** Human-readable explanation of why the request could not be served. */
+ detail: string;
+ }
+
/**
* * `high` - high
* * `medium` - medium