: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
feat(cohorts): read the person sizing scan caps from settings (#96743)
Matheus Batistac3552d6e82c0
diff --git a/posthog/settings/cohorts.py b/posthog/settings/cohorts.pyindex ed8b99ba3fe8..c5917bfd1841 100644--- a/posthog/settings/cohorts.py+++ b/posthog/settings/cohorts.py@@ -33,6 +33,19 @@ BEHAVIORAL_BACKFILL_PERSON_DEFAULT_HORIZON_DAYS: int = get_from_env(BEHAVIORAL_BACKFILL_PERSON_TOPIC_BYTES_BUDGET: int = get_from_env("BEHAVIORAL_BACKFILL_PERSON_TOPIC_BYTES_BUDGET", 0, type_cast=int)+# Bounds the ClickHouse sizing scan that runs before a person-property run is created. The scan+# reads the team's whole person history on the user-facing cluster, so it carries its own limits+# rather than the query defaults. `read_overflow_mode: throw` turns either limit into a refusal to+# create the run, instead of a run sized off a partial scan.+#+# Do not set either to 0. ClickHouse reads 0 as "no limit" for both, so a cleared value removes the+# bound rather than disabling it.+BEHAVIORAL_BACKFILL_PERSON_SIZING_MAX_BYTES: int = get_from_env(+ "BEHAVIORAL_BACKFILL_PERSON_SIZING_MAX_BYTES", 10_000_000_000, type_cast=int+)+BEHAVIORAL_BACKFILL_PERSON_SIZING_MAX_SECONDS: int = get_from_env(+ "BEHAVIORAL_BACKFILL_PERSON_SIZING_MAX_SECONDS", 30, type_cast=int+)BEHAVIORAL_BACKFILL_PERSON_SIZING_ATTESTED: bool = get_from_env("BEHAVIORAL_BACKFILL_PERSON_SIZING_ATTESTED", False, type_cast=str_to_bool)diff --git a/posthog/tasks/calculate_cohort.py b/posthog/tasks/calculate_cohort.pyindex 3b93eed4d6cf..4123813d3207 100644--- a/posthog/tasks/calculate_cohort.py+++ b/posthog/tasks/calculate_cohort.py@@ -996,8 +996,9 @@ COHORT_BACKFILL_REFUSAL_OUTCOMES: dict[BackfillRefusalReason, str] = {BackfillRefusalReason.COHORT_INELIGIBLE: "refused_ineligible",BackfillRefusalReason.INVALID_HORIZON: "refused_ineligible",BackfillRefusalReason.PINNING_CAP_EXCEEDED: "refused_ineligible",- # Not transient: the sizing scan's read cap is deterministic, so a cohort that trips it trips it- # again on every later trigger until someone raises the limit. Nothing clears on its own.+ # Not transient: the sizing scan's read and time caps are deterministic, so a cohort that trips+ # one trips it again on every later trigger until someone raises the limit. Nothing clears on+ # its own.BackfillRefusalReason.SIZING_SCAN_CAP_EXCEEDED: "refused_ineligible",BackfillRefusalReason.DEFINITION_CHANGED: "refused_transient",}@@ -1006,7 +1007,8 @@ COHORT_BACKFILL_REFUSAL_OUTCOMES: dict[BackfillRefusalReason, str] = {# acks_late: a countdown message acked on receipt sits in one worker's memory for the whole window# and dies with it, after the edit's supersession already ran. The creators refuse duplicates, so# the redelivery this trades into is harmless. The queue matches the module's other-# ClickHouse-touching tasks: the person creator runs a sizing scan capped at 30 s.+# ClickHouse-touching tasks: the person creator runs a sizing scan bounded by+# `BEHAVIORAL_BACKFILL_PERSON_SIZING_MAX_SECONDS`.@shared_task(ignore_result=True,acks_late=True,diff --git a/products/cohorts/backend/backfill/sizing.py b/products/cohorts/backend/backfill/sizing.pyindex 23eb96d509f5..a0408887cff2 100644--- a/products/cohorts/backend/backfill/sizing.py+++ b/products/cohorts/backend/backfill/sizing.py@@ -6,6 +6,7 @@ from django.conf import settingsfrom posthog.clickhouse.client import sync_executefrom posthog.errors import InternalCHQueryError+from posthog.exceptions import ClickHouseQueryTimeOut# Calibrated against a serialized `PersonSeed` (rust/cohort-core/src/seed/person.rs): the fixed# envelope (schema_version, kind, team_id, person_id, scanned_at_ms, run_id, claim_epoch) plus one@@ -14,15 +15,16 @@ from posthog.errors import InternalCHQueryErrorPERSON_SEED_BASE_BYTES = 256PERSON_SEED_PER_HASH_BYTES = 38-# TOO_MANY_ROWS / TOO_MANY_BYTES: what `read_overflow_mode: throw` raises when the scan hits the-# caps below. Deterministic for a given team, unlike a timeout or transport failure.+# TOO_MANY_ROWS / TOO_MANY_BYTES: what `read_overflow_mode: throw` raises when the scan hits+# `BEHAVIORAL_BACKFILL_PERSON_SIZING_MAX_BYTES`. Deterministic for a given team, unlike a transport+# failure._READ_CAP_ERROR_CODES = (158, 307)class PersonSeedEstimateScanCapExceeded(Exception):- """The sizing scan hit its own read cap: the team's person history exceeds what the estimate may- read, so the answer will not change on retry and the caller should refuse rather than repeat the- capped scan."""+ """The sizing scan hit one of its own caps: the team's person history exceeds what the estimate+ may read or how long it may run, so the answer will not change on retry and the caller should+ refuse rather than repeat the capped scan."""@dataclass(frozen=True)@@ -52,10 +54,12 @@ def estimate_person_seed_topic_bytes(person_scan_since: datetime,pinned_condition_count: int,) -> PersonSeedEstimate:+ max_bytes_to_read = settings.BEHAVIORAL_BACKFILL_PERSON_SIZING_MAX_BYTES+ max_execution_time = settings.BEHAVIORAL_BACKFILL_PERSON_SIZING_MAX_SECONDS# `person` is ORDER BY (team_id, id) with only a minmax index on `_timestamp`, and rows are# rewritten in place on every update, so the window bound prunes close to nothing: this reads the- # team's whole person history either way. `max_bytes_to_read` is what actually bounds it, and it- # throws rather than letting the gate size a run off a partial scan.+ # team's whole person history either way. `BEHAVIORAL_BACKFILL_PERSON_SIZING_MAX_BYTES` is what+ # actually bounds it, and it throws rather than letting the gate size a run off a partial scan.## Collapsing versions per id before counting keeps persons whose latest in-window row is a# deletion out of the estimate — counting them inflates the topic-byte figure and biases the@@ -75,17 +79,25 @@ def estimate_person_seed_topic_bytes(""",{"team_id": team_id, "person_scan_since": person_scan_since},settings={- "max_execution_time": 30,- "max_bytes_to_read": 10_000_000_000,+ "max_execution_time": max_execution_time,+ "max_bytes_to_read": max_bytes_to_read,"read_overflow_mode": "throw",},team_id=team_id,readonly=True,)+ except ClickHouseQueryTimeOut as error:+ # `max_execution_time` is this gate's own cap, so a timeout means the same thing as the byte+ # cap: the team's person history does not fit, and a retry pays the whole scan again for the+ # same answer. `trigger_cohort_backfill_run_task` retries every other exception three times,+ # which at a 300 s cap is 20 minutes of scans on the user-facing cluster per cohort save.+ raise PersonSeedEstimateScanCapExceeded(+ f"Person sizing scan for team {team_id} exceeded its {max_execution_time}s time cap"+ ) from errorexcept InternalCHQueryError as error:if error.code in _READ_CAP_ERROR_CODES:raise PersonSeedEstimateScanCapExceeded(- f"Person sizing scan for team {team_id} exceeded its read cap"+ f"Person sizing scan for team {team_id} exceeded its {max_bytes_to_read} byte read cap") from errorraiseestimated_persons = int(rows[0][0])diff --git a/products/cohorts/backend/backfill/test/test_sizing.py b/products/cohorts/backend/backfill/test/test_sizing.pyindex 0ad2632b2060..cf423bc4374b 100644--- a/products/cohorts/backend/backfill/test/test_sizing.py+++ b/products/cohorts/backend/backfill/test/test_sizing.py@@ -4,10 +4,19 @@ from unittest import mockfrom django.test import SimpleTestCase, override_settings-from products.cohorts.backend.backfill.sizing import estimate_person_seed_topic_bytes+from parameterized import parameterized+from posthog.errors import InternalCHQueryError+from posthog.exceptions import ClickHouseQueryTimeOut-@override_settings(BEHAVIORAL_BACKFILL_PERSON_TOPIC_BYTES_BUDGET=10_000)+from products.cohorts.backend.backfill.sizing import PersonSeedEstimateScanCapExceeded, estimate_person_seed_topic_bytes+++@override_settings(+ BEHAVIORAL_BACKFILL_PERSON_TOPIC_BYTES_BUDGET=10_000,+ BEHAVIORAL_BACKFILL_PERSON_SIZING_MAX_BYTES=20_000_000_000,+ BEHAVIORAL_BACKFILL_PERSON_SIZING_MAX_SECONDS=300,+)class TestPersonBackfillSizing(SimpleTestCase):@mock.patch("products.cohorts.backend.backfill.sizing.sync_execute",@@ -40,9 +49,32 @@ class TestPersonBackfillSizing(SimpleTestCase):sync_execute.call_args.args[1],{"team_id": 7, "person_scan_since": person_scan_since},)+ # Both caps come from settings, so an environment that raises them for one large team gets a+ # scan that can finish rather than a run that always refuses.self.assertEqual(sync_execute.call_args.kwargs["settings"],- {"max_execution_time": 30, "max_bytes_to_read": 10_000_000_000, "read_overflow_mode": "throw"},+ {"max_execution_time": 300, "max_bytes_to_read": 20_000_000_000, "read_overflow_mode": "throw"},)self.assertEqual(sync_execute.call_args.kwargs["team_id"], 7)self.assertTrue(sync_execute.call_args.kwargs["readonly"])++ @parameterized.expand(+ [+ ("too_many_rows", InternalCHQueryError("rows", code=158, code_name="too_many_rows")),+ ("too_many_bytes", InternalCHQueryError("bytes", code=307, code_name="too_many_bytes")),+ ("timeout", ClickHouseQueryTimeOut()),+ ]+ )+ def test_a_scan_that_hits_a_cap_refuses(self, _name: str, raised: Exception) -> None:+ # The callers turn this exception into a deterministic refusal. Any other exception is+ # retried, which pays for the whole scan again on the user-facing cluster.+ with mock.patch("products.cohorts.backend.backfill.sizing.sync_execute", side_effect=raised):+ with self.assertRaises(PersonSeedEstimateScanCapExceeded):+ estimate_person_seed_topic_bytes(7, datetime(2026, 5, 1, tzinfo=UTC), 2)++ def test_an_unrelated_clickhouse_error_propagates(self) -> None:+ raised = InternalCHQueryError("no such table", code=60, code_name="unknown_table")++ with mock.patch("products.cohorts.backend.backfill.sizing.sync_execute", side_effect=raised):+ with self.assertRaises(InternalCHQueryError):+ estimate_person_seed_topic_bytes(7, datetime(2026, 5, 1, tzinfo=UTC), 2)