: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
from collections.abc import Sequence
from dataclasses import dataclass
from datetime import UTC, date, datetime, timedelta
from typing import Any
from django.conf import settings
from django.utils import timezone as django_timezone
from posthog.clickhouse.client import sync_execute
from posthog.clickhouse.workload import Workload
from posthog.dataclasses import frozen
from posthog.errors import InternalCHQueryError
from posthog.exceptions import ClickHouseQueryTimeOut
from posthog.models.flag_evaluations.sql import FLAG_EVALUATIONS_SOURCE_EVENT
from products.cohorts.backend.backfill.flag_calls_table import FlagCallsTable
# 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
# quoted 16-char condition hash in both `evaluated` and `matched` — the worst case, where every
# pinned condition came back TRUE. Recalibrate when that struct's wire fields change.
PERSON_SEED_BASE_BYTES = 256
PERSON_SEED_PER_HASH_BYTES = 38
# 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)
# A week, so a weekend day never stands in for the weekday peak.
BEHAVIORAL_SCAN_ESTIMATE_DAYS = 7
_BEHAVIORAL_SCAN_ESTIMATE_MAX_SECONDS = 60
class PersonSeedEstimateScanCapExceeded(Exception):
"""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)
class PersonSeedEstimate:
estimated_persons: int
pinned_condition_count: int
bytes_per_seed: int
estimated_topic_bytes: int
budget_bytes: int
@property
def over_budget(self) -> bool:
return self.estimated_topic_bytes > self.budget_bytes
def as_preconditions(self) -> dict[str, Any]:
return {
"person_seed_estimated_persons": self.estimated_persons,
"person_seed_pinned_condition_count": self.pinned_condition_count,
"person_seed_bytes_per_seed": self.bytes_per_seed,
"person_seed_estimated_topic_bytes": self.estimated_topic_bytes,
"person_seed_topic_bytes_budget": self.budget_bytes,
}
def estimate_person_seed_topic_bytes(
team_id: int,
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. `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
# budget gate toward refusing runs that would have fit.
#
# `person` is sorted by (team_id, id), so in-order aggregation streams the GROUP BY instead of
# holding every id in a hash table. No `readonly=True`: a configured readonly user takes
# precedence over the offline host.
try:
rows = sync_execute(
"""
SELECT count()
FROM (
SELECT id
FROM person
WHERE team_id = %(team_id)s
AND _timestamp >= %(person_scan_since)s
GROUP BY id
HAVING argMax(is_deleted, version) = 0
)
""",
{"team_id": team_id, "person_scan_since": person_scan_since},
settings={
"max_execution_time": max_execution_time,
"max_bytes_to_read": max_bytes_to_read,
"read_overflow_mode": "throw",
"optimize_aggregation_in_order": 1,
},
workload=Workload.OFFLINE,
team_id=team_id,
)
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 per cohort save.
raise PersonSeedEstimateScanCapExceeded(
f"Person sizing scan for team {team_id} exceeded its {max_execution_time}s time cap"
) from error
except InternalCHQueryError as error:
if error.code in _READ_CAP_ERROR_CODES:
raise PersonSeedEstimateScanCapExceeded(
f"Person sizing scan for team {team_id} exceeded its {max_bytes_to_read} byte read cap"
) from error
raise
estimated_persons = int(rows[0][0])
bytes_per_seed = PERSON_SEED_BASE_BYTES + PERSON_SEED_PER_HASH_BYTES * pinned_condition_count
return PersonSeedEstimate(
estimated_persons=estimated_persons,
pinned_condition_count=pinned_condition_count,
bytes_per_seed=bytes_per_seed,
estimated_topic_bytes=estimated_persons * bytes_per_seed,
budget_bytes=settings.BEHAVIORAL_BACKFILL_PERSON_TOPIC_BYTES_BUDGET,
)
@frozen
class BehavioralScanEstimate:
"""A recent sample, not a bound: an older day, or a day in the run's timezone, can hold more events. The
seeder reads fewer rows where every condition on an event name has a row filter."""
days_sampled: int
peak_day: date | None
peak_day_events: int
peak_day_events_by_name: dict[str, int]
max_events_per_day: int
@property
def over_limit(self) -> bool:
return self.max_events_per_day > 0 and self.peak_day_events > self.max_events_per_day
def largest_events(self, count: int) -> list[tuple[str, int]]:
return sorted(self.peak_day_events_by_name.items(), key=lambda item: (-item[1], item[0]))[:count]
def as_preconditions(self) -> dict[str, Any]:
return {
"behavioral_scan_days_sampled": self.days_sampled,
"behavioral_scan_peak_day": self.peak_day.isoformat() if self.peak_day else None,
"behavioral_scan_peak_day_events": self.peak_day_events,
"behavioral_scan_max_events_per_day": self.max_events_per_day,
}
def estimate_behavioral_scan_events(
team_id: int,
event_names: Sequence[str],
*,
flag_calls_table: FlagCallsTable,
max_events_per_day: int,
) -> BehavioralScanEstimate:
"""Counts each event name in the table that cohort-seeder scans it from."""
until = django_timezone.now().astimezone(UTC).replace(hour=0, minute=0, second=0, microsecond=0)
window = {"team_id": team_id, "since": until - timedelta(days=BEHAVIORAL_SCAN_ESTIMATE_DAYS), "until": until}
queries: list[tuple[str, dict[str, Any]]] = []
counts_flag_calls_on_flag_evaluations = (
flag_calls_table == FlagCallsTable.FLAG_EVALUATIONS and FLAG_EVALUATIONS_SOURCE_EVENT in event_names
)
names_on_events = [
name
for name in event_names
if not (counts_flag_calls_on_flag_evaluations and name == FLAG_EVALUATIONS_SOURCE_EVENT)
]
if counts_flag_calls_on_flag_evaluations:
queries.append(
(
"""
SELECT toDate(timestamp) AS day, %(flag_called)s AS event, count() AS events
FROM flag_evaluations
WHERE team_id = %(team_id)s
AND timestamp >= %(since)s
AND timestamp < %(until)s
GROUP BY day
""",
{**window, "flag_called": FLAG_EVALUATIONS_SOURCE_EVENT},
)
)
if names_on_events:
queries.append(
(
"""
SELECT toDate(timestamp) AS day, event, count() AS events
FROM events
WHERE team_id = %(team_id)s
AND timestamp >= %(since)s
AND timestamp < %(until)s
AND event IN %(event_names)s
GROUP BY day, event
""",
{**window, "event_names": names_on_events},
)
)
by_day: dict[date, dict[str, int]] = {}
for query, params in queries:
rows = sync_execute(
query,
params,
settings={"max_execution_time": _BEHAVIORAL_SCAN_ESTIMATE_MAX_SECONDS},
workload=Workload.OFFLINE,
team_id=team_id,
)
for day, event, count in rows:
by_day.setdefault(day, {})[event] = int(count)
peak_day = max(by_day, key=lambda day: (sum(by_day[day].values()), day), default=None)
peak_day_events_by_name = by_day[peak_day] if peak_day is not None else {}
return BehavioralScanEstimate(
days_sampled=BEHAVIORAL_SCAN_ESTIMATE_DAYS,
peak_day=peak_day,
peak_day_events=sum(peak_day_events_by_name.values()),
peak_day_events_by_name=peak_day_events_by_name,
max_events_per_day=max_events_per_day,
)