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.

feat(experiments): add enroll mode to the precompute enrollment census (#93980)

Juraj Majerike24ed76c2307
diff --git a/posthog/settings/temporal.py b/posthog/settings/temporal.py
index cb0e6f6498e0..a9b74529bb03 100644
--- a/posthog/settings/temporal.py
+++ b/posthog/settings/temporal.py
@@ -287,3 +287,7 @@ SIGNALS_INBOX_PR_NOTIFICATION_POLL_SECONDS: int = get_from_env(
# Incoming webhook for experiment precompute canary divergence alerts. Unset: Slack alerting is skipped.
EXPERIMENT_CANARY_SLACK_WEBHOOK_URL: str = os.getenv("EXPERIMENT_CANARY_SLACK_WEBHOOK_URL", "")
+
+# "report_only": the enrollment census logs candidates and writes nothing (default).
+# "enroll": the census also enables precomputation for qualifying teams, capped per run.
+EXPERIMENT_PRECOMPUTE_ENROLLMENT_MODE: str = os.getenv("EXPERIMENT_PRECOMPUTE_ENROLLMENT_MODE", "report_only")
diff --git a/products/experiments/backend/temporal/enrollment_census_logic.py b/products/experiments/backend/temporal/enrollment_census_logic.py
index ef91fbb727ef..62658ef0a72a 100644
--- a/products/experiments/backend/temporal/enrollment_census_logic.py
+++ b/products/experiments/backend/temporal/enrollment_census_logic.py
@@ -3,17 +3,23 @@
Finds teams whose experiment metric reads run as direct event scans only because the
team is not enrolled in precomputation (`experiment_precompute_skip_reason = 'team_disabled'`),
measures their pain over a trailing window, and reports the ones crossing the enrollment
-criteria. Report-only: this module never writes to `TeamExperimentsConfig`.
+criteria. In "enroll" mode (`EXPERIMENT_PRECOMPUTE_ENROLLMENT_MODE`) it also enables
+precomputation for a capped number of candidates per run. Additive only: the single write
+anywhere in this module is False to True, and teams a human touched are never modified.
"""
+from django.conf import settings
+from django.db import IntegrityError, transaction
from django.db.models import Count
import structlog
from posthog.clickhouse.client import sync_execute
from posthog.dataclasses import frozen
+from posthog.models.team import Team
from products.experiments.backend.models.experiment import Experiment
+from products.experiments.backend.models.team_experiments_config import TeamExperimentsConfig
logger = structlog.get_logger(__name__)
@@ -39,6 +45,13 @@ BUILD_CAP_EXCLUSION_BYTES = int(2.5 * 10**12)
EXCLUSION_BUILD_BYTE_CAP = "build_byte_cap"
+ENROLLMENT_MODE_ENROLL = "enroll"
+
+# Enroll at most this many teams per daily run, worst (most bytes rescanned) first. Makes
+# the rollout gradual by construction: each wave gets a day of canary and query-perf
+# scrutiny before the next.
+MAX_ENROLLMENTS_PER_RUN = 5
+
# Reads query_log_archive, not system.query_log: the archive outlives query_log's short
# retention and stores log_comment as a typed JSON column. The lc_product prefilter keeps
# the scan small enough for one query over the full window; the raw system.query_log
@@ -212,6 +225,72 @@ def build_census_report(stats: list[TeamDirectScanStats], window_days: int) -> E
)
+def enroll_candidates(report: EnrollmentCensusReport) -> list[int]:
+ """Enable precomputation for up to MAX_ENROLLMENTS_PER_RUN candidates, worst first.
+
+ Additive only: the single write is False to True with set_by="auto". Teams a human
+ touched (set_by="manual", in either direction) and already-enabled teams are skipped.
+
+ The wave commits atomically: a mid-loop failure enrolls nobody, so an activity retry
+ starts from a clean slate instead of topping up a partial wave with a fresh counter.
+ A worker crash in the gap after commit but before the activity completes can still
+ replay one full wave; that enrolls the next-worst qualifying teams a day early, which
+ is acceptable.
+ """
+ enrolled: list[int] = []
+ with transaction.atomic():
+ enrolled = _enroll_candidates_locked(report)
+ return enrolled
+
+
+def _enroll_candidates_locked(report: EnrollmentCensusReport) -> list[int]:
+ enrolled: list[int] = []
+ for candidate in report.candidates:
+ if len(enrolled) >= MAX_ENROLLMENTS_PER_RUN:
+ break
+ # query_log_archive outlives team deletion: a deleted team's scans still qualify it,
+ # and creating a config for it would raise and abort the rest of the wave.
+ if not Team.objects.filter(id=candidate.stats.team_id).exists():
+ logger.info("experiment_precompute_enrollment_skipped_deleted_team", team_id=candidate.stats.team_id)
+ continue
+ try:
+ with transaction.atomic():
+ config, _ = TeamExperimentsConfig.objects.get_or_create(team_id=candidate.stats.team_id)
+ except IntegrityError:
+ continue
+ if config.experiment_precomputation_enabled:
+ continue
+ if config.precomputation_enabled_set_by == TeamExperimentsConfig.PrecomputationEnabledSetBy.MANUAL:
+ logger.info(
+ "experiment_precompute_enrollment_skipped_manual",
+ team_id=candidate.stats.team_id,
+ )
+ continue
+ # Conditional UPDATE, not a save of the read row: a human toggling the team between
+ # our read and this write must win, in either direction.
+ updated = (
+ TeamExperimentsConfig.objects.filter(team_id=candidate.stats.team_id)
+ .filter(experiment_precomputation_enabled=False)
+ .exclude(precomputation_enabled_set_by=TeamExperimentsConfig.PrecomputationEnabledSetBy.MANUAL)
+ .update(
+ experiment_precomputation_enabled=True,
+ precomputation_enabled_set_by=TeamExperimentsConfig.PrecomputationEnabledSetBy.AUTO,
+ )
+ )
+ if not updated:
+ continue
+ enrolled.append(candidate.stats.team_id)
+ logger.info(
+ "experiment_precompute_enrollment_enrolled",
+ team_id=candidate.stats.team_id,
+ reasons=list(candidate.reasons),
+ total_read_bytes=candidate.stats.total_read_bytes,
+ running_experiments=candidate.running_experiments,
+ running_metrics=candidate.running_metrics,
+ )
+ return enrolled
+
+
def run_enrollment_census_sync(window_days: int = CENSUS_WINDOW_DAYS) -> EnrollmentCensusReport:
stats = fetch_direct_scan_stats(window_days)
report = build_census_report(stats, window_days)
@@ -238,11 +317,17 @@ def run_enrollment_census_sync(window_days: int = CENSUS_WINDOW_DAYS) -> Enrollm
max_read_bytes=excluded_team.stats.max_read_bytes,
total_read_bytes=excluded_team.stats.total_read_bytes,
)
+ enrolled: list[int] = []
+ if settings.EXPERIMENT_PRECOMPUTE_ENROLLMENT_MODE == ENROLLMENT_MODE_ENROLL:
+ enrolled = enroll_candidates(report)
+
logger.info(
"experiment_precompute_enrollment_census_finished",
window_days=report.window_days,
evaluated_teams=report.evaluated_teams,
candidates=len(report.candidates),
excluded=len(report.excluded),
+ mode=settings.EXPERIMENT_PRECOMPUTE_ENROLLMENT_MODE,
+ enrolled=enrolled,
)
return report
diff --git a/products/experiments/backend/temporal/test_enrollment_census_logic.py b/products/experiments/backend/temporal/test_enrollment_census_logic.py
index b280a5a4ffae..82f38341dd36 100644
--- a/products/experiments/backend/temporal/test_enrollment_census_logic.py
+++ b/products/experiments/backend/temporal/test_enrollment_census_logic.py
@@ -4,18 +4,27 @@ from typing import Any
from freezegun import freeze_time
from posthog.test.base import BaseTest
+from unittest.mock import patch
+from django.test import override_settings
from django.utils import timezone
from parameterized import parameterized
+from posthog.models.team import Team
+
from products.experiments.backend.models.experiment import Experiment, ExperimentSavedMetric, ExperimentToSavedMetric
+from products.experiments.backend.models.team_experiments_config import TeamExperimentsConfig
from products.experiments.backend.temporal.enrollment_census_logic import (
BUILD_CAP_EXCLUSION_BYTES,
EXCLUSION_BUILD_BYTE_CAP,
+ MAX_ENROLLMENTS_PER_RUN,
+ EnrollmentCensusReport,
TeamDirectScanStats,
TeamRunningLoad,
build_census_report,
+ enroll_candidates,
+ run_enrollment_census_sync,
running_experiment_load,
)
from products.feature_flags.backend.models.feature_flag import FeatureFlag
@@ -97,3 +106,83 @@ class TestEnrollmentCensusCriteria(BaseTest):
assert running_experiment_load([self.team.id]) == {
self.team.id: TeamRunningLoad(running_experiments=1, running_metrics=4)
}
+
+
+class TestEnrollmentWrites(BaseTest):
+ def _team(self) -> Team:
+ return Team.objects.create(organization=self.organization, name=f"team-{uuid.uuid4().hex[:8]}")
+
+ def _report_for(self, teams: list[Team]) -> EnrollmentCensusReport:
+ # Descending bytes in list order, matching the census sort.
+ stats = [
+ _stats(team_id=team.id, total_read_bytes=(len(teams) - i + 5) * 10**12) for i, team in enumerate(teams)
+ ]
+ return build_census_report(stats, window_days=14)
+
+ def test_enrolls_worst_first_up_to_cap(self):
+ teams = [self._team() for _ in range(MAX_ENROLLMENTS_PER_RUN + 2)]
+ report = self._report_for(teams)
+
+ enrolled = enroll_candidates(report)
+
+ assert enrolled == [team.id for team in teams[:MAX_ENROLLMENTS_PER_RUN]]
+ for team in teams[:MAX_ENROLLMENTS_PER_RUN]:
+ config = TeamExperimentsConfig.objects.get(team=team)
+ assert config.experiment_precomputation_enabled
+ assert config.precomputation_enabled_set_by == TeamExperimentsConfig.PrecomputationEnabledSetBy.AUTO
+ for team in teams[MAX_ENROLLMENTS_PER_RUN:]:
+ assert not TeamExperimentsConfig.objects.filter(team=team, experiment_precomputation_enabled=True).exists()
+
+ def test_never_overrides_a_human_and_skips_enabled_without_burning_cap(self):
+ manually_disabled, already_enabled = self._team(), self._team()
+ TeamExperimentsConfig.objects.update_or_create(
+ team=manually_disabled,
+ defaults={
+ "experiment_precomputation_enabled": False,
+ "precomputation_enabled_set_by": TeamExperimentsConfig.PrecomputationEnabledSetBy.MANUAL,
+ },
+ )
+ TeamExperimentsConfig.objects.update_or_create(
+ team=already_enabled,
+ defaults={
+ "experiment_precomputation_enabled": True,
+ "precomputation_enabled_set_by": TeamExperimentsConfig.PrecomputationEnabledSetBy.MANUAL,
+ },
+ )
+ # More fresh teams than cap slots: if the two skipped teams burned slots,
+ # fewer than a full capful would enroll.
+ fresh_teams = [self._team() for _ in range(MAX_ENROLLMENTS_PER_RUN)]
+ report = self._report_for([manually_disabled, already_enabled, *fresh_teams])
+
+ enrolled = enroll_candidates(report)
+
+ assert enrolled == [team.id for team in fresh_teams]
+ config = TeamExperimentsConfig.objects.get(team=manually_disabled)
+ assert not config.experiment_precomputation_enabled
+ assert config.precomputation_enabled_set_by == TeamExperimentsConfig.PrecomputationEnabledSetBy.MANUAL
+
+ @parameterized.expand([("report_only", "report_only", False), ("enroll", "enroll", True)])
+ def test_mode_gates_the_write(self, _name: str, mode: str, expect_write: bool):
+ team = self._team()
+ row = (team.id, 100, 0, 10**9, 6 * 10**12, 0, 3)
+ with (
+ override_settings(EXPERIMENT_PRECOMPUTE_ENROLLMENT_MODE=mode),
+ patch(
+ "products.experiments.backend.temporal.enrollment_census_logic.sync_execute",
+ return_value=[row],
+ ),
+ ):
+ run_enrollment_census_sync()
+
+ enabled = TeamExperimentsConfig.objects.filter(team=team, experiment_precomputation_enabled=True).exists()
+ assert enabled == expect_write
+
+ def test_deleted_team_is_skipped_and_later_candidates_still_enroll(self):
+ fresh = self._team()
+ deleted_team_stats = _stats(team_id=999_999_999, total_read_bytes=9 * 10**12)
+ fresh_stats = _stats(team_id=fresh.id, total_read_bytes=6 * 10**12)
+ report = build_census_report([deleted_team_stats, fresh_stats], window_days=14)
+
+ enrolled = enroll_candidates(report)
+
+ assert enrolled == [fresh.id]