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.

chore(feature-flags): return frozen dataclasses instead of tuples (#76138)

Arno Hillend5d222348833
diff --git a/posthog/api/cohort.py b/posthog/api/cohort.py
index 5bc7638a01b9..04b1d0f2e873 100644
--- a/posthog/api/cohort.py
+++ b/posthog/api/cohort.py
@@ -5,6 +5,7 @@ import uuid
import hashlib
from collections.abc import Iterator
from copy import deepcopy
+from dataclasses import dataclass
from typing import Annotated, Any, ClassVar, Literal, Optional, Union, cast
from django.db.models import OuterRef, QuerySet, Subquery
@@ -184,11 +185,18 @@ def validate_filters_and_compute_realtime_support(
return filters_dict, current_cohort_type, [str(e)]
-def generate_cohort_filter_bytecode(filter_data: dict, team: Team) -> tuple[list[Any] | None, str | None, str | None]:
+@dataclass(frozen=True, kw_only=True, slots=True)
+class CohortFilterBytecodeResult:
+ bytecode: list[Any] | None = None
+ error: str | None = None
+ condition_hash: str | None = None
+
+
+def generate_cohort_filter_bytecode(filter_data: dict, team: Team) -> CohortFilterBytecodeResult:
"""
Generate HogQL bytecode for cohort filter data.
Similar to generate_template_bytecode in validation.py but for cohort-specific filters.
- Returns tuple of (bytecode, error, conditionHash)
+ Returns a CohortFilterBytecodeResult with bytecode, error, and condition_hash.
"""
try:
# Only treat behavioral as event matcher + optional event properties; unsupported values return None
@@ -196,34 +204,34 @@ def generate_cohort_filter_bytecode(filter_data: dict, team: Team) -> tuple[list
expr = build_behavioral_event_expr(filter_data, team)
# Unsupported behavioral filters return None → skip bytecode
if expr is None:
- return None, "Unsupported behavioral filter for realtime bytecode", None
+ return CohortFilterBytecodeResult(error="Unsupported behavioral filter for realtime bytecode")
bytecode = create_bytecode(expr, cohort_membership_supported=True, null_safe_comparisons=True).bytecode
condition_hash = None
if bytecode:
bytecode_str = json.dumps(bytecode, sort_keys=True)
condition_hash = hashlib.sha256(bytecode_str.encode()).hexdigest()[:16]
- return bytecode, None, condition_hash
+ return CohortFilterBytecodeResult(bytecode=bytecode, condition_hash=condition_hash)
# Check if it's a cohort filter referencing another cohort
if filter_data.get("type") == "cohort":
cohort_id = filter_data.get("value")
if cohort_id is None:
# If cohort_id is missing, don't generate bytecode
- return None, None, None
+ return CohortFilterBytecodeResult()
# Type narrowing: cohort_id is not None at this point, and should be int
try:
cohort_id_int = int(cohort_id)
except (ValueError, TypeError):
- return None, None, None
+ return CohortFilterBytecodeResult()
try:
referenced_cohort = Cohort.objects.get(team__project_id=team.project_id, id=cohort_id_int)
# Check if the referenced cohort is realtime
if referenced_cohort.cohort_type != CohortType.REALTIME:
# Don't generate bytecode for non-realtime cohort references
- return None, None, None
+ return CohortFilterBytecodeResult()
except Cohort.DoesNotExist:
# If cohort doesn't exist, don't generate bytecode
- return None, None, None
+ return CohortFilterBytecodeResult()
property_obj = Property(**filter_data)
expr = property_to_expr(property_obj, team)
@@ -236,10 +244,10 @@ def generate_cohort_filter_bytecode(filter_data: dict, team: Team) -> tuple[list
bytecode_str = json.dumps(bytecode, sort_keys=True)
condition_hash = hashlib.sha256(bytecode_str.encode()).hexdigest()[:16]
- return bytecode, None, condition_hash
+ return CohortFilterBytecodeResult(bytecode=bytecode, condition_hash=condition_hash)
except Exception as e:
logger.warning(f"Failed to generate bytecode for cohort filter: {e}")
- return None, str(e), None
+ return CohortFilterBytecodeResult(error=str(e))
class FilterBytecodeMixin(BaseModel):
@@ -253,15 +261,13 @@ class FilterBytecodeMixin(BaseModel):
if info and info.context:
team = info.context.get("team")
if team:
- bytecode, error, condition_hash = generate_cohort_filter_bytecode(
- self.model_dump(exclude_none=True), team
- )
- if bytecode:
- self.bytecode = bytecode
- if condition_hash:
- self.conditionHash = condition_hash
- if error:
- self.bytecode_error = error
+ result = generate_cohort_filter_bytecode(self.model_dump(exclude_none=True), team)
+ if result.bytecode:
+ self.bytecode = result.bytecode
+ if result.condition_hash:
+ self.conditionHash = result.condition_hash
+ if result.error:
+ self.bytecode_error = result.error
return self
diff --git a/posthog/api/test/test_cohort_bytecode.py b/posthog/api/test/test_cohort_bytecode.py
index 2529eb389328..9abc71271db6 100644
--- a/posthog/api/test/test_cohort_bytecode.py
+++ b/posthog/api/test/test_cohort_bytecode.py
@@ -538,16 +538,16 @@ class TestCohortBytecodeScenarios(APIBaseTest):
"value": 13,
"operator": "gt",
}
- bytecode_gt, error_gt, hash_gt = generate_cohort_filter_bytecode(filter_data_gt, self.team)
- self.assertIsNone(error_gt)
- self.assertIsNotNone(bytecode_gt)
+ result_gt = generate_cohort_filter_bytecode(filter_data_gt, self.team)
+ self.assertIsNone(result_gt.error)
+ self.assertIsNotNone(result_gt.bytecode)
# The bytecode should contain null-safe wrapping operations
- assert bytecode_gt is not None # Type narrowing for mypy
- self.assertIn("isNull", bytecode_gt) # isNull function calls
- self.assertIn(Operation.OR, bytecode_gt) # OR operation for combining null checks
- self.assertIn(Operation.JUMP_IF_FALSE, bytecode_gt) # Conditional jump
- self.assertIn(Operation.FALSE, bytecode_gt) # Return false if null
- self.assertIn(Operation.GT, bytecode_gt) # The actual GT comparison
+ assert result_gt.bytecode is not None # Type narrowing for mypy
+ self.assertIn("isNull", result_gt.bytecode) # isNull function calls
+ self.assertIn(Operation.OR, result_gt.bytecode) # OR operation for combining null checks
+ self.assertIn(Operation.JUMP_IF_FALSE, result_gt.bytecode) # Conditional jump
+ self.assertIn(Operation.FALSE, result_gt.bytecode) # Return false if null
+ self.assertIn(Operation.GT, result_gt.bytecode) # The actual GT comparison
# Test LT operator
filter_data_lt = {
@@ -556,14 +556,14 @@ class TestCohortBytecodeScenarios(APIBaseTest):
"value": 100,
"operator": "lt",
}
- bytecode_lt, error_lt, hash_lt = generate_cohort_filter_bytecode(filter_data_lt, self.team)
- self.assertIsNone(error_lt)
- self.assertIsNotNone(bytecode_lt)
- assert bytecode_lt is not None # Type narrowing for mypy
- self.assertIn("isNull", bytecode_lt)
- self.assertIn(Operation.OR, bytecode_lt)
- self.assertIn(Operation.JUMP_IF_FALSE, bytecode_lt)
- self.assertIn(Operation.LT, bytecode_lt)
+ result_lt = generate_cohort_filter_bytecode(filter_data_lt, self.team)
+ self.assertIsNone(result_lt.error)
+ self.assertIsNotNone(result_lt.bytecode)
+ assert result_lt.bytecode is not None # Type narrowing for mypy
+ self.assertIn("isNull", result_lt.bytecode)
+ self.assertIn(Operation.OR, result_lt.bytecode)
+ self.assertIn(Operation.JUMP_IF_FALSE, result_lt.bytecode)
+ self.assertIn(Operation.LT, result_lt.bytecode)
# Test GTE operator
filter_data_gte = {
@@ -572,14 +572,14 @@ class TestCohortBytecodeScenarios(APIBaseTest):
"value": 18,
"operator": "gte",
}
- bytecode_gte, error_gte, hash_gte = generate_cohort_filter_bytecode(filter_data_gte, self.team)
- self.assertIsNone(error_gte)
- self.assertIsNotNone(bytecode_gte)
- assert bytecode_gte is not None # Type narrowing for mypy
- self.assertIn("isNull", bytecode_gte)
- self.assertIn(Operation.OR, bytecode_gte)
- self.assertIn(Operation.JUMP_IF_FALSE, bytecode_gte)
- self.assertIn(Operation.GT_EQ, bytecode_gte)
+ result_gte = generate_cohort_filter_bytecode(filter_data_gte, self.team)
+ self.assertIsNone(result_gte.error)
+ self.assertIsNotNone(result_gte.bytecode)
+ assert result_gte.bytecode is not None # Type narrowing for mypy
+ self.assertIn("isNull", result_gte.bytecode)
+ self.assertIn(Operation.OR, result_gte.bytecode)
+ self.assertIn(Operation.JUMP_IF_FALSE, result_gte.bytecode)
+ self.assertIn(Operation.GT_EQ, result_gte.bytecode)
# Test LTE operator
filter_data_lte = {
@@ -588,14 +588,14 @@ class TestCohortBytecodeScenarios(APIBaseTest):
"value": 65,
"operator": "lte",
}
- bytecode_lte, error_lte, hash_lte = generate_cohort_filter_bytecode(filter_data_lte, self.team)
- self.assertIsNone(error_lte)
- self.assertIsNotNone(bytecode_lte)
- assert bytecode_lte is not None # Type narrowing for mypy
- self.assertIn("isNull", bytecode_lte)
- self.assertIn(Operation.OR, bytecode_lte)
- self.assertIn(Operation.JUMP_IF_FALSE, bytecode_lte)
- self.assertIn(Operation.LT_EQ, bytecode_lte)
+ result_lte = generate_cohort_filter_bytecode(filter_data_lte, self.team)
+ self.assertIsNone(result_lte.error)
+ self.assertIsNotNone(result_lte.bytecode)
+ assert result_lte.bytecode is not None # Type narrowing for mypy
+ self.assertIn("isNull", result_lte.bytecode)
+ self.assertIn(Operation.OR, result_lte.bytecode)
+ self.assertIn(Operation.JUMP_IF_FALSE, result_lte.bytecode)
+ self.assertIn(Operation.LT_EQ, result_lte.bytecode)
# Test that EQ operator does NOT get wrapped (should not have null-safe wrapping)
filter_data_eq = {
@@ -604,12 +604,12 @@ class TestCohortBytecodeScenarios(APIBaseTest):
"value": 25,
"operator": "exact",
}
- bytecode_eq, error_eq, hash_eq = generate_cohort_filter_bytecode(filter_data_eq, self.team)
- self.assertIsNone(error_eq)
- self.assertIsNotNone(bytecode_eq)
- assert bytecode_eq is not None # Type narrowing for mypy
+ result_eq = generate_cohort_filter_bytecode(filter_data_eq, self.team)
+ self.assertIsNone(result_eq.error)
+ self.assertIsNotNone(result_eq.bytecode)
+ assert result_eq.bytecode is not None # Type narrowing for mypy
# EQ should not have the null-safe wrapping
- self.assertIn(Operation.EQ, bytecode_eq)
+ self.assertIn(Operation.EQ, result_eq.bytecode)
# Should NOT have the wrapping pattern (no JUMP_IF_FALSE for null checks)
# Should NOT have the wrapping pattern (no isNull function for null checks)
- self.assertNotIn("isNull", bytecode_eq)
+ self.assertNotIn("isNull", result_eq.bytecode)
diff --git a/posthog/management/commands/test/test_survey_cohort_bytecode_stl.py b/posthog/management/commands/test/test_survey_cohort_bytecode_stl.py
index 858d131426de..f23412f7183d 100644
--- a/posthog/management/commands/test/test_survey_cohort_bytecode_stl.py
+++ b/posthog/management/commands/test/test_survey_cohort_bytecode_stl.py
@@ -277,11 +277,11 @@ class TestAggregateSurvey(BaseTest):
def test_real_compiler_bytecode_is_walked_and_isnull_is_supported(self):
from posthog.api.cohort import generate_cohort_filter_bytecode
- bytecode, error, condition_hash = generate_cohort_filter_bytecode(
+ bytecode_result = generate_cohort_filter_bytecode(
{"key": "age", "type": "person", "value": 13, "operator": "gt"}, self.team
)
- self.assertIsNone(error)
- assert bytecode is not None
+ self.assertIsNone(bytecode_result.error)
+ assert bytecode_result.bytecode is not None
row = (
101,
@@ -290,7 +290,11 @@ class TestAggregateSurvey(BaseTest):
"properties": {
"type": "AND",
"values": [
- {"type": "person", "conditionHash": condition_hash, "bytecode": bytecode},
+ {
+ "type": "person",
+ "conditionHash": bytecode_result.condition_hash,
+ "bytecode": bytecode_result.bytecode,
+ },
],
}
},
@@ -313,7 +317,7 @@ class TestSurveyCommand(BaseTest):
def test_command_writes_survey_json_for_realtime_cohorts(self):
from posthog.api.cohort import generate_cohort_filter_bytecode
- bytecode, _error, condition_hash = generate_cohort_filter_bytecode(
+ bytecode_result = generate_cohort_filter_bytecode(
{"key": "age", "type": "person", "value": 13, "operator": "gt"}, self.team
)
Cohort.objects.create(
@@ -330,8 +334,8 @@ class TestSurveyCommand(BaseTest):
"key": "age",
"value": 13,
"operator": "gt",
- "conditionHash": condition_hash,
- "bytecode": bytecode,
+ "conditionHash": bytecode_result.condition_hash,
+ "bytecode": bytecode_result.bytecode,
},
],
}
diff --git a/posthog/storage/cache_expiry_manager.py b/posthog/storage/cache_expiry_manager.py
index 3c6df8c1d87b..317df0220f4a 100644
--- a/posthog/storage/cache_expiry_manager.py
+++ b/posthog/storage/cache_expiry_manager.py
@@ -8,6 +8,7 @@ across different HyperCache types (flags, team metadata, etc.).
from __future__ import annotations
import time
+from dataclasses import dataclass
import structlog
@@ -85,9 +86,15 @@ def get_teams_with_expiring_caches(
return []
+@dataclass(frozen=True, kw_only=True, slots=True)
+class CacheRefreshCounts:
+ successful: int
+ failed: int
+
+
def refresh_expiring_caches(
config: HyperCacheManagementConfig, ttl_threshold_hours: int = 24, limit: int = 5000
-) -> tuple[int, int]:
+) -> CacheRefreshCounts:
"""
Refresh caches that are expiring soon to prevent cache misses.
@@ -102,13 +109,13 @@ def refresh_expiring_caches(
limit: Maximum number of teams to refresh per run (default 5000)
Returns:
- Tuple of (successful_count, failed_count)
+ CacheRefreshCounts with successful and failed counts
"""
teams = get_teams_with_expiring_caches(config, ttl_threshold_hours, limit)
if not teams:
logger.info(f"No {config.log_prefix} to refresh")
- return 0, 0
+ return CacheRefreshCounts(successful=0, failed=0)
successful = 0
failed = 0
@@ -144,7 +151,7 @@ def refresh_expiring_caches(
failed=failed,
)
- return successful, failed
+ return CacheRefreshCounts(successful=successful, failed=failed)
def cleanup_stale_expiry_tracking(config: HyperCacheManagementConfig) -> int:
diff --git a/posthog/storage/remote_config_cache.py b/posthog/storage/remote_config_cache.py
index 5fa68d53a9a7..064ec87bb89a 100644
--- a/posthog/storage/remote_config_cache.py
+++ b/posthog/storage/remote_config_cache.py
@@ -21,6 +21,7 @@ from posthog.metrics import TOMBSTONE_COUNTER
from posthog.models.remote_config import RemoteConfig
from posthog.models.team.team import Team
from posthog.storage.cache_expiry_manager import (
+ CacheRefreshCounts,
cleanup_stale_expiry_tracking as cleanup_generic,
get_teams_with_expiring_caches as get_teams_generic,
)
@@ -83,16 +84,16 @@ REMOTE_CONFIG_HYPERCACHE_MANAGEMENT_CONFIG = HyperCacheManagementConfig(
)
-def refresh_expiring_caches(ttl_threshold_hours: int = 24, limit: int = 5000) -> tuple[int, int]:
+def refresh_expiring_caches(ttl_threshold_hours: int = 24, limit: int = 5000) -> CacheRefreshCounts:
"""
- Refresh array/config.json caches expiring within ``ttl_threshold_hours``; returns (successful, failed).
+ Refresh array/config.json caches expiring within ``ttl_threshold_hours``; returns successful and failed counts.
Batch-loads every expiring team's config in one query — the config lives in a separate
table from Team, so re-stamping per team would be an N+1.
"""
teams = get_teams_generic(REMOTE_CONFIG_HYPERCACHE_MANAGEMENT_CONFIG, ttl_threshold_hours, limit)
if not teams:
- return 0, 0
+ return CacheRefreshCounts(successful=0, failed=0)
team_by_id = {team.id: team for team in teams}
configs = dict(RemoteConfig.objects.filter(team__in=teams).values_list("team_id", "config"))
@@ -119,7 +120,7 @@ def refresh_expiring_caches(ttl_threshold_hours: int = 24, limit: int = 5000) ->
successful=successful,
failed=failed,
)
- return successful, failed
+ return CacheRefreshCounts(successful=successful, failed=failed)
def cleanup_stale_expiry_tracking() -> int:
diff --git a/posthog/storage/team_llm_gateway_policy_cache.py b/posthog/storage/team_llm_gateway_policy_cache.py
index ca62c793a297..4d0896b398af 100644
--- a/posthog/storage/team_llm_gateway_policy_cache.py
+++ b/posthog/storage/team_llm_gateway_policy_cache.py
@@ -29,7 +29,10 @@ import structlog
from posthog.caching.ai_gateway_redis_cache import AI_GATEWAY_DEDICATED_CACHE_ALIAS
from posthog.models.team.team import Team
-from posthog.storage.cache_expiry_manager import refresh_expiring_caches as refresh_generic
+from posthog.storage.cache_expiry_manager import (
+ CacheRefreshCounts,
+ refresh_expiring_caches as refresh_generic,
+)
from posthog.storage.hypercache import HyperCache, HyperCacheStoreMissing, KeyType
from posthog.storage.hypercache_manager import (
HyperCacheManagementConfig,
@@ -139,7 +142,7 @@ LLM_GATEWAY_POLICY_HYPERCACHE_MANAGEMENT_CONFIG = HyperCacheManagementConfig(
)
-def refresh_expiring_caches(ttl_threshold_hours: int = 24, limit: int = 5000) -> tuple[int, int]:
+def refresh_expiring_caches(ttl_threshold_hours: int = 24, limit: int = 5000) -> CacheRefreshCounts:
"""
Refresh policy caches whose TTL falls below the threshold. Mirrors the
team_metadata refresh pipeline so the cache stays warm under a growing
diff --git a/posthog/storage/team_metadata_cache.py b/posthog/storage/team_metadata_cache.py
index 257a15cde693..1a6d700daafd 100644
--- a/posthog/storage/team_metadata_cache.py
+++ b/posthog/storage/team_metadata_cache.py
@@ -54,6 +54,7 @@ from posthog.caching.flags_redis_cache import FLAGS_DEDICATED_CACHE_ALIAS
from posthog.metrics import TOMBSTONE_COUNTER
from posthog.models.team.team import Team
from posthog.storage.cache_expiry_manager import (
+ CacheRefreshCounts,
cleanup_stale_expiry_tracking as cleanup_generic,
get_teams_with_expiring_caches as get_teams_generic,
refresh_expiring_caches as refresh_generic,
@@ -450,7 +451,7 @@ def get_teams_with_expiring_caches(ttl_threshold_hours: int = 24, limit: int = 5
return get_teams_generic(TEAM_HYPERCACHE_MANAGEMENT_CONFIG, ttl_threshold_hours, limit)
-def refresh_expiring_caches(ttl_threshold_hours: int = 24, limit: int = 5000) -> tuple[int, int]:
+def refresh_expiring_caches(ttl_threshold_hours: int = 24, limit: int = 5000) -> CacheRefreshCounts:
"""
Refresh caches that are expiring soon to prevent cache misses.
@@ -468,7 +469,7 @@ def refresh_expiring_caches(ttl_threshold_hours: int = 24, limit: int = 5000) ->
limit: Maximum number of teams to refresh per run (default 5000)
Returns:
- Tuple of (successful_refreshes, failed_refreshes)
+ CacheRefreshCounts with successful and failed refresh counts
"""
return refresh_generic(TEAM_HYPERCACHE_MANAGEMENT_CONFIG, ttl_threshold_hours, limit)
diff --git a/posthog/storage/test/test_remote_config_cache.py b/posthog/storage/test/test_remote_config_cache.py
index 696e44b29dad..e722e91711aa 100644
--- a/posthog/storage/test/test_remote_config_cache.py
+++ b/posthog/storage/test/test_remote_config_cache.py
@@ -2,6 +2,7 @@ from posthog.test.base import BaseTest
from unittest.mock import MagicMock, patch
from posthog.models.remote_config import RemoteConfig
+from posthog.storage.cache_expiry_manager import CacheRefreshCounts
from posthog.storage.remote_config_cache import (
cleanup_stale_expiry_tracking,
refresh_expiring_caches,
@@ -63,9 +64,9 @@ class TestRefreshExpiringRemoteConfigCaches(BaseTest):
mock_get_client.return_value = mock_redis
mock_redis.zrangebyscore.return_value = [self.team.api_token.encode()]
- successful, failed = refresh_expiring_caches(ttl_threshold_hours=24)
+ counts = refresh_expiring_caches(ttl_threshold_hours=24)
- assert (successful, failed) == (1, 0)
+ assert counts == CacheRefreshCounts(successful=1, failed=0)
mock_redis.zrangebyscore.assert_called_once_with(
"remote_config_cache_expiry",
"-inf",
@@ -84,7 +85,7 @@ class TestRefreshExpiringRemoteConfigCaches(BaseTest):
mock_get_client.return_value = mock_redis
mock_redis.zrangebyscore.return_value = []
- assert refresh_expiring_caches(ttl_threshold_hours=24) == (0, 0)
+ assert refresh_expiring_caches(ttl_threshold_hours=24) == CacheRefreshCounts(successful=0, failed=0)
class TestCleanupStaleRemoteConfigExpiryTracking(BaseTest):
diff --git a/posthog/tasks/remote_config.py b/posthog/tasks/remote_config.py
index 2175e8a4b75a..a16ac0d26f99 100644
--- a/posthog/tasks/remote_config.py
+++ b/posthog/tasks/remote_config.py
@@ -67,7 +67,7 @@ def refresh_expiring_remote_config_cache_entries() -> None:
logger.info("Starting remote config cache refresh")
try:
- successful, failed = refresh_expiring_caches(ttl_threshold_hours=24)
+ counts = refresh_expiring_caches(ttl_threshold_hours=24)
# Scan after refresh to push coverage/TTL metrics to Pushgateway.
stats_after = get_cache_stats()
@@ -76,8 +76,8 @@ def refresh_expiring_remote_config_cache_entries() -> None:
logger.info(
"Completed remote config cache refresh",
- successful_refreshes=successful,
- failed_refreshes=failed,
+ successful_refreshes=counts.successful,
+ failed_refreshes=counts.failed,
total_cached=stats_after.get("total_cached", 0),
total_teams=stats_after.get("total_teams", 0),
cache_coverage=stats_after.get("cache_coverage", "unknown"),
diff --git a/posthog/tasks/team_llm_gateway_policy.py b/posthog/tasks/team_llm_gateway_policy.py
index 5dd04a80b732..50466fcaa02a 100644
--- a/posthog/tasks/team_llm_gateway_policy.py
+++ b/posthog/tasks/team_llm_gateway_policy.py
@@ -61,14 +61,14 @@ def refresh_expiring_llm_gateway_policy_cache_entries() -> None:
start_time = time.time()
try:
- successful, failed = refresh_expiring_caches(ttl_threshold_hours=24)
+ counts = refresh_expiring_caches(ttl_threshold_hours=24)
# get_cache_stats also pushes coverage/TTL gauges to Prometheus, matching
# the team_metadata refresh task so the policy cache is observable too.
stats_after = get_cache_stats()
logger.info(
"Completed llm-gateway policy cache refresh",
- successful_refreshes=successful,
- failed_refreshes=failed,
+ successful_refreshes=counts.successful,
+ failed_refreshes=counts.failed,
total_cached=stats_after.get("total_cached", 0),
cache_coverage=stats_after.get("cache_coverage", "unknown"),
ttl_distribution=stats_after.get("ttl_distribution", {}),
diff --git a/posthog/tasks/team_metadata.py b/posthog/tasks/team_metadata.py
index d1147fd92d42..e859c78f9ec7 100644
--- a/posthog/tasks/team_metadata.py
+++ b/posthog/tasks/team_metadata.py
@@ -114,7 +114,7 @@ def refresh_expiring_team_metadata_cache_entries() -> None:
logger.info("Starting team metadata cache sync")
try:
- successful, failed = refresh_expiring_caches(ttl_threshold_hours=24)
+ counts = refresh_expiring_caches(ttl_threshold_hours=24)
# Note: Teams processed metrics are pushed to Pushgateway by
# cache_expiry_manager.refresh_expiring_caches() via push_hypercache_teams_processed_metrics()
@@ -126,8 +126,8 @@ def refresh_expiring_team_metadata_cache_entries() -> None:
logger.info(
"Completed team metadata cache refresh",
- successful_refreshes=successful,
- failed_refreshes=failed,
+ successful_refreshes=counts.successful,
+ failed_refreshes=counts.failed,
total_cached=stats_after.get("total_cached", 0),
total_teams=stats_after.get("total_teams", 0),
cache_coverage=stats_after.get("cache_coverage", "unknown"),
diff --git a/posthog/tasks/test/test_remote_config.py b/posthog/tasks/test/test_remote_config.py
index c5866cd81ea4..69cdd1e81422 100644
--- a/posthog/tasks/test/test_remote_config.py
+++ b/posthog/tasks/test/test_remote_config.py
@@ -9,6 +9,7 @@ from parameterized import parameterized
from posthog.models.project import Project
from posthog.models.remote_config import RemoteConfig
+from posthog.storage.cache_expiry_manager import CacheRefreshCounts
from posthog.tasks.remote_config import (
cleanup_stale_remote_config_expiry_tracking_task,
refresh_expiring_remote_config_cache_entries,
@@ -110,7 +111,10 @@ class TestRemoteConfigCacheTasks(BaseTest):
def test_refresh_runs_work_when_flags_redis_url_set(self) -> None:
with (
override_settings(FLAGS_REDIS_URL="redis://test:6379/0"),
- patch("posthog.tasks.remote_config.refresh_expiring_caches", return_value=(0, 0)) as mock_refresh,
+ patch(
+ "posthog.tasks.remote_config.refresh_expiring_caches",
+ return_value=CacheRefreshCounts(successful=0, failed=0),
+ ) as mock_refresh,
patch("posthog.tasks.remote_config.get_cache_stats", return_value={}),
):
refresh_expiring_remote_config_cache_entries()
diff --git a/products/cohorts/backend/parity/recompute.py b/products/cohorts/backend/parity/recompute.py
index c6ba87c559c5..b8e686985d8b 100644
--- a/products/cohorts/backend/parity/recompute.py
+++ b/products/cohorts/backend/parity/recompute.py
@@ -448,13 +448,26 @@ def _person_day_totals(matches: Sequence[DayMatch]) -> dict[tuple[date, str], in
return totals
+@dataclass(frozen=True, kw_only=True, slots=True)
+class DomainCounts:
+ grace: int
+ seed: int
+ boundary: int
+ unseeded: int
+ post: int
+
+ @property
+ def total(self) -> int:
+ return self.grace + self.seed + self.boundary + self.unseeded + self.post
+
+
def _domain_counts(
matches: Sequence[DayMatch],
*,
window: frozenset[date],
ctx: RunContext,
-) -> tuple[int, int, int, int, int]:
- """(grace, seed, boundary, unseeded, post) in-window match counts for one person.
+) -> DomainCounts:
+ """Per-domain in-window match counts for one person.
``seed`` / ``boundary`` / ``unseeded`` partition the pre-boundary window days: boundary-day first
(the seed/live handoff day, even if a chunk exists for it), then confirmed-seed days, then the
@@ -476,7 +489,7 @@ def _domain_counts(
seed += count
else:
unseeded += count
- return grace, seed, boundary, unseeded, post
+ return DomainCounts(grace=grace, seed=seed, boundary=boundary, unseeded=unseeded, post=post)
def _classify_missing_person(
@@ -491,19 +504,19 @@ def _classify_missing_person(
post: the highest-precedence domain whose cumulative count crosses the membership threshold. The
classes are exhaustive — the final fall-through implies ``post > 0``, since the three preceding
sums were all below the threshold the total clears."""
- grace, seed, boundary, unseeded, post = _domain_counts(matches, window=window, ctx=ctx)
- if grace + seed + boundary + unseeded + post == 0:
+ counts = _domain_counts(matches, window=window, ctx=ctx)
+ if counts.total == 0:
# The member-set read put this person in the oracle, so the day read over the same event and
# window has to find their matches. Zero means the two reads disagree — override/merge drift
# between them, or a dropped chunk — which is not the ingestion lag `grace` stands for.
return "missing_unattributed"
- if seed + boundary + unseeded + post < min_count:
+ if counts.seed + counts.boundary + counts.unseeded + counts.post < min_count:
return "missing_grace" # crossing depends on the last grace-minutes — lag noise
- if seed >= min_count:
+ if counts.seed >= min_count:
return "missing_seed_domain" # confirmed seed days alone qualify — unexpected, gates FAIL
- if seed + boundary >= min_count:
+ if counts.seed + counts.boundary >= min_count:
return "missing_boundary_day" # needs boundary-day pre-boundary events — decaying gap
- if seed + boundary + unseeded >= min_count:
+ if counts.seed + counts.boundary + counts.unseeded >= min_count:
return "missing_unseeded_day" # needs an unseeded pre-boundary window day — gates FAIL
return "missing_post_boundary" # needs post-boundary events the live path owns — gates FAIL
diff --git a/products/feature_flags/backend/flags_cache.py b/products/feature_flags/backend/flags_cache.py
index 3f50ac459ea9..a14c3775f3dd 100644
--- a/products/feature_flags/backend/flags_cache.py
+++ b/products/feature_flags/backend/flags_cache.py
@@ -50,6 +50,7 @@ from posthog.kafka_client.topics import KAFKA_FLAGS_CACHE_INVALIDATION
from posthog.metrics import TOMBSTONE_COUNTER
from posthog.models.team import Team
from posthog.storage.cache_expiry_manager import (
+ CacheRefreshCounts,
cleanup_stale_expiry_tracking as cleanup_generic,
get_teams_with_expiring_caches,
refresh_expiring_caches,
@@ -870,7 +871,7 @@ def get_teams_with_expiring_flags_caches(ttl_threshold_hours: int = 24, limit: i
return get_teams_with_expiring_caches(FLAGS_HYPERCACHE_MANAGEMENT_CONFIG, ttl_threshold_hours, limit)
-def refresh_expiring_flags_caches(ttl_threshold_hours: int = 24, limit: int = 5000) -> tuple[int, int]:
+def refresh_expiring_flags_caches(ttl_threshold_hours: int = 24, limit: int = 5000) -> CacheRefreshCounts:
"""
Refresh flags caches that are expiring soon to prevent cache misses.
@@ -892,7 +893,7 @@ def refresh_expiring_flags_caches(ttl_threshold_hours: int = 24, limit: int = 50
- Responsiveness: Completes quickly enough to not block other operations
Returns:
- Tuple of (successful_refreshes, failed_refreshes)
+ CacheRefreshCounts with successful and failed refresh counts
"""
return refresh_expiring_caches(FLAGS_HYPERCACHE_MANAGEMENT_CONFIG, ttl_threshold_hours, limit)
diff --git a/products/feature_flags/backend/tasks.py b/products/feature_flags/backend/tasks.py
index 3c467e118c86..9497e3a698a5 100644
--- a/products/feature_flags/backend/tasks.py
+++ b/products/feature_flags/backend/tasks.py
@@ -256,14 +256,14 @@ def refresh_expiring_flags_cache_entries(self: PushGatewayTask) -> None:
limit=settings.FLAGS_CACHE_REFRESH_LIMIT,
)
- successful, failed = refresh_expiring_flags_caches(
+ counts = refresh_expiring_flags_caches(
ttl_threshold_hours=settings.FLAGS_CACHE_REFRESH_TTL_THRESHOLD_HOURS,
limit=settings.FLAGS_CACHE_REFRESH_LIMIT,
)
# Record metrics
- successful_gauge.set(successful)
- failed_gauge.set(failed)
+ successful_gauge.set(counts.successful)
+ failed_gauge.set(counts.failed)
# Note: Teams processed metrics are pushed to Pushgateway by
# cache_expiry_manager.refresh_expiring_caches() via push_hypercache_teams_processed_metrics()
@@ -275,8 +275,8 @@ def refresh_expiring_flags_cache_entries(self: PushGatewayTask) -> None:
logger.info(
"Completed flags cache refresh",
- successful_refreshes=successful,
- failed_refreshes=failed,
+ successful_refreshes=counts.successful,
+ failed_refreshes=counts.failed,
total_cached=stats_after.get("total_cached", 0),
total_teams=stats_after.get("total_teams", 0),
cache_coverage=stats_after.get("cache_coverage", "unknown"),
@@ -472,20 +472,20 @@ def refresh_expiring_flag_definitions_cache_entries(self: PushGatewayTask) -> No
limit=settings.FLAGS_CACHE_REFRESH_LIMIT,
)
- successful, failed = refresh_expiring_caches(
+ counts = refresh_expiring_caches(
config=FLAG_DEFINITIONS_HYPERCACHE_MANAGEMENT_CONFIG,
ttl_threshold_hours=settings.FLAGS_CACHE_REFRESH_TTL_THRESHOLD_HOURS,
limit=settings.FLAGS_CACHE_REFRESH_LIMIT,
)
- successful_gauge.set(successful)
- failed_gauge.set(failed)
+ successful_gauge.set(counts.successful)
+ failed_gauge.set(counts.failed)
duration = time.time() - start_time
logger.info(
"Completed flag definitions cache refresh",
- successful_refreshes=successful,
- failed_refreshes=failed,
+ successful_refreshes=counts.successful,
+ failed_refreshes=counts.failed,
duration_seconds=duration,
)
diff --git a/products/feature_flags/backend/test/test_flag_definitions_cache_tasks.py b/products/feature_flags/backend/test/test_flag_definitions_cache_tasks.py
index 7df803fade2b..3785384ecebb 100644
--- a/products/feature_flags/backend/test/test_flag_definitions_cache_tasks.py
+++ b/products/feature_flags/backend/test/test_flag_definitions_cache_tasks.py
@@ -2,6 +2,7 @@ from unittest.mock import MagicMock, patch
from django.test import TestCase
+from posthog.storage.cache_expiry_manager import CacheRefreshCounts
from posthog.tasks.test.utils import PushGatewayTaskTestMixin
from products.feature_flags.backend.tasks import (
@@ -13,11 +14,13 @@ from products.feature_flags.backend.tasks import (
class TestRefreshExpiringFlagDefinitionsCacheEntries(PushGatewayTaskTestMixin, TestCase):
@patch("posthog.storage.cache_expiry_manager.refresh_expiring_caches")
def test_refreshes_cache(self, mock_refresh: MagicMock) -> None:
- mock_refresh.return_value = (5, 0)
+ mock_refresh.return_value = CacheRefreshCounts(successful=5, failed=0)
refresh_expiring_flag_definitions_cache_entries()
mock_refresh.assert_called_once()
+ assert self.registry.get_sample_value("posthog_flag_definitions_cache_refresh_successful_count") == 5
+ assert self.registry.get_sample_value("posthog_flag_definitions_cache_refresh_failed_count") == 0
@patch("posthog.storage.cache_expiry_manager.refresh_expiring_caches")
def test_propagates_error(self, mock_refresh: MagicMock) -> None:
diff --git a/products/feature_flags/backend/test/test_flags_cache.py b/products/feature_flags/backend/test/test_flags_cache.py
index 06e618959c12..16c48fe58ab0 100644
--- a/products/feature_flags/backend/test/test_flags_cache.py
+++ b/products/feature_flags/backend/test/test_flags_cache.py
@@ -28,6 +28,7 @@ from parameterized import parameterized
from posthog.kafka_client.topics import KAFKA_FLAGS_CACHE_INVALIDATION
from posthog.models import Team
+from posthog.storage.cache_expiry_manager import CacheRefreshCounts
from products.cohorts.backend.models.cohort import Cohort
from products.experiments.backend.models.experiment import Experiment
@@ -1581,13 +1582,13 @@ class TestBatchOperations(BaseTest):
refresh_expiring_flags_caches,
)
- mock_refresh.return_value = (2, 0) # successful, failed
+ mock_refresh.return_value = CacheRefreshCounts(successful=2, failed=0)
- successful, failed = refresh_expiring_flags_caches(ttl_threshold_hours=24)
+ counts = refresh_expiring_flags_caches(ttl_threshold_hours=24)
# Should return result from generic function
- self.assertEqual(successful, 2)
- self.assertEqual(failed, 0)
+ self.assertEqual(counts.successful, 2)
+ self.assertEqual(counts.failed, 0)
# Should call generic refresh_expiring_caches with correct config
mock_refresh.assert_called_once_with(FLAGS_HYPERCACHE_MANAGEMENT_CONFIG, 24, settings.FLAGS_CACHE_REFRESH_LIMIT)
diff --git a/products/feature_flags/backend/user_blast_radius.py b/products/feature_flags/backend/user_blast_radius.py
index faf580e89968..48e412cc5cf5 100644
--- a/products/feature_flags/backend/user_blast_radius.py
+++ b/products/feature_flags/backend/user_blast_radius.py
@@ -25,7 +25,7 @@ from posthog.queries.base import relative_date_parse_for_feature_flag_matching
from products.cohorts.backend.models.cohort import Cohort
-@dataclass
+@dataclass(frozen=True, kw_only=True, slots=True)
class BlastRadiusResult:
affected: int
total: int
@@ -101,10 +101,9 @@ def get_user_blast_radius(
cleaned_filter = replace_proxy_properties(team, feature_flag_condition)
if group_type_index is not None:
- affected, total = _get_group_blast_radius(team, cleaned_filter, group_type_index)
+ return _get_group_blast_radius(team, cleaned_filter, group_type_index)
else:
- affected, total = _get_person_blast_radius(team, cleaned_filter)
- return BlastRadiusResult(affected=affected, total=total)
+ return _get_person_blast_radius(team, cleaned_filter)
def get_user_blast_radius_persons(
@@ -123,7 +122,7 @@ def get_user_blast_radius_persons(
return _get_person_blast_radius_persons(team, cleaned_filter, cursor=cursor)
-def _get_person_blast_radius(team: Team, filter: Filter) -> tuple[int, int]:
+def _get_person_blast_radius(team: Team, filter: Filter) -> BlastRadiusResult:
"""Calculate blast radius for person-based feature flags using HogQL."""
from posthog.hogql.query import execute_hogql_query
@@ -132,7 +131,7 @@ def _get_person_blast_radius(team: Team, filter: Filter) -> tuple[int, int]:
if len(properties) == 0:
# No filters means all persons are affected
total_users = team.persons_seen_so_far
- return total_users, total_users
+ return BlastRadiusResult(affected=total_users, total=total_users)
# Build the SELECT query - property_to_expr handles all properties including cohorts
select_query = _build_person_query(team, filter, return_count=True)
@@ -148,7 +147,7 @@ def _get_person_blast_radius(team: Team, filter: Filter) -> tuple[int, int]:
total_users = team.persons_seen_so_far
blast_radius = min(total_count, total_users)
- return blast_radius, total_users
+ return BlastRadiusResult(affected=blast_radius, total=total_users)
def _build_person_query(team: Team, filter: Filter, return_count: bool = True, cursor: Optional[str] = None):
@@ -204,7 +203,7 @@ def _build_person_query(team: Team, filter: Filter, return_count: bool = True, c
return select_query
-def _get_group_blast_radius(team: Team, filter: Filter, group_type_index: GroupTypeIndex) -> tuple[int, int]:
+def _get_group_blast_radius(team: Team, filter: Filter, group_type_index: GroupTypeIndex) -> BlastRadiusResult:
"""Calculate blast radius for group-based feature flags using HogQL."""
from posthog.hogql.query import execute_hogql_query
@@ -225,7 +224,7 @@ def _get_group_blast_radius(team: Team, filter: Filter, group_type_index: GroupT
if len(properties) == 0:
# No filters means all groups of this type are affected
total_groups = team.groups_seen_so_far(group_type_index)
- return total_groups, total_groups
+ return BlastRadiusResult(affected=total_groups, total=total_groups)
# Build the SELECT query for groups
select_query = _build_group_query(team, filter, group_type_index, return_count=True)
@@ -241,7 +240,7 @@ def _get_group_blast_radius(team: Team, filter: Filter, group_type_index: GroupT
total_affected = response.results[0][0] if response.results else 0
total_groups = team.groups_seen_so_far(group_type_index)
- return total_affected, total_groups
+ return BlastRadiusResult(affected=total_affected, total=total_groups)
PERSON_BATCH_SIZE = 500
diff --git a/products/workflows/backend/api/hog_flow.py b/products/workflows/backend/api/hog_flow.py
index 4393a2c1c7d0..01a10a6cc0df 100644
--- a/products/workflows/backend/api/hog_flow.py
+++ b/products/workflows/backend/api/hog_flow.py
@@ -73,6 +73,7 @@ from products.cohorts.backend.models.cohort import Cohort
from products.cohorts.backend.models.util import get_all_cohort_dependencies
from products.feature_flags.backend.user_blast_radius import (
PERSON_BATCH_SIZE,
+ BlastRadiusResult,
get_user_blast_radius,
get_user_blast_radius_persons,
)
@@ -3442,16 +3443,16 @@ class HogFlowViewSet(
if dedupe_key is not None and group_type_index is None and use_workflows_batch_audience_query(self.team):
total = self.team.persons_seen_so_far
affected = min(get_batch_audience_count(self.team, filters, dedupe_key), total)
+ blast_radius = BlastRadiusResult(affected=affected, total=total)
applied_dedupe_key = dedupe_key
else:
- result = get_user_blast_radius(self.team, filters, group_type_index)
- affected, total = result.affected, result.total
+ blast_radius = get_user_blast_radius(self.team, filters, group_type_index)
return Response(
BlastRadiusSerializer(
{
- "affected": affected,
- "total": total,
+ "affected": blast_radius.affected,
+ "total": blast_radius.total,
"limit": get_hogflow_batch_trigger_limit(self.team_id),
"dedupe_key": applied_dedupe_key,
"confirm_token": mint_audience_confirm_token(