:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
feat(growth): schedule ai enrichment classification daily (#77786)
Matt Brookerd42577b175ba
diff --git a/posthog/dags/locations/growth.py b/posthog/dags/locations/growth.pyindex 0989548ef127..5567752d08fc 100644--- a/posthog/dags/locations/growth.py+++ b/posthog/dags/locations/growth.py@@ -1,6 +1,7 @@import dagsterfrom products.growth.dags import (+ ai_enrichment,github_sdk_versions,identity_matching,oauth,@@ -22,20 +23,26 @@ jobs = [team_production_event_activation.detect_first_team_production_event_job,product_push_campaigns.product_push_campaigns_job,]+schedules = [+ oauth.oauth_clear_expired_oauth_tokens_schedule,+ github_sdk_versions.cache_github_sdk_versions_schedule,+ user_product_list.sync_cross_sell_products_monthly_schedule,+ team_production_event_activation.detect_first_team_production_event_schedule,+ product_push_campaigns.product_push_campaigns_schedule,+]# Identity matching processes internal PostHog data that only exists on Cloud US (team 2),# so the job is not registered on Cloud EU.if identity_matching.is_identity_matching_registered():jobs.append(identity_matching.identity_matching_job)+# AI enrichment sends organization signup data to an external LLM gateway, so — like+# identity matching — it is not registered on Cloud EU.+if ai_enrichment.is_ai_enrichment_registered():+ jobs.append(ai_enrichment.ai_enrichment_job)+ schedules.append(ai_enrichment.ai_enrichment_schedule)defs = dagster.Definitions(jobs=jobs,- schedules=[- oauth.oauth_clear_expired_oauth_tokens_schedule,- github_sdk_versions.cache_github_sdk_versions_schedule,- user_product_list.sync_cross_sell_products_monthly_schedule,- team_production_event_activation.detect_first_team_production_event_schedule,- product_push_campaigns.product_push_campaigns_schedule,- ],+ schedules=schedules,loggers=loggers,resources=resources,)diff --git a/products/growth/backend/enrichment/labels.py b/products/growth/backend/enrichment/labels.pyindex cbbe142ab9cf..90424e8e6877 100644--- a/products/growth/backend/enrichment/labels.py+++ b/products/growth/backend/enrichment/labels.py@@ -13,9 +13,9 @@ from typing import Any, Literal, castfrom django.db.models import QuerySet-from openai import OpenAI+from openai import APIConnectionError, InternalServerError, OpenAI, RateLimitErrorfrom openai.types.chat import ChatCompletionMessageParam-from tenacity import retry, retry_if_not_exception_type, stop_after_attempt, wait_exponential, wait_random+from tenacity import retry, retry_if_exception_type, stop_after_attempt, wait_exponential, wait_randomfrom posthog.llm.semantic_enrichment import extract_json_objectfrom posthog.models.organization import Organization, OrganizationMembership@@ -334,9 +334,14 @@ def _parse_custom_output(config: EnrichmentPromptConfig, data: dict[str, Any]) -@retry(- # Only transient failures earn a retry: a reply that structurally cannot satisfy the schema- # fails identically all three times and just triples the spend.- retry=retry_if_not_exception_type(OutputParseError),+ # Allowlist, not a blacklist: only failures that can plausibly succeed on a retry earn one.+ # APIConnectionError covers its APITimeoutError subclass too. Everything else — most+ # importantly AuthenticationError and OutputParseError — fails identically on every attempt,+ # so retrying it just triples the spend for the same outcome. This also stops tenacity's+ # three attempts from stacking with the SDK's own retries on a hard failure like a bad+ # gateway credential; see max_retries=0 at every client construction site for the other half+ # of that fix.+ retry=retry_if_exception_type((APIConnectionError, RateLimitError, InternalServerError)),stop=stop_after_attempt(3),# Jitter so a worker pool that all hit a 429 together doesn't retry in lockstep.wait=wait_exponential(multiplier=1, min=2, max=30) + wait_random(0, 2),diff --git a/products/growth/backend/management/commands/enrichment_label_batch.py b/products/growth/backend/management/commands/enrichment_label_batch.pyindex f5829df26e54..d93e84fad48a 100644--- a/products/growth/backend/management/commands/enrichment_label_batch.py+++ b/products/growth/backend/management/commands/enrichment_label_batch.py@@ -69,6 +69,15 @@ class Command(BaseCommand):default=0.5,help="Fail the run if succeeded/attempted drops below this fraction",)+ parser.add_argument(+ "--expected-version",+ default=None,+ help=(+ "If set, abort before spending if the label's current active version doesn't match. "+ "Guards a caller that resolved the active version separately (e.g. a scheduler deciding "+ "what to count as pending) against a version bump racing its own call."+ ),+ )def handle(self, *args: Any, **options: Any) -> None:label: str = options["label"]@@ -76,6 +85,7 @@ class Command(BaseCommand):workers: int = options["workers"]max_failures: int = options["max_failures"]min_success_rate: float = options["min_success_rate"]+ expected_version: str | None = options["expected_version"]if workers < 1:raise CommandError("--workers must be at least 1")if limit is not None and limit < 1:@@ -86,6 +96,11 @@ class Command(BaseCommand):config = get_active_config(label)if config is None:raise CommandError(f"No active EnrichmentPromptConfig for label {label!r}")+ if expected_version is not None and config.version != expected_version:+ raise CommandError(+ f"label {label!r} active version is {config.version!r}, expected {expected_version!r}; "+ "the active version changed after the caller resolved it, aborting"+ )try:validate_input_fields(config)validate_output_fields(config)@@ -133,6 +148,13 @@ class Command(BaseCommand):# breaker had already tripped — excluded from success_rate's denominator below so an# aborted run's ratio reflects what was actually tried, not what was merely queued."aborted": 0,+ # A declined-at-enumeration-time org (the common case) never increments "attempted"+ # at all - see _attempt_targets. This one is for the rarer case _process's own+ # re-check catches: a fetch that WAS approved when enumerated (so "attempted" already+ # counted it) but got revoked before its own turn. Both cases add to+ # "skipped_no_ai_consent" for reporting; only this one needs subtracting out of+ # "attempted" below, or it would double-subtract.+ "consent_revoked_after_attempt": 0,}counts_lock = threading.Lock()failure_streak = 0@@ -178,8 +200,12 @@ class Command(BaseCommand):counts["skipped_existing"] += 1returnif not ai_processing_approved(fetch.organization_id):+ # This fetch passed the enumeration-time check (or "attempted" wouldn't have+ # counted it) and got revoked between then and now - see+ # test_revoking_mid_run_is_honored_for_orgs_still_queued.with counts_lock:counts["skipped_no_ai_consent"] += 1+ counts["consent_revoked_after_attempt"] += 1returnsignup_domain = signup_domain_for_organization(fetch.organization)output = classify_payload(config, fetch.payload, signup_domain, client)@@ -266,6 +292,19 @@ class Command(BaseCommand):with counts_lock:counts["skipped_existing"] += 1continue+ # Checked here, before the limit, and again in _process at spend-time: a+ # declined org costs nothing, so it must not consume a --limit slot - --limit+ # is a spend bound. Checking only at spend-time (the old behavior) let more+ # than --limit declined orgs ordered ahead of an approved one exhaust the+ # whole run without a single verdict written, which a consent-filtered+ # candidate count downstream (see products/growth/dags/ai_enrichment.py) can't+ # tell apart from a real failure. The spend-time re-check stays for a+ # revocation landing after this point but before that fetch's own turn (see+ # test_revoking_mid_run_is_honored_for_orgs_still_queued).+ if not ai_processing_approved(fetch.organization_id):+ with counts_lock:+ counts["skipped_no_ai_consent"] += 1+ continueif limit is not None and counts["attempted"] >= limit:return# Not lock-guarded: this generator is only ever driven by one thread at a time@@ -294,9 +333,13 @@ class Command(BaseCommand):# succeeded/tried rather than a raw count: an alert can fire on the ratio, and on a run# that attempted nothing at all, which is what a silently broken input source looks like.# "tried" excludes aborted items so a circuit-broken run doesn't dilute the ratio with- # work that was queued but never actually attempted, and consent skips for the same- # reason: an archive of orgs that all declined is a correct empty run, not a failed one.- tried = counts["attempted"] - counts["aborted"] - counts["skipped_no_ai_consent"]+ # work that was queued but never actually attempted. Consent skips are excluded for the+ # same reason (an archive of orgs that all declined is a correct empty run, not a failed+ # one), but only "consent_revoked_after_attempt" needs subtracting here - a declined org+ # caught at enumeration time never incremented "attempted" to begin with (see+ # _attempt_targets), so subtracting the full skipped_no_ai_consent count here would+ # double-subtract and could push "tried" negative.+ tried = counts["attempted"] - counts["aborted"] - counts["consent_revoked_after_attempt"]success_rate = counts["succeeded"] / tried if tried else Noneelapsed_seconds = time.monotonic() - started_atsummary = (diff --git a/products/growth/backend/tests/test_enrichment_label_commands.py b/products/growth/backend/tests/test_enrichment_label_commands.pyindex 3f8bed716d13..6d9d73c21976 100644--- a/products/growth/backend/tests/test_enrichment_label_commands.py+++ b/products/growth/backend/tests/test_enrichment_label_commands.py@@ -351,6 +351,43 @@ class TestExitCodeAndSummary(_BatchCommandTestCase):call_command("enrichment_label_batch", label="test_label", limit=limit)+class TestExpectedVersionGuard(_BatchCommandTestCase):+ """--expected-version lets a caller that resolved the active version itself (the ai_enrichment+ dag) assert nothing changed it before spending - see ai_enrichment.py's module docstring."""++ def test_a_mismatched_expected_version_aborts_before_any_spend(self):+ self._config(version="v2")+ self._fetch()+ client = _mock_llm_client()++ with patch(f"{_BATCH_COMMAND_MODULE}.get_llm_client", return_value=client):+ with self.assertRaises(CommandError):+ call_command("enrichment_label_batch", label="test_label", workers=1, expected_version="v1")++ client.chat.completions.create.assert_not_called()+ assert EnrichmentLabelResult.objects.count() == 0++ def test_a_matching_expected_version_runs_normally(self):+ self._config(version="v2")+ self._fetch()+ client = _mock_llm_client()++ with patch(f"{_BATCH_COMMAND_MODULE}.get_llm_client", return_value=client):+ call_command("enrichment_label_batch", label="test_label", workers=1, expected_version="v2")++ assert EnrichmentLabelResult.objects.count() == 1++ def test_omitting_expected_version_is_unchanged_manual_cli_behavior(self):+ self._config()+ self._fetch()+ client = _mock_llm_client()++ with patch(f"{_BATCH_COMMAND_MODULE}.get_llm_client", return_value=client):+ call_command("enrichment_label_batch", label="test_label", workers=1)++ assert EnrichmentLabelResult.objects.count() == 1++class TestWorkerConnectionErrors(NonAtomicBaseTest):"""Non-atomic: worker threads get their own DB connections, matching the pattern inTestEnrichmentLabelBatchConcurrency (test_enrichment_labels.py) for the same reason."""@@ -505,6 +542,33 @@ class TestAiProcessingConsent(_BatchCommandTestCase):assert "skipped_no_ai_consent 1" in out.getvalue()+ def test_a_declined_org_ordered_before_an_approved_one_does_not_consume_the_limit(self):+ # Regression: --limit used to count a declined org as "attempted" the moment it was+ # enumerated, before the consent check (which only ran later, at spend-time inside+ # _process). A declined org costs nothing, so with --limit 1 and a declined org sorting+ # first by organization_id, the run used to exhaust its whole budget on that one free+ # skip and never even enumerate the approved org behind it - zero verdicts, yet the+ # command still exited 0 (tried == 0 skips the "every attempted org failed" check). A+ # consent-filtered candidate count downstream can't tell that apart from a real failure.+ self._config()+ org_x = Organization.objects.create(name="x")+ org_y = Organization.objects.create(name="y")+ declined_org, approved_org = sorted([org_x, org_y], key=lambda org: str(org.id))+ declined_org.is_ai_data_processing_approved = False+ declined_org.save(update_fields=["is_ai_data_processing_approved"])+ self._fetch(organization=declined_org)+ self._fetch(organization=approved_org)+ client = _mock_llm_client()+ out = StringIO()++ with patch(f"{_BATCH_COMMAND_MODULE}.get_llm_client", return_value=client):+ call_command("enrichment_label_batch", label="test_label", workers=1, limit=1, stdout=out)++ assert EnrichmentLabelResult.objects.filter(organization=approved_org).exists()+ assert "attempted 1" in out.getvalue()+ assert "skipped_no_ai_consent 1" in out.getvalue()+ assert "failures 0" in out.getvalue()+def test_the_dry_run_prints_a_skip_row_rather_than_an_error(self):self._config()self.organization.is_ai_data_processing_approved = Falsediff --git a/products/growth/backend/tests/test_enrichment_labels.py b/products/growth/backend/tests/test_enrichment_labels.pyindex 2673d8aabace..1ace10929798 100644--- a/products/growth/backend/tests/test_enrichment_labels.py+++ b/products/growth/backend/tests/test_enrichment_labels.py@@ -9,6 +9,7 @@ from django.core.management import call_commandfrom django.core.management.base import CommandErrorfrom django.test import SimpleTestCase+import openaifrom parameterized import parameterizedfrom posthog.models.organization import Organization, OrganizationMembership@@ -256,6 +257,83 @@ class TestConfigurableOutputFields(SimpleTestCase):assert classify_payload(config, {"company": "Acme"}, None, client)["flag"] is True+class TestCallAndParseRetryAllowlist(SimpleTestCase):+ """The retry predicate is an allowlist, not a blacklist: a transient failure (connection+ error, timeout, 429, 5xx) earns tenacity's 3 attempts; anything else — most importantly+ AuthenticationError, which used to retry 3x under the old not-OutputParseError blacklist and+ stack with the SDK's own retries on top — fails on the first attempt."""++ def _config(self) -> EnrichmentPromptConfig:+ return EnrichmentPromptConfig(+ name="test_label",+ version="test-v1",+ prompt_text="judge it.",+ model="gpt-5-mini",+ input_fields=["company"],+ output_fields=[{"key": "flag", "type": "boolean", "description": ""}],+ )++ @parameterized.expand(+ [+ ("connection_error", lambda: openai.APIConnectionError(request=MagicMock())),+ ("timeout_error", lambda: openai.APITimeoutError(request=MagicMock())),+ ("rate_limit", lambda: openai.RateLimitError(message="rate limited", response=MagicMock(), body={})),+ (+ "server_error",+ lambda: openai.InternalServerError(message="upstream boom", response=MagicMock(), body={}),+ ),+ ]+ )+ def test_transient_failures_are_retried_to_the_full_attempt_budget(self, _name, make_error):+ config = self._config()+ client = MagicMock()+ error = make_error()+ client.chat.completions.create.side_effect = error++ with patch("tenacity.nap.time.sleep"), self.assertRaises(type(error)):+ classify_payload(config, {"company": "Acme"}, None, client)++ assert client.chat.completions.create.call_count == 3++ @parameterized.expand(+ [+ (+ "authentication_error",+ lambda: openai.AuthenticationError(message="bad key", response=MagicMock(), body={}),+ ),+ ("bad_request", lambda: openai.BadRequestError(message="bad request", response=MagicMock(), body={})),+ ("permission_denied", lambda: openai.PermissionDeniedError(message="nope", response=MagicMock(), body={})),+ ("unrelated_bug", lambda: RuntimeError("unexpected")),+ ]+ )+ def test_non_transient_failures_are_not_retried(self, _name, make_error):+ config = self._config()+ client = MagicMock()+ error = make_error()+ client.chat.completions.create.side_effect = error++ with patch("tenacity.nap.time.sleep"), self.assertRaises(type(error)):+ classify_payload(config, {"company": "Acme"}, None, client)++ assert client.chat.completions.create.call_count == 1++ def test_a_transient_failure_that_then_succeeds_is_billed_for_exactly_two_calls(self):+ config = self._config()+ client = MagicMock()+ good_response = MagicMock()+ good_response.choices[0].message.content = json.dumps({"flag": True})+ client.chat.completions.create.side_effect = [+ openai.RateLimitError(message="rate limited", response=MagicMock(), body={}),+ good_response,+ ]++ with patch("tenacity.nap.time.sleep"):+ result = classify_payload(config, {"company": "Acme"}, None, client)++ assert result["flag"] is True+ assert client.chat.completions.create.call_count == 2++class TestEnrichmentLabelBatch(BaseTest):def _config(self, version: str = "ai-pilled-clay-v1", prompt_text: str = "... Email: {email}", is_active: bool = Truediff --git a/products/growth/dags/ai_enrichment.py b/products/growth/dags/ai_enrichment.pynew file mode 100644index 000000000000..c38a4ca2e38b--- /dev/null+++ b/products/growth/dags/ai_enrichment.py@@ -0,0 +1,216 @@+"""Daily Dagster job driving AI enrichment classification for every active label.++`products/growth/backend/management/commands/enrichment_label_batch.py` is the classifier+engine: candidate selection, the per-label advisory lock, the ThreadPoolExecutor worker pool,+the consecutive-failure circuit breaker, and the success-rate gate all live there. This file+only schedules it — one op per run wraps `call_command("enrichment_label_batch", ...)` once+for every label with an active `EnrichmentPromptConfig`, so the command stays the single+source of truth for how a label actually gets classified.++Concurrency: labels are classified in a plain sequential loop inside one op, not fanned out+via `DynamicOutput.map()`. At any instant at most one label's command is running, so total+in-flight LLM calls are bounded by that command's own `--workers` (the same bound a manual+`enrichment_label_batch` run has) — never the sum across labels. `ee/billing/dags/+customer_archetype.py`'s cross-batch semaphore exists because batches for the *same* asset+run concurrently under its executor; nothing here runs concurrently, so that machinery would+add a lock with nothing to protect.++Spend bound: `--limit` (this module's `DEFAULT_LABEL_LIMIT`) caps attempted orgs per label+per run — see the PR description for the worst-case dollar arithmetic behind the default.++Absence-of-output check: a run that finds pending candidates but persists zero verdicts is+indistinguishable, from the command's own exit code, from a quiet day with nothing to do — a+zero-output pass through a working gateway looks identical to one where every call to it is+silently swallowed. `check_enrichment_run_op` re-counts candidates and verdicts itself and+raises if that happened, so the failure reaches #alerts-growth instead of going unnoticed.++Version pinning: a label's active version is resolved fresh inside `_run_one_label`, right+before counting and calling the command — never once for every label at op start. The op runs+labels sequentially and can take hours; resolving all versions up front and carrying them+across the whole loop would let a version bump for a label further down the list silently+detach the candidate count (still keyed to the old version) from what the command actually+writes (under whatever version is live when its turn comes up) — a real run reads as+`candidates > 0, created == 0` and false-alerts. `--expected-version` closes the remaining gap+between resolving here and the command resolving again for itself: if the two disagree, the+command aborts loudly as a command failure instead of a confusing silent one.++Environment: sends organization signup data to an external LLM gateway, so — like+`identity_matching.py` — it is not registered on Cloud EU.+"""++from dataclasses import dataclass++from django.conf import settings+from django.core.management import call_command++import dagster+import pydantic++from posthog.dags.common import JobOwners, skip_if_already_running+from posthog.exceptions_capture import capture_exception++from products.growth.backend.enrichment.labels import get_active_config, latest_fetches_qs+from products.growth.backend.models import EnrichmentLabelResult, EnrichmentPromptConfig++# Roughly a day of signups plus headroom. This is the run's spend cap: see the PR description+# for the worst-case dollars-per-run arithmetic at this value.+DEFAULT_LABEL_LIMIT = 600++# Sequential across however many labels are active; generous relative to a single label's+# typical run so a slow gateway day doesn't trip it, but still short of Dagster run retention+# edge cases. ee/billing/dags/customer_archetype.py's weekly job (thousands of accounts) uses+# 12 hours; this job runs daily against a much smaller per-label cap, so a fraction of that+# is enough headroom.+MAX_RUNTIME_SECONDS = 6 * 60 * 60+++def is_ai_enrichment_registered() -> bool:+ return settings.CLOUD_DEPLOYMENT != "EU"+++class AiEnrichmentConfig(dagster.Config):+ limit: int = pydantic.Field(+ default=DEFAULT_LABEL_LIMIT,+ gt=0,+ description="Max orgs attempted per label per run — passed straight through to enrichment_label_batch --limit.",+ )+ workers: int = pydantic.Field(+ default=5,+ gt=0,+ description="Bounded concurrency for LLM calls within one label's run — passed through to --workers.",+ )+++@dataclass(frozen=True, kw_only=True)+class LabelRunResult:+ label: str+ # None only when the label was active when listed but had no active config left by the time+ # _run_one_label got to it (deactivated, not merely bumped) — candidates/created are 0 in+ # that case and the command's own CommandError carries the failure.+ prompt_version: str | None+ candidates: int+ created: int+ error: str | None+++def count_pending_candidates(label: str, prompt_version: str) -> int:+ """How many orgs the batch command would actually attempt for this label right now.++ Mirrors enrichment_label_batch's own targeting (latest fetch per org, minus one already+ holding a verdict under this exact label + prompt version) rather than importing its+ private `_attempt_targets` — that generator is a closure over the command's run-scoped+ counters and circuit breaker, not a reusable query. Also filters to AI-processing-approved+ orgs: the command enumerates a consent-declined org as "attempted" too, but never spends on+ it (see `ai_processing_approved` in enrichment/labels.py), so counting it here would make a+ day of nothing-but-declined-orgs look like a silent failure downstream.+ """+ latest_fetch_ids = latest_fetches_qs().values_list("id", flat=True)+ already_labeled = EnrichmentLabelResult.objects.filter(+ label_name=label, prompt_version=prompt_version, fetch_id__in=latest_fetch_ids+ ).values_list("fetch_id", flat=True)+ return (+ latest_fetches_qs()+ .exclude(id__in=already_labeled)+ .filter(organization__is_ai_data_processing_approved=True)+ .count()+ )+++def _run_one_label(context: dagster.OpExecutionContext, *, label: str, limit: int, workers: int) -> LabelRunResult:+ """Resolves the label's active version itself, right here — not from a snapshot taken once+ for every label at op start. See the module docstring for why that distinction matters."""+ config = get_active_config(label)+ prompt_version = config.version if config is not None else None++ candidates = count_pending_candidates(label, prompt_version) if prompt_version is not None else 0+ before = (+ EnrichmentLabelResult.objects.filter(label_name=label, prompt_version=prompt_version).count()+ if prompt_version is not None+ else 0+ )++ error: str | None = None+ try:+ # expected_version=None when we couldn't resolve one either — the command's own+ # "No active EnrichmentPromptConfig" error already covers that case.+ call_command(+ "enrichment_label_batch", label=label, limit=limit, workers=workers, expected_version=prompt_version+ )+ except Exception as e:+ error = str(e)+ context.log.warning(f"enrichment_label_batch failed for label {label!r}: {e}")+ capture_exception(e, {"label": label, "prompt_version": prompt_version})++ created = (+ EnrichmentLabelResult.objects.filter(label_name=label, prompt_version=prompt_version).count() - before+ if prompt_version is not None+ else 0+ )+ context.log.info(f"label {label!r} ({prompt_version}): {candidates} candidates, {created} verdicts created")+ return LabelRunResult(+ label=label, prompt_version=prompt_version, candidates=candidates, created=created, error=error+ )+++def classify_pending_organizations_op(+ context: dagster.OpExecutionContext, config: AiEnrichmentConfig+) -> list[LabelRunResult]:+ """Run enrichment_label_batch once per active label, sequentially. See the module+ docstring for why this stays a plain loop instead of a DynamicOutput fan-out."""+ active_label_names = list(EnrichmentPromptConfig.objects.filter(is_active=True).values_list("name", flat=True))+ if not active_label_names:+ context.log.info("No active EnrichmentPromptConfig rows; nothing to classify")+ return []++ results = [+ _run_one_label(context, label=label, limit=config.limit, workers=config.workers) for label in active_label_names+ ]++ context.add_output_metadata(+ {+ "labels_processed": dagster.MetadataValue.int(len(results)),+ "total_candidates": dagster.MetadataValue.int(sum(r.candidates for r in results)),+ "total_created": dagster.MetadataValue.int(sum(r.created for r in results)),+ }+ )+ return results+++def check_enrichment_run_op(context: dagster.OpExecutionContext, results: list[LabelRunResult]) -> None:+ """Fail the run — and with it the job, routing to #alerts-growth — on either a command+ failure or a label that had pending candidates but produced no verdicts at all. A run that+ merely succeeds while classifying nothing raises nothing on its own; this is what makes+ that case loud instead of silent."""+ command_failures = [r for r in results if r.error is not None]+ silent_failures = [r for r in results if r.error is None and r.candidates > 0 and r.created == 0]+ if not command_failures and not silent_failures:+ context.log.info(f"ai_enrichment run OK: {len(results)} label(s) processed")+ return++ problems = [f"{r.label}: command failed ({r.error})" for r in command_failures]+ problems += [f"{r.label}: {r.candidates} candidates but 0 verdicts created" for r in silent_failures]+ raise dagster.Failure("ai_enrichment run had problems: " + "; ".join(problems))+++ description="Daily job classifying pending organizations for every active AI enrichment label.",+ tags={"owner": JobOwners.TEAM_GROWTH.value, "dagster/max_runtime": str(MAX_RUNTIME_SECONDS)},+)+def ai_enrichment_job():+ check_enrichment_run_op(classify_pending_organizations_op())+++ job=ai_enrichment_job,+ cron_schedule="0 7 * * *",+ execution_timezone="UTC",+ default_status=dagster.DefaultScheduleStatus.STOPPED,+)+@skip_if_already_running+def ai_enrichment_schedule(context: dagster.ScheduleEvaluationContext):+ # Never stack runs: enrichment_label_batch's own per-label advisory lock already refuses a+ # second concurrent run of the same label, but skipping here avoids paying for the+ # candidate-counting queries on a run that would fail immediately anyway.+ return dagster.RunRequest()diff --git a/products/growth/dags/tests/test_ai_enrichment.py b/products/growth/dags/tests/test_ai_enrichment.pynew file mode 100644index 000000000000..af6d65302b61--- /dev/null+++ b/products/growth/dags/tests/test_ai_enrichment.py@@ -0,0 +1,286 @@+from typing import Any++import pytest+from posthog.test.base import BaseTest+from unittest.mock import patch++from django.core.management.base import CommandError++from parameterized import parameterized++from posthog.models.organization import Organization++from products.growth.backend.models import EnrichmentLabelResult, EnrichmentPromptConfig, OrganizationEnrichmentFetch+from products.growth.dags import ai_enrichment+from products.growth.dags.ai_enrichment import ai_enrichment_job, count_pending_candidates, is_ai_enrichment_registered++_MODULE = "products.growth.dags.ai_enrichment"++_OUTPUT_FIELDS = [{"key": "is_ai", "type": "boolean", "description": ""}]+++class _EnrichmentDagTestCase(BaseTest):+ def _config(self, **overrides: Any) -> EnrichmentPromptConfig:+ params: dict[str, Any] = {+ "name": "test_label",+ "version": "v1",+ "prompt_text": "... Email: {email}",+ "model": "gpt-5-mini",+ "input_fields": ["name"],+ "output_fields": _OUTPUT_FIELDS,+ "is_active": True,+ }+ params.update(overrides)+ return EnrichmentPromptConfig.objects.create(**params)++ def _fetch(self, organization: Organization | None = None) -> OrganizationEnrichmentFetch:+ return OrganizationEnrichmentFetch.objects.create(+ organization=organization or self.organization, provider="harmonic", payload={"name": "Acme"}+ )+++class TestCountPendingCandidates(_EnrichmentDagTestCase):+ def test_counts_a_fetch_with_no_verdict_yet(self):+ self._config()+ self._fetch()++ assert count_pending_candidates("test_label", "v1") == 1++ def test_excludes_a_fetch_already_labeled_under_this_exact_version(self):+ config = self._config()+ fetch = self._fetch()+ EnrichmentLabelResult.objects.create(+ organization=self.organization,+ fetch=fetch,+ label_name="test_label",+ prompt_version=config.version,+ prompt_hash="h",+ model="gpt-5-mini",+ )++ assert count_pending_candidates("test_label", config.version) == 0++ def test_a_verdict_under_a_retired_version_does_not_hide_the_candidate(self):+ # A rename or re-version leaves prior verdicts stamped with the old version - see+ # EnrichmentPromptConfig's docstring. The pending count must key off the exact+ # (label, active version) pair the caller is about to run, not just the label.+ fetch = self._fetch()+ EnrichmentLabelResult.objects.create(+ organization=self.organization,+ fetch=fetch,+ label_name="test_label",+ prompt_version="v0-retired",+ prompt_hash="h",+ model="gpt-5-mini",+ )++ assert count_pending_candidates("test_label", "v1") == 1++ def test_excludes_an_org_that_declined_ai_processing(self):+ self._config()+ self._fetch()+ Organization.objects.filter(id=self.organization.id).update(is_ai_data_processing_approved=False)++ assert count_pending_candidates("test_label", "v1") == 0++ def test_zero_when_there_is_nothing_pending(self):+ assert count_pending_candidates("test_label", "v1") == 0+++class TestAiEnrichmentJob(_EnrichmentDagTestCase):+ def test_calls_batch_command_once_per_active_label_with_the_configured_limit_and_workers(self):+ config_a = self._config(name="label_a")+ config_b = self._config(name="label_b")+ # No pending fetches for either label, so the absence-of-output check can't fire and+ # mask what this test is actually asserting.++ with patch(f"{_MODULE}.call_command") as mock_call_command:+ result = ai_enrichment_job.execute_in_process(+ run_config={"ops": {"classify_pending_organizations_op": {"config": {"limit": 42, "workers": 3}}}}+ )++ assert result.success+ calls_by_label = {call.kwargs["label"]: call for call in mock_call_command.call_args_list}+ assert calls_by_label.keys() == {"label_a", "label_b"}+ for call in calls_by_label.values():+ assert call.args == ("enrichment_label_batch",)+ assert call.kwargs["limit"] == 42+ assert call.kwargs["workers"] == 3+ # expected_version is each label's own currently-resolved version, passed through so the+ # command can abort if it disagrees - see test_a_version_bump_between_labels below.+ assert calls_by_label["label_a"].kwargs["expected_version"] == config_a.version+ assert calls_by_label["label_b"].kwargs["expected_version"] == config_b.version++ def test_a_version_bump_between_labels_does_not_false_alert(self):+ # Regression: resolving every label's version once at op start (rather than fresh,+ # immediately before that label's own turn in the sequential loop) let a bump for a+ # label further down the list detach the candidate count (still keyed to the old+ # version) from what the command actually wrote under - a real run read as+ # "candidates > 0, created == 0" and false-alerted. Order-independent: whichever label+ # is processed first bumps the *other*, not-yet-processed, label's version.+ self._config(name="label_a", version="v1")+ fetch_a = self._fetch()+ self._config(name="label_b", version="v1")+ org_b = Organization.objects.create(name="org-b")+ fetch_b = self._fetch(organization=org_b)+ fetches = {"label_a": fetch_a, "label_b": fetch_b}+ processed_order: list[str] = []++ def _fake_batch_run(_name: str, **kwargs: Any) -> None:+ label = kwargs["label"]+ processed_order.append(label)+ if len(processed_order) == 1:+ other = "label_b" if label == "label_a" else "label_a"+ EnrichmentPromptConfig.objects.filter(name=other, version="v1").update(is_active=False)+ EnrichmentPromptConfig.objects.create(+ name=other,+ version="v2",+ prompt_text="p",+ model="gpt-5-mini",+ input_fields=["name"],+ output_fields=_OUTPUT_FIELDS,+ is_active=True,+ )+ expected_version = "v1"+ else:+ expected_version = "v2"+ assert kwargs["expected_version"] == expected_version+ fetch = fetches[label]+ EnrichmentLabelResult.objects.create(+ organization=fetch.organization,+ fetch=fetch,+ label_name=label,+ prompt_version=expected_version,+ prompt_hash="h",+ model="gpt-5-mini",+ )++ with patch(f"{_MODULE}.call_command", side_effect=_fake_batch_run):+ result = ai_enrichment_job.execute_in_process()++ assert result.success+ assert EnrichmentLabelResult.objects.count() == 2++ def test_default_limit_matches_the_module_constant(self):+ self._config()++ with patch(f"{_MODULE}.call_command") as mock_call_command:+ result = ai_enrichment_job.execute_in_process()++ assert result.success+ assert mock_call_command.call_args.kwargs["limit"] == ai_enrichment.DEFAULT_LABEL_LIMIT++ def test_only_active_configs_are_classified(self):+ self._config(name="inactive_label", is_active=False)++ with patch(f"{_MODULE}.call_command") as mock_call_command:+ result = ai_enrichment_job.execute_in_process()++ assert result.success+ mock_call_command.assert_not_called()++ def test_no_active_labels_is_a_no_op_success(self):+ with patch(f"{_MODULE}.call_command") as mock_call_command:+ result = ai_enrichment_job.execute_in_process()++ assert result.success+ mock_call_command.assert_not_called()++ def test_raises_when_candidates_exist_but_the_command_creates_no_verdicts(self):+ # A run that finds pending orgs but persists nothing is exactly the silent-failure shape+ # this check exists to catch - the command's own exit code alone can't distinguish it+ # from a legitimately quiet day.+ self._config()+ self._fetch()++ with patch(f"{_MODULE}.call_command"), pytest.raises(Exception, match="candidates but 0 verdicts created"):+ ai_enrichment_job.execute_in_process()++ def test_does_not_raise_when_there_were_no_candidates_to_begin_with(self):+ self._config()++ with patch(f"{_MODULE}.call_command") as mock_call_command:+ result = ai_enrichment_job.execute_in_process()++ assert result.success+ mock_call_command.assert_called_once()++ def test_a_command_error_fails_the_job_and_is_captured(self):+ self._config()+ self._fetch()++ with (+ patch(f"{_MODULE}.call_command", side_effect=CommandError("aborted after 25 consecutive failures")),+ patch(f"{_MODULE}.capture_exception") as capture_mock,+ pytest.raises(Exception, match="command failed"),+ ):+ ai_enrichment_job.execute_in_process()++ capture_mock.assert_called_once()++ def test_succeeds_when_the_command_actually_creates_a_verdict(self):+ config = self._config()+ fetch = self._fetch()++ def _fake_batch_run(_name: str, **kwargs: Any) -> None:+ EnrichmentLabelResult.objects.create(+ organization=fetch.organization,+ fetch=fetch,+ label_name=config.name,+ prompt_version=config.version,+ prompt_hash="h",+ model="gpt-5-mini",+ )++ with patch(f"{_MODULE}.call_command", side_effect=_fake_batch_run):+ result = ai_enrichment_job.execute_in_process()++ assert result.success+ assert EnrichmentLabelResult.objects.count() == 1++ def test_one_labels_absence_failure_does_not_stop_another_label_from_running(self):+ self._config(name="silent_label")+ self._fetch()+ other_config = self._config(name="working_label")+ other_org = Organization.objects.create(name="other")+ other_fetch = self._fetch(organization=other_org)++ def _fake_batch_run(_name: str, **kwargs: Any) -> None:+ if kwargs["label"] == "working_label":+ EnrichmentLabelResult.objects.create(+ organization=other_org,+ fetch=other_fetch,+ label_name=other_config.name,+ prompt_version=other_config.version,+ prompt_hash="h",+ model="gpt-5-mini",+ )+ # silent_label's call does nothing, simulating the silent-failure shape.++ with (+ patch(f"{_MODULE}.call_command", side_effect=_fake_batch_run),+ pytest.raises(Exception, match="silent_label"),+ ):+ ai_enrichment_job.execute_in_process()++ # working_label still ran to completion despite silent_label's problem.+ assert EnrichmentLabelResult.objects.filter(label_name="working_label").count() == 1++ def test_job_has_owner_and_runtime_tags(self):+ tags = ai_enrichment_job.tags+ assert tags["owner"] == "team-growth"+ assert "dagster/max_runtime" in tags+++ [+ ("unset", None, True),+ ("local", "LOCAL", True),+ ("dev", "DEV", True),+ ("us", "US", True),+ ("eu", "EU", False),+ ]+)+def test_ai_enrichment_registered_per_environment(_name: str, cloud_deployment: str | None, registered: bool) -> None:+ with patch.object(ai_enrichment.settings, "CLOUD_DEPLOYMENT", cloud_deployment):+ assert is_ai_enrichment_registered() is registered