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(scheduled-changes): stop a bad tzdata file from blocking startup (#103758)

posthog[bot]e89cc8462e8e
diff --git a/posthog/tasks/process_scheduled_changes.py b/posthog/tasks/process_scheduled_changes.py
index f5ef371e056c..e73b0b2245da 100644
--- a/posthog/tasks/process_scheduled_changes.py
+++ b/posthog/tasks/process_scheduled_changes.py
@@ -1,7 +1,7 @@
import os
import json
import socket
-from datetime import UTC, datetime
+from datetime import UTC, datetime, tzinfo
from zoneinfo import ZoneInfo, ZoneInfoNotFoundError
from django.core.exceptions import ObjectDoesNotExist, ValidationError
@@ -117,25 +117,26 @@ def compute_next_run(current: datetime, interval: str) -> datetime:
raise ValueError(f"Unknown recurrence interval: {interval}")
-UTC_ZONE_INFO = ZoneInfo("UTC")
-
-
-def resolve_schedule_timezone(tz_name: str | None) -> ZoneInfo:
+def resolve_schedule_timezone(tz_name: str | None) -> tzinfo:
"""
- Resolve a stored timezone name to a ZoneInfo, falling back to UTC for NULL or invalid values.
+ Resolve a stored timezone name to a tzinfo, falling back to UTC for NULL or invalid values.
Pre-resolving once per scheduled change keeps the catch-up loop off the exception path when
a row carries a malformed timezone string.
+
+ ZoneInfo reads a TZif file from the system tzdata path. A name that no file matches raises
+ ZoneInfoNotFoundError, but a file that exists and is truncated or corrupt raises ValueError
+ instead. Both mean the timezone is unusable, so both fall back to UTC.
"""
if not tz_name:
- return UTC_ZONE_INFO
+ return UTC
try:
return ZoneInfo(tz_name)
- except ZoneInfoNotFoundError:
- return UTC_ZONE_INFO
+ except (ZoneInfoNotFoundError, ValueError):
+ return UTC
-def compute_next_run_cron(cron_expr: str, current: datetime, tz: ZoneInfo = UTC_ZONE_INFO) -> datetime:
+def compute_next_run_cron(cron_expr: str, current: datetime, tz: tzinfo = UTC) -> datetime:
"""
Compute the next scheduled run time from a cron expression.
diff --git a/posthog/tasks/test/test_process_scheduled_changes.py b/posthog/tasks/test/test_process_scheduled_changes.py
index 9487d2fac927..d8ad9e413803 100644
--- a/posthog/tasks/test/test_process_scheduled_changes.py
+++ b/posthog/tasks/test/test_process_scheduled_changes.py
@@ -1,17 +1,27 @@
+import ast
import json
+import inspect
+import tempfile
+import zoneinfo
+import importlib
+from collections.abc import Iterator
+from contextlib import contextmanager
from datetime import UTC, datetime, timedelta
+from pathlib import Path
from typing import Any, cast
import time_machine
from posthog.test.base import APIBaseTest, QueryMatchingTest, snapshot_postgres_queries
from unittest.mock import patch
+from django.test import SimpleTestCase
+
from parameterized import parameterized
from posthog.models import Organization
from posthog.models.activity_logging.activity_log import ActivityLog
from posthog.models.team import Team
-from posthog.tasks.process_scheduled_changes import process_scheduled_changes
+from posthog.tasks.process_scheduled_changes import process_scheduled_changes, resolve_schedule_timezone
from products.feature_flags.backend.models.feature_flag import FeatureFlag
from products.feature_flags.backend.models.scheduled_change import ScheduledChange
@@ -1649,7 +1659,7 @@ class TestProcessScheduledChanges(APIBaseTest, QueryMatchingTest):
datetime(2024, 1, 16, 9, 0, tzinfo=UTC),
),
# Unknown / typo'd timezone falls back to UTC rather than raising and stalling
- # the schedule. Exercises the ZoneInfoNotFoundError branch.
+ # the schedule.
(
"invalid_timezone_falls_back_to_utc",
"2024-01-15T09:00:00Z",
@@ -1714,3 +1724,53 @@ class TestProcessScheduledChanges(APIBaseTest, QueryMatchingTest):
scheduled_change.refresh_from_db()
self.assertEqual(scheduled_change.scheduled_at, expected_next)
+
+
+@contextmanager
+def corrupt_system_tzdata() -> Iterator[None]:
+ """
+ Point the zoneinfo search path at a directory whose TZif files are corrupt.
+
+ A name that no file matches raises ZoneInfoNotFoundError and then falls back to the tzdata
+ package, so an empty directory does not reproduce the failure. The file has to exist and be
+ unreadable, which is what makes ZoneInfo raise ValueError.
+ """
+ original_tzpath = zoneinfo.TZPATH
+ with tempfile.TemporaryDirectory() as tzdir:
+ for name in ("UTC", "America/New_York"):
+ tzfile = Path(tzdir) / name
+ tzfile.parent.mkdir(parents=True, exist_ok=True)
+ tzfile.write_bytes(b"this is not a TZif file")
+ zoneinfo.reset_tzpath([tzdir])
+ zoneinfo.ZoneInfo.clear_cache()
+ try:
+ yield
+ finally:
+ zoneinfo.reset_tzpath(original_tzpath)
+ zoneinfo.ZoneInfo.clear_cache()
+
+
+class TestScheduledChangesWithoutReadableTzdata(SimpleTestCase):
+ @parameterized.expand([("unreadable_zone", "America/New_York"), ("unreadable_utc", "UTC")])
+ def test_corrupt_tzif_file_falls_back_to_utc(self, _name: str, tz_name: str) -> None:
+ with corrupt_system_tzdata():
+ self.assertEqual(resolve_schedule_timezone(tz_name), UTC)
+
+ def test_module_builds_no_zoneinfo_at_import_time(self) -> None:
+ # posthog/tasks/__init__.py imports this module, so a ZoneInfo built at module scope
+ # reads a TZif file while every management command is still starting up. One corrupt
+ # file then stops the process before it runs, the temporal worker included. Use
+ # datetime.UTC, which needs no tzdata file.
+ module = importlib.import_module(resolve_schedule_timezone.__module__)
+ module_scope = [
+ statement
+ for statement in ast.parse(inspect.getsource(module)).body
+ if not isinstance(statement, ast.FunctionDef | ast.AsyncFunctionDef | ast.ClassDef)
+ ]
+ zoneinfo_calls = [
+ node
+ for statement in module_scope
+ for node in ast.walk(statement)
+ if isinstance(node, ast.Call) and isinstance(node.func, ast.Name) and node.func.id == "ZoneInfo"
+ ]
+ self.assertEqual(zoneinfo_calls, [])