: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(flags): pre-create hypercache verification task metric series (#80022)
Phil Haacka84baadb58dd
diff --git a/posthog/celery.py b/posthog/celery.pyindex 9579934b4520..a16900f65045 100644--- a/posthog/celery.py+++ b/posthog/celery.py@@ -23,6 +23,8 @@ from django_structlog.celery.steps import DjangoStructLogInitStepfrom opentelemetry import tracefrom prometheus_client import Counter, Histogram, start_http_server+from posthog.celery_task_names import LIVENESS_ALERTED_TASK_NAMES+# When PROMETHEUS_MULTIPROC_DIR is set (by bin/docker-worker-celery),# prometheus_client uses file-backed storage so all prefork children's# metrics are aggregated into a single /metrics endpoint. Without it,@@ -54,7 +56,7 @@ CELERY_TASK_SUCCESS_COUNTER = Counter(CELERY_TASK_FAILURE_COUNTER = Counter("posthog_celery_task_failure",- "task failure signal is dispatched when a task succeeds.",+ "task failure signal is dispatched when a task fails.",labelnames=["task_name"],)@@ -98,7 +100,30 @@ task_timings: dict[str, float] = {}def _initialize_worker_metrics() -> None:- """Initialize metrics that need to survive pod restarts."""+ """Initialize metrics that need to survive pod restarts.++ Each initializer runs unconditionally and carries its own worker-type gate, so+ adding one here cannot be silently skipped by another's early return.+ """+ _initialize_liveness_alerted_task_series()+ _initialize_cohort_backlog_metric()+++def _initialize_liveness_alerted_task_series() -> None:+ # Counter series are created lazily on a task's first prerun/success/failure event,+ # so a task that stops running vanishes from the metrics once its pods are replaced+ # (vmalert reads an empty result as resolved) instead of freezing at zero, where the+ # `increase(...) == 0` liveness alerts pinning these names can see it.+ signal_counters = (CELERY_TASK_PRE_RUN_COUNTER, CELERY_TASK_SUCCESS_COUNTER, CELERY_TASK_FAILURE_COUNTER)+ try:+ for task_name in LIVENESS_ALERTED_TASK_NAMES:+ for counter in signal_counters:+ counter.labels(task_name=task_name)+ except Exception:+ logger.warning("failed_to_initialize_task_metric_series", exc_info=True)+++def _initialize_cohort_backlog_metric() -> None:# Only initialize cohort metrics on long-running workers that handle cohort calculationsif not _is_longrunning_worker():returndiff --git a/posthog/celery_task_names.py b/posthog/celery_task_names.pynew file mode 100644index 000000000000..1ef5f1d49578--- /dev/null+++ b/posthog/celery_task_names.py@@ -0,0 +1,24 @@+# Task names pinned by vmalert liveness alerts in PostHog/charts (currently+# FlagsCacheVerificationNotRunning), which fire on+# `increase(posthog_celery_task_success_total{task_name="..."}[window]) == 0`.+#+# Each name here must be passed as `name=` to its @shared_task decorator, so the+# task_name label the alert matches on stays stable across module moves and renames,+# and is pre-created at worker start (posthog/celery.py, _initialize_worker_metrics)+# so a task that stops running freezes at zero instead of vanishing from the metrics.+#+# This module must stay import-light (like posthog/celery_queues.py): the metric seed+# reads it without importing task code, because an import error killing the seed is+# exactly the failure mode the alerts exist to catch.++VERIFY_FLAGS_CACHE_TASK_NAME = "posthog.tasks.hypercache_verification.verify_and_fix_flags_cache_task"+VERIFY_TEAM_METADATA_CACHE_TASK_NAME = "posthog.tasks.hypercache_verification.verify_and_fix_team_metadata_cache_task"+VERIFY_FLAG_DEFINITIONS_CACHE_TASK_NAME = (+ "posthog.tasks.hypercache_verification.verify_and_fix_flag_definitions_cache_task"+)++LIVENESS_ALERTED_TASK_NAMES = (+ VERIFY_FLAGS_CACHE_TASK_NAME,+ VERIFY_TEAM_METADATA_CACHE_TASK_NAME,+ VERIFY_FLAG_DEFINITIONS_CACHE_TASK_NAME,+)diff --git a/posthog/tasks/hypercache_verification.py b/posthog/tasks/hypercache_verification.pyindex c46c8d33bd2c..6354fdd4717e 100644--- a/posthog/tasks/hypercache_verification.py+++ b/posthog/tasks/hypercache_verification.py@@ -20,6 +20,11 @@ from celery import shared_taskfrom celery.exceptions import SoftTimeLimitExceededfrom prometheus_client import Counter+from posthog.celery_task_names import (+ VERIFY_FLAG_DEFINITIONS_CACHE_TASK_NAME,+ VERIFY_FLAGS_CACHE_TASK_NAME,+ VERIFY_TEAM_METADATA_CACHE_TASK_NAME,+)from posthog.exceptions_capture import capture_exceptionfrom posthog.storage.hypercache_manager import HyperCacheManagementConfigfrom posthog.storage.hypercache_verifier import TeamBatchFetchError, VerifyTeamFn, _run_verification_for_cache@@ -199,6 +204,7 @@ def _run_cache_verification(cache_type: CacheType, chunk_size: int) -> None:bind=True,base=PushGatewayTask,ignore_result=True,+ name=VERIFY_FLAGS_CACHE_TASK_NAME,queue=CeleryQueue.FEATURE_FLAGS_LONG_RUNNING.value,soft_time_limit=20 * 60, # 20 min soft limittime_limit=25 * 60, # 25 min hard limit (matches LOCK_TIMEOUT_SECONDS)@@ -223,6 +229,7 @@ def verify_and_fix_flags_cache_task(self: PushGatewayTask) -> None:bind=True,base=PushGatewayTask,ignore_result=True,+ name=VERIFY_TEAM_METADATA_CACHE_TASK_NAME,queue=CeleryQueue.DEFAULT.value,soft_time_limit=20 * 60, # 20 min soft limittime_limit=25 * 60, # 25 min hard limit (matches LOCK_TIMEOUT_SECONDS)@@ -247,6 +254,7 @@ def verify_and_fix_team_metadata_cache_task(self: PushGatewayTask) -> None:bind=True,base=PushGatewayTask,ignore_result=True,+ name=VERIFY_FLAG_DEFINITIONS_CACHE_TASK_NAME,queue=CeleryQueue.FEATURE_FLAGS_LONG_RUNNING.value,soft_time_limit=25 * 60, # 25 min soft limittime_limit=30 * 60, # 30 min hard limit (matches FLAG_DEFINITIONS_LOCK_TIMEOUT_SECONDS)diff --git a/posthog/test/test_celery.py b/posthog/test/test_celery.pyindex 3d09fa1d4fb5..f14594e1b18a 100644--- a/posthog/test/test_celery.py+++ b/posthog/test/test_celery.py@@ -1,3 +1,4 @@+import osimport threadingfrom unittest import TestCase@@ -5,9 +6,15 @@ from unittest.mock import MagicMock, patchimport posthoganalyticsfrom parameterized import parameterized+from prometheus_client import REGISTRYimport posthog.celery-from posthog.celery import on_worker_process_shutdown+from posthog.celery import _initialize_worker_metrics, on_worker_process_shutdown+from posthog.celery_task_names import (+ VERIFY_FLAG_DEFINITIONS_CACHE_TASK_NAME,+ VERIFY_FLAGS_CACHE_TASK_NAME,+ VERIFY_TEAM_METADATA_CACHE_TASK_NAME,+)from posthog.tasks.tasks import clickhouse_errors_count@@ -65,6 +72,31 @@ class TestAnalyticsMetricsConfig(TestCase):assert config["service_name"]+class TestWorkerMetricsInitialization(TestCase):+ # "celery" excludes long_running, so this also proves the seed does not depend on+ # the queue set (and keeps the DB-touching cohort branch off).+ @patch.dict(os.environ, {"CELERY_WORKER_QUEUES": "celery"})+ def test_seeds_hypercache_verification_task_series(self) -> None:+ _initialize_worker_metrics()++ for task_name in (+ VERIFY_FLAGS_CACHE_TASK_NAME,+ VERIFY_TEAM_METADATA_CACHE_TASK_NAME,+ VERIFY_FLAG_DEFINITIONS_CACHE_TASK_NAME,+ ):+ for sample_name in (+ "posthog_celery_task_pre_run_total",+ "posthog_celery_task_success_total",+ "posthog_celery_task_failure_total",+ ):+ # Existence, not == 0: another test running one of these tasks in the+ # same process increments the counter, and the alert only needs the+ # series to exist.+ assert REGISTRY.get_sample_value(sample_name, {"task_name": task_name}) is not None, (+ f"{sample_name} has no series for {task_name}"+ )++class TestCeleryMetrics(TestCase):@patch("posthog.clickhouse.client.sync_execute")@patch("posthog.metrics.push_to_gateway")