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.

fix(temporal): resolve realtime cohorts threshold overlaps and timestamp bugs (#57545)

Gustavo H. Strassburger9880796c1e26
diff --git a/posthog/temporal/messaging/quantiles_storage.py b/posthog/temporal/messaging/quantiles_storage.py
new file mode 100644
index 000000000000..f99f71011d85
--- /dev/null
+++ b/posthog/temporal/messaging/quantiles_storage.py
@@ -0,0 +1,364 @@
+"""
+Redis-based quantiles storage service for consistent percentile thresholds across workflows.
+
+This module provides atomic caching of duration quantiles to ensure all realtime cohort workflows
+use the same percentile boundaries, preventing overlapping threshold ranges between tiers.
+
+Race Condition Handling:
+- Uses Redis SET NX (atomic set-if-not-exists) to prevent multiple workflows from calculating quantiles
+- Implements retry logic with exponential backoff when cache write fails due to race conditions
+- TTL set to 2 hours to ensure fresh data while allowing workflow coordination
+"""
+
+import json
+import time
+import uuid
+import random
+import datetime as dt
+import statistics
+import dataclasses
+from typing import Optional
+
+import structlog
+
+from posthog.redis import get_client
+
+LOGGER = structlog.get_logger(__name__)
+
+# Cache key format: quantiles:2024-01-15:14 (hourly buckets)
+QUANTILES_KEY_PREFIX = "duration_quantiles:"
+# Short TTL since we want relatively fresh data but need consistency within the hour
+DEFAULT_TTL = 2 * 60 * 60 # 2 hours
+# Lock to prevent race conditions when calculating quantiles
+LOCK_KEY_PREFIX = "duration_quantiles_lock:"
+LOCK_TTL = 300 # 5 minutes
+# Retry configuration for handling race conditions
+# Conservative limits to avoid blocking database_sync_to_async thread pool
+MAX_RETRIES = 3
+BASE_RETRY_DELAY = 0.05 # 50ms
+MAX_RETRY_DELAY = 0.2 # 200ms max
+
+
[email protected](frozen=True)
+class CachedQuantiles:
+ """Cached quantile boundaries plus the maximum observed value used for p100.
+
+ Caching the max alongside the quantiles guarantees workflows that share the same
+ cache entry produce identical p100 thresholds, even if the underlying queryset
+ changes between workflows within the cache window.
+ """
+
+ quantiles: list[float]
+ max_value: int
+
+
+def _get_cache_key(hour_bucket: str) -> str:
+ """Generate Redis key for quantiles cache."""
+ return f"{QUANTILES_KEY_PREFIX}{hour_bucket}"
+
+
+def _get_lock_key(hour_bucket: str) -> str:
+ """Generate Redis key for quantiles calculation lock."""
+ return f"{LOCK_KEY_PREFIX}{hour_bucket}"
+
+
+def _get_current_hour_bucket() -> str:
+ """Get current hour bucket for cache key (e.g., '2024-01-15:14')."""
+ now = dt.datetime.now(dt.UTC)
+ return now.strftime("%Y-%m-%d:%H")
+
+
+def _get_previous_hour_bucket() -> str:
+ """Get previous hour bucket for fallback cache lookup (e.g., '2024-01-15:13')."""
+ now = dt.datetime.now(dt.UTC)
+ previous_hour = now - dt.timedelta(hours=1)
+ return previous_hour.strftime("%Y-%m-%d:%H")
+
+
+def store_quantiles(quantiles_data: list[float], max_value: int, hour_bucket: Optional[str] = None) -> bool:
+ """
+ Atomically store quantiles in Redis if not already cached.
+
+ Args:
+ quantiles_data: List of 99 quantile values (p1 through p99)
+ max_value: Maximum observed duration; used as the p100 threshold by all
+ workflows that share this cache entry, ensuring tier consistency.
+ hour_bucket: Optional hour bucket, defaults to current hour
+
+ Returns:
+ True if successfully stored, False if another process already stored them
+ """
+ if hour_bucket is None:
+ hour_bucket = _get_current_hour_bucket()
+
+ cache_key = _get_cache_key(hour_bucket)
+ lock_key = _get_lock_key(hour_bucket)
+
+ redis_client = get_client()
+ lock_token = None
+
+ try:
+ # Generate unique token for this lock acquisition
+ lock_token = uuid.uuid4().hex
+
+ # Try to acquire lock atomically with unique token
+ lock_acquired = redis_client.set(lock_key, lock_token, nx=True, ex=LOCK_TTL) or False
+
+ if not lock_acquired:
+ LOGGER.info(
+ "Quantiles calculation lock already held by another process",
+ hour_bucket=hour_bucket,
+ cache_key=cache_key,
+ )
+ return False
+
+ # Check if cache was set while we were acquiring the lock
+ if redis_client.exists(cache_key):
+ LOGGER.info(
+ "Quantiles already cached by another process during lock acquisition",
+ hour_bucket=hour_bucket,
+ cache_key=cache_key,
+ )
+ return False
+
+ # Store quantiles with TTL
+ payload_json = json.dumps({"quantiles": quantiles_data, "max_value": max_value})
+ redis_client.setex(cache_key, DEFAULT_TTL, payload_json)
+
+ LOGGER.info(
+ "Successfully stored quantiles in cache",
+ hour_bucket=hour_bucket,
+ cache_key=cache_key,
+ quantiles_count=len(quantiles_data),
+ max_value=max_value,
+ ttl_seconds=DEFAULT_TTL,
+ )
+
+ return True
+
+ except Exception as e:
+ LOGGER.warning("Failed to store quantiles in cache", hour_bucket=hour_bucket, cache_key=cache_key, error=str(e))
+ return False
+
+ finally:
+ # Only release the lock if we acquired it and still hold the same token
+ if lock_token:
+ try:
+ # Use Lua script for atomic compare-and-delete
+ lua_script = """
+ if redis.call("GET", KEYS[1]) == ARGV[1] then
+ return redis.call("DEL", KEYS[1])
+ else
+ return 0
+ end
+ """
+ result = redis_client.eval(lua_script, 1, lock_key, lock_token)
+ if result == 0:
+ LOGGER.warning(
+ "Lock token mismatch during release - lock may have expired or been taken by another process",
+ lock_key=lock_key,
+ hour_bucket=hour_bucket,
+ )
+ except Exception as e:
+ LOGGER.warning("Failed to release quantiles calculation lock", lock_key=lock_key, error=str(e))
+
+
+def get_quantiles(hour_bucket: Optional[str] = None) -> Optional[CachedQuantiles]:
+ """
+ Retrieve cached quantiles from Redis.
+
+ Args:
+ hour_bucket: Optional hour bucket, defaults to current hour
+
+ Returns:
+ CachedQuantiles with 99 quantile values and the cached max if cached,
+ None if not found or unparseable.
+ """
+ if hour_bucket is None:
+ hour_bucket = _get_current_hour_bucket()
+
+ cache_key = _get_cache_key(hour_bucket)
+ redis_client = get_client()
+
+ try:
+ cached_data = redis_client.get(cache_key)
+
+ if cached_data is None:
+ LOGGER.info("No quantiles found in cache", hour_bucket=hour_bucket, cache_key=cache_key)
+ return None
+
+ payload = json.loads(cached_data)
+
+ # Reject any payload that doesn't carry both quantiles and max_value, including
+ # legacy bare-list entries from earlier versions of this branch. Treat as a miss
+ # so callers fall back to recalculation rather than silently mixing formats.
+ if not isinstance(payload, dict) or "quantiles" not in payload or "max_value" not in payload:
+ LOGGER.warning(
+ "Cached quantiles payload is missing required fields",
+ hour_bucket=hour_bucket,
+ cache_key=cache_key,
+ )
+ try:
+ redis_client.delete(cache_key)
+ except Exception:
+ pass
+ return None
+
+ cached = CachedQuantiles(quantiles=payload["quantiles"], max_value=int(payload["max_value"]))
+
+ LOGGER.info(
+ "Successfully retrieved quantiles from cache",
+ hour_bucket=hour_bucket,
+ cache_key=cache_key,
+ quantiles_count=len(cached.quantiles),
+ max_value=cached.max_value,
+ )
+
+ return cached
+
+ except (json.JSONDecodeError, TypeError, ValueError) as e:
+ LOGGER.warning(
+ "Failed to parse cached quantiles data", hour_bucket=hour_bucket, cache_key=cache_key, error=str(e)
+ )
+ # Delete corrupted cache entry
+ try:
+ redis_client.delete(cache_key)
+ except Exception:
+ pass
+ return None
+
+ except Exception as e:
+ LOGGER.warning(
+ "Failed to retrieve quantiles from cache", hour_bucket=hour_bucket, cache_key=cache_key, error=str(e)
+ )
+ return None
+
+
+def get_cached_quantiles_or_calculate(
+ durations_list: list[int], hour_bucket: Optional[str] = None, max_retries: int = MAX_RETRIES
+) -> Optional[CachedQuantiles]:
+ """
+ Get quantiles from cache first, regardless of current data size.
+ Only calculate new quantiles if cache is empty and we have sufficient data.
+
+ This ensures workflows can reuse cached quantiles even when the current
+ query returns insufficient data (e.g., cohort count dropped mid-hour).
+ """
+ if hour_bucket is None:
+ hour_bucket = _get_current_hour_bucket()
+
+ # First, try to get from current hour bucket cache
+ cached = get_quantiles(hour_bucket)
+ if cached is not None:
+ return cached
+
+ # Cache miss - try previous hour bucket to handle hour-boundary issue
+ # This prevents overlapping thresholds when schedules run near :59/:00
+ previous_hour_bucket = _get_previous_hour_bucket()
+ if previous_hour_bucket != hour_bucket: # Only check if different from current
+ cached = get_quantiles(previous_hour_bucket)
+ if cached is not None:
+ LOGGER.info(
+ "Using quantiles from previous hour bucket to handle hour-boundary timing",
+ current_bucket=hour_bucket,
+ previous_bucket=previous_hour_bucket,
+ )
+ return cached
+
+ # No cache available - only calculate if we have sufficient current data
+ if len(durations_list) < 2:
+ LOGGER.error(
+ "No cached quantiles available and insufficient current data for calculation",
+ hour_bucket=hour_bucket,
+ previous_bucket=previous_hour_bucket,
+ data_points=len(durations_list),
+ )
+ return None
+
+ # Continue with calculation using the current implementation
+ return _calculate_and_cache_quantiles(durations_list, hour_bucket, max_retries)
+
+
+def _calculate_and_cache_quantiles(
+ durations_list: list[int], hour_bucket: str, max_retries: int = MAX_RETRIES
+) -> Optional[CachedQuantiles]:
+ """
+ Calculate and cache quantiles atomically with retry logic for race conditions.
+
+ Assumes cache has already been checked. This function only calculates new quantiles
+ when we know we have sufficient data and need to populate the cache.
+
+ Args:
+ durations_list: List of duration values in milliseconds (must have >= 2 elements)
+ hour_bucket: Time bucket for cache key
+ max_retries: Maximum number of retries for handling race conditions
+
+ Returns:
+ CachedQuantiles with 99 quantile values (p1 through p99) and the max
+ observed duration, or None on failure.
+ """
+ try:
+ # Calculate quantiles and capture max from the same dataset so the cached
+ # p100 stays in lockstep with the cached p1..p99 boundaries.
+ quantiles = statistics.quantiles(durations_list, n=100, method="inclusive")
+ max_value = int(max(durations_list))
+
+ # Try to store in cache with retry logic for race conditions
+ for attempt in range(max_retries):
+ stored = store_quantiles(quantiles, max_value, hour_bucket)
+
+ if stored:
+ # We successfully stored the quantiles
+ LOGGER.info(
+ "Successfully calculated and cached quantiles",
+ hour_bucket=hour_bucket,
+ attempt=attempt + 1,
+ data_points=len(durations_list),
+ )
+ return CachedQuantiles(quantiles=quantiles, max_value=max_value)
+
+ # Another process stored quantiles while we were calculating
+ # Try to retrieve the stored values
+ cached = get_quantiles(hour_bucket)
+ if cached is not None:
+ LOGGER.info(
+ "Using quantiles calculated by another process", hour_bucket=hour_bucket, attempt=attempt + 1
+ )
+ return cached
+
+ # Cache still empty, retry with exponential backoff
+ if attempt < max_retries - 1:
+ delay = min(BASE_RETRY_DELAY * (2**attempt) + random.uniform(0, 0.1), MAX_RETRY_DELAY)
+ LOGGER.info(
+ "Retrying quantiles calculation after delay",
+ hour_bucket=hour_bucket,
+ attempt=attempt + 1,
+ delay_seconds=delay,
+ )
+ time.sleep(delay)
+
+ # All retries exhausted. Do not return uncached locally computed quantiles,
+ # because doing so can reintroduce inconsistent percentile boundaries across workflows.
+ # Perform one final cache read in case another process populated the cache
+ # after our last retry attempt, otherwise fail closed.
+ cached = get_quantiles(hour_bucket)
+ if cached is not None:
+ LOGGER.info(
+ "Using quantiles calculated by another process after final cache check",
+ hour_bucket=hour_bucket,
+ max_retries=max_retries,
+ )
+ return cached
+
+ LOGGER.error(
+ "Failed to obtain cached quantiles after all retries; returning None to preserve consistency",
+ hour_bucket=hour_bucket,
+ max_retries=max_retries,
+ )
+ return None
+
+ except (statistics.StatisticsError, TypeError, ValueError) as e:
+ LOGGER.warning(
+ "Failed to calculate quantiles", hour_bucket=hour_bucket, error=str(e), data_points=len(durations_list)
+ )
+ return None
diff --git a/posthog/temporal/messaging/realtime_cohort_calculation_workflow.py b/posthog/temporal/messaging/realtime_cohort_calculation_workflow.py
index d7923302ab22..b3c2d213ff08 100644
--- a/posthog/temporal/messaging/realtime_cohort_calculation_workflow.py
+++ b/posthog/temporal/messaging/realtime_cohort_calculation_workflow.py
@@ -226,10 +226,11 @@ async def flush_kafka_batch(
@database_sync_to_async
def _batch_update_cohort_metrics(cohort_durations: dict[int, int]) -> int:
- """Batch update cohort durations and last backfill timestamp.
+ """Batch update cohort durations and realtime calculation timestamp.
Only updates duration_ms when it changed by more than DURATION_UPDATE_RELATIVE_THRESHOLD from the previous value.
- Always updates last_backfill_person_properties_at and last_realtime_cohort_calculation_at for all processed cohorts.
+ Always updates last_realtime_cohort_calculation_at for all processed cohorts.
+ Does NOT update last_backfill_person_properties_at - that should only be updated by the backfilling person properties workflow.
Returns count of cohorts that had their duration updated.
"""
@@ -241,7 +242,6 @@ def _batch_update_cohort_metrics(cohort_durations: dict[int, int]) -> int:
duration_updates_count = 0
for cohort in all_cohorts:
- cohort.last_backfill_person_properties_at = now
cohort.last_realtime_cohort_calculation_at = now
new_duration = cohort_durations[cohort.pk]
@@ -259,12 +259,11 @@ def _batch_update_cohort_metrics(cohort_durations: dict[int, int]) -> int:
cohort.last_calculation_duration_ms = new_duration
duration_updates_count += 1
- # Single bulk_update for all cohorts — updates last_backfill_person_properties_at, last_realtime_cohort_calculation_at, and last_calculation_duration_ms
+ # Single bulk_update for all cohorts — updates last_realtime_cohort_calculation_at and last_calculation_duration_ms
if all_cohorts:
Cohort.objects.bulk_update(
all_cohorts,
[
- "last_backfill_person_properties_at",
"last_realtime_cohort_calculation_at",
"last_calculation_duration_ms",
],
diff --git a/posthog/temporal/messaging/realtime_cohort_calculation_workflow_coordinator.py b/posthog/temporal/messaging/realtime_cohort_calculation_workflow_coordinator.py
index ecf46e336b7b..f427c02c60ec 100644
--- a/posthog/temporal/messaging/realtime_cohort_calculation_workflow_coordinator.py
+++ b/posthog/temporal/messaging/realtime_cohort_calculation_workflow_coordinator.py
@@ -19,6 +19,7 @@ from posthog.sync import database_sync_to_async
from posthog.temporal.common.base import PostHogWorkflow
from posthog.temporal.common.logger import get_logger
from posthog.temporal.messaging.constants import get_child_workflow_id, get_percentile_bucket_label
+from posthog.temporal.messaging.quantiles_storage import get_cached_quantiles_or_calculate
from posthog.temporal.messaging.realtime_cohort_calculation_workflow import (
RealtimeCohortCalculationWorkflow,
RealtimeCohortCalculationWorkflowInputs,
@@ -168,12 +169,10 @@ class RealtimeCohortSelectionResult:
async def calculate_percentile_thresholds(
inputs: QueryPercentileThresholdsInput,
) -> QueryPercentileThresholds | None:
- """Calculate percentile thresholds directly from duration data."""
+ """Calculate percentile thresholds using cached quantiles to ensure consistency across workflows."""
@database_sync_to_async
def get_thresholds():
- import statistics
-
try:
# Get cohorts with recent duration data (past 24 hours)
recent_cohorts = Cohort.objects.filter(
@@ -188,27 +187,50 @@ async def calculate_percentile_thresholds(
durations_list = list(recent_cohorts)
- if len(durations_list) < 2:
- return None
-
# Calculate specific percentile thresholds
min_percentile = inputs.min_percentile
max_percentile = inputs.max_percentile
- # Compute quantiles once to avoid duplicate allocation and sorting
- quantiles = statistics.quantiles(durations_list, n=100, method="inclusive")
+ # Get quantiles from cache or calculate atomically
+ # This ensures all workflows use the same percentile boundaries
+ # Check cache first even if current query has insufficient data
+ cached = get_cached_quantiles_or_calculate(durations_list)
+
+ if cached is None:
+ LOGGER.warning("Failed to get or calculate quantiles")
+ # Emit metric for monitoring quantiles unavailability.
+ # This runs inside an activity, so use the activity meter rather than the
+ # workflow meter (which would raise outside a workflow event loop).
+ try:
+ quantiles_unavailable_counter = temporalio.activity.metric_meter().create_counter(
+ "quantiles_unavailable", "Count of times quantiles were unavailable for percentile calculations"
+ )
+ quantiles_unavailable_counter.add(1)
+ except RuntimeError:
+ # Not in activity context (e.g., during tests), skip metric
+ pass
+ return None
+
+ quantiles = cached.quantiles
+ cached_max = cached.max_value
# Special handling for p0: use 0 instead of calculating from data
if min_percentile is None or min_percentile <= 0.0:
min_threshold = 0
+ elif min_percentile >= 99.9:
+ # p100 case - use cached max so all workflows sharing this cache entry
+ # get identical p100 boundaries even if current durations_list differs.
+ min_threshold = cached_max
else:
+ # For percentiles 1-99, quantiles[0] is p1, quantiles[1] is p2, etc.
min_threshold = int(quantiles[int(min_percentile) - 1])
# Calculate max threshold
if max_percentile is None or max_percentile >= 99.9:
- # p100 case - use actual maximum from data
- max_threshold = int(max(durations_list))
+ # p100 case - use cached max for cross-workflow consistency.
+ max_threshold = cached_max
else:
+ # For percentiles 1-99, quantiles[0] is p1, quantiles[1] is p2, etc.
max_threshold = int(quantiles[int(max_percentile) - 1])
return QueryPercentileThresholds(
@@ -216,9 +238,9 @@ async def calculate_percentile_thresholds(
max_threshold_ms=max_threshold,
)
- except (statistics.StatisticsError, TypeError, ValueError) as e:
+ except (TypeError, ValueError, IndexError) as e:
LOGGER.warning(
- "Failed to calculate percentile thresholds from duration data",
+ "Failed to calculate percentile thresholds from cached quantiles",
error=str(e),
error_type=type(e).__name__,
)
diff --git a/posthog/temporal/messaging/test/test_quantiles_integration.py b/posthog/temporal/messaging/test/test_quantiles_integration.py
new file mode 100644
index 000000000000..c2ccdb9ae12e
--- /dev/null
+++ b/posthog/temporal/messaging/test/test_quantiles_integration.py
@@ -0,0 +1,287 @@
+"""
+Integration tests for quantiles storage with real Redis concurrency scenarios.
+
+Tests actual Redis operations and thread-based concurrency to verify
+our locking mechanism works in practice.
+"""
+
+import time
+import threading
+from concurrent.futures import ThreadPoolExecutor, as_completed
+
+import pytest
+from unittest.mock import patch
+
+from posthog.redis import get_client
+from posthog.temporal.messaging.quantiles_storage import (
+ CachedQuantiles,
+ _get_cache_key,
+ _get_lock_key,
+ get_cached_quantiles_or_calculate,
+ get_quantiles,
+ store_quantiles,
+)
+
+
+class TestQuantilesConcurrencyIntegration:
+ """Integration tests using real Redis for concurrency scenarios."""
+
+ def setup_method(self):
+ """Clean up Redis before each test."""
+ redis_client = get_client()
+ # Clean up any test keys
+ test_keys = redis_client.keys("duration_quantiles*")
+ if test_keys:
+ redis_client.delete(*test_keys)
+
+ def teardown_method(self):
+ """Clean up Redis after each test."""
+ redis_client = get_client()
+ test_keys = redis_client.keys("duration_quantiles*")
+ if test_keys:
+ redis_client.delete(*test_keys)
+
+ def test_concurrent_quantiles_calculation_real_redis(self):
+ """Test that concurrent workers get consistent quantiles using real Redis."""
+ durations = list(range(100, 1000, 20)) # Realistic data
+ hour_bucket = "2024-01-15:14"
+
+ results = []
+ errors = []
+
+ def worker_function(worker_id):
+ """Simulate a Temporal worker calculating quantiles."""
+ try:
+ result = get_cached_quantiles_or_calculate(durations, hour_bucket, max_retries=3)
+ return worker_id, result
+ except Exception as e:
+ errors.append(f"Worker {worker_id}: {e}")
+ return worker_id, None
+
+ # Simulate 5 workers starting simultaneously
+ with ThreadPoolExecutor(max_workers=5) as executor:
+ futures = [executor.submit(worker_function, i) for i in range(5)]
+
+ for future in as_completed(futures):
+ worker_id, result = future.result()
+ results.append((worker_id, result))
+
+ # Verify no errors occurred
+ assert len(errors) == 0, f"Errors occurred: {errors}"
+
+ # All workers should have gotten a result
+ assert len(results) == 5
+
+ # All results should be identical (consistency achieved)
+ first_result = results[0][1]
+ assert first_result is not None, "First result should not be None"
+
+ for worker_id, result in results:
+ assert result is not None, f"Worker {worker_id} got None result"
+ assert result == first_result, f"Worker {worker_id} got different result: {result} vs {first_result}"
+
+ # Verify the cache was actually used (should be in Redis now)
+ cached_result = get_quantiles(hour_bucket)
+ assert cached_result == first_result
+
+ def test_lock_contention_with_real_redis(self):
+ """Test lock contention behavior with real Redis operations."""
+ hour_bucket = "2024-01-15:15"
+ cache_key = _get_cache_key(hour_bucket)
+ lock_key = _get_lock_key(hour_bucket)
+
+ redis_client = get_client()
+
+ # Manually acquire the lock to simulate contention
+ lock_acquired = redis_client.set(lock_key, "locked", nx=True, ex=300)
+ assert lock_acquired, "Should be able to acquire lock initially"
+
+ try:
+ # Try to store quantiles while lock is held by another process
+ test_quantiles = [100.0, 200.0, 300.0]
+ result = store_quantiles(test_quantiles, max_value=400, hour_bucket=hour_bucket)
+
+ # Should fail because lock is already held
+ assert result is False, "Should fail to store when lock is held"
+
+ # Cache should still be empty
+ assert not redis_client.exists(cache_key), "Cache should be empty when store fails"
+
+ finally:
+ # Release the lock
+ redis_client.delete(lock_key)
+
+ # Now storing should succeed
+ result = store_quantiles(test_quantiles, max_value=400, hour_bucket=hour_bucket)
+ assert result is True, "Should succeed after lock is released"
+ assert redis_client.exists(cache_key), "Cache should exist after successful store"
+
+ def test_cache_expiration_behavior(self):
+ """Test that cache expiration works correctly."""
+ hour_bucket = "2024-01-15:16"
+ test_quantiles = [100.0, 200.0, 300.0]
+ test_max = 400
+
+ # Store with short TTL for testing
+ redis_client = get_client()
+ cache_key = _get_cache_key(hour_bucket)
+
+ # Store quantiles with 1 second TTL
+ with patch("posthog.temporal.messaging.quantiles_storage.DEFAULT_TTL", 1):
+ result = store_quantiles(test_quantiles, max_value=test_max, hour_bucket=hour_bucket)
+ assert result is True
+
+ # Should be retrievable immediately
+ cached_result = get_quantiles(hour_bucket)
+ assert cached_result == CachedQuantiles(quantiles=test_quantiles, max_value=test_max)
+
+ # Wait for expiration
+ time.sleep(1.1)
+
+ # Should be gone now
+ cached_result = get_quantiles(hour_bucket)
+ assert cached_result is None
+ assert not redis_client.exists(cache_key)
+
+ def test_realistic_workflow_simulation(self):
+ """Simulate the actual scenario: p0-p50 and p50-p80 workflows starting together."""
+ durations = [
+ # Simulated cohort durations from database query
+ 100,
+ 150,
+ 200,
+ 250,
+ 300,
+ 350,
+ 400,
+ 450,
+ 500,
+ 550,
+ 600,
+ 650,
+ 700,
+ 750,
+ 800,
+ 850,
+ 900,
+ 950,
+ 1000,
+ 1100,
+ 1200,
+ 1300,
+ 1400,
+ 1500,
+ 1600,
+ 1700,
+ 1800,
+ 1900,
+ 2000,
+ ]
+ hour_bucket = "2024-01-15:17"
+
+ p0_p50_result = None
+ p50_p80_result = None
+ errors = []
+
+ def p0_p50_workflow():
+ """Simulate p0-p50 workflow calculating quantiles."""
+ nonlocal p0_p50_result
+ try:
+ cached = get_cached_quantiles_or_calculate(durations, hour_bucket)
+ if cached:
+ # Calculate p0-p50 thresholds
+ p50_index = 50 - 1 # quantiles[49] is p50
+ p0_p50_result = {"min_threshold_ms": 0, "max_threshold_ms": int(cached.quantiles[p50_index])}
+ except Exception as e:
+ errors.append(f"p0-p50 workflow error: {e}")
+
+ def p50_p80_workflow():
+ """Simulate p50-p80 workflow calculating quantiles."""
+ nonlocal p50_p80_result
+ try:
+ cached = get_cached_quantiles_or_calculate(durations, hour_bucket)
+ if cached:
+ # Calculate p50-p80 thresholds
+ p50_index = 50 - 1 # quantiles[49] is p50
+ p80_index = 80 - 1 # quantiles[79] is p80
+ p50_p80_result = {
+ "min_threshold_ms": int(cached.quantiles[p50_index]),
+ "max_threshold_ms": int(cached.quantiles[p80_index]),
+ }
+ except Exception as e:
+ errors.append(f"p50-p80 workflow error: {e}")
+
+ # Start both workflows simultaneously
+ threads = [threading.Thread(target=p0_p50_workflow), threading.Thread(target=p50_p80_workflow)]
+
+ for thread in threads:
+ thread.start()
+
+ for thread in threads:
+ thread.join(timeout=5) # 5 second timeout
+
+ # Verify no errors
+ assert len(errors) == 0, f"Workflow errors: {errors}"
+
+ # Both workflows should have results
+ assert p0_p50_result is not None, "p0-p50 workflow should have result"
+ assert p50_p80_result is not None, "p50-p80 workflow should have result"
+
+ # Critical test: No overlapping thresholds (the bug we fixed)
+ assert p0_p50_result["max_threshold_ms"] == p50_p80_result["min_threshold_ms"], (
+ f"Threshold overlap detected! p0-p50 max: {p0_p50_result['max_threshold_ms']}, "
+ f"p50-p80 min: {p50_p80_result['min_threshold_ms']}"
+ )
+
+ # Verify logical order
+ assert p0_p50_result["min_threshold_ms"] == 0
+ assert p0_p50_result["max_threshold_ms"] < p50_p80_result["max_threshold_ms"]
+
+ def test_high_concurrency_stress_test(self):
+ """Stress test with many concurrent workers to verify robustness."""
+ durations = list(range(50, 500, 5)) # Large dataset
+ hour_bucket = "2024-01-15:18"
+ num_workers = 10
+
+ results = []
+ errors = []
+
+ def stress_worker(worker_id):
+ """Worker that tries to get quantiles under high concurrency."""
+ try:
+ # Add small random delay to increase contention
+ time.sleep(0.001 * (worker_id % 3))
+ result = get_cached_quantiles_or_calculate(durations, hour_bucket, max_retries=5)
+ return worker_id, result, time.time()
+ except Exception as e:
+ errors.append(f"Worker {worker_id}: {e}")
+ return worker_id, None, time.time()
+
+ start_time = time.time()
+
+ with ThreadPoolExecutor(max_workers=num_workers) as executor:
+ futures = [executor.submit(stress_worker, i) for i in range(num_workers)]
+
+ for future in as_completed(futures):
+ worker_id, result, finish_time = future.result()
+ results.append((worker_id, result, finish_time))
+
+ end_time = time.time()
+
+ # Verify no errors
+ assert len(errors) == 0, f"Stress test errors: {errors}"
+
+ # All workers completed successfully
+ assert len(results) == num_workers
+
+ # All got same result
+ first_result = results[0][1]
+ assert first_result is not None
+
+ for worker_id, result, _ in results:
+ assert result == first_result, f"Worker {worker_id} got inconsistent result"
+
+ # Test completed in reasonable time (should not be blocked excessively)
+ total_time = end_time - start_time
+ assert total_time < 10, f"Stress test took too long: {total_time}s"
diff --git a/posthog/temporal/messaging/test/test_quantiles_storage.py b/posthog/temporal/messaging/test/test_quantiles_storage.py
new file mode 100644
index 000000000000..7a5c2d7fa97f
--- /dev/null
+++ b/posthog/temporal/messaging/test/test_quantiles_storage.py
@@ -0,0 +1,292 @@
+"""
+Tests for quantiles storage module.
+
+Tests the mathematical correctness of percentile calculations and Redis caching logic.
+"""
+
+import json
+import statistics
+
+import pytest
+from unittest.mock import Mock, patch
+
+from posthog.temporal.messaging.quantiles_storage import (
+ CachedQuantiles,
+ _get_cache_key,
+ _get_current_hour_bucket,
+ _get_lock_key,
+ get_cached_quantiles_or_calculate,
+ get_quantiles,
+ store_quantiles,
+)
+
+
+class TestQuantilesMath:
+ """Test the mathematical correctness of percentile calculations."""
+
+ @pytest.mark.parametrize(
+ "durations,description",
+ [
+ (list(range(1, 101)), "sequential 1-100"),
+ (
+ [100, 200, 300, 500, 800, 1000, 1500, 2000, 3000, 5000, 8000, 10000, 15000, 20000, 30000],
+ "realistic durations",
+ ),
+ ([10, 20, 30, 40, 50, 60, 70, 80, 90, 100], "known dataset"),
+ ([1000] * 50, "identical values"),
+ ([100, 900], "two values"),
+ (
+ [
+ 50,
+ 75,
+ 100,
+ 125,
+ 150,
+ 200,
+ 250,
+ 300,
+ 350,
+ 400,
+ 450,
+ 500,
+ 550,
+ 600,
+ 650,
+ 700,
+ 750,
+ 800,
+ 850,
+ 900,
+ 1000,
+ 1200,
+ 1400,
+ 1600,
+ 1800,
+ 2000,
+ 2500,
+ 3000,
+ 3500,
+ 4000,
+ 5000,
+ 6000,
+ 8000,
+ 10000,
+ 15000,
+ 20000,
+ ],
+ "real scenario cohort durations",
+ ),
+ ],
+ )
+ def test_percentile_math_correctness(self, durations, description):
+ """Test mathematical correctness of percentile calculations with various datasets."""
+ quantiles = statistics.quantiles(durations, n=100, method="inclusive")
+
+ # Test tier boundaries don't overlap
+ p50_value = quantiles[50 - 1]
+ p80_value = quantiles[80 - 1]
+ p90_value = quantiles[90 - 1]
+
+ p0_min = 0
+ p50_int = int(p50_value)
+ p80_int = int(p80_value)
+ p90_int = int(p90_value)
+ p100_int = int(max(durations))
+
+ # Verify tier boundaries don't overlap
+ tier_boundaries = [
+ ("p0-p50", p0_min, p50_int),
+ ("p50-p80", p50_int, p80_int),
+ ("p80-p90", p80_int, p90_int),
+ ("p90-p100", p90_int, p100_int),
+ ]
+
+ for i, (tier_name, tier_min, tier_max) in enumerate(tier_boundaries):
+ # Each tier should have min <= max
+ assert tier_min <= tier_max, f"{description} - {tier_name}: min ({tier_min}) should be <= max ({tier_max})"
+
+ # Adjacent tiers should connect seamlessly
+ if i > 0:
+ prev_tier_name, prev_tier_min, prev_tier_max = tier_boundaries[i - 1]
+ assert prev_tier_max == tier_min, (
+ f"{description} - {prev_tier_name} max ({prev_tier_max}) should equal {tier_name} min ({tier_min})"
+ )
+
+ # Test monotonic increase of percentiles
+ test_percentiles = [10, 25, 50, 75, 90, 95, 99]
+ prev_value = 0
+ for p in test_percentiles:
+ current_value = quantiles[p - 1]
+ assert prev_value <= current_value, (
+ f"{description} - p{p - 10 if p > 10 else 0} ({prev_value}) should be <= p{p} ({current_value})"
+ )
+ prev_value = current_value
+
+ # Verify p100 is the actual maximum
+ p99 = quantiles[99 - 1]
+ p100 = max(durations)
+ assert p99 <= p100, f"{description} - p99 ({p99}) should be <= p100 ({p100})"
+
+
+class TestQuantilesCache:
+ """Test Redis caching functionality."""
+
+ def test_cache_key_generation(self):
+ """Test cache key generation is consistent."""
+ hour_bucket = "2024-01-15:14"
+ expected_key = "duration_quantiles:2024-01-15:14"
+ assert _get_cache_key(hour_bucket) == expected_key
+
+ def test_lock_key_generation(self):
+ """Test lock key generation is consistent."""
+ hour_bucket = "2024-01-15:14"
+ expected_key = "duration_quantiles_lock:2024-01-15:14"
+ assert _get_lock_key(hour_bucket) == expected_key
+
+ def test_current_hour_bucket_format(self):
+ """Test 2-hour bucket format is correct."""
+ with patch("posthog.temporal.messaging.quantiles_storage.dt") as mock_dt:
+ # Test hour 14 (even) -> bucket starts at 14
+ mock_now = Mock()
+ mock_now.hour = 14
+ mock_now.strftime.return_value = "2024-01-15:14"
+ mock_dt.datetime.now.return_value = mock_now
+
+ result = _get_current_hour_bucket()
+ assert result == "2024-01-15:14"
+
+ # Test hour 15 (odd) -> bucket starts at 14
+ mock_now.hour = 15
+ mock_now.strftime.return_value = "2024-01-15:14"
+
+ result = _get_current_hour_bucket()
+ assert result == "2024-01-15:14"
+
+ mock_dt.datetime.now.assert_called_with(mock_dt.UTC)
+
+ @patch("posthog.temporal.messaging.quantiles_storage.get_client")
+ def test_store_quantiles_success(self, mock_get_client):
+ """Test successful quantile storage."""
+ mock_redis = Mock()
+ mock_redis.set.return_value = True # Lock acquired
+ mock_redis.exists.return_value = False # No existing cache
+ mock_get_client.return_value = mock_redis
+
+ quantiles = [100.0, 200.0, 300.0]
+ result = store_quantiles(quantiles, max_value=400, hour_bucket="2024-01-15:14")
+
+ assert result is True
+ mock_redis.set.assert_called_once() # Lock
+ mock_redis.setex.assert_called_once() # Store data
+ # Lock release uses an atomic Lua compare-and-delete via redis_client.eval
+ mock_redis.eval.assert_called_once()
+ # Persisted payload is the new dict format including max_value
+ stored_payload = json.loads(mock_redis.setex.call_args.args[2])
+ assert stored_payload == {"quantiles": quantiles, "max_value": 400}
+
+ @patch("posthog.temporal.messaging.quantiles_storage.get_client")
+ def test_store_quantiles_lock_contention(self, mock_get_client):
+ """Test behavior when lock is already held."""
+ mock_redis = Mock()
+ mock_redis.set.return_value = False # Lock not acquired
+ mock_get_client.return_value = mock_redis
+
+ quantiles = [100.0, 200.0, 300.0]
+ result = store_quantiles(quantiles, max_value=400, hour_bucket="2024-01-15:14")
+
+ assert result is False
+ mock_redis.setex.assert_not_called() # Should not store
+
+ @patch("posthog.temporal.messaging.quantiles_storage.get_client")
+ def test_get_quantiles_hit(self, mock_get_client):
+ """Test successful cache retrieval."""
+ mock_redis = Mock()
+ cached_data = json.dumps({"quantiles": [100.0, 200.0, 300.0], "max_value": 400})
+ mock_redis.get.return_value = cached_data
+ mock_get_client.return_value = mock_redis
+
+ result = get_quantiles("2024-01-15:14")
+
+ assert result == CachedQuantiles(quantiles=[100.0, 200.0, 300.0], max_value=400)
+
+ @patch("posthog.temporal.messaging.quantiles_storage.get_client")
+ def test_get_quantiles_miss(self, mock_get_client):
+ """Test cache miss."""
+ mock_redis = Mock()
+ mock_redis.get.return_value = None
+ mock_get_client.return_value = mock_redis
+
+ result = get_quantiles("2024-01-15:14")
+
+ assert result is None
+
+ @patch("posthog.temporal.messaging.quantiles_storage.get_client")
+ def test_get_quantiles_legacy_format_is_treated_as_miss(self, mock_get_client):
+ """Legacy bare-list cache entries should be discarded so callers recalculate
+ with the new max_value contract instead of silently mixing formats."""
+ mock_redis = Mock()
+ mock_redis.get.return_value = json.dumps([100.0, 200.0, 300.0])
+ mock_get_client.return_value = mock_redis
+
+ result = get_quantiles("2024-01-15:14")
+
+ assert result is None
+ mock_redis.delete.assert_called_once()
+
+ @patch("posthog.temporal.messaging.quantiles_storage.get_client")
+ @patch("posthog.temporal.messaging.quantiles_storage.time.sleep")
+ def test_get_or_calculate_race_condition_handling(self, mock_sleep, mock_get_client):
+ """Test race condition handling with retry logic."""
+ mock_redis = Mock()
+ mock_get_client.return_value = mock_redis
+
+ with patch("statistics.quantiles", return_value=[100.0, 200.0, 300.0]):
+ cached_payload = json.dumps({"quantiles": [100.0, 200.0, 300.0], "max_value": 250})
+ # First call: cache miss for current bucket
+ # Second call: cache miss for previous bucket
+ # Third call: lock contention, then cache hit after retry
+ mock_redis.get.side_effect = [
+ None, # Initial cache miss (current hour)
+ None, # Previous hour cache miss
+ None, # Still miss after first store attempt fails
+ cached_payload, # Hit after retry
+ ]
+ mock_redis.set.side_effect = [False, True] # First lock fails, second succeeds
+ mock_redis.exists.return_value = False
+
+ durations = [50, 100, 150, 200, 250]
+ result = get_cached_quantiles_or_calculate(durations, "2024-01-15:14", max_retries=2)
+
+ assert result == CachedQuantiles(quantiles=[100.0, 200.0, 300.0], max_value=250)
+ assert mock_sleep.call_count == 1 # Should retry once
+
+ def test_race_condition_scenario_realistic(self):
+ """Test realistic race condition scenario with multiple workflows."""
+ # This test simulates what happens when p0-p50 and p50-p80 workflows
+ # start at the same time and both try to calculate quantiles
+
+ durations = list(range(100, 1000, 10)) # Realistic duration spread
+ cached_payload = json.dumps({"quantiles": [200.0, 400.0, 600.0], "max_value": 990})
+
+ with patch("posthog.temporal.messaging.quantiles_storage.get_client") as mock_get_client:
+ mock_redis = Mock()
+ mock_get_client.return_value = mock_redis
+ mock_redis.exists.return_value = False
+ # Workflow 1: both current and previous-hour buckets miss → calculates and stores;
+ # Workflow 2: current-hour bucket hits the populated cache.
+ mock_redis.get.side_effect = [
+ None, # workflow 1: current bucket miss
+ None, # workflow 1: previous-hour fallback miss
+ cached_payload, # workflow 2: current bucket hit
+ ]
+ mock_redis.set.side_effect = [True] # workflow 1 acquires lock
+
+ # First workflow calculates and stores
+ result1 = get_cached_quantiles_or_calculate(durations, "2024-01-15:14")
+
+ # Second workflow gets from cache
+ result2 = get_cached_quantiles_or_calculate(durations, "2024-01-15:14")
+
+ # Both should be populated; workflow 2's result is the canonical cached value
+ assert result1 is not None
+ assert result2 == CachedQuantiles(quantiles=[200.0, 400.0, 600.0], max_value=990)
diff --git a/posthog/temporal/messaging/test/test_realtime_cohort_calculation_workflow.py b/posthog/temporal/messaging/test/test_realtime_cohort_calculation_workflow.py
index 8a47f6f92551..83f95df55899 100644
--- a/posthog/temporal/messaging/test/test_realtime_cohort_calculation_workflow.py
+++ b/posthog/temporal/messaging/test/test_realtime_cohort_calculation_workflow.py
@@ -1,10 +1,12 @@
import os
-import statistics
import pytest
from unittest.mock import Mock, patch
-from posthog.temporal.messaging.realtime_cohort_calculation_workflow import flush_kafka_batch
+from posthog.temporal.messaging.realtime_cohort_calculation_workflow import (
+ _batch_update_cohort_metrics,
+ flush_kafka_batch,
+)
from posthog.temporal.messaging.realtime_cohort_calculation_workflow_coordinator import (
CohortSelectionActivityInput,
QueryPercentileThresholds,
@@ -944,6 +946,8 @@ class TestQueryPercentileThresholdsActivity:
@pytest.mark.asyncio
async def test_get_percentile_thresholds_defaults_to_p0_p100(self):
"""Should default to p0-p100 when percentiles not specified."""
+ from posthog.temporal.messaging.quantiles_storage import CachedQuantiles
+
inputs = QueryPercentileThresholdsInput() # No percentiles specified
# Mock cohort queryset with duration data (in milliseconds)
@@ -954,12 +958,18 @@ class TestQueryPercentileThresholdsActivity:
mock_queryset.values_list.return_value = mock_durations
mock_cohort.objects.filter.return_value = mock_queryset
- result = await get_query_percentile_thresholds_activity(inputs)
+ # Pin the cache lookup so the test isn't affected by Redis state from
+ # previous tests in the session.
+ with patch(
+ "posthog.temporal.messaging.realtime_cohort_calculation_workflow_coordinator.get_cached_quantiles_or_calculate",
+ return_value=CachedQuantiles(quantiles=[float(d) for d in mock_durations] * 10, max_value=5000),
+ ):
+ result = await get_query_percentile_thresholds_activity(inputs)
assert result is not None
- # p0 is treated as a lower bound of 0, p100 should be the maximum observed value (5000)
+ # p0 is treated as a lower bound of 0, p100 should be the cached max value (5000)
assert result.min_threshold_ms == 0 # p0 (lower bound)
- assert result.max_threshold_ms == 5000 # p100 (max value)
+ assert result.max_threshold_ms == 5000 # p100 (cached max)
@pytest.mark.asyncio
@pytest.mark.django_db
@@ -989,14 +999,21 @@ class TestQueryPercentileThresholdsActivity:
mock_queryset.values_list.return_value = [1000]
mock_cohort.objects.filter.return_value = mock_queryset
- result = await get_query_percentile_thresholds_activity(inputs)
+ # Patch the imported reference (not the source module) and force a cache miss
+ # so the activity falls through to the insufficient-data check inside
+ # get_cached_quantiles_or_calculate.
+ with patch(
+ "posthog.temporal.messaging.realtime_cohort_calculation_workflow_coordinator.get_cached_quantiles_or_calculate",
+ return_value=None,
+ ):
+ result = await get_query_percentile_thresholds_activity(inputs)
assert result is None
@pytest.mark.asyncio
@pytest.mark.django_db
async def test_get_percentile_thresholds_statistics_error(self):
- """Should return None when statistics.quantiles raises an error."""
+ """Should return None when quantiles calculation fails."""
inputs = QueryPercentileThresholdsInput(min_percentile=75.0, max_percentile=90.0)
# Mock data that will cause statistics error (too few points for percentile calculation)
@@ -1005,8 +1022,11 @@ class TestQueryPercentileThresholdsActivity:
mock_queryset.values_list.return_value = [100, 200] # Valid data
mock_cohort.objects.filter.return_value = mock_queryset
- # Mock statistics.quantiles to raise StatisticsError
- with patch("statistics.quantiles", side_effect=statistics.StatisticsError("Insufficient data")):
+ # Mock the quantiles cache to return None (indicating calculation failure)
+ with patch(
+ "posthog.temporal.messaging.realtime_cohort_calculation_workflow_coordinator.get_cached_quantiles_or_calculate",
+ return_value=None,
+ ):
result = await get_query_percentile_thresholds_activity(inputs)
assert result is None
@@ -1014,7 +1034,7 @@ class TestQueryPercentileThresholdsActivity:
@pytest.mark.asyncio
@pytest.mark.django_db
async def test_get_percentile_thresholds_invalid_data_types(self):
- """Should return None when Cohort duration data has invalid types."""
+ """Should return None when quantiles calculation fails due to invalid data."""
inputs = QueryPercentileThresholdsInput(min_percentile=80.0, max_percentile=95.0)
# Invalid duration data format (non-numeric values)
@@ -1023,7 +1043,12 @@ class TestQueryPercentileThresholdsActivity:
mock_queryset.values_list.return_value = ["invalid-duration", "another-invalid"]
mock_cohort.objects.filter.return_value = mock_queryset
- result = await get_query_percentile_thresholds_activity(inputs)
+ # Mock the quantiles cache to return None (indicating calculation failure due to invalid data)
+ with patch(
+ "posthog.temporal.messaging.realtime_cohort_calculation_workflow_coordinator.get_cached_quantiles_or_calculate",
+ return_value=None,
+ ):
+ result = await get_query_percentile_thresholds_activity(inputs)
assert result is None
@@ -1062,7 +1087,7 @@ class TestQueryPercentileThresholdsActivity:
@pytest.mark.asyncio
@pytest.mark.django_db
async def test_get_percentile_thresholds_type_error(self):
- """Should return None when data contains non-numeric values that cause TypeError."""
+ """Should return None when quantiles calculation fails due to type errors."""
inputs = QueryPercentileThresholdsInput(min_percentile=70.0, max_percentile=85.0)
# Mock data that will cause TypeError during max() operation
@@ -1072,7 +1097,12 @@ class TestQueryPercentileThresholdsActivity:
mock_queryset.values_list.return_value = [100, None, 200, 300]
mock_cohort.objects.filter.return_value = mock_queryset
- result = await get_query_percentile_thresholds_activity(inputs)
+ # Mock the quantiles cache to return None (indicating calculation failure due to type errors)
+ with patch(
+ "posthog.temporal.messaging.realtime_cohort_calculation_workflow_coordinator.get_cached_quantiles_or_calculate",
+ return_value=None,
+ ):
+ result = await get_query_percentile_thresholds_activity(inputs)
assert result is None
@@ -1428,3 +1458,167 @@ class TestCoordinatorWorkflowInsufficientData:
workflow_logger.info.assert_any_call(
"Duration percentile filtering p0.0-p90.0: disabled (no historical query data)"
)
+
+
+class TestBatchUpdateCohortMetrics:
+ """Tests for _batch_update_cohort_metrics timestamp handling regression."""
+
+ @pytest.mark.asyncio
+ @pytest.mark.django_db
+ async def test_batch_update_cohort_metrics_timestamp_fix(self):
+ """
+ Regression test for timestamp bug fix.
+
+ - Asserts last_backfill_person_properties_at is NOT updated
+ - Asserts last_realtime_cohort_calculation_at IS updated
+ - Asserts last_calculation_duration_ms updates respect the DURATION_UPDATE_RELATIVE_THRESHOLD
+ """
+ from datetime import timedelta
+
+ from django.utils import timezone
+
+ from asgiref.sync import sync_to_async
+
+ from posthog.models.cohort.cohort import Cohort, CohortType
+ from posthog.models.organization import Organization
+ from posthog.models.team.team import Team
+
+ # Create test organization and team
+ organization = await sync_to_async(Organization.objects.create)(name="Test Organization")
+ team = await sync_to_async(Team.objects.create)(name="Test Team", organization=organization)
+
+ # Set fixed timestamps for comparison
+ initial_backfill_time = timezone.now() - timedelta(hours=24)
+ initial_realtime_time = timezone.now() - timedelta(hours=12)
+
+ # Create test cohorts with various duration scenarios
+ cohort1 = await sync_to_async(Cohort.objects.create)(
+ name="Cohort 1",
+ team=team,
+ cohort_type=CohortType.REALTIME,
+ last_backfill_person_properties_at=initial_backfill_time,
+ last_realtime_cohort_calculation_at=initial_realtime_time,
+ last_calculation_duration_ms=1000, # 1 second
+ )
+
+ cohort2 = await sync_to_async(Cohort.objects.create)(
+ name="Cohort 2",
+ team=team,
+ cohort_type=CohortType.REALTIME,
+ last_backfill_person_properties_at=initial_backfill_time,
+ last_realtime_cohort_calculation_at=initial_realtime_time,
+ last_calculation_duration_ms=2000, # 2 seconds
+ )
+
+ # Prepare duration updates
+ # Cohort 1: Small change below threshold (should NOT update duration)
+ new_duration_1 = 1100 # 10% change, below DURATION_UPDATE_RELATIVE_THRESHOLD (25%)
+
+ # Cohort 2: Large change above threshold (should update duration)
+ new_duration_2 = 3000 # 50% change, above DURATION_UPDATE_RELATIVE_THRESHOLD (25%)
+
+ cohort_durations = {cohort1.id: new_duration_1, cohort2.id: new_duration_2}
+
+ # Execute the function
+ duration_updates_count = await _batch_update_cohort_metrics(cohort_durations)
+
+ # Refresh cohorts from database
+ await sync_to_async(cohort1.refresh_from_db)()
+ await sync_to_async(cohort2.refresh_from_db)()
+
+ # Assert last_backfill_person_properties_at is NOT updated
+ assert cohort1.last_backfill_person_properties_at == initial_backfill_time
+ assert cohort2.last_backfill_person_properties_at == initial_backfill_time
+
+ # Assert last_realtime_cohort_calculation_at IS updated for both
+ assert cohort1.last_realtime_cohort_calculation_at > initial_realtime_time
+ assert cohort2.last_realtime_cohort_calculation_at > initial_realtime_time
+
+ # Assert duration updates respect the DURATION_UPDATE_RELATIVE_THRESHOLD
+ # Cohort 1: small change, should NOT update duration
+ assert cohort1.last_calculation_duration_ms == 1000 # Original value
+
+ # Cohort 2: large change, should update duration
+ assert cohort2.last_calculation_duration_ms == 3000 # New value
+
+ # Assert correct count of duration updates
+ assert duration_updates_count == 1 # Only cohort2 should have had duration updated
+
+ @pytest.mark.asyncio
+ @pytest.mark.django_db
+ async def test_batch_update_cohort_metrics_first_calculation(self):
+ """Test that first calculation always updates duration regardless of threshold."""
+ from asgiref.sync import sync_to_async
+
+ from posthog.models.cohort.cohort import Cohort, CohortType
+ from posthog.models.organization import Organization
+ from posthog.models.team.team import Team
+
+ # Create test organization and team
+ organization = await sync_to_async(Organization.objects.create)(name="Test Organization")
+ team = await sync_to_async(Team.objects.create)(name="Test Team", organization=organization)
+
+ cohort = await sync_to_async(Cohort.objects.create)(
+ name="New Cohort",
+ team=team,
+ cohort_type=CohortType.REALTIME,
+ last_calculation_duration_ms=None, # No previous calculation
+ )
+
+ initial_realtime_time = cohort.last_realtime_cohort_calculation_at
+
+ # Prepare first duration
+ first_duration = 5000 # 5 seconds
+ cohort_durations = {cohort.id: first_duration}
+
+ # Execute the function
+ duration_updates_count = await _batch_update_cohort_metrics(cohort_durations)
+
+ # Refresh cohort from database
+ await sync_to_async(cohort.refresh_from_db)()
+
+ # Assert last_realtime_cohort_calculation_at IS updated
+ assert cohort.last_realtime_cohort_calculation_at != initial_realtime_time
+
+ # Assert duration is updated for first calculation
+ assert cohort.last_calculation_duration_ms == 5000
+
+ # Assert correct count
+ assert duration_updates_count == 1
+
+ @pytest.mark.asyncio
+ @pytest.mark.django_db
+ async def test_batch_update_cohort_metrics_zero_previous_duration(self):
+ """Test that cohorts with zero previous duration always get updated."""
+ from asgiref.sync import sync_to_async
+
+ from posthog.models.cohort.cohort import Cohort, CohortType
+ from posthog.models.organization import Organization
+ from posthog.models.team.team import Team
+
+ # Create test organization and team
+ organization = await sync_to_async(Organization.objects.create)(name="Test Organization")
+ team = await sync_to_async(Team.objects.create)(name="Test Team", organization=organization)
+
+ cohort = await sync_to_async(Cohort.objects.create)(
+ name="Zero Duration Cohort",
+ team=team,
+ cohort_type=CohortType.REALTIME,
+ last_calculation_duration_ms=0, # Zero previous duration
+ )
+
+ # Prepare new duration
+ new_duration = 100 # Small value
+ cohort_durations = {cohort.id: new_duration}
+
+ # Execute the function
+ duration_updates_count = await _batch_update_cohort_metrics(cohort_durations)
+
+ # Refresh cohort from database
+ await sync_to_async(cohort.refresh_from_db)()
+
+ # Assert duration is updated even though change is small (because previous was 0)
+ assert cohort.last_calculation_duration_ms == 100
+
+ # Assert correct count
+ assert duration_updates_count == 1
diff --git a/posthog/temporal/messaging/test/test_threshold_calculation_math.py b/posthog/temporal/messaging/test/test_threshold_calculation_math.py
new file mode 100644
index 000000000000..2940434ef501
--- /dev/null
+++ b/posthog/temporal/messaging/test/test_threshold_calculation_math.py
@@ -0,0 +1,257 @@
+"""
+Tests for mathematical correctness of threshold calculations with caching.
+
+Verifies that the integration between quantiles caching and threshold calculation
+produces consistent, non-overlapping tier boundaries.
+"""
+
+import statistics
+
+import pytest
+from unittest.mock import Mock, patch
+
+from posthog.temporal.messaging.quantiles_storage import CachedQuantiles
+from posthog.temporal.messaging.realtime_cohort_calculation_workflow_coordinator import (
+ QueryPercentileThresholdsInput,
+ calculate_percentile_thresholds,
+)
+
+
+class TestThresholdCalculationMath:
+ """Test mathematical correctness of threshold calculations."""
+
+ @pytest.mark.parametrize(
+ "durations,description",
+ [
+ (
+ [
+ 100,
+ 150,
+ 200,
+ 250,
+ 300,
+ 350,
+ 400,
+ 450,
+ 500,
+ 550,
+ 600,
+ 650,
+ 700,
+ 750,
+ 800,
+ 850,
+ 900,
+ 950,
+ 1000,
+ 1050,
+ 1100,
+ 1200,
+ 1300,
+ 1400,
+ 1500,
+ 1600,
+ 1700,
+ 1800,
+ 1900,
+ 2000,
+ 2200,
+ 2400,
+ 2600,
+ 2800,
+ 3000,
+ 3200,
+ 3400,
+ 3600,
+ 3800,
+ 4000,
+ 4500,
+ 5000,
+ 5500,
+ 6000,
+ 6500,
+ 7000,
+ 7500,
+ 8000,
+ 8500,
+ 9000,
+ 10000,
+ 12000,
+ 14000,
+ 16000,
+ 18000,
+ 20000,
+ 25000,
+ 30000,
+ 40000,
+ 50000,
+ ],
+ "realistic cohort durations",
+ ),
+ (
+ [
+ 100,
+ 150,
+ 200,
+ 250,
+ 300,
+ 350,
+ 400,
+ 450,
+ 498,
+ 501,
+ 520,
+ 540,
+ 560,
+ 580,
+ 601,
+ 650,
+ 700,
+ 800,
+ 900,
+ 1000,
+ 1200,
+ 1500,
+ 2000,
+ ],
+ "problematic scenario from bug report",
+ ),
+ ],
+ )
+ @pytest.mark.asyncio
+ async def test_tier_boundaries_no_overlap_with_caching(self, durations, description):
+ """Test that cached quantiles produce non-overlapping tier boundaries."""
+ expected_quantiles = statistics.quantiles(durations, n=100, method="inclusive")
+ expected_max = int(max(durations))
+
+ with patch("posthog.temporal.messaging.realtime_cohort_calculation_workflow_coordinator.Cohort") as mock_cohort:
+ mock_queryset = Mock()
+ mock_queryset.values_list.return_value = durations
+ mock_cohort.objects.filter.return_value = mock_queryset
+
+ with patch(
+ "posthog.temporal.messaging.realtime_cohort_calculation_workflow_coordinator.get_cached_quantiles_or_calculate"
+ ) as mock_get_quantiles:
+ mock_get_quantiles.return_value = CachedQuantiles(quantiles=expected_quantiles, max_value=expected_max)
+
+ # Calculate thresholds for all tiers
+ p0_p50_input = QueryPercentileThresholdsInput(min_percentile=0.0, max_percentile=50.0)
+ p50_p80_input = QueryPercentileThresholdsInput(min_percentile=50.0, max_percentile=80.0)
+ p80_p90_input = QueryPercentileThresholdsInput(min_percentile=80.0, max_percentile=90.0)
+ p90_p100_input = QueryPercentileThresholdsInput(min_percentile=90.0, max_percentile=100.0)
+
+ p0_p50_thresholds = await calculate_percentile_thresholds(p0_p50_input)
+ p50_p80_thresholds = await calculate_percentile_thresholds(p50_p80_input)
+ p80_p90_thresholds = await calculate_percentile_thresholds(p80_p90_input)
+ p90_p100_thresholds = await calculate_percentile_thresholds(p90_p100_input)
+
+ # Verify all calculations succeeded
+ assert p0_p50_thresholds is not None
+ assert p50_p80_thresholds is not None
+ assert p80_p90_thresholds is not None
+ assert p90_p100_thresholds is not None
+
+ # Verify tier boundaries align perfectly (no gaps or overlaps)
+ assert p0_p50_thresholds.min_threshold_ms == 0 # p0 is always 0
+ assert p0_p50_thresholds.max_threshold_ms == p50_p80_thresholds.min_threshold_ms, (
+ f"{description} - p0-p50 max ({p0_p50_thresholds.max_threshold_ms}) should equal p50-p80 min ({p50_p80_thresholds.min_threshold_ms})"
+ )
+ assert p50_p80_thresholds.max_threshold_ms == p80_p90_thresholds.min_threshold_ms, (
+ f"{description} - p50-p80 max ({p50_p80_thresholds.max_threshold_ms}) should equal p80-p90 min ({p80_p90_thresholds.min_threshold_ms})"
+ )
+ assert p80_p90_thresholds.max_threshold_ms == p90_p100_thresholds.min_threshold_ms, (
+ f"{description} - p80-p90 max ({p80_p90_thresholds.max_threshold_ms}) should equal p90-p100 min ({p90_p100_thresholds.min_threshold_ms})"
+ )
+
+ # Verify p100 is the actual maximum
+ assert p90_p100_thresholds.max_threshold_ms == max(durations), (
+ f"{description} - p100 value ({p90_p100_thresholds.max_threshold_ms}) should equal max duration ({max(durations)})"
+ )
+
+ @pytest.mark.asyncio
+ async def test_consistent_calculations_across_calls(self):
+ """Test that multiple calls with same cache return identical results."""
+ durations = list(range(100, 2000, 50)) # Clean test data
+
+ expected_quantiles = statistics.quantiles(durations, n=100, method="inclusive")
+ expected_max = int(max(durations))
+
+ with patch("posthog.temporal.messaging.realtime_cohort_calculation_workflow_coordinator.Cohort") as mock_cohort:
+ mock_queryset = Mock()
+ mock_queryset.values_list.return_value = durations
+ mock_cohort.objects.filter.return_value = mock_queryset
+
+ with patch(
+ "posthog.temporal.messaging.realtime_cohort_calculation_workflow_coordinator.get_cached_quantiles_or_calculate"
+ ) as mock_get_quantiles:
+ # Ensure cache returns same quantiles every time
+ mock_get_quantiles.return_value = CachedQuantiles(quantiles=expected_quantiles, max_value=expected_max)
+
+ # Multiple workflows calculating p50-p80 thresholds
+ input_data = QueryPercentileThresholdsInput(min_percentile=50.0, max_percentile=80.0)
+
+ result1 = await calculate_percentile_thresholds(input_data)
+ result2 = await calculate_percentile_thresholds(input_data)
+ result3 = await calculate_percentile_thresholds(input_data)
+
+ # All results should be identical
+ assert result1 is not None
+ assert result2 is not None
+ assert result3 is not None
+ assert result1.min_threshold_ms == result2.min_threshold_ms == result3.min_threshold_ms
+ assert result1.max_threshold_ms == result2.max_threshold_ms == result3.max_threshold_ms
+
+ # Cache should only be called once per calculation (or multiple times but returning same data)
+ assert mock_get_quantiles.call_count >= 3
+
+ @pytest.mark.asyncio
+ async def test_percentile_edge_cases(self):
+ """Test edge cases in percentile calculations."""
+ durations = [500, 1000, 1500] # Minimal data
+
+ expected_quantiles = statistics.quantiles(durations, n=100, method="inclusive")
+ expected_max = int(max(durations))
+
+ with patch("posthog.temporal.messaging.realtime_cohort_calculation_workflow_coordinator.Cohort") as mock_cohort:
+ mock_queryset = Mock()
+ mock_queryset.values_list.return_value = durations
+ mock_cohort.objects.filter.return_value = mock_queryset
+
+ with patch(
+ "posthog.temporal.messaging.realtime_cohort_calculation_workflow_coordinator.get_cached_quantiles_or_calculate"
+ ) as mock_get_quantiles:
+ mock_get_quantiles.return_value = CachedQuantiles(quantiles=expected_quantiles, max_value=expected_max)
+
+ # Test p0 edge case
+ p0_input = QueryPercentileThresholdsInput(min_percentile=0.0, max_percentile=10.0)
+ p0_result = await calculate_percentile_thresholds(p0_input)
+ assert p0_result is not None
+ assert p0_result.min_threshold_ms == 0 # p0 should always be 0
+
+ # Test p100 edge case
+ p100_input = QueryPercentileThresholdsInput(min_percentile=99.0, max_percentile=100.0)
+ p100_result = await calculate_percentile_thresholds(p100_input)
+ assert p100_result is not None
+ assert p100_result.max_threshold_ms == max(durations) # p100 should be actual max
+
+ @pytest.mark.asyncio
+ async def test_threshold_calculation_with_cache_failure(self):
+ """Test threshold calculation when cache fails."""
+ durations = [100, 200, 300, 400, 500]
+
+ with patch("posthog.temporal.messaging.realtime_cohort_calculation_workflow_coordinator.Cohort") as mock_cohort:
+ mock_queryset = Mock()
+ mock_queryset.values_list.return_value = durations
+ mock_cohort.objects.filter.return_value = mock_queryset
+
+ with patch(
+ "posthog.temporal.messaging.realtime_cohort_calculation_workflow_coordinator.get_cached_quantiles_or_calculate"
+ ) as mock_get_quantiles:
+ # Simulate cache failure
+ mock_get_quantiles.return_value = None
+
+ input_data = QueryPercentileThresholdsInput(min_percentile=25.0, max_percentile=75.0)
+ result = await calculate_percentile_thresholds(input_data)
+
+ # Should return None when quantiles calculation fails
+ assert result is None