:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
fix(flags): reduce info logs flood in stderr in hypercache (#65865)
Ryan Chung63191818b73a
diff --git a/posthog/settings/logs.py b/posthog/settings/logs.pyindex 3407ae7880af..d0532af0723d 100644--- a/posthog/settings/logs.py+++ b/posthog/settings/logs.py@@ -2,6 +2,7 @@ import osimport loggingimport warningsimport threading+from typing import Anyimport structlog@@ -27,10 +28,19 @@ if IS_INTERACTIVE_SHELL:class FilterStatsd(logging.Filter):- def filter(self, record):+ def filter(self, record: logging.LogRecord) -> bool:return not record.name.startswith("statsd.client")+class MaxLevelFilter(logging.Filter):+ def __init__(self, level: int) -> None:+ super().__init__()+ self.level = level++ def filter(self, record: logging.LogRecord) -> bool:+ return record.levelno <= self.level++def add_pid_and_tid(logger: logging.Logger, method_name: str, event_dict: structlog.types.EventDict) -> structlog.types.EventDict:@@ -67,7 +77,7 @@ structlog.configure(# Configure all logs to be handled by structlog `ProcessorFormatter` and# rendered either as pretty colored console lines or as single JSON lines.-LOGGING = {+LOGGING: dict[str, Any] = {"version": 1,"disable_existing_loggers": True,"formatters": {@@ -85,7 +95,11 @@ LOGGING = {"filters": {"filter_statsd": {"()": "posthog.settings.logs.FilterStatsd",- }+ },+ "max_level_info": {+ "()": "posthog.settings.logs.MaxLevelFilter",+ "level": logging.INFO,+ },},"handlers": {"console": {@@ -93,6 +107,18 @@ LOGGING = {"formatter": LOGGING_FORMATTER_NAME,"filters": ["filter_statsd"],},+ "console_stdout_info": {+ "class": "logging.StreamHandler",+ "formatter": LOGGING_FORMATTER_NAME,+ "filters": ["filter_statsd", "max_level_info"],+ "stream": "ext://sys.stdout",+ },+ "console_stderr_warning": {+ "class": "logging.StreamHandler",+ "formatter": LOGGING_FORMATTER_NAME,+ "filters": ["filter_statsd"],+ "level": "WARNING",+ },"null": {"class": "logging.NullHandler",},@@ -111,8 +137,18 @@ LOGGING = {"posthog.tasks.email": {"level": "INFO", "handlers": ["console"], "propagate": False},"products.exports.backend.tasks": {"level": "INFO", "handlers": ["console"], "propagate": False},"posthog.tasks.ai_observability_usage_report": {"level": "INFO", "handlers": ["console"], "propagate": False},- "posthog.tasks.hypercache_verification": {"level": "INFO", "handlers": ["console"], "propagate": False},- "posthog.storage.hypercache_verifier": {"level": "INFO", "handlers": ["console"], "propagate": False},+ # Hypercache verify-and-fix can emit expected high-volume INFO bursts.+ # Keep those off stderr so stream-based collectors don't relabel them as errors.+ "posthog.tasks.hypercache_verification": {+ "level": "INFO",+ "handlers": ["console_stdout_info", "console_stderr_warning"],+ "propagate": False,+ },+ "posthog.storage.hypercache_verifier": {+ "level": "INFO",+ "handlers": ["console_stdout_info", "console_stderr_warning"],+ "propagate": False,+ },"posthog.auth.mfa": {"level": "INFO", "handlers": ["console"], "propagate": False},"posthog.security.command_exec_audit": {"level": "INFO", "handlers": ["console"], "propagate": False},"products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.load": {diff --git a/posthog/settings/test_logs.py b/posthog/settings/test_logs.pynew file mode 100644index 000000000000..b0bba00d2a7a--- /dev/null+++ b/posthog/settings/test_logs.py@@ -0,0 +1,38 @@+import logging+import logging.config++from posthog.settings import logs+++def _record(level: int) -> logging.LogRecord:+ return logging.LogRecord("test", level, __file__, 1, "message", args=(), exc_info=None)+++def test_level_filters_split_info_from_warnings() -> None:+ max_info = logs.MaxLevelFilter(logging.INFO)++ assert max_info.filter(_record(logging.INFO))+ assert not max_info.filter(_record(logging.WARNING))+++def test_logging_config_can_be_applied() -> None:+ config = dict(logs.LOGGING)+ config["disable_existing_loggers"] = False+ logging.config.dictConfig(config)+++def test_default_console_logging_handler_keeps_default_stream() -> None:+ assert "stream" not in logs.LOGGING["handlers"]["console"]+++def test_hypercache_info_logs_route_to_stdout_with_warnings_on_stderr() -> None:+ assert logs.LOGGING["handlers"]["console_stdout_info"]["stream"] == "ext://sys.stdout"+ assert "stream" not in logs.LOGGING["handlers"]["console_stderr_warning"]+ assert logs.LOGGING["loggers"]["posthog.storage.hypercache_verifier"]["handlers"] == [+ "console_stdout_info",+ "console_stderr_warning",+ ]+ assert logs.LOGGING["loggers"]["posthog.tasks.hypercache_verification"]["handlers"] == [+ "console_stdout_info",+ "console_stderr_warning",+ ]diff --git a/posthog/storage/hypercache_verifier.py b/posthog/storage/hypercache_verifier.pyindex 38325378bc6f..35a2559ddb0b 100644--- a/posthog/storage/hypercache_verifier.py+++ b/posthog/storage/hypercache_verifier.py@@ -36,6 +36,9 @@ HYPERCACHE_VERIFY_FIX_COUNTER = Counter(# Maximum number of team IDs to store for loggingMAX_FIXED_TEAM_IDS_TO_LOG = 10+# Maximum number of per-team fix detail logs emitted at INFO per verification run.+MAX_FIX_DETAIL_INFO_LOGS = 10+@dataclassclass VerificationResult:@@ -50,6 +53,8 @@ class VerificationResult:skipped_for_grace_period: int = 0fixed_team_ids: list[int] = field(default_factory=list)skipped_team_ids: list[int] = field(default_factory=list)+ # Per-run logging cap state, not a verification outcome.+ fix_detail_info_logs_emitted: int = 0@propertydef total_fixed(self) -> int:@@ -129,32 +134,36 @@ def verify_and_fix_all_teams(batch_number += 1batch_start = result.totalbatch_fixes_start = result.total_fixed+ batch_fix_failures_start = result.fix_failed_verify_and_fix_batch(teams, config, verify_team_fn, cache_type, result)batch_verified = result.total - batch_startbatch_fixed = result.total_fixed - batch_fixes_start+ batch_fix_failures = result.fix_failed - batch_fix_failures_start# Log periodically to avoid log spam while still showing progress+ log_message = Noneif batch_number % PROGRESS_LOG_BATCH_INTERVAL == 0:- logger.info(- "Verification progress",- cache_type=cache_type,- batch_number=batch_number,- teams_verified_total=result.total,- teams_fixed_total=result.total_fixed,- last_team_id=teams[-1].id,- )+ log_message = "Verification progress"elif batch_fixed > 0:- # Always log batches that had fixes+ log_message = "Batch completed with fixes"++ if log_message:logger.info(- "Batch completed with fixes",+ log_message,cache_type=cache_type,batch_number=batch_number,batch_verified=batch_verified,batch_fixed=batch_fixed,+ batch_fix_failures=batch_fix_failures,teams_verified_total=result.total,teams_fixed_total=result.total_fixed,+ cache_miss_fixed_total=result.cache_miss_fixed,+ cache_mismatch_fixed_total=result.cache_mismatch_fixed,+ expiry_missing_fixed_total=result.expiry_missing_fixed,+ fix_failures_total=result.fix_failed,+ last_team_id=teams[-1].id,)last_id = teams[-1].id@@ -321,7 +330,9 @@ def _fix_and_record(log_kwargs["diff_fields"] = verification["diff_fields"]if "diff_flags" in verification:log_kwargs["diff_flags"] = verification["diff_flags"]- logger.info("Fixing cache entry", **log_kwargs)+ if result.fix_detail_info_logs_emitted < MAX_FIX_DETAIL_INFO_LOGS:+ logger.info("Fixing cache entry", **log_kwargs)+ result.fix_detail_info_logs_emitted += 1try:# Use preloaded db_data if available to avoid redundant DB querydiff --git a/posthog/storage/test/test_hypercache_verifier.py b/posthog/storage/test/test_hypercache_verifier.pyindex 99e1754e6263..f72676dfd876 100644--- a/posthog/storage/test/test_hypercache_verifier.py+++ b/posthog/storage/test/test_hypercache_verifier.py@@ -9,7 +9,7 @@ Tests cover:"""from posthog.test.base import BaseTest-from unittest.mock import MagicMock, patch+from unittest.mock import MagicMock, call, patchfrom django.test import TestCase, override_settings@@ -173,6 +173,44 @@ class TestFixAndRecord(BaseTest):assert result.fix_failed == 1assert self.team.id not in result.fixed_team_ids+ @parameterized.expand(+ [+ ("under_cap", 0, True),+ ("at_cap", 1, False),+ ]+ )+ def test_fix_detail_info_log_respects_cap(self, _name, initial_logs_emitted, should_log):+ mock_config = MagicMock()+ mock_config.update_fn.return_value = True++ result = VerificationResult(fix_detail_info_logs_emitted=initial_logs_emitted)++ with (+ patch("posthog.storage.hypercache_verifier.MAX_FIX_DETAIL_INFO_LOGS", 1),+ patch("posthog.storage.hypercache_verifier.logger.info") as mock_info,+ ):+ _fix_and_record(+ team=self.team,+ config=mock_config,+ issue_type="cache_mismatch",+ cache_type="test_cache",+ result=result,+ verification={"status": "mismatch", "diff_fields": ["payload"]},+ )++ fix_detail_call = call(+ "Fixing cache entry",+ team_id=self.team.id,+ issue_type="cache_mismatch",+ cache_type="test_cache",+ diff_fields=["payload"],+ )+ if should_log:+ assert fix_detail_call in mock_info.call_args_list+ else:+ assert fix_detail_call not in mock_info.call_args_list+ assert result.fix_detail_info_logs_emitted == 1+def test_exception_in_update_fn_increments_fix_failed(self):"""Test that exception in update_fn increments fix_failed."""mock_config = MagicMock()@@ -895,6 +933,124 @@ class TestVerifyAndFixAllTeams(BaseTest):assert result.total == result.cache_miss_fixedassert len(result.fixed_team_ids) == result.total+ def test_fixed_batches_under_progress_interval_emit_batch_fix_logs(self):+ team2 = Team.objects.create(organization=self.organization, name="Team 2")++ mock_config = MagicMock()+ mock_config.get_teams_queryset.return_value = Team.objects.filter(id__in=[self.team.id, team2.id])+ mock_config.hypercache.batch_load_fn = None+ mock_config.hypercache.batch_get_from_cache.return_value = {}+ mock_config.update_fn.return_value = True+ mock_config.get_team_ids_to_skip_fix_fn = None++ def verify_fn(team, db_batch_data, cache_batch_data):+ return {"status": "miss", "issue": "CACHE_MISS"}++ with (+ patch("posthog.storage.hypercache_verifier.MAX_FIX_DETAIL_INFO_LOGS", 0),+ patch("posthog.storage.hypercache_verifier.PROGRESS_LOG_BATCH_INTERVAL", 999),+ patch("posthog.storage.hypercache_verifier.batch_check_expiry_tracking", return_value={}),+ patch("posthog.storage.hypercache_verifier.logger.info") as mock_info,+ ):+ result = verify_and_fix_all_teams(+ config=mock_config,+ verify_team_fn=verify_fn,+ cache_type="test_cache",+ chunk_size=1,+ )++ assert result.total == 2+ assert result.total_fixed == 2+ assert [mock_call.args for mock_call in mock_info.call_args_list] == [+ ("Batch completed with fixes",),+ ("Batch completed with fixes",),+ ]+ assert [mock_call.kwargs["batch_number"] for mock_call in mock_info.call_args_list] == [1, 2]+ assert [mock_call.kwargs["batch_verified"] for mock_call in mock_info.call_args_list] == [1, 1]+ assert [mock_call.kwargs["batch_fixed"] for mock_call in mock_info.call_args_list] == [1, 1]+ assert [mock_call.kwargs["teams_verified_total"] for mock_call in mock_info.call_args_list] == [1, 2]+ assert [mock_call.kwargs["teams_fixed_total"] for mock_call in mock_info.call_args_list] == [1, 2]++ def test_fix_detail_info_logs_are_capped_during_verification_run(self):+ teams = [+ self.team,+ Team.objects.create(organization=self.organization, name="Team 2"),+ Team.objects.create(organization=self.organization, name="Team 3"),+ ]++ mock_config = MagicMock()+ mock_config.get_teams_queryset.return_value = Team.objects.filter(id__in=[team.id for team in teams])+ mock_config.hypercache.batch_load_fn = None+ mock_config.hypercache.batch_get_from_cache.return_value = {}+ mock_config.update_fn.return_value = True+ mock_config.get_team_ids_to_skip_fix_fn = None++ def verify_fn(team, db_batch_data, cache_batch_data):+ return {"status": "miss", "issue": "CACHE_MISS"}++ with (+ patch("posthog.storage.hypercache_verifier.MAX_FIX_DETAIL_INFO_LOGS", 2),+ patch("posthog.storage.hypercache_verifier.PROGRESS_LOG_BATCH_INTERVAL", 999),+ patch("posthog.storage.hypercache_verifier.batch_check_expiry_tracking", return_value={}),+ patch("posthog.storage.hypercache_verifier.logger.info") as mock_info,+ ):+ result = verify_and_fix_all_teams(+ config=mock_config,+ verify_team_fn=verify_fn,+ cache_type="test_cache",+ chunk_size=1,+ )++ fix_detail_calls = [+ mock_call for mock_call in mock_info.call_args_list if mock_call.args == ("Fixing cache entry",)+ ]+ assert len(fix_detail_calls) == 2+ assert result.fix_detail_info_logs_emitted == 2+ assert result.total == 3+ assert result.total_fixed == 3++ def test_periodic_progress_log_reports_aggregate_fix_and_failure_counts(self):+ team2 = Team.objects.create(organization=self.organization, name="Team 2")++ mock_config = MagicMock()+ mock_config.get_teams_queryset.return_value = Team.objects.filter(id__in=[self.team.id, team2.id])+ mock_config.hypercache.batch_load_fn = None+ mock_config.hypercache.batch_get_from_cache.return_value = {}+ mock_config.update_fn.side_effect = [True, False]+ mock_config.get_team_ids_to_skip_fix_fn = None++ def verify_fn(team, db_batch_data, cache_batch_data):+ return {"status": "miss", "issue": "CACHE_MISS"}++ with (+ patch("posthog.storage.hypercache_verifier.MAX_FIX_DETAIL_INFO_LOGS", 0),+ patch("posthog.storage.hypercache_verifier.PROGRESS_LOG_BATCH_INTERVAL", 1),+ patch("posthog.storage.hypercache_verifier.batch_check_expiry_tracking", return_value={}),+ patch("posthog.storage.hypercache_verifier.logger.info") as mock_info,+ ):+ result = verify_and_fix_all_teams(+ config=mock_config,+ verify_team_fn=verify_fn,+ cache_type="test_cache",+ chunk_size=2,+ )++ assert result.total == 2+ assert result.total_fixed == 1+ assert result.fix_failed == 1+ mock_info.assert_called_once()++ call_args = mock_info.call_args+ assert call_args.args == ("Verification progress",)+ assert call_args.kwargs["batch_fixed"] == 1+ assert call_args.kwargs["batch_fix_failures"] == 1+ assert call_args.kwargs["teams_verified_total"] == 2+ assert call_args.kwargs["teams_fixed_total"] == 1+ assert call_args.kwargs["cache_miss_fixed_total"] == 1+ assert call_args.kwargs["cache_mismatch_fixed_total"] == 0+ assert call_args.kwargs["expiry_missing_fixed_total"] == 0+ assert call_args.kwargs["fix_failures_total"] == 1+@override_settings(FLAGS_REDIS_URL="redis://test")class TestVerifyAndFixAllTeamsQuerysetScoping(BaseTest):diff --git a/products/replay_vision/backend/prompt_suggestions.py b/products/replay_vision/backend/prompt_suggestions.pyindex e30ac549ae04..bd32d8d0c00d 100644--- a/products/replay_vision/backend/prompt_suggestions.py+++ b/products/replay_vision/backend/prompt_suggestions.py@@ -107,7 +107,7 @@ def _describe_reasoning(observation: ReplayObservation) -> str:def _label(observation: ReplayObservation) -> ReplayObservationLabel:"""Typed accessor for the reverse one-to-one: guaranteed by the label__isnull=False filters here."""- return observation.label # type: ignore[attr-defined]+ return observation.labeldef _example_line(observation: ReplayObservation) -> str: