Skip to content

:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.

refactor(growth): run the enrichment recheck in its own workflow (#100322)

Matt Brooker5b486880b676
diff --git a/products/growth/backend/temporal/signup_enrichment/__init__.py b/products/growth/backend/temporal/signup_enrichment/__init__.py
index 919ee3f06538..658873da1fef 100644
--- a/products/growth/backend/temporal/signup_enrichment/__init__.py
+++ b/products/growth/backend/temporal/signup_enrichment/__init__.py
@@ -11,11 +11,17 @@ from products.growth.backend.temporal.signup_enrichment.reenrichment import (
select_reenrichment_candidates_activity,
)
from products.growth.backend.temporal.signup_enrichment.workflow import (
+ SignupEnrichmentRecheckWorkflow,
SignupEnrichmentWorkflow,
enrich_signup_organization_activity,
)
-WORKFLOWS = [SignupEnrichmentWorkflow, IcpReenrichmentSweepWorkflow, HarmonicEnrichmentStatusPollWorkflow]
+WORKFLOWS = [
+ SignupEnrichmentWorkflow,
+ SignupEnrichmentRecheckWorkflow,
+ IcpReenrichmentSweepWorkflow,
+ HarmonicEnrichmentStatusPollWorkflow,
+]
ACTIVITIES = [
enrich_signup_organization_activity,
diff --git a/products/growth/backend/temporal/signup_enrichment/tests/signup_enrichment_pre_recheck_child_history.json b/products/growth/backend/temporal/signup_enrichment/tests/signup_enrichment_pre_recheck_child_history.json
new file mode 100644
index 000000000000..5b6e089ac8c3
--- /dev/null
+++ b/products/growth/backend/temporal/signup_enrichment/tests/signup_enrichment_pre_recheck_child_history.json
@@ -0,0 +1,373 @@
+{
+ "events": [
+ {
+ "eventId": "1",
+ "eventTime": "2026-09-14T13:13:32.883Z",
+ "eventType": "EVENT_TYPE_WORKFLOW_EXECUTION_STARTED",
+ "workflowExecutionStartedEventAttributes": {
+ "workflowType": {
+ "name": "signup-enrichment"
+ },
+ "taskQueue": {
+ "name": "signup-enrichment-replay-fixture"
+ },
+ "input": {
+ "payloads": [
+ {
+ "metadata": {
+ "encoding": "anNvbi9wbGFpbg=="
+ },
+ "data": "eyJkaXN0aW5jdF9pZCI6ImQxIiwiZG9tYWluIjoic3RyaXBlLmNvbSIsImdlb2lwX2NvdW50cnlfY29kZSI6bnVsbCwib3JnYW5pemF0aW9uX2lkIjoib3JnLTEiLCJyb2xlX2F0X29yZ2FuaXphdGlvbiI6bnVsbH0="
+ }
+ ]
+ },
+ "workflowExecutionTimeout": "315360000s",
+ "workflowRunTimeout": "315360000s",
+ "workflowTaskTimeout": "10s",
+ "originalExecutionRunId": "7288506c-1456-4c3c-8c8c-48efb2a06502",
+ "identity": "replay-fixture",
+ "firstExecutionRunId": "7288506c-1456-4c3c-8c8c-48efb2a06502",
+ "attempt": 1,
+ "firstWorkflowTaskBackoff": "0s",
+ "priority": {}
+ }
+ },
+ {
+ "eventId": "2",
+ "eventTime": "2026-09-14T13:13:32.883Z",
+ "eventType": "EVENT_TYPE_WORKFLOW_TASK_SCHEDULED",
+ "workflowTaskScheduledEventAttributes": {
+ "taskQueue": {
+ "name": "signup-enrichment-replay-fixture"
+ },
+ "startToCloseTimeout": "10s",
+ "attempt": 1
+ }
+ },
+ {
+ "eventId": "3",
+ "eventTime": "2026-09-14T13:13:32.884Z",
+ "eventType": "EVENT_TYPE_WORKFLOW_TASK_STARTED",
+ "workflowTaskStartedEventAttributes": {
+ "scheduledEventId": "2",
+ "identity": "replay-fixture",
+ "historySizeBytes": "449"
+ }
+ },
+ {
+ "eventId": "4",
+ "eventTime": "2026-09-14T13:13:32.899Z",
+ "eventType": "EVENT_TYPE_WORKFLOW_TASK_COMPLETED",
+ "workflowTaskCompletedEventAttributes": {
+ "scheduledEventId": "2",
+ "identity": "replay-fixture",
+ "binaryChecksum": "91e100948e480e0d64f712d2808dc815",
+ "sdkMetadata": {
+ "coreUsedFlags": [2, 1, 3],
+ "sdkName": "temporal-python",
+ "sdkVersion": "1.24.0"
+ },
+ "meteringMetadata": {}
+ }
+ },
+ {
+ "eventId": "5",
+ "eventTime": "2026-09-14T13:13:32.899Z",
+ "eventType": "EVENT_TYPE_ACTIVITY_TASK_SCHEDULED",
+ "activityTaskScheduledEventAttributes": {
+ "activityId": "1",
+ "activityType": {
+ "name": "enrich_signup_organization_activity"
+ },
+ "taskQueue": {
+ "name": "signup-enrichment-replay-fixture",
+ "kind": "TASK_QUEUE_KIND_NORMAL"
+ },
+ "header": {},
+ "input": {
+ "payloads": [
+ {
+ "metadata": {
+ "encoding": "anNvbi9wbGFpbg=="
+ },
+ "data": "eyJkaXN0aW5jdF9pZCI6ImQxIiwiZG9tYWluIjoic3RyaXBlLmNvbSIsImdlb2lwX2NvdW50cnlfY29kZSI6bnVsbCwib3JnYW5pemF0aW9uX2lkIjoib3JnLTEiLCJyb2xlX2F0X29yZ2FuaXphdGlvbiI6bnVsbH0="
+ },
+ {
+ "metadata": {
+ "encoding": "anNvbi9wbGFpbg=="
+ },
+ "data": "ZmFsc2U="
+ },
+ {
+ "metadata": {
+ "encoding": "anNvbi9wbGFpbg=="
+ },
+ "data": "ZmFsc2U="
+ }
+ ]
+ },
+ "scheduleToCloseTimeout": "315360000s",
+ "scheduleToStartTimeout": "315360000s",
+ "startToCloseTimeout": "90s",
+ "heartbeatTimeout": "0s",
+ "workflowTaskCompletedEventId": "3",
+ "retryPolicy": {
+ "initialInterval": "5s",
+ "backoffCoefficient": 2.0,
+ "maximumInterval": "500s",
+ "maximumAttempts": 3
+ },
+ "priority": {}
+ }
+ },
+ {
+ "eventId": "6",
+ "eventTime": "2026-09-14T13:13:32.899Z",
+ "eventType": "EVENT_TYPE_ACTIVITY_TASK_STARTED",
+ "activityTaskStartedEventAttributes": {
+ "scheduledEventId": "5",
+ "identity": "replay-fixture",
+ "attempt": 1
+ }
+ },
+ {
+ "eventId": "7",
+ "eventTime": "2026-09-14T13:13:32.902Z",
+ "eventType": "EVENT_TYPE_ACTIVITY_TASK_COMPLETED",
+ "activityTaskCompletedEventAttributes": {
+ "result": {
+ "payloads": [
+ {
+ "metadata": {
+ "encoding": "anNvbi9wbGFpbg=="
+ },
+ "data": "eyJmaWVsZHNfZmlsbGVkIjowLCJtYXRjaGVkIjpmYWxzZX0="
+ }
+ ]
+ },
+ "scheduledEventId": "5",
+ "startedEventId": "6",
+ "identity": "replay-fixture"
+ }
+ },
+ {
+ "eventId": "8",
+ "eventTime": "2026-09-14T13:13:32.902Z",
+ "eventType": "EVENT_TYPE_WORKFLOW_TASK_SCHEDULED",
+ "workflowTaskScheduledEventAttributes": {
+ "taskQueue": {
+ "name": "signup-enrichment-replay-fixture"
+ },
+ "startToCloseTimeout": "10s",
+ "attempt": 1
+ }
+ },
+ {
+ "eventId": "9",
+ "eventTime": "2026-09-14T13:13:32.902Z",
+ "eventType": "EVENT_TYPE_WORKFLOW_TASK_STARTED",
+ "workflowTaskStartedEventAttributes": {
+ "scheduledEventId": "8",
+ "identity": "replay-fixture",
+ "historySizeBytes": "1176"
+ }
+ },
+ {
+ "eventId": "10",
+ "eventTime": "2026-09-14T13:13:32.904Z",
+ "eventType": "EVENT_TYPE_WORKFLOW_TASK_COMPLETED",
+ "workflowTaskCompletedEventAttributes": {
+ "scheduledEventId": "8",
+ "identity": "replay-fixture",
+ "binaryChecksum": "91e100948e480e0d64f712d2808dc815",
+ "sdkMetadata": {},
+ "meteringMetadata": {}
+ }
+ },
+ {
+ "eventId": "11",
+ "eventTime": "2026-09-14T13:13:32.904Z",
+ "eventType": "EVENT_TYPE_TIMER_STARTED",
+ "timerStartedEventAttributes": {
+ "timerId": "1",
+ "startToFireTimeout": "14400s",
+ "workflowTaskCompletedEventId": "9"
+ }
+ },
+ {
+ "eventId": "12",
+ "eventTime": "2026-09-14T17:13:32.904Z",
+ "eventType": "EVENT_TYPE_TIMER_FIRED",
+ "timerFiredEventAttributes": {
+ "timerId": "1",
+ "startedEventId": "11"
+ }
+ },
+ {
+ "eventId": "13",
+ "eventTime": "2026-09-14T17:13:32.904Z",
+ "eventType": "EVENT_TYPE_WORKFLOW_TASK_SCHEDULED",
+ "workflowTaskScheduledEventAttributes": {
+ "taskQueue": {
+ "name": "signup-enrichment-replay-fixture"
+ },
+ "startToCloseTimeout": "10s",
+ "attempt": 1
+ }
+ },
+ {
+ "eventId": "14",
+ "eventTime": "2026-09-14T17:13:32.904Z",
+ "eventType": "EVENT_TYPE_WORKFLOW_TASK_STARTED",
+ "workflowTaskStartedEventAttributes": {
+ "scheduledEventId": "13",
+ "identity": "replay-fixture",
+ "historySizeBytes": "1412"
+ }
+ },
+ {
+ "eventId": "15",
+ "eventTime": "2026-09-14T17:13:32.904Z",
+ "eventType": "EVENT_TYPE_WORKFLOW_TASK_COMPLETED",
+ "workflowTaskCompletedEventAttributes": {
+ "scheduledEventId": "13",
+ "identity": "replay-fixture",
+ "binaryChecksum": "91e100948e480e0d64f712d2808dc815",
+ "sdkMetadata": {},
+ "meteringMetadata": {}
+ }
+ },
+ {
+ "eventId": "16",
+ "eventTime": "2026-09-14T17:13:32.904Z",
+ "eventType": "EVENT_TYPE_ACTIVITY_TASK_SCHEDULED",
+ "activityTaskScheduledEventAttributes": {
+ "activityId": "2",
+ "activityType": {
+ "name": "enrich_signup_organization_activity"
+ },
+ "taskQueue": {
+ "name": "signup-enrichment-replay-fixture",
+ "kind": "TASK_QUEUE_KIND_NORMAL"
+ },
+ "header": {},
+ "input": {
+ "payloads": [
+ {
+ "metadata": {
+ "encoding": "anNvbi9wbGFpbg=="
+ },
+ "data": "eyJkaXN0aW5jdF9pZCI6ImQxIiwiZG9tYWluIjoic3RyaXBlLmNvbSIsImdlb2lwX2NvdW50cnlfY29kZSI6bnVsbCwib3JnYW5pemF0aW9uX2lkIjoib3JnLTEiLCJyb2xlX2F0X29yZ2FuaXphdGlvbiI6bnVsbH0="
+ },
+ {
+ "metadata": {
+ "encoding": "anNvbi9wbGFpbg=="
+ },
+ "data": "dHJ1ZQ=="
+ },
+ {
+ "metadata": {
+ "encoding": "anNvbi9wbGFpbg=="
+ },
+ "data": "ZmFsc2U="
+ }
+ ]
+ },
+ "scheduleToCloseTimeout": "315360000s",
+ "scheduleToStartTimeout": "315360000s",
+ "startToCloseTimeout": "90s",
+ "heartbeatTimeout": "0s",
+ "workflowTaskCompletedEventId": "14",
+ "retryPolicy": {
+ "initialInterval": "5s",
+ "backoffCoefficient": 2.0,
+ "maximumInterval": "500s",
+ "maximumAttempts": 3
+ },
+ "priority": {}
+ }
+ },
+ {
+ "eventId": "17",
+ "eventTime": "2026-09-14T17:13:32.904Z",
+ "eventType": "EVENT_TYPE_ACTIVITY_TASK_STARTED",
+ "activityTaskStartedEventAttributes": {
+ "scheduledEventId": "16",
+ "identity": "replay-fixture",
+ "attempt": 1
+ }
+ },
+ {
+ "eventId": "18",
+ "eventTime": "2026-09-14T17:13:32.905Z",
+ "eventType": "EVENT_TYPE_ACTIVITY_TASK_COMPLETED",
+ "activityTaskCompletedEventAttributes": {
+ "result": {
+ "payloads": [
+ {
+ "metadata": {
+ "encoding": "anNvbi9wbGFpbg=="
+ },
+ "data": "eyJmaWVsZHNfZmlsbGVkIjozLCJtYXRjaGVkIjp0cnVlfQ=="
+ }
+ ]
+ },
+ "scheduledEventId": "16",
+ "startedEventId": "17",
+ "identity": "replay-fixture"
+ }
+ },
+ {
+ "eventId": "19",
+ "eventTime": "2026-09-14T17:13:32.905Z",
+ "eventType": "EVENT_TYPE_WORKFLOW_TASK_SCHEDULED",
+ "workflowTaskScheduledEventAttributes": {
+ "taskQueue": {
+ "name": "signup-enrichment-replay-fixture"
+ },
+ "startToCloseTimeout": "10s",
+ "attempt": 1
+ }
+ },
+ {
+ "eventId": "20",
+ "eventTime": "2026-09-14T17:13:32.905Z",
+ "eventType": "EVENT_TYPE_WORKFLOW_TASK_STARTED",
+ "workflowTaskStartedEventAttributes": {
+ "scheduledEventId": "19",
+ "identity": "replay-fixture",
+ "historySizeBytes": "2107"
+ }
+ },
+ {
+ "eventId": "21",
+ "eventTime": "2026-09-14T17:13:32.906Z",
+ "eventType": "EVENT_TYPE_WORKFLOW_TASK_COMPLETED",
+ "workflowTaskCompletedEventAttributes": {
+ "scheduledEventId": "19",
+ "identity": "replay-fixture",
+ "binaryChecksum": "91e100948e480e0d64f712d2808dc815",
+ "sdkMetadata": {},
+ "meteringMetadata": {}
+ }
+ },
+ {
+ "eventId": "22",
+ "eventTime": "2026-09-14T17:13:32.906Z",
+ "eventType": "EVENT_TYPE_WORKFLOW_EXECUTION_COMPLETED",
+ "workflowExecutionCompletedEventAttributes": {
+ "result": {
+ "payloads": [
+ {
+ "metadata": {
+ "encoding": "anNvbi9wbGFpbg=="
+ },
+ "data": "eyJmaWVsZHNfZmlsbGVkIjozLCJtYXRjaGVkIjp0cnVlfQ=="
+ }
+ ]
+ },
+ "workflowTaskCompletedEventId": "20"
+ }
+ }
+ ]
+}
diff --git a/products/growth/backend/temporal/signup_enrichment/tests/test_workflow.py b/products/growth/backend/temporal/signup_enrichment/tests/test_workflow.py
index 9a3d9750abbc..8e4861b99b58 100644
--- a/products/growth/backend/temporal/signup_enrichment/tests/test_workflow.py
+++ b/products/growth/backend/temporal/signup_enrichment/tests/test_workflow.py
@@ -1,17 +1,24 @@
import uuid
+import asyncio
import datetime as dt
+from pathlib import Path
import pytest
from unittest.mock import AsyncMock, MagicMock, patch
+from temporalio.api.enums.v1 import EventType
+from temporalio.client import WorkflowExecutionStatus, WorkflowHistory
from temporalio.testing import WorkflowEnvironment
-from temporalio.worker import UnsandboxedWorkflowRunner, Worker
+from temporalio.worker import Replayer, UnsandboxedWorkflowRunner, Worker
+
+from posthog.dataclasses import frozen
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.temporal.signup_enrichment.workflow import (
SignupEnrichmentInputs,
+ SignupEnrichmentRecheckWorkflow,
SignupEnrichmentWorkflow,
enrich_signup_organization_activity,
)
@@ -22,13 +29,33 @@ _MODULE = "products.growth.backend.temporal.signup_enrichment.workflow"
_INPUTS = SignupEnrichmentInputs(organization_id="org-1", distinct_id="d1", domain="stripe.com")
_TASK_QUEUE = "signup-enrichment-test-queue"
_EVALUATED_AT = dt.datetime(2026, 9, 14, 12, 0, tzinfo=dt.UTC)
+_RECHECK_ID = f"signup-enrichment-recheck-{_INPUTS.organization_id}"
+_TEST_RECHECK_DELAY = dt.timedelta(milliseconds=100)
+# An execution that took the un-patched path, where the recheck is a timer and a second activity
+# in this same workflow, recorded against a mocked activity.
+_PRE_CHILD_HISTORY = Path(__file__).parent / "signup_enrichment_pre_recheck_child_history.json"
+
+
+@frozen
+class _EnrichmentRun:
+ parent_result: dict
+ recheck_result: dict
+ parent_history: WorkflowHistory
+ recheck_history: WorkflowHistory
+ pha_client: MagicMock
+ enrich: AsyncMock
+ snapshot: MagicMock
def _events(pha_client: MagicMock, name: str) -> list:
return [c for c in pha_client.capture.call_args_list if c.kwargs["event"] == name]
-async def _run(enrich_side_effect) -> tuple[dict, MagicMock, AsyncMock, MagicMock]:
+def _event_types(history: WorkflowHistory) -> list[int]:
+ return [event.event_type for event in history.events]
+
+
+async def _run(enrich_side_effect) -> _EnrichmentRun:
pha_client = MagicMock()
enrich = AsyncMock(side_effect=enrich_side_effect)
with (
@@ -36,6 +63,9 @@ async def _run(enrich_side_effect) -> tuple[dict, MagicMock, AsyncMock, MagicMoc
patch(f"{_MODULE}.enrich_organization", enrich),
patch(f"{_MODULE}._deterministic_company_type", return_value=None),
patch(f"{_MODULE}.capture_signup_enrichment_snapshot") as snapshot,
+ # A handle from get_workflow_handle never unlocks the time-skipping clock, so the child
+ # has to reach its activity on a delay that elapses in real time.
+ patch(f"{_MODULE}.RECHECK_DELAY", _TEST_RECHECK_DELAY),
patch("posthog.models.Organization.objects") as org_objects,
):
org_objects.filter.return_value.exists.return_value = True
@@ -43,17 +73,30 @@ async def _run(enrich_side_effect) -> tuple[dict, MagicMock, AsyncMock, MagicMoc
async with Worker(
env.client,
task_queue=_TASK_QUEUE,
- workflows=[SignupEnrichmentWorkflow],
+ workflows=[SignupEnrichmentWorkflow, SignupEnrichmentRecheckWorkflow],
activities=[enrich_signup_organization_activity],
workflow_runner=UnsandboxedWorkflowRunner(),
):
- result = await env.client.execute_workflow(
+ parent = await env.client.start_workflow(
SignupEnrichmentWorkflow.run,
_INPUTS,
id=f"signup-enrichment-{uuid.uuid4()}",
task_queue=_TASK_QUEUE,
)
- return result, pha_client, enrich, snapshot
+ parent_result = await parent.result()
+ recheck = env.client.get_workflow_handle(_RECHECK_ID)
+ recheck_result = await recheck.result()
+ parent_history = await parent.fetch_history()
+ recheck_history = await recheck.fetch_history()
+ return _EnrichmentRun(
+ parent_result=parent_result,
+ recheck_result=recheck_result,
+ parent_history=parent_history,
+ recheck_history=recheck_history,
+ pha_client=pha_client,
+ enrich=enrich,
+ snapshot=snapshot,
+ )
async def test_miss_then_recheck_upgrades_without_a_second_completed_event():
@@ -65,17 +108,35 @@ async def test_miss_then_recheck_upgrades_without_a_second_completed_event():
fit_evaluated_at=_EVALUATED_AT,
enrichment_status="COMPLETE",
)
- result, pha_client, enrich, snapshot = await _run([miss, match])
+ run = await _run([miss, match])
- assert result == {"matched": True, "fields_filled": 3}
- assert enrich.await_count == 2
+ assert run.parent_result == {"matched": False, "fields_filled": 0}
+ assert run.recheck_result == {"matched": True, "fields_filled": 3}
+ assert run.enrich.await_count == 2
# The is_recheck label is threaded through to the enrichment core: False first, True on recheck.
- assert enrich.await_args_list[0].kwargs["ctx"].is_recheck is False
- assert enrich.await_args_list[1].kwargs["ctx"].is_recheck is True
+ assert run.enrich.await_args_list[0].kwargs["ctx"].is_recheck is False
+ assert run.enrich.await_args_list[1].kwargs["ctx"].is_recheck is True
# is_recheck=True skips the at-signup snapshot, so it is captured only on the first attempt.
- snapshot.assert_called_once()
+ run.snapshot.assert_called_once()
+
+ parent_types = _event_types(run.parent_history)
+ # A timer in the parent's own history is what keeps every signup execution in flight for the
+ # whole delay, so a deploy that edits the parent replays all of them.
+ assert EventType.EVENT_TYPE_TIMER_STARTED not in parent_types
+ assert parent_types.count(EventType.EVENT_TYPE_ACTIVITY_TASK_SCHEDULED) == 1
+ assert EventType.EVENT_TYPE_START_CHILD_WORKFLOW_EXECUTION_INITIATED in parent_types
+
+ recheck_types = _event_types(run.recheck_history)
+ assert recheck_types.index(EventType.EVENT_TYPE_TIMER_STARTED) < recheck_types.index(
+ EventType.EVENT_TYPE_ACTIVITY_TASK_SCHEDULED
+ )
+ assert [
+ event.timer_started_event_attributes.start_to_fire_timeout.ToTimedelta()
+ for event in run.recheck_history.events
+ if event.event_type == EventType.EVENT_TYPE_TIMER_STARTED
+ ] == [_TEST_RECHECK_DELAY]
- recheck = _events(pha_client, "signup_enrichment_recheck")
+ recheck = _events(run.pha_client, "signup_enrichment_recheck")
assert len(recheck) == 1
assert recheck[0].kwargs["properties"] == {
"upgraded": True,
@@ -86,30 +147,71 @@ async def test_miss_then_recheck_upgrades_without_a_second_completed_event():
"icp_fit_evaluation_kind": "recheck",
"harmonic_enrichment_status": "COMPLETE",
}
- # The launch signal fires exactly once — on the first attempt, unchanged.
- completed = _events(pha_client, "signup_enrichment_completed")
+ # The launch signal fires exactly once, on the first attempt, unchanged.
+ completed = _events(run.pha_client, "signup_enrichment_completed")
assert len(completed) == 1
assert completed[0].kwargs["properties"]["matched"] is False
assert completed[0].kwargs["properties"]["icp_fit_status"] == "not_found"
async def test_match_on_first_attempt_still_runs_the_recheck():
- """The recheck now runs for every org, matched or not — it also re-scores against Clay's
- bridge columns, which may not have landed yet at the first attempt."""
fields = EnrichmentFields(company_type="STARTUP", headcount=130)
match = EnrichmentOutcome(provider_fields=fields, fit=IcpFitResult(status="scored", score=61))
- result, pha_client, enrich, snapshot = await _run([match, match])
+ run = await _run([match, match])
- assert result == {"matched": True, "fields_filled": 2}
- assert enrich.await_count == 2
- assert enrich.await_args_list[1].kwargs["ctx"].is_recheck is True
- snapshot.assert_called_once()
+ assert run.parent_result == {"matched": True, "fields_filled": 2}
+ assert run.recheck_result == {"matched": True, "fields_filled": 2}
+ assert run.enrich.await_count == 2
+ assert run.enrich.await_args_list[1].kwargs["ctx"].is_recheck is True
+ run.snapshot.assert_called_once()
- # Already matched at the first attempt, so matching again at recheck is not an upgrade.
- recheck = _events(pha_client, "signup_enrichment_recheck")
+ # Already matched at the first attempt, so matching again at recheck is not an upgrade. The
+ # child can only tell because the parent passed its own outcome down.
+ recheck = _events(run.pha_client, "signup_enrichment_recheck")
assert len(recheck) == 1
assert recheck[0].kwargs["properties"]["upgraded"] is False
- assert len(_events(pha_client, "signup_enrichment_completed")) == 1
+ assert len(_events(run.pha_client, "signup_enrichment_completed")) == 1
+
+
+async def test_a_second_signup_dispatch_keeps_its_first_leg_while_a_recheck_is_pending():
+ fields = EnrichmentFields(company_type="STARTUP", headcount=130)
+ match = EnrichmentOutcome(provider_fields=fields, fit=IcpFitResult(status="scored", score=61))
+ enrich = AsyncMock(side_effect=[match, match])
+ with (
+ patch(f"{_MODULE}.get_regional_ph_client", return_value=MagicMock()),
+ patch(f"{_MODULE}.enrich_organization", enrich),
+ patch(f"{_MODULE}._deterministic_company_type", return_value=None),
+ patch(f"{_MODULE}.capture_signup_enrichment_snapshot"),
+ 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=[SignupEnrichmentWorkflow, SignupEnrichmentRecheckWorkflow],
+ activities=[enrich_signup_organization_activity],
+ workflow_runner=UnsandboxedWorkflowRunner(),
+ ):
+ # Skipped time would retire the first recheck child before the second dispatch
+ # reaches its own child start, which is the collision under test.
+ with env.auto_time_skipping_disabled():
+ results = []
+ for _ in range(2):
+ parent = await env.client.start_workflow(
+ SignupEnrichmentWorkflow.run,
+ _INPUTS,
+ id=f"signup-enrichment-{uuid.uuid4()}",
+ task_queue=_TASK_QUEUE,
+ )
+ results.append(await parent.result())
+ second_types = _event_types(await parent.fetch_history())
+ recheck_status = (await env.client.get_workflow_handle(_RECHECK_ID).describe()).status
+
+ assert results == [{"matched": True, "fields_filled": 2}, {"matched": True, "fields_filled": 2}]
+ assert EventType.EVENT_TYPE_START_CHILD_WORKFLOW_EXECUTION_FAILED in second_types
+ assert recheck_status == WorkflowExecutionStatus.RUNNING
+ assert enrich.await_count == 2
async def test_recheck_skips_deleted_organization():
@@ -128,3 +230,14 @@ async def test_recheck_skips_deleted_organization():
assert result["matched"] is False
enrich_mock.assert_not_called()
client_mock.assert_not_called()
+
+
+async def test_history_recorded_before_the_recheck_child_still_replays():
+ history = WorkflowHistory.from_json(
+ "signup-enrichment-org-1", await asyncio.to_thread(_PRE_CHILD_HISTORY.read_text)
+ )
+
+ await Replayer(
+ workflows=[SignupEnrichmentWorkflow, SignupEnrichmentRecheckWorkflow],
+ workflow_runner=UnsandboxedWorkflowRunner(),
+ ).replay_workflow(history)
diff --git a/products/growth/backend/temporal/signup_enrichment/workflow.py b/products/growth/backend/temporal/signup_enrichment/workflow.py
index 2d5471cdcb62..441f30f84956 100644
--- a/products/growth/backend/temporal/signup_enrichment/workflow.py
+++ b/products/growth/backend/temporal/signup_enrichment/workflow.py
@@ -12,8 +12,10 @@ import datetime as dt
import dataclasses
from temporalio import activity, workflow
-from temporalio.common import RetryPolicy
+from temporalio.common import RetryPolicy, WorkflowIDReusePolicy
+from temporalio.exceptions import WorkflowAlreadyStartedError
+from posthog.dataclasses import frozen
from posthog.exceptions_capture import capture_exception
from posthog.ph_client import get_regional_ph_client
from posthog.temporal.common.base import PostHogWorkflow
@@ -198,6 +200,45 @@ async def enrich_signup_organization_activity(
pha_client.shutdown()
+async def _execute_enrich_activity(
+ inputs: SignupEnrichmentInputs, *, is_recheck: bool, first_attempt_matched: bool = False
+) -> dict[str, typing.Any]:
+ return await workflow.execute_activity(
+ enrich_signup_organization_activity,
+ args=[inputs, is_recheck, first_attempt_matched],
+ start_to_close_timeout=ENRICH_ACTIVITY_TIMEOUT,
+ # Onboarding routing already degrades to a safe default when enrichment is absent.
+ retry_policy=RetryPolicy(maximum_attempts=MAX_ENRICH_ATTEMPTS, initial_interval=dt.timedelta(seconds=5)),
+ )
+
+
+@frozen
+class SignupEnrichmentRecheckInputs:
+ signup: SignupEnrichmentInputs
+ first_attempt_matched: bool = False
+
+
[email protected](name="signup-enrichment-recheck")
+class SignupEnrichmentRecheckWorkflow(PostHogWorkflow):
+ @staticmethod
+ def parse_inputs(inputs: list[str]) -> SignupEnrichmentRecheckInputs:
+ loaded = json.loads(inputs[0])
+ return SignupEnrichmentRecheckInputs(
+ signup=SignupEnrichmentInputs(**loaded["signup"]),
+ first_attempt_matched=loaded.get("first_attempt_matched", False),
+ )
+
+ @workflow.run
+ async def run(self, inputs: SignupEnrichmentRecheckInputs) -> dict[str, typing.Any]:
+ # Unconditional: give Harmonic's seeded async enrichment time to index the company, and
+ # Clay's bridge columns time to land, then look/score once more for every org, matched
+ # or not on the first pass.
+ await workflow.sleep(RECHECK_DELAY)
+ return await _execute_enrich_activity(
+ inputs.signup, is_recheck=True, first_attempt_matched=inputs.first_attempt_matched
+ )
+
+
@workflow.defn(name="signup-enrichment")
class SignupEnrichmentWorkflow(PostHogWorkflow):
"""Fire-and-forget enrichment for one organization, started right after signup."""
@@ -208,21 +249,22 @@ class SignupEnrichmentWorkflow(PostHogWorkflow):
@workflow.run
async def run(self, inputs: SignupEnrichmentInputs) -> dict[str, typing.Any]:
- first_result = await self._enrich(inputs, is_recheck=False)
+ first_result = await _execute_enrich_activity(inputs, is_recheck=False)
+ first_attempt_matched = bool(first_result.get("matched"))
- # Unconditional: give Harmonic's seeded async enrichment time to index the company, and
- # Clay's bridge columns time to land, then look/score once more — for every org, matched
- # or not on the first pass.
+ if workflow.patched("signup-enrichment-recheck-child-2026-09"):
+ try:
+ await workflow.start_child_workflow(
+ SignupEnrichmentRecheckWorkflow.run,
+ SignupEnrichmentRecheckInputs(signup=inputs, first_attempt_matched=first_attempt_matched),
+ id=f"signup-enrichment-recheck-{inputs.organization_id}",
+ parent_close_policy=workflow.ParentClosePolicy.ABANDON,
+ id_reuse_policy=WorkflowIDReusePolicy.ALLOW_DUPLICATE,
+ )
+ except WorkflowAlreadyStartedError:
+ LOGGER.bind(organization_id=inputs.organization_id).info("signup_enrichment_recheck_already_pending")
+ return first_result
+
+ # Executions recorded before the recheck child existed replay through this path.
await workflow.sleep(RECHECK_DELAY)
- return await self._enrich(inputs, is_recheck=True, first_attempt_matched=bool(first_result.get("matched")))
-
- async def _enrich(
- self, inputs: SignupEnrichmentInputs, *, is_recheck: bool, first_attempt_matched: bool = False
- ) -> dict[str, typing.Any]:
- return await workflow.execute_activity(
- enrich_signup_organization_activity,
- args=[inputs, is_recheck, first_attempt_matched],
- start_to_close_timeout=ENRICH_ACTIVITY_TIMEOUT,
- # Onboarding routing already degrades to a safe default when enrichment is absent.
- retry_policy=RetryPolicy(maximum_attempts=MAX_ENRICH_ATTEMPTS, initial_interval=dt.timedelta(seconds=5)),
- )
+ return await _execute_enrich_activity(inputs, is_recheck=True, first_attempt_matched=first_attempt_matched)