: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
fix(temporal): stop search attribute registration hanging at exit (#105475)
Raúl Negrón-Otero2db293bc203d
diff --git a/.depot/workflows/ci-backend.yml b/.depot/workflows/ci-backend.ymlindex dc2e249f0257..ec8dfc60912d 100644--- a/.depot/workflows/ci-backend.yml+++ b/.depot/workflows/ci-backend.yml@@ -1231,9 +1231,10 @@ jobs:admin_psql -c "DROP DATABASE IF EXISTS test_posthog;" || truefi- name: Register Temporal search attributes+ timeout-minutes: 10run: |bin/wait-for-docker temporal- python manage.py register_temporal_search_attributes+ PYTHONFAULTHANDLER=1 timeout --signal=ABRT --kill-after=30s 3m python manage.py register_temporal_search_attributes- name: Restore test durations from cacheuses: actions/cache/restore@cdf6c1fa76f9f475f3d7449005a359c84ca0f306 # v5.0.3with:diff --git a/.github/workflows/ci-backend.yml b/.github/workflows/ci-backend.ymlindex 091e175fb7ae..a4fa1007e09d 100644--- a/.github/workflows/ci-backend.yml+++ b/.github/workflows/ci-backend.yml@@ -1073,9 +1073,12 @@ jobs:# data_warehouse tests use custom search attributes (PostHogTeamId, PostHogOrgId,# PostHogDagId) when scheduling materialization, so they must be registered# before tests run.+ # If the command hangs, SIGABRT makes faulthandler print the Python stack of each+ # thread before the process exits, so the log shows where it stopped.+ timeout-minutes: 10run: |bin/wait-for-docker temporal- python manage.py register_temporal_search_attributes+ PYTHONFAULTHANDLER=1 timeout --signal=ABRT --kill-after=30s 3m python manage.py register_temporal_search_attributes- name: Restore test durations from cache# pytest-split distributes this product's tests across shards usingdiff --git a/posthog/management/commands/register_temporal_search_attributes.py b/posthog/management/commands/register_temporal_search_attributes.pyindex 370d277c529f..72166e63531a 100644--- a/posthog/management/commands/register_temporal_search_attributes.py+++ b/posthog/management/commands/register_temporal_search_attributes.py@@ -1,19 +1,21 @@-import gc-import asyncioimport logging+from django.conf import settingsfrom django.core.management.base import BaseCommand+import grpcimport structlogimport temporalio.api.enums.v1 as enumsimport temporalio.api.operatorservice.v1 as ops+from temporalio.api.operatorservice.v1.service_pb2_grpc import OperatorServiceStubfrom temporalio.common import SearchAttributeKey-from posthog.temporal.common.client import async_connectfrom posthog.temporal.common.search_attributes import POSTHOG_SEARCH_ATTRIBUTESlogger = structlog.get_logger(__name__)+_RPC_TIMEOUT_SECONDS = 60+# Maps SearchAttributeKey value_type to the protobuf IndexedValueType enum_TYPE_MAP: dict[type, enums.IndexedValueType.ValueType] = {int: enums.IndexedValueType.INDEXED_VALUE_TYPE_INT,@@ -30,6 +32,60 @@ def _resolve_type(key: SearchAttributeKey) -> enums.IndexedValueType.ValueType:return value_type+# A plain gRPC channel, not the temporalio Client. The Client completes RPCs on Tokio threads. At exit, CPython+# can drop its Tokio runtime while one of those threads waits for the GIL, and the process then never exits+# (https://github.com/temporalio/sdk-python/issues/300 tracks the same race).+def _open_channel() -> grpc.Channel:+ target = f"{settings.TEMPORAL_HOST}:{settings.TEMPORAL_PORT}"+ if settings.TEMPORAL_CLIENT_CERT and settings.TEMPORAL_CLIENT_KEY:+ credentials = grpc.ssl_channel_credentials(+ private_key=settings.TEMPORAL_CLIENT_KEY.encode(),+ certificate_chain=settings.TEMPORAL_CLIENT_CERT.encode(),+ )+ return grpc.secure_channel(target, credentials)+ return grpc.insecure_channel(target)+++def register_search_attributes(operator_service: OperatorServiceStub, namespace: str, dry_run: bool) -> None:+ # Match the Temporal SDK clients, which send the target namespace in this header on every request.+ rpc_metadata = (("temporal-namespace", namespace),)++ # List existing attributes+ resp = operator_service.ListSearchAttributes(+ ops.ListSearchAttributesRequest(namespace=namespace),+ timeout=_RPC_TIMEOUT_SECONDS,+ metadata=rpc_metadata,+ )+ existing = set(resp.custom_attributes.keys())++ # Find which ones need registering+ to_register = {}+ for key in POSTHOG_SEARCH_ATTRIBUTES:+ if key.name in existing:+ logger.info("Already registered", attribute=key.name)+ else:+ to_register[key.name] = _resolve_type(key)++ if not to_register:+ logger.info("All search attributes already registered")+ return++ if dry_run:+ for name, typ in to_register.items():+ logger.info("Would register", attribute=name, type=enums.IndexedValueType.Name(typ))+ return++ logger.info(f"Registering {len(to_register)} search attribute(s)", attributes=list(to_register.keys()))++ operator_service.AddSearchAttributes(+ ops.AddSearchAttributesRequest(namespace=namespace, search_attributes=to_register),+ timeout=_RPC_TIMEOUT_SECONDS,+ metadata=rpc_metadata,+ )++ logger.info("Done")++class Command(BaseCommand):help = "Register PostHog custom search attributes in Temporal"# A setup step in CI, dev runs and preview environments. The command never touches the ORM or the@@ -51,51 +107,5 @@ class Command(BaseCommand):def handle(self, **options):logger.setLevel(logging.INFO)- asyncio.run(self._run(options))-- async def _run(self, options):- namespace = options["namespace"]- dry_run = options["dry_run"]- temporal = await async_connect()-- try:- # List existing attributes- resp = await temporal.operator_service.list_search_attributes(- ops.ListSearchAttributesRequest(namespace=namespace)- )- existing = set(resp.custom_attributes.keys())-- # Find which ones need registering- to_register = {}- for key in POSTHOG_SEARCH_ATTRIBUTES:- if key.name in existing:- logger.info("Already registered", attribute=key.name)- else:- to_register[key.name] = _resolve_type(key)-- if not to_register:- logger.info("All search attributes already registered")- return-- if dry_run:- for name, typ in to_register.items():- logger.info("Would register", attribute=name, type=enums.IndexedValueType.Name(typ))- return-- logger.info(f"Registering {len(to_register)} search attribute(s)", attributes=list(to_register.keys()))-- await temporal.operator_service.add_search_attributes(- ops.AddSearchAttributesRequest(- namespace=namespace,- search_attributes=to_register,- )- )-- logger.info("Done")- finally:- # Drop the Temporal client reference and force GC before the event- # loop tears down. The Rust/gRPC bridge spawns background threads- # that crash during CPython finalization ("PyGILState_Release: thread- # state … must be current") if the bridge destructor hasn't run yet.- del temporal- gc.collect()+ with _open_channel() as channel:+ register_search_attributes(OperatorServiceStub(channel), options["namespace"], options["dry_run"])