: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(temporal): let a worker autoscale its task pollers (#116018)
Tom Owers0cb52d1a7605
diff --git a/posthog/settings/temporal.py b/posthog/settings/temporal.pyindex 8dcd2e5894d9..8a1f1d1b5d29 100644--- a/posthog/settings/temporal.py+++ b/posthog/settings/temporal.py@@ -50,6 +50,21 @@ TEMPORAL_ACTIVITY_RAMP_THROTTLE_MS: int | None = get_from_env("TEMPORAL_ACTIVITY_RAMP_THROTTLE_MS", None, optional=True, type_cast=int)+# Opt-in task poller autoscaling. A MAX turns it on for that task type, and the SDK default+# (5 pollers) applies when unset. Fixed poller counts leave a small worker fleet short of pollers.+TEMPORAL_ACTIVITY_POLLER_AUTOSCALING_MIN: int | None = get_from_env(+ "TEMPORAL_ACTIVITY_POLLER_AUTOSCALING_MIN", None, optional=True, type_cast=int+)+TEMPORAL_ACTIVITY_POLLER_AUTOSCALING_MAX: int | None = get_from_env(+ "TEMPORAL_ACTIVITY_POLLER_AUTOSCALING_MAX", None, optional=True, type_cast=int+)+TEMPORAL_WORKFLOW_POLLER_AUTOSCALING_MIN: int | None = get_from_env(+ "TEMPORAL_WORKFLOW_POLLER_AUTOSCALING_MIN", None, optional=True, type_cast=int+)+TEMPORAL_WORKFLOW_POLLER_AUTOSCALING_MAX: int | None = get_from_env(+ "TEMPORAL_WORKFLOW_POLLER_AUTOSCALING_MAX", None, optional=True, type_cast=int+)+TEMPORAL_HEALTH_PORT: int | None = get_from_env("TEMPORAL_HEALTH_PORT", None, optional=True, type_cast=int)TEMPORAL_HEALTH_MAX_IDLE_SECONDS: float | None = get_from_env("TEMPORAL_HEALTH_MAX_IDLE_SECONDS", None, optional=True, type_cast=floatdiff --git a/posthog/temporal/common/worker.py b/posthog/temporal/common/worker.pyindex e422cb1fa404..0ab36ab7ed00 100644--- a/posthog/temporal/common/worker.py+++ b/posthog/temporal/common/worker.py@@ -12,7 +12,13 @@ from prometheus_client import REGISTRYfrom temporalio.client import Pluginfrom temporalio.contrib.opentelemetry import OpenTelemetryPluginfrom temporalio.runtime import PrometheusConfig, Runtime, TelemetryConfig-from temporalio.worker import ResourceBasedSlotConfig, UnsandboxedWorkflowRunner, Worker, WorkerTuner+from temporalio.worker import (+ PollerBehaviorAutoscaling,+ ResourceBasedSlotConfig,+ UnsandboxedWorkflowRunner,+ Worker,+ WorkerTuner,+)from posthog.temporal.ai_observability.eval_reports.metrics import (EVAL_REPORTS_LATENCY_HISTOGRAM_BUCKETS,@@ -219,6 +225,29 @@ class ManagedWorker:DEFAULT_MAX_CONCURRENT_TASKS = 50+def build_poller_autoscaling(+ task_type: str, minimum: int | None, maximum: int | None+) -> PollerBehaviorAutoscaling | None:+ """Return an autoscaling poller behavior, or None to keep the SDK default when maximum is unset."""+ if maximum is None:+ if minimum is not None:+ logger.warning(+ "poller_autoscaling_minimum_ignored",+ task_type=task_type,+ minimum=minimum,+ reason="maximum is not set, so the SDK default poller behavior is used",+ )+ return None+ effective_minimum = PollerBehaviorAutoscaling.minimum if minimum is None else minimum+ if effective_minimum < 1:+ raise ValueError(f"{task_type} poller autoscaling minimum must be at least 1, got {effective_minimum}")+ if maximum < effective_minimum:+ raise ValueError(+ f"{task_type} poller autoscaling maximum ({maximum}) must be at least the minimum ({effective_minimum})"+ )+ return PollerBehaviorAutoscaling(minimum=effective_minimum, maximum=maximum, initial=effective_minimum)++async def create_worker(host: str,port: int,@@ -458,6 +487,22 @@ async def create_worker(min(max_concurrent_activities or DEFAULT_MAX_CONCURRENT_TASKS, settings.ASYNCIFY_MAX_WORKERS))+ poller_kwargs: dict[str, typing.Any] = {}+ activity_poller_behavior = build_poller_autoscaling(+ "activity",+ settings.TEMPORAL_ACTIVITY_POLLER_AUTOSCALING_MIN,+ settings.TEMPORAL_ACTIVITY_POLLER_AUTOSCALING_MAX,+ )+ if activity_poller_behavior is not None:+ poller_kwargs["activity_task_poller_behavior"] = activity_poller_behavior+ workflow_poller_behavior = build_poller_autoscaling(+ "workflow",+ settings.TEMPORAL_WORKFLOW_POLLER_AUTOSCALING_MIN,+ settings.TEMPORAL_WORKFLOW_POLLER_AUTOSCALING_MAX,+ )+ if workflow_poller_behavior is not None:+ poller_kwargs["workflow_task_poller_behavior"] = workflow_poller_behavior+if target_memory_usage is not None:worker = Worker(client,@@ -482,6 +527,7 @@ async def create_worker(# Worker will flush heartbeats every# min(heartbeat_timeout * 0.8, max_heartbeat_throttle_interval).max_heartbeat_throttle_interval=dt.timedelta(seconds=5),+ **poller_kwargs,)else:worker = Worker(@@ -498,6 +544,7 @@ async def create_worker(# Worker will flush heartbeats every# min(heartbeat_timeout * 0.8, max_heartbeat_throttle_interval).max_heartbeat_throttle_interval=dt.timedelta(seconds=5),+ **poller_kwargs,)return ManagedWorker(worker=worker, metrics_server=metrics_server)diff --git a/posthog/temporal/tests/common/test_worker_pollers.py b/posthog/temporal/tests/common/test_worker_pollers.pynew file mode 100644index 000000000000..5dfaef380773--- /dev/null+++ b/posthog/temporal/tests/common/test_worker_pollers.py@@ -0,0 +1,106 @@+import pytest+from unittest import mock++from django.test import override_settings++from temporalio.worker import PollerBehaviorAutoscaling++from posthog.temporal.common.worker import build_poller_autoscaling, create_worker+++ "minimum,maximum,expected",+ [+ (None, None, None),+ (4, None, None),+ (None, 20, PollerBehaviorAutoscaling(minimum=1, maximum=20, initial=1)),+ (3, 20, PollerBehaviorAutoscaling(minimum=3, maximum=20, initial=3)),+ (5, 5, PollerBehaviorAutoscaling(minimum=5, maximum=5, initial=5)),+ ],+)+def test_build_poller_autoscaling(minimum, maximum, expected):+ assert build_poller_autoscaling("activity", minimum, maximum) == expected+++ "minimum,maximum",+ [+ (None, 0),+ (0, 10),+ (-1, 10),+ (10, 5),+ ],+)+def test_build_poller_autoscaling_rejects_invalid_values(minimum, maximum):+ with pytest.raises(ValueError):+ build_poller_autoscaling("activity", minimum, maximum)++[email protected]("target_memory_usage", [None, 0.8])+ "poller_settings,expected_kwargs",+ [+ ({}, {}),+ (+ {"TEMPORAL_ACTIVITY_POLLER_AUTOSCALING_MAX": 30},+ {"activity_task_poller_behavior": PollerBehaviorAutoscaling(minimum=1, maximum=30, initial=1)},+ ),+ (+ {"TEMPORAL_ACTIVITY_POLLER_AUTOSCALING_MIN": 5, "TEMPORAL_ACTIVITY_POLLER_AUTOSCALING_MAX": 30},+ {"activity_task_poller_behavior": PollerBehaviorAutoscaling(minimum=5, maximum=30, initial=5)},+ ),+ (+ {"TEMPORAL_WORKFLOW_POLLER_AUTOSCALING_MIN": 2, "TEMPORAL_WORKFLOW_POLLER_AUTOSCALING_MAX": 10},+ {"workflow_task_poller_behavior": PollerBehaviorAutoscaling(minimum=2, maximum=10, initial=2)},+ ),+ ],+)+async def test_create_worker_passes_poller_behavior_only_when_configured(+ poller_settings, expected_kwargs, target_memory_usage+):+ with (+ override_settings(**poller_settings),+ mock.patch("posthog.temporal.common.worker.connect", new=mock.AsyncMock()),+ mock.patch("posthog.temporal.common.worker.Runtime"),+ mock.patch("posthog.temporal.common.worker.configure_asyncify_executor"),+ mock.patch("posthog.temporal.common.worker.WorkerTuner"),+ mock.patch("posthog.temporal.common.worker.Worker") as worker_cls,+ ):+ await create_worker(+ host="localhost",+ port=7233,+ metrics_port=0,+ namespace="default",+ task_queue="test-queue",+ workflows=[],+ activities=[],+ enable_combined_metrics_server=False,+ target_memory_usage=target_memory_usage,+ )++ kwargs = worker_cls.call_args.kwargs+ poller_kwargs = {k: v for k, v in kwargs.items() if k.endswith("poller_behavior")}+ assert poller_kwargs == expected_kwargs+++async def test_create_worker_rejects_invalid_poller_settings():+ with (+ override_settings(TEMPORAL_ACTIVITY_POLLER_AUTOSCALING_MIN=10, TEMPORAL_ACTIVITY_POLLER_AUTOSCALING_MAX=5),+ mock.patch("posthog.temporal.common.worker.connect", new=mock.AsyncMock()),+ mock.patch("posthog.temporal.common.worker.Runtime"),+ mock.patch("posthog.temporal.common.worker.configure_asyncify_executor"),+ mock.patch("posthog.temporal.common.worker.Worker"),+ pytest.raises(ValueError),+ ):+ await create_worker(+ host="localhost",+ port=7233,+ metrics_port=0,+ namespace="default",+ task_queue="test-queue",+ workflows=[],+ activities=[],+ enable_combined_metrics_server=False,+ )