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(devex): validate dataclass invariants at construction (#83528)

Arno Hillene82cae025a33
diff --git a/posthog/dags/property_definitions.py b/posthog/dags/property_definitions.py
index fdcd01f99db3..9013f6a83df7 100644
--- a/posthog/dags/property_definitions.py
+++ b/posthog/dags/property_definitions.py
@@ -15,6 +15,13 @@ class TimeRange:
start_time: datetime.datetime
end_time: datetime.datetime
+ def __post_init__(self) -> None:
+ if self.start_time > self.end_time:
+ raise ValueError(
+ f"TimeRange start_time must not be after end_time: "
+ f"start_time={self.start_time}, end_time={self.end_time}"
+ )
+
def get_expression(self, column: str) -> str:
return f"{column} >= '{self.start_time.isoformat()}' AND {column} < '{self.end_time.isoformat()}'"
diff --git a/posthog/dags/tests/test_property_definitions.py b/posthog/dags/tests/test_property_definitions.py
index 7d06a35969b0..aea9dd1d9644 100644
--- a/posthog/dags/tests/test_property_definitions.py
+++ b/posthog/dags/tests/test_property_definitions.py
@@ -4,12 +4,15 @@ from dataclasses import dataclass
from datetime import datetime, timedelta
from uuid import UUID
+import pytest
+
import dagster
from posthog.clickhouse.cluster import ClickhouseCluster, Query
from posthog.dags.property_definitions import (
DetectPropertyTypeExpression,
PropertyDefinitionsConfig,
+ TimeRange,
property_definitions_ingestion_job,
setup_job,
)
@@ -235,3 +238,15 @@ def test_ingestion_job(cluster: ClickhouseCluster) -> None:
(1, 1, "property", "Numeric", None, 2, int(PropertyDefinition.Type.GROUP), start_at),
(1, 1, "property", "Numeric", None, None, int(PropertyDefinition.Type.PERSON), start_at + duration / 2),
]
+
+
+def test_time_range_accepts_ordered_and_equal_bounds() -> None:
+ start = datetime(2026, 1, 1)
+ assert TimeRange(start, start).end_time == start
+ assert TimeRange(start, start + timedelta(hours=1)).start_time == start
+
+
+def test_time_range_rejects_reversed_bounds() -> None:
+ start = datetime(2026, 1, 1)
+ with pytest.raises(ValueError, match="start_time"):
+ TimeRange(start, start - timedelta(seconds=1))
diff --git a/posthog/slo/context.py b/posthog/slo/context.py
index e9b2a6496d36..15ee7f1ca47c 100644
--- a/posthog/slo/context.py
+++ b/posthog/slo/context.py
@@ -54,8 +54,12 @@ class SloSpec:
# can weight each event by 1/sample_rate to reconstruct the true rate.
sample_rate: float = 1.0
+ def __post_init__(self) -> None:
+ if not (0.0 <= self.sample_rate <= 1.0):
+ raise ValueError(f"SloSpec sample_rate must be between 0 and 1, got {self.sample_rate}")
+
[email protected](frozen=False)
class SloHandle:
operation: SloOperation | None = None
completion_properties: dict[str, JsonValue] = dataclasses.field(default_factory=dict)
diff --git a/posthog/slo/test/test_slo_context.py b/posthog/slo/test/test_slo_context.py
index af4948699d5a..08df3ef26826 100644
--- a/posthog/slo/test/test_slo_context.py
+++ b/posthog/slo/test/test_slo_context.py
@@ -359,3 +359,14 @@ def test_slo_operation_sampled_out_still_propagates_exception(
mock_emit_slo_started.assert_not_called()
mock_emit_slo_completed.assert_not_called()
+
+
[email protected]("sample_rate", [0.0, 0.01, 1.0])
+def test_slo_spec_accepts_sample_rate_within_unit_interval(sample_rate: float) -> None:
+ assert dataclasses.replace(_build_spec(), sample_rate=sample_rate).sample_rate == sample_rate
+
+
[email protected]("sample_rate", [-0.01, 1.01, 50.0])
+def test_slo_spec_rejects_sample_rate_outside_unit_interval(sample_rate: float) -> None:
+ with pytest.raises(ValueError, match="sample_rate"):
+ dataclasses.replace(_build_spec(), sample_rate=sample_rate)
diff --git a/posthog/temporal/health_checks/framework.py b/posthog/temporal/health_checks/framework.py
index 0717c6ec2713..36ebd233031b 100644
--- a/posthog/temporal/health_checks/framework.py
+++ b/posthog/temporal/health_checks/framework.py
@@ -153,6 +153,18 @@ class HealthCheckRegistration:
product: Product | None
remediation: Remediation | None
+ def __post_init__(self) -> None:
+ # A fraction, not a percent: 50 here would silently skip the rollout filter and hit every team.
+ if not (0.0 <= self.rollout_percentage <= 1.0):
+ raise ValueError(
+ f"HealthCheckRegistration rollout_percentage must be between 0 and 1, got {self.rollout_percentage}"
+ )
+ if not (0.0 <= self.not_processed_threshold <= 1.0):
+ raise ValueError(
+ f"HealthCheckRegistration not_processed_threshold must be between 0 and 1, "
+ f"got {self.not_processed_threshold}"
+ )
+
def _register_health_check(cls: type[HealthCheck]) -> None:
existing = HEALTH_CHECKS.get(cls.kind)
diff --git a/posthog/temporal/health_checks/tests/test_framework.py b/posthog/temporal/health_checks/tests/test_framework.py
new file mode 100644
index 000000000000..502b72a16587
--- /dev/null
+++ b/posthog/temporal/health_checks/tests/test_framework.py
@@ -0,0 +1,53 @@
+from typing import Any
+
+import pytest
+
+from posthog.dags.common.owners import JobOwners
+from posthog.temporal.health_checks.framework import HealthCheckRegistration
+
+
+def _registration(**overrides: Any) -> HealthCheckRegistration:
+ fields: dict[str, Any] = {
+ "name": "Stub check",
+ "kind": "stub_check",
+ "owner": JobOwners.TEAM_INGESTION,
+ "schedule": None,
+ "batch_size": 250,
+ "max_concurrent": 1,
+ "rollout_percentage": 1.0,
+ "not_processed_threshold": 0.1,
+ "dry_run": False,
+ "active_since_days": 90,
+ "product": None,
+ "remediation": None,
+ }
+ fields.update(overrides)
+ return HealthCheckRegistration(**fields)
+
+
+ "field,value",
+ [
+ ("rollout_percentage", 0.0),
+ ("rollout_percentage", 0.01),
+ ("rollout_percentage", 1.0),
+ ("not_processed_threshold", 0.0),
+ ("not_processed_threshold", 1.0),
+ ],
+)
+def test_accepts_fractional_values(field: str, value: float) -> None:
+ assert getattr(_registration(**{field: value}), field) == value
+
+
+ "field,value",
+ [
+ ("rollout_percentage", -0.1),
+ ("rollout_percentage", 50.0),
+ ("not_processed_threshold", -0.1),
+ ("not_processed_threshold", 2.0),
+ ],
+)
+def test_rejects_out_of_range_fractions(field: str, value: float) -> None:
+ with pytest.raises(ValueError, match=field):
+ _registration(**{field: value})
diff --git a/posthog/test/dataclass_frozen_baseline.txt b/posthog/test/dataclass_frozen_baseline.txt
index 700fce3ca0cf..6cae3d2be083 100644
--- a/posthog/test/dataclass_frozen_baseline.txt
+++ b/posthog/test/dataclass_frozen_baseline.txt
@@ -50,7 +50,6 @@
1 posthog/personhog_client/fake_client.py
1 posthog/persons_seed.py
1 posthog/session/backfill.py
-1 posthog/slo/context.py
1 posthog/storage/auth_token_cache_verifier.py
1 posthog/storage/hypercache_manager.py
1 posthog/storage/hypercache_verifier.py
@@ -1422,7 +1421,6 @@
2 posthog/temporal/tests/test_slo_interceptor.py
2 posthog/temporal/tests/utils/workflow.py
2 posthog/temporal/utils.py
-2 products/batch_exports/backend/temporal/batch_exports.py
2 products/batch_exports/backend/temporal/destinations/s3_batch_export.py
2 products/batch_exports/backend/temporal/pipeline/types.py
2 products/batch_exports/backend/tests/temporal/pipeline/test_entrypoint.py
diff --git a/posthog/test/test_utils.py b/posthog/test/test_utils.py
index c064e177cda4..6e3774356d9e 100644
--- a/posthog/test/test_utils.py
+++ b/posthog/test/test_utils.py
@@ -33,6 +33,7 @@ from posthog.utils import (
HAS_PERSON_EMAIL_ABSENT_TTL_SECONDS,
HAS_PERSON_EMAIL_ABSENT_YOUNG_PROJECT_TTL_SECONDS,
HAS_PERSON_EMAIL_PRESENT_TTL_SECONDS,
+ DayRange,
PotentialSecurityProblemException,
_build_flag_provider,
_read_preload_manifest,
@@ -1493,3 +1494,16 @@ class TestReadPreloadManifest(SimpleTestCase):
path = self._write_manifest(content)
assert _read_preload_manifest(path, include_authenticated_shell=True) == ("", (), "")
+
+
+class TestDayRange(SimpleTestCase):
+ START = datetime(2026, 1, 1, tzinfo=ZoneInfo("UTC"))
+
+ @parameterized.expand([("same_instant", timedelta(0)), ("full_day", timedelta(days=1))])
+ def test_accepts_ordered_bounds(self, _name: str, delta: timedelta) -> None:
+ day_range = DayRange(start=self.START, end=self.START + delta)
+ assert day_range.end - day_range.start == delta
+
+ def test_rejects_reversed_bounds(self) -> None:
+ with pytest.raises(ValueError, match="start"):
+ DayRange(start=self.START, end=self.START - timedelta(seconds=1))
diff --git a/posthog/utils.py b/posthog/utils.py
index abca3968b3bf..9fe8ba6cb9d1 100644
--- a/posthog/utils.py
+++ b/posthog/utils.py
@@ -143,6 +143,10 @@ class DayRange:
start: datetime.datetime
end: datetime.datetime
+ def __post_init__(self) -> None:
+ if self.start > self.end:
+ raise ValueError(f"DayRange start must not be after end: start={self.start}, end={self.end}")
+
def get_previous_day(at: Optional[datetime.datetime] = None) -> DayRange:
"""
diff --git a/products/apm/backend/logic/anomaly_detection/config.py b/products/apm/backend/logic/anomaly_detection/config.py
index 7fbd349dd518..ba09ca8d40dc 100644
--- a/products/apm/backend/logic/anomaly_detection/config.py
+++ b/products/apm/backend/logic/anomaly_detection/config.py
@@ -93,6 +93,12 @@ class DetectionConfig:
# A recurrence within this window reopens the resolved issue; later ones are new.
reopen_window_buckets: int = 7 * BUCKETS_PER_DAY
+ def __post_init__(self) -> None:
+ if not (0.0 <= self.exclusion_cap_fraction <= 1.0):
+ raise ValueError(
+ f"DetectionConfig exclusion_cap_fraction must be between 0 and 1, got {self.exclusion_cap_fraction}"
+ )
+
@property
def alpha_per_bucket(self) -> float:
return self.false_flag_budget_per_day / BUCKETS_PER_DAY
diff --git a/products/apm/backend/tests/test_anomaly_baseline.py b/products/apm/backend/tests/test_anomaly_baseline.py
index 72cb90945b0a..c8cc21dfba54 100644
--- a/products/apm/backend/tests/test_anomaly_baseline.py
+++ b/products/apm/backend/tests/test_anomaly_baseline.py
@@ -1,6 +1,8 @@
from datetime import UTC, datetime
from zoneinfo import ZoneInfo
+import pytest
+
import numpy as np
from parameterized import parameterized
@@ -176,3 +178,14 @@ class TestCandidateSlicePadding:
step_offset = (index - positions) % step_buckets
distance = np.minimum(step_offset, step_buckets - step_offset)
assert float(distance.max()) <= candidate_slice_pad_buckets(config)
+
+
+class TestDetectionConfigValidation:
+ @parameterized.expand([("zero", 0.0), ("default", 0.5), ("one", 1.0)])
+ def test_accepts_fractional_exclusion_cap(self, _name: str, fraction: float) -> None:
+ assert DetectionConfig(exclusion_cap_fraction=fraction).exclusion_cap_fraction == fraction
+
+ @parameterized.expand([("negative", -0.1), ("above_one", 1.1), ("percent_style", 50.0)])
+ def test_rejects_out_of_range_exclusion_cap(self, _name: str, fraction: float) -> None:
+ with pytest.raises(ValueError, match="exclusion_cap_fraction"):
+ DetectionConfig(exclusion_cap_fraction=fraction)
diff --git a/products/batch_exports/backend/temporal/batch_exports.py b/products/batch_exports/backend/temporal/batch_exports.py
index 0358bc9c3033..b9c0aa885b16 100644
--- a/products/batch_exports/backend/temporal/batch_exports.py
+++ b/products/batch_exports/backend/temporal/batch_exports.py
@@ -375,6 +375,10 @@ class DataInterval:
start: dt.datetime
end: dt.datetime
+ def __post_init__(self) -> None:
+ if self.start > self.end:
+ raise ValueError(f"DataInterval start must not be after end: start={self.start}, end={self.end}")
+
def get_data_interval(interval: str, data_interval_end: str | None, timezone: str | None = None) -> DataInterval:
"""Return the start and end of an export's data interval.
@@ -444,7 +448,7 @@ def get_data_interval(interval: str, data_interval_end: str | None, timezone: st
return DataInterval(start=data_interval_start_dt, end=data_interval_end_dt)
[email protected](frozen=False)
class StartBatchExportRunInputs:
"""Inputs to the 'start_batch_export_run' activity.
@@ -593,7 +597,7 @@ async def check_is_over_limit(team_id: int) -> bool:
return False
[email protected](frozen=False)
class FinishBatchExportRunInputs:
"""Inputs to the 'finish_batch_export_run' activity.
diff --git a/products/batch_exports/backend/tests/temporal/test_batch_exports.py b/products/batch_exports/backend/tests/temporal/test_batch_exports.py
index fcf8a87148af..b32157e62f6d 100644
--- a/products/batch_exports/backend/tests/temporal/test_batch_exports.py
+++ b/products/batch_exports/backend/tests/temporal/test_batch_exports.py
@@ -498,3 +498,16 @@ def test_generate_query_ranges(remaining_range, done_ranges, expected):
"""Test generate_query_ranges returns the expected query ranges."""
result = list(generate_query_ranges(remaining_range, done_ranges))
assert result == expected
+
+
[email protected]("delta", [dt.timedelta(0), dt.timedelta(hours=1)])
+def test_data_interval_accepts_ordered_bounds(delta: dt.timedelta) -> None:
+ end = dt.datetime(2023, 8, 1, tzinfo=dt.UTC)
+ interval = DataInterval(start=end - delta, end=end)
+ assert interval.end - interval.start == delta
+
+
+def test_data_interval_rejects_reversed_bounds() -> None:
+ end = dt.datetime(2023, 8, 1, tzinfo=dt.UTC)
+ with pytest.raises(ValueError, match="start"):
+ DataInterval(start=end + dt.timedelta(seconds=1), end=end)
diff --git a/products/replay_vision/backend/quota.py b/products/replay_vision/backend/quota.py
index 3363e1654554..94c30858873d 100644
--- a/products/replay_vision/backend/quota.py
+++ b/products/replay_vision/backend/quota.py
@@ -156,6 +156,10 @@ class BillingPeriod:
start: datetime
end: datetime
+ def __post_init__(self) -> None:
+ if self.start >= self.end:
+ raise ValueError(f"BillingPeriod start must be before end: start={self.start}, end={self.end}")
+
def _current_month_bounds(now: datetime) -> BillingPeriod:
return BillingPeriod(start=start_of_month(now), end=next_month_start(now))
@@ -170,9 +174,11 @@ def _current_period_bounds(organization: Organization | None, now: datetime) ->
"""The org's active billing period when synced and current, else the calendar month containing `now`."""
billing_period = organization.current_billing_period if organization else None
if billing_period:
- synced = BillingPeriod(start=_as_utc(billing_period.start), end=_as_utc(billing_period.end))
- if synced.start <= now < synced.end:
- return synced
+ start = _as_utc(billing_period.start)
+ end = _as_utc(billing_period.end)
+ # Gate before constructing so a malformed synced period falls back to the calendar month
+ if start <= now < end:
+ return BillingPeriod(start=start, end=end)
return _current_month_bounds(now)
diff --git a/products/replay_vision/backend/tests/test_quota.py b/products/replay_vision/backend/tests/test_quota.py
index 494b04ee883f..799a7178256b 100644
--- a/products/replay_vision/backend/tests/test_quota.py
+++ b/products/replay_vision/backend/tests/test_quota.py
@@ -881,3 +881,16 @@ class TestObserveQuotaEnforcement(_VisionQuotaTestCase):
assert "observations running" in resp.json()["detail"]
# Blocked before any workflow start.
mock_sync_connect.assert_not_called()
+
+
+class TestBillingPeriodValidation(SimpleTestCase):
+ START = datetime(2026, 7, 1, tzinfo=UTC)
+
+ def test_accepts_ordered_bounds(self) -> None:
+ period = BillingPeriod(start=self.START, end=self.START + timedelta(days=31))
+ assert period.end - period.start == timedelta(days=31)
+
+ @parameterized.expand([("empty", timedelta(0)), ("reversed", timedelta(seconds=-1))])
+ def test_rejects_empty_or_reversed_window(self, _name: str, delta: timedelta) -> None:
+ with self.assertRaisesRegex(ValueError, "start"):
+ BillingPeriod(start=self.START, end=self.START + delta)