: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): re-score ICP fit when the wizard's AI-SDK stamp lands (#95195)
Matt Brookera72b30375250
diff --git a/posthog/settings/dynamic_settings.py b/posthog/settings/dynamic_settings.pyindex 8725f53b79db..fd39612a52a2 100644--- a/posthog/settings/dynamic_settings.py+++ b/posthog/settings/dynamic_settings.py@@ -281,6 +281,12 @@ CONSTANCE_CONFIG = {"Max organizations the daily ICP re-enrichment sweep re-fetches from Harmonic per run. The provider spend bound.",int,),+ "GROWTH_RESCORE_WEBHOOK_SECRET": (+ get_from_env("GROWTH_RESCORE_WEBHOOK_SECRET", default=""),+ "Shared secret the wizard-stamp ICP re-score webhook (products/growth/backend/presentation/views/rescore.py) "+ "checks against the X-PostHog-Webhook-Secret header. Set by the realtime destination that calls it.",+ str,+ ),"CLICKHOUSE_KILL_SWITCH": (get_from_env("CLICKHOUSE_KILL_SWITCH", "off"),"ClickHouse overload protection. Values: 'off', 'light' (reduce resources, shed background work), 'full' (aggressive caps on everything).",@@ -371,6 +377,7 @@ CONSTANCE_CONFIG = {SETTINGS_ALLOWING_API_OVERRIDE = ("GROWTH_SIGNUP_ENRICHMENT_ENABLED","GROWTH_ICP_REENRICH_DAILY_CAP",+ "GROWTH_RESCORE_WEBHOOK_SECRET","HOGQL_DEFERRED_REVENUE_VIEWS_ENABLED","HOGQL_SHARED_INSIGHT_DATABASE_ENABLED","RECORDINGS_PERFORMANCE_EVENTS_TTL_WEEKS",@@ -444,4 +451,5 @@ SECRET_SETTINGS = ["CONVERSATIONS_EMAIL_WEBHOOK_SIGNING_KEY","CONVERSATIONS_EMAIL_MAILGUN_API_KEY","GITHUB_WEBHOOK_SECRET",+ "GROWTH_RESCORE_WEBHOOK_SECRET",]diff --git a/products/growth/backend/facade/__init__.py b/products/growth/backend/facade/__init__.pynew file mode 100644index 000000000000..5fdbb5ef1e1a--- /dev/null+++ b/products/growth/backend/facade/__init__.py@@ -0,0 +1 @@+"""Facade boundary for the growth product."""diff --git a/products/growth/backend/facade/api.py b/products/growth/backend/facade/api.pynew file mode 100644index 000000000000..9f169d022ab9--- /dev/null+++ b/products/growth/backend/facade/api.py@@ -0,0 +1,38 @@+from typing import Literal++from posthog.dataclasses import frozen+from posthog.exceptions_capture import capture_exception+from posthog.models.instance_setting import get_instance_setting+from posthog.utils import get_instance_region++from products.growth.backend.models import OrganizationEnrichment+from products.growth.backend.temporal.signup_enrichment.trigger import dispatch_wizard_stamp_rescore++WizardStampRescoreSkipReason = Literal["disabled", "no_enrichment_record", "dispatch_backlog_full", "dispatch_failed"]+++@frozen+class WizardStampRescoreOutcome:+ queued: bool+ reason: WizardStampRescoreSkipReason | None = None+++def _rescore_enabled() -> bool:+ try:+ return bool(get_instance_setting("GROWTH_SIGNUP_ENRICHMENT_ENABLED"))+ except Exception as e:+ capture_exception(e)+ return False+++def request_wizard_stamp_rescore(organization_id: str) -> WizardStampRescoreOutcome:+ if not _rescore_enabled() or get_instance_region() not in ("US", "EU"):+ return WizardStampRescoreOutcome(queued=False, reason="disabled")++ if not OrganizationEnrichment.objects.filter(organization_id=organization_id).exists():+ return WizardStampRescoreOutcome(queued=False, reason="no_enrichment_record")++ failure = dispatch_wizard_stamp_rescore(organization_id)+ if failure is not None:+ return WizardStampRescoreOutcome(queued=False, reason=failure)+ return WizardStampRescoreOutcome(queued=True)diff --git a/products/growth/backend/presentation/__init__.py b/products/growth/backend/presentation/__init__.pynew file mode 100644index 000000000000..dc86af67fd0d--- /dev/null+++ b/products/growth/backend/presentation/__init__.py@@ -0,0 +1 @@+"""HTTP presentation layer of the growth product (DRF viewsets and serializers)."""diff --git a/products/growth/backend/presentation/views/__init__.py b/products/growth/backend/presentation/views/__init__.pynew file mode 100644index 000000000000..5a27aa3eef02--- /dev/null+++ b/products/growth/backend/presentation/views/__init__.py@@ -0,0 +1,3 @@+"""DRF viewsets for growth — submodule paths (`backend.presentation.views.*`) are part+of the shared tach interface for isolated products.+"""diff --git a/products/growth/backend/presentation/views/rescore.py b/products/growth/backend/presentation/views/rescore.pynew file mode 100644index 000000000000..1fe93c97c99a--- /dev/null+++ b/products/growth/backend/presentation/views/rescore.py@@ -0,0 +1,76 @@+"""Webhook for the wizard-stamp ICP re-score, called by a PostHog realtime destination the instant the setup wizard's AI-SDK stamp lands on an org.++Authenticated by a shared secret header instead of session or personal-API-key auth, since the caller is our own destination, not a user.+"""++import hmac++from drf_spectacular.utils import OpenApiResponse, extend_schema+from rest_framework import serializers, viewsets+from rest_framework.decorators import action+from rest_framework.request import Request+from rest_framework.response import Response++from posthog.api.utils import ErrorResponseSerializer+from posthog.models.instance_setting import get_instance_setting+from posthog.rate_limit import IPThrottle++from products.growth.backend.facade.api import request_wizard_stamp_rescore++WEBHOOK_SECRET_HEADER = "X-PostHog-Webhook-Secret"+++class GrowthRescoreWebhookThrottle(IPThrottle):+ """Bounds a misconfigured or runaway destination, on top of the shared-secret gate."""++ scope = "growth_rescore_webhook"+ rate = "300/minute"+++class RescoreRequestSerializer(serializers.Serializer):+ organization_id = serializers.UUIDField(+ help_text="Organization to re-score, from the $group_key of the wizard's $groupidentify event."+ )+++class RescoreResponseSerializer(serializers.Serializer):+ queued = serializers.BooleanField(help_text="Whether the re-score workflow was dispatched.")+ reason = serializers.ChoiceField(+ choices=["disabled", "no_enrichment_record", "dispatch_backlog_full", "dispatch_failed"],+ allow_null=True,+ help_text="Why nothing was dispatched. Null when queued.",+ )+++class GrowthEnrichmentViewSet(viewsets.ViewSet):+ authentication_classes = []+ permission_classes = []+ scope_object = "INTERNAL"++ @extend_schema(+ request=RescoreRequestSerializer,+ responses={+ 202: OpenApiResponse(response=RescoreResponseSerializer),+ 400: OpenApiResponse(response=ErrorResponseSerializer, description="Missing or invalid organization_id."),+ 401: OpenApiResponse(description="Missing or incorrect webhook secret."),+ 503: OpenApiResponse(description="No webhook secret is configured on this instance."),+ },+ summary="Re-score an organization's ICP fit after its wizard AI-SDK stamp lands.",+ description="Called by a PostHog realtime destination, not by API clients. Requires the "+ f"{WEBHOOK_SECRET_HEADER} header to match the GROWTH_RESCORE_WEBHOOK_SECRET instance setting.",+ )+ @action(methods=["POST"], detail=False, throttle_classes=[GrowthRescoreWebhookThrottle])+ def rescore(self, request: Request, **kwargs) -> Response:+ secret = get_instance_setting("GROWTH_RESCORE_WEBHOOK_SECRET")+ if not secret:+ return Response(status=503)+ # Django decodes headers as latin-1, and compare_digest rejects a non-ASCII str. The+ # secret is ASCII, so a header that is not cannot match.+ provided = request.headers.get(WEBHOOK_SECRET_HEADER, "")+ if not provided.isascii() or not hmac.compare_digest(secret, provided):+ return Response(status=401)++ serializer = RescoreRequestSerializer(data=request.data)+ serializer.is_valid(raise_exception=True)+ outcome = request_wizard_stamp_rescore(str(serializer.validated_data["organization_id"]))+ return Response(RescoreResponseSerializer(instance=outcome).data, status=202)diff --git a/products/growth/backend/routes.py b/products/growth/backend/routes.pyindex d8f860e3656e..15eb5638b3bc 100644--- a/products/growth/backend/routes.py+++ b/products/growth/backend/routes.py@@ -3,6 +3,7 @@ from posthog.api.routing import RouterRegistryfrom products.growth.backend.api.ai_enrichment import AIEnrichmentViewSetfrom products.growth.backend.api.identity_matching import IdentityMatchingLinkViewSetfrom products.growth.backend.api.product_push import ProductPushCampaignViewSet+from products.growth.backend.presentation.views.rescore import GrowthEnrichmentViewSetdef register_routes(routers: RouterRegistry) -> None:@@ -17,3 +18,5 @@ def register_routes(routers: RouterRegistry) -> None:)# Staff-only, unscoped: prompt configs are instance-global, not team/org scoped.routers.root.register(r"growth_ai_enrichment", AIEnrichmentViewSet, "growth_ai_enrichment")+ # Unauthenticated, unscoped: called by a realtime destination via shared-secret header.+ routers.root.register(r"growth_enrichment", GrowthEnrichmentViewSet, "growth_enrichment")diff --git a/products/growth/backend/temporal/signup_enrichment/__init__.py b/products/growth/backend/temporal/signup_enrichment/__init__.pyindex 658873da1fef..6849af19a317 100644--- a/products/growth/backend/temporal/signup_enrichment/__init__.py+++ b/products/growth/backend/temporal/signup_enrichment/__init__.py@@ -10,6 +10,10 @@ from products.growth.backend.temporal.signup_enrichment.reenrichment import (report_sweep_run_activity,select_reenrichment_candidates_activity,)+from products.growth.backend.temporal.signup_enrichment.rescore import (+ WizardStampRescoreWorkflow,+ resolve_wizard_rescore_signup_inputs_activity,+)from products.growth.backend.temporal.signup_enrichment.workflow import (SignupEnrichmentRecheckWorkflow,SignupEnrichmentWorkflow,@@ -21,6 +25,7 @@ WORKFLOWS = [SignupEnrichmentRecheckWorkflow,IcpReenrichmentSweepWorkflow,HarmonicEnrichmentStatusPollWorkflow,+ WizardStampRescoreWorkflow,]ACTIVITIES = [@@ -31,4 +36,5 @@ ACTIVITIES = [select_status_poll_candidates_activity,poll_status_batch_activity,report_status_poll_run_activity,+ resolve_wizard_rescore_signup_inputs_activity,]diff --git a/products/growth/backend/temporal/signup_enrichment/rescore.py b/products/growth/backend/temporal/signup_enrichment/rescore.pynew file mode 100644index 000000000000..7bbd92b01a58--- /dev/null+++ b/products/growth/backend/temporal/signup_enrichment/rescore.py@@ -0,0 +1,96 @@+"""Event-driven ICP re-score triggered when the setup wizard's AI-SDK stamp lands on an org's group properties.++Delegates to enrich_signup_organization_activity so scoring stays identical to the +4h recheck.+"""++import json+import typing+import datetime as dt+import dataclasses++from temporalio import activity, workflow+from temporalio.common import RetryPolicy++from posthog.temporal.common.base import PostHogWorkflow+from posthog.temporal.common.logger import get_logger+from posthog.temporal.common.utils import close_db_connections++from products.growth.backend.temporal.signup_enrichment.workflow import (+ ENRICH_ACTIVITY_TIMEOUT,+ MAX_ENRICH_ATTEMPTS,+ SignupEnrichmentInputs,+ enrich_signup_organization_activity,+)++LOGGER = get_logger(__name__)++RESOLVE_ACTIVITY_TIMEOUT = dt.timedelta(seconds=30)++# Lets the stamp's group-property write land before the recheck reads it.+STAMP_SETTLE_DELAY = dt.timedelta(seconds=60)++[email protected](frozen=True)+class WizardStampRescoreInputs:+ organization_id: str+++@close_db_connections+async def resolve_wizard_rescore_signup_inputs_activity(+ inputs: WizardStampRescoreInputs,+) -> typing.Optional[dict[str, typing.Any]]:+ """Resolves the signup identity through the shared gate, since the webhook body carries only the organization id."""+ from asgiref.sync import sync_to_async # noqa: PLC0415++ from products.growth.backend.enrichment.gates import SignupIdentity, resolve_signup_identity # noqa: PLC0415+ from products.growth.backend.models import OrganizationEnrichment # noqa: PLC0415++ logger = LOGGER.bind(organization_id=inputs.organization_id)++ def _resolve() -> typing.Optional[dict[str, typing.Any]]:+ identity = resolve_signup_identity(inputs.organization_id)+ if not isinstance(identity, SignupIdentity):+ logger.info("wizard_stamp_rescore_no_signup_identity", reason=identity.reason)+ return None++ record = OrganizationEnrichment.objects.filter(organization_id=inputs.organization_id).only("data").first()++ return {+ "organization_id": inputs.organization_id,+ "distinct_id": identity.distinct_id,+ "domain": identity.domain,+ "role_at_organization": record.data.get("signup_role") if record else None,+ }++ return await sync_to_async(_resolve)()++[email protected](name="wizard-stamp-rescore")+class WizardStampRescoreWorkflow(PostHogWorkflow):+ """Runs independently of SignupEnrichmentWorkflow's own +4h recheck: an org can get both, or only whichever fires first, since either one lands the same wizard-aware score."""++ @staticmethod+ def parse_inputs(inputs: list[str]) -> WizardStampRescoreInputs:+ return WizardStampRescoreInputs(**json.loads(inputs[0]))++ @workflow.run+ async def run(self, inputs: WizardStampRescoreInputs) -> dict[str, typing.Any]:+ await workflow.sleep(STAMP_SETTLE_DELAY)++ signup_inputs = await workflow.execute_activity(+ resolve_wizard_rescore_signup_inputs_activity,+ inputs,+ start_to_close_timeout=RESOLVE_ACTIVITY_TIMEOUT,+ retry_policy=RetryPolicy(maximum_attempts=3),+ )+ if signup_inputs is None:+ return {"matched": False, "skipped": "no_signup_identity"}++ # first_attempt_matched is pinned True because this trigger has no first attempt to compare against, keeping the recheck-only "upgraded" property from firing here.+ return await workflow.execute_activity(+ enrich_signup_organization_activity,+ args=[SignupEnrichmentInputs(**signup_inputs), True, True],+ start_to_close_timeout=ENRICH_ACTIVITY_TIMEOUT,+ retry_policy=RetryPolicy(maximum_attempts=MAX_ENRICH_ATTEMPTS, initial_interval=dt.timedelta(seconds=5)),+ )diff --git a/products/growth/backend/temporal/signup_enrichment/tests/test_rescore.py b/products/growth/backend/temporal/signup_enrichment/tests/test_rescore.pynew file mode 100644index 000000000000..b6164d6a602d--- /dev/null+++ b/products/growth/backend/temporal/signup_enrichment/tests/test_rescore.py@@ -0,0 +1,224 @@+import uuid+import datetime as dt++from posthog.test.base import BaseTest+from unittest.mock import AsyncMock, MagicMock, patch++from django.test import override_settings++from asgiref.sync import async_to_sync+from temporalio import activity+from temporalio.exceptions import WorkflowAlreadyStartedError+from temporalio.testing import WorkflowEnvironment+from temporalio.worker import UnsandboxedWorkflowRunner, Worker++from posthog.models.organization import Organization, OrganizationMembership+from posthog.models.user import User++from products.growth.backend.enrichment.core import EnrichmentOutcome+from products.growth.backend.enrichment.fields import EnrichmentFields+from products.growth.backend.enrichment.fit_score import IcpFitResult+from products.growth.backend.models import OrganizationEnrichment+from products.growth.backend.temporal.signup_enrichment.rescore import (+ WizardStampRescoreInputs,+ WizardStampRescoreWorkflow,+ resolve_wizard_rescore_signup_inputs_activity,+)+from products.growth.backend.temporal.signup_enrichment.trigger import dispatch_wizard_stamp_rescore+from products.growth.backend.temporal.signup_enrichment.workflow import enrich_signup_organization_activity++_TRIGGER_MODULE = "products.growth.backend.temporal.signup_enrichment.trigger"+_WORKFLOW_MODULE = "products.growth.backend.temporal.signup_enrichment.workflow"+++class TestResolveWizardRescoreSignupInputs(BaseTest):+ def _resolve(self, organization_id: str) -> dict | None:+ return async_to_sync(resolve_wizard_rescore_signup_inputs_activity)(+ WizardStampRescoreInputs(organization_id=organization_id)+ )++ def test_resolves_identity_and_role_from_the_earliest_member(self):+ organization = Organization.objects.create(name="wizard.example")+ user = User.objects.create_user(email="[email protected]", password=None, first_name="f")+ OrganizationMembership.objects.create(organization=organization, user=user)+ OrganizationEnrichment.objects.create(organization=organization, data={"signup_role": "engineering"})++ result = self._resolve(str(organization.id))++ assert result == {+ "organization_id": str(organization.id),+ "distinct_id": user.distinct_id,+ "domain": "wizard.example",+ "role_at_organization": "engineering",+ }++ def test_role_is_none_without_a_recorded_signup_role(self):+ organization = Organization.objects.create(name="norole.example")+ user = User.objects.create_user(email="[email protected]", password=None, first_name="f")+ OrganizationMembership.objects.create(organization=organization, user=user)++ result = self._resolve(str(organization.id))++ assert result is not None+ assert result["role_at_organization"] is None++ def test_returns_none_when_the_organization_has_no_member(self):+ organization = Organization.objects.create(name="ghost.example")++ assert self._resolve(str(organization.id)) is None++ def test_returns_none_when_the_signup_user_left(self):+ organization = Organization.objects.create(name="left.example")+ user = User.objects.create_user(email="[email protected]", password=None, first_name="f")+ membership = OrganizationMembership.objects.create(organization=organization, user=user)+ OrganizationMembership.objects.filter(pk=membership.pk).update(+ joined_at=organization.created_at + dt.timedelta(hours=1)+ )++ assert self._resolve(str(organization.id)) is None++ def test_returns_none_for_a_generic_email_domain(self):+ organization = Organization.objects.create(name="personal.example")+ user = User.objects.create_user(email="[email protected]", password=None, first_name="f")+ OrganizationMembership.objects.create(organization=organization, user=user)++ assert self._resolve(str(organization.id)) is None+++_TASK_QUEUE = "wizard-stamp-rescore-test-queue"+_SIGNUP_INPUTS_DICT = {+ "organization_id": "org-1",+ "distinct_id": "d1",+ "domain": "stripe.com",+ "role_at_organization": "engineering",+}+++async def _run_workflow(resolved_inputs, enrich_side_effect=None):+ @activity.defn(name=resolve_wizard_rescore_signup_inputs_activity.__name__)+ async def _fake_resolve(_inputs: WizardStampRescoreInputs) -> dict | None:+ return resolved_inputs++ enrich = AsyncMock(+ side_effect=enrich_side_effect+ or [+ EnrichmentOutcome(+ provider_fields=EnrichmentFields(company_type="STARTUP"), fit=IcpFitResult(status="scored", score=61)+ )+ ]+ )+ pha_client = MagicMock()+ with (+ patch(f"{_WORKFLOW_MODULE}.get_regional_ph_client", return_value=pha_client),+ patch(f"{_WORKFLOW_MODULE}.enrich_organization", enrich),+ patch(f"{_WORKFLOW_MODULE}._deterministic_company_type", return_value=None),+ patch("posthog.models.Organization.objects") as org_objects,+ ):+ org_objects.filter.return_value.exists.return_value = True+ async with await WorkflowEnvironment.start_time_skipping() as env:+ async with Worker(+ env.client,+ task_queue=_TASK_QUEUE,+ workflows=[WizardStampRescoreWorkflow],+ activities=[_fake_resolve, enrich_signup_organization_activity],+ workflow_runner=UnsandboxedWorkflowRunner(),+ ):+ result = await env.client.execute_workflow(+ WizardStampRescoreWorkflow.run,+ WizardStampRescoreInputs(organization_id="org-1"),+ id=f"wizard-stamp-rescore-{uuid.uuid4()}",+ task_queue=_TASK_QUEUE,+ )+ return result, enrich, pha_client+++async def test_rescores_with_the_resolved_identity_after_the_settle_delay():+ result, enrich, _ = await _run_workflow(_SIGNUP_INPUTS_DICT)++ assert result == {"matched": True, "fields_filled": 1}+ enrich.assert_awaited_once()+ assert enrich.await_args.kwargs["ctx"].is_recheck is True+ assert enrich.await_args.kwargs["ctx"].role_at_organization == "engineering"+ assert enrich.await_args.kwargs["ctx"].domain == "stripe.com"+++async def test_skips_the_enrich_activity_when_no_signup_identity_resolves():+ result, enrich, _ = await _run_workflow(None)++ assert result == {"matched": False, "skipped": "no_signup_identity"}+ enrich.assert_not_awaited()+++async def test_first_attempt_matched_is_pinned_true_so_upgraded_never_fires():+ outcome = EnrichmentOutcome(+ provider_fields=EnrichmentFields(company_type="STARTUP"), fit=IcpFitResult(status="scored", score=61)+ )+ _, _, pha_client = await _run_workflow(_SIGNUP_INPUTS_DICT, enrich_side_effect=[outcome])++ recheck_events = [c for c in pha_client.capture.call_args_list if c.kwargs["event"] == "signup_enrichment_recheck"]+ assert len(recheck_events) == 1+ assert recheck_events[0].kwargs["properties"]["upgraded"] is False+++class TestDispatchWizardStampRescore:+ class _InlineExecutor:+ def submit(self, fn, *args):+ fn(*args)++ def setup_method(self):+ self._executor_patch = patch(f"{_TRIGGER_MODULE}._dispatch_executor", self._InlineExecutor())+ self._executor_patch.start()++ def teardown_method(self):+ self._executor_patch.stop()++ def _dispatch_mocks(self):+ return (+ patch(f"{_TRIGGER_MODULE}.sync_connect"),+ patch(f"{_TRIGGER_MODULE}.asyncio.run"),+ )++ @override_settings(SIGNUP_ENRICHMENT_TASK_QUEUE="signup-enrichment-test-queue")+ def test_starts_the_workflow_with_the_dedupe_id_and_task_queue(self):+ connect, run = self._dispatch_mocks()+ with connect as connect_mock, run:+ dispatch_wizard_stamp_rescore("org-1")++ connect_mock.assert_called_once()+ args, kwargs = connect_mock.return_value.start_workflow.call_args+ assert args[0] == "wizard-stamp-rescore"+ assert args[1] == WizardStampRescoreInputs(organization_id="org-1")+ assert kwargs["id"] == "wizard-stamp-rescore-org-1"+ assert kwargs["task_queue"] == "signup-enrichment-test-queue"++ def test_already_running_workflow_is_a_no_op_not_an_error(self):+ connect, run = self._dispatch_mocks()+ with connect, run as run_mock:+ run_mock.side_effect = WorkflowAlreadyStartedError("wizard-stamp-rescore-org-1", "wizard-stamp-rescore")+ with patch(f"{_TRIGGER_MODULE}.capture_exception") as capture_mock:+ dispatch_wizard_stamp_rescore("org-1") # must not raise++ capture_mock.assert_not_called()++ def test_dispatch_dropped_when_backlog_full(self):+ import threading++ full = threading.BoundedSemaphore(1)+ full.acquire()+ connect, run = self._dispatch_mocks()+ with patch(f"{_TRIGGER_MODULE}._dispatch_slots", full):+ with connect as connect_mock, run:+ assert dispatch_wizard_stamp_rescore("org-1") == "dispatch_backlog_full"+ connect_mock.assert_not_called()++ def test_a_rejected_submission_is_reported_separately_from_a_full_backlog(self):+ class _RejectingExecutor:+ def submit(self, fn, *args):+ raise RuntimeError("executor is shut down")++ connect, run = self._dispatch_mocks()+ with patch(f"{_TRIGGER_MODULE}._dispatch_executor", _RejectingExecutor()):+ with patch(f"{_TRIGGER_MODULE}.capture_exception"):+ with connect as connect_mock, run:+ assert dispatch_wizard_stamp_rescore("org-1") == "dispatch_failed"+ connect_mock.assert_not_called()diff --git a/products/growth/backend/temporal/signup_enrichment/trigger.py b/products/growth/backend/temporal/signup_enrichment/trigger.pyindex d92f5c4a6568..f06fb3050cca 100644--- a/products/growth/backend/temporal/signup_enrichment/trigger.py+++ b/products/growth/backend/temporal/signup_enrichment/trigger.py@@ -10,6 +10,7 @@ for every signup so consumers can read it either way.import asyncioimport threadingfrom concurrent.futures import ThreadPoolExecutor+from typing import Literalfrom django.conf import settingsfrom django.db import transaction@@ -26,10 +27,13 @@ from posthog.utils import GenericEmailsfrom products.growth.backend.enrichment import gatesfrom products.growth.backend.enrichment.writer import record_signup_work_email+from products.growth.backend.temporal.signup_enrichment.rescore import WizardStampRescoreInputsfrom products.growth.backend.temporal.signup_enrichment.workflow import SignupEnrichmentInputslogger = structlog.get_logger(__name__)+RescoreDispatchFailure = Literal["dispatch_backlog_full", "dispatch_failed"]+_generic_emails = GenericEmails()# Bounded dispatch pool: a slow or unreachable Temporal must never let signup-triggered@@ -87,6 +91,56 @@ def start_signup_enrichment_workflow(transaction.on_commit(lambda: _submit_dispatch(inputs))+def dispatch_wizard_stamp_rescore(organization_id: str) -> RescoreDispatchFailure | None:+ """Shares the bounded dispatch pool with signup dispatch so an unreachable Temporal can't pile up threads on the web pod, same as it does for signups. Returns None once the run is submitted, otherwise why it was not."""+ return _submit_rescore_dispatch(organization_id)+++def _submit_rescore_dispatch(organization_id: str) -> RescoreDispatchFailure | None:+ if not _dispatch_slots.acquire(blocking=False):+ logger.warning(+ "wizard_stamp_rescore_dispatch_dropped", organization_id=organization_id, reason="dispatch_backlog_full"+ )+ return "dispatch_backlog_full"+ try:+ _dispatch_executor.submit(_rescore_dispatch_and_release, organization_id)+ except Exception as e:+ _dispatch_slots.release()+ capture_exception(e)+ return "dispatch_failed"+ return None+++def _rescore_dispatch_and_release(organization_id: str) -> None:+ try:+ _rescore_dispatch(organization_id)+ finally:+ _dispatch_slots.release()+++def _rescore_dispatch(organization_id: str) -> None:+ try:+ client = sync_connect()+ asyncio.run(+ client.start_workflow(+ "wizard-stamp-rescore",+ WizardStampRescoreInputs(organization_id=organization_id),+ id=f"wizard-stamp-rescore-{organization_id}",+ task_queue=settings.SIGNUP_ENRICHMENT_TASK_QUEUE,+ id_reuse_policy=WorkflowIDReusePolicy.ALLOW_DUPLICATE,+ )+ )+ except WorkflowAlreadyStartedError:+ # A stamp landing while the previous run is still in flight hits the same workflow id and is dropped, collapsing near-simultaneous stamps into one run.+ logger.info("wizard_stamp_rescore_dispatch_skipped", organization_id=organization_id)+ except RPCError as e:+ logger.info("wizard_stamp_rescore_dispatch_skipped", organization_id=organization_id, error=str(e))+ except Exception as e:+ capture_exception(e)+ else:+ logger.info("wizard_stamp_rescore_dispatch_started", organization_id=organization_id)++def dispatch_signup_enrichment(inputs: SignupEnrichmentInputs) -> None:"""Synchronous dispatch for operational re-runs (management commands).diff --git a/products/growth/backend/tests/test_rescore_api.py b/products/growth/backend/tests/test_rescore_api.pynew file mode 100644index 000000000000..36f2f1e38367--- /dev/null+++ b/products/growth/backend/tests/test_rescore_api.py@@ -0,0 +1,124 @@+import uuid++from posthog.test.base import APIBaseTest+from unittest.mock import patch++from parameterized import parameterized++from posthog.models.instance_setting import override_instance_config++from products.growth.backend.models import OrganizationEnrichment++_URL = "/api/growth_enrichment/rescore/"+_SECRET = "wh_secret_test_value"+_MODULE = "products.growth.backend.facade.api"+++class TestGrowthEnrichmentRescoreAPI(APIBaseTest):+ def setUp(self):+ super().setUp()+ self.enterContext(override_instance_config("GROWTH_RESCORE_WEBHOOK_SECRET", _SECRET))+ self.enterContext(override_instance_config("GROWTH_SIGNUP_ENRICHMENT_ENABLED", True))+ self.enterContext(patch(f"{_MODULE}.get_instance_region", return_value="US"))++ def _post(self, organization_id: str | None, secret: str | None = _SECRET):+ body = {} if organization_id is None else {"organization_id": organization_id}+ if secret is None:+ return self.client.post(_URL, body, format="json")+ return self.client.post(_URL, body, format="json", HTTP_X_POSTHOG_WEBHOOK_SECRET=secret)++ def test_missing_secret_returns_401_and_dispatches_nothing(self):+ with patch(f"{_MODULE}.dispatch_wizard_stamp_rescore") as dispatch_mock:+ response = self._post(str(self.organization.id), secret=None)++ assert response.status_code == 401+ dispatch_mock.assert_not_called()++ @parameterized.expand([("plain", "not-the-secret"), ("non_ascii", "not-the-secret\u00ff")])+ def test_wrong_secret_returns_401_and_dispatches_nothing(self, _name, secret):+ with patch(f"{_MODULE}.dispatch_wizard_stamp_rescore") as dispatch_mock:+ response = self._post(str(self.organization.id), secret=secret)++ assert response.status_code == 401+ dispatch_mock.assert_not_called()++ def test_unconfigured_secret_returns_503(self):+ with override_instance_config("GROWTH_RESCORE_WEBHOOK_SECRET", ""):+ with patch(f"{_MODULE}.dispatch_wizard_stamp_rescore") as dispatch_mock:+ response = self._post(str(self.organization.id))++ assert response.status_code == 503+ dispatch_mock.assert_not_called()++ def test_missing_organization_id_returns_400(self):+ response = self._post(None)++ assert response.status_code == 400++ def test_non_uuid_organization_id_returns_400(self):+ response = self._post("not-a-uuid")++ assert response.status_code == 400++ def test_kill_switch_off_returns_queued_false_disabled(self):+ OrganizationEnrichment.objects.create(organization=self.organization)+ with override_instance_config("GROWTH_SIGNUP_ENRICHMENT_ENABLED", False):+ with patch(f"{_MODULE}.dispatch_wizard_stamp_rescore") as dispatch_mock:+ response = self._post(str(self.organization.id))++ assert response.status_code == 202+ assert response.json() == {"queued": False, "reason": "disabled"}+ dispatch_mock.assert_not_called()++ def test_self_hosted_region_returns_queued_false_disabled(self):+ OrganizationEnrichment.objects.create(organization=self.organization)+ with patch(f"{_MODULE}.get_instance_region", return_value="DEV"):+ with patch(f"{_MODULE}.dispatch_wizard_stamp_rescore") as dispatch_mock:+ response = self._post(str(self.organization.id))++ assert response.status_code == 202+ assert response.json() == {"queued": False, "reason": "disabled"}+ dispatch_mock.assert_not_called()++ def test_no_enrichment_record_returns_queued_false(self):+ assert not OrganizationEnrichment.objects.filter(organization=self.organization).exists()+ with patch(f"{_MODULE}.dispatch_wizard_stamp_rescore") as dispatch_mock:+ response = self._post(str(self.organization.id))++ assert response.status_code == 202+ assert response.json() == {"queued": False, "reason": "no_enrichment_record"}+ dispatch_mock.assert_not_called()++ def test_valid_request_dispatches_and_returns_queued_true(self):+ OrganizationEnrichment.objects.create(organization=self.organization)+ with patch(f"{_MODULE}.dispatch_wizard_stamp_rescore", return_value=None) as dispatch_mock:+ response = self._post(str(self.organization.id))++ assert response.status_code == 202+ assert response.json() == {"queued": True, "reason": None}+ dispatch_mock.assert_called_once_with(str(self.organization.id))++ def test_full_dispatch_pool_returns_queued_false(self):+ OrganizationEnrichment.objects.create(organization=self.organization)+ with patch(f"{_MODULE}.dispatch_wizard_stamp_rescore", return_value="dispatch_backlog_full") as dispatch_mock:+ response = self._post(str(self.organization.id))++ assert response.status_code == 202+ assert response.json() == {"queued": False, "reason": "dispatch_backlog_full"}+ dispatch_mock.assert_called_once_with(str(self.organization.id))++ def test_failed_dispatch_submission_returns_queued_false(self):+ OrganizationEnrichment.objects.create(organization=self.organization)+ with patch(f"{_MODULE}.dispatch_wizard_stamp_rescore", return_value="dispatch_failed"):+ response = self._post(str(self.organization.id))++ assert response.status_code == 202+ assert response.json() == {"queued": False, "reason": "dispatch_failed"}++ def test_unknown_organization_id_returns_no_enrichment_record(self):+ with patch(f"{_MODULE}.dispatch_wizard_stamp_rescore") as dispatch_mock:+ response = self._post(str(uuid.uuid4()))++ assert response.status_code == 202+ assert response.json() == {"queued": False, "reason": "no_enrichment_record"}+ dispatch_mock.assert_not_called()diff --git a/products/growth/frontend/generated/api.schemas.ts b/products/growth/frontend/generated/api.schemas.tsindex ee79a518a576..fd9db57ca4bf 100644--- a/products/growth/frontend/generated/api.schemas.ts+++ b/products/growth/frontend/generated/api.schemas.ts@@ -164,6 +164,39 @@ export interface SaveRequestApi {output_fields: OutputFieldApi[]}+export interface RescoreRequestApi {+ /** Organization to re-score, from the $group_key of the wizard's $groupidentify event. */+ organization_id: string+}++/**+ * * `disabled` - disabled+ * * `no_enrichment_record` - no_enrichment_record+ * * `dispatch_backlog_full` - dispatch_backlog_full+ * * `dispatch_failed` - dispatch_failed+ */+export type RescoreResponseReasonEnumApi =+ (typeof RescoreResponseReasonEnumApi)[keyof typeof RescoreResponseReasonEnumApi]++export const RescoreResponseReasonEnumApi = {+ Disabled: 'disabled',+ NoEnrichmentRecord: 'no_enrichment_record',+ DispatchBacklogFull: 'dispatch_backlog_full',+ DispatchFailed: 'dispatch_failed',+} as const++export interface RescoreResponseApi {+ /** Whether the re-score workflow was dispatched. */+ queued: boolean+ /** Why nothing was dispatched. Null when queued.+ *+ * * `disabled` - disabled+ * * `no_enrichment_record` - no_enrichment_record+ * * `dispatch_backlog_full` - dispatch_backlog_full+ * * `dispatch_failed` - dispatch_failed */+ reason: RescoreResponseReasonEnumApi | null+}+export interface ProductPushCampaignApi {/** Campaign id. Stable for the campaign's lifetime — key per-user dismissal state on it. */readonly id: stringdiff --git a/products/growth/frontend/generated/api.ts b/products/growth/frontend/generated/api.tsindex 64cbc0089f8d..23f9023bff33 100644--- a/products/growth/frontend/generated/api.ts+++ b/products/growth/frontend/generated/api.ts@@ -21,6 +21,8 @@ import type {LabelListResponseApi,ProductPushCampaignActiveRetrieveParams,ProductPushCampaignApi,+ RescoreRequestApi,+ RescoreResponseApi,RunRequestApi,SaveRequestApi,SdkHealthReportApi,@@ -180,6 +182,26 @@ export const growthAiEnrichmentSaveCreate = async (})}+export const getGrowthEnrichmentRescoreCreateUrl = () => {+ return `/api/growth_enrichment/rescore/`+}++/**+ * Called by a PostHog realtime destination, not by API clients. Requires the X-PostHog-Webhook-Secret header to match the GROWTH_RESCORE_WEBHOOK_SECRET instance setting.+ * @summary Re-score an organization's ICP fit after its wizard AI-SDK stamp lands.+ */+export const growthEnrichmentRescoreCreate = async (+ rescoreRequestApi: RescoreRequestApi,+ options?: RequestInit+): Promise<RescoreResponseApi> => {+ return apiMutator<RescoreResponseApi>(getGrowthEnrichmentRescoreCreateUrl(), {+ ...options,+ method: 'POST',+ headers: { 'Content-Type': 'application/json', ...options?.headers },+ body: JSON.stringify(rescoreRequestApi),+ })+}+export const getProductPushCampaignActiveRetrieveUrl = (organizationId: string,params?: ProductPushCampaignActiveRetrieveParamsdiff --git a/products/growth/frontend/generated/api.zod.ts b/products/growth/frontend/generated/api.zod.tsindex e656ba7c5e8c..f0cb368aecc7 100644--- a/products/growth/frontend/generated/api.zod.ts+++ b/products/growth/frontend/generated/api.zod.ts@@ -174,3 +174,13 @@ export const GrowthAiEnrichmentSaveCreateBody = /* @__PURE__ */ zod.object({"Output schema: list of {key, type, description}. type is 'boolean', 'number', or 'string'. This is the classifier's entire output contract - the label is a human name and is never an output key, so renaming a label changes nothing about what a version computes. Keys must match ^[a-z][a-z0-9_]\*$, be unique, and not be 'meta' or 'inputs'. At most 20 fields."),})++/**+ * Called by a PostHog realtime destination, not by API clients. Requires the X-PostHog-Webhook-Secret header to match the GROWTH_RESCORE_WEBHOOK_SECRET instance setting.+ * @summary Re-score an organization's ICP fit after its wizard AI-SDK stamp lands.+ */+export const GrowthEnrichmentRescoreCreateBody = /* @__PURE__ */ zod.object({+ organization_id: zod+ .uuid()+ .describe("Organization to re-score, from the $group_key of the wizard's $groupidentify event."),+})diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.tsindex fdade5e4d6e8..a27962ac193e 100644--- a/services/mcp/src/api/generated.ts+++ b/services/mcp/src/api/generated.ts@@ -79355,6 +79355,39 @@ export namespace Schemas {scan?: ScanEvidence;}+ export interface RescoreRequest {+ /** Organization to re-score, from the $group_key of the wizard's $groupidentify event. */+ organization_id: string;+ }++ /**+ * * `disabled` - disabled+ * * `no_enrichment_record` - no_enrichment_record+ * * `dispatch_backlog_full` - dispatch_backlog_full+ * * `dispatch_failed` - dispatch_failed+ */+ export type RescoreResponseReasonEnum = typeof RescoreResponseReasonEnum[keyof typeof RescoreResponseReasonEnum];+++ export const RescoreResponseReasonEnum = {+ Disabled: 'disabled',+ NoEnrichmentRecord: 'no_enrichment_record',+ DispatchBacklogFull: 'dispatch_backlog_full',+ DispatchFailed: 'dispatch_failed',+ } as const;++ export interface RescoreResponse {+ /** Whether the re-score workflow was dispatched. */+ queued: boolean;+ /** Why nothing was dispatched. Null when queued.+ *+ * * `disabled` - disabled+ * * `no_enrichment_record` - no_enrichment_record+ * * `dispatch_backlog_full` - dispatch_backlog_full+ * * `dispatch_failed` - dispatch_failed */+ reason: RescoreResponseReasonEnum | null;+ }+export interface ResetPasswordResponse {username: string;password: string;