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(experiments): delete dead app-layer helpers and finished commands (#100936)

Anders714425630d3e
diff --git a/posthog/constants.py b/posthog/constants.py
index ad7d54969480..bf8f9af6b279 100644
--- a/posthog/constants.py
+++ b/posthog/constants.py
@@ -335,7 +335,6 @@ SUBSCRIPTION_AI_PROMPT_FEATURE_FLAG_KEY = "ai-subscriptions"
# Enable only after every subscriptions worker has deployed the gallery claim boundary. Older workers
# share the v2 activity name and would otherwise send the legacy layout during a rolling deployment.
SUBSCRIPTION_SLACK_GALLERY_FEATURE_FLAG_KEY = "subscription-slack-gallery"
-EXPERIMENTS_SYNC_QUERIES_FEATURE_FLAG_KEY = "experiments-sync-queries"
EXPERIMENTS_RETENTION_METRIC_EVENTS_PREAGGREGATION_FEATURE_FLAG_KEY = (
"experiments-retention-metric-events-preaggregation"
)
diff --git a/posthog/management/commands/backfill_team_experiment_stats_method.py b/posthog/management/commands/backfill_team_experiment_stats_method.py
deleted file mode 100644
index 0e35c137bd2e..000000000000
--- a/posthog/management/commands/backfill_team_experiment_stats_method.py
+++ /dev/null
@@ -1,61 +0,0 @@
-from django.core.management.base import BaseCommand
-
-from posthog.models import Organization, Team
-
-
-class Command(BaseCommand):
- help = "Backfill default_experiment_stats_method from Organization to Team"
-
- def add_arguments(self, parser):
- parser.add_argument(
- "--dry-run",
- action="store_true",
- help="Show what would be updated without making changes",
- )
- parser.add_argument(
- "--batch-size",
- type=int,
- default=1000,
- help="Number of organizations to process before printing progress (default: 1000)",
- )
-
- def handle(self, *args, **options):
- dry_run = options["dry_run"]
- batch_size = options["batch_size"]
-
- # Get orgs with non-default stats method (frequentist)
- # Most orgs will have bayesian (default) or null, so this should be a small subset
- orgs_queryset = Organization.objects.exclude(default_experiment_stats_method__isnull=True).exclude(
- default_experiment_stats_method="bayesian"
- )
-
- org_count = orgs_queryset.count()
- self.stdout.write(f"Found {org_count} organizations with non-default experiment stats method")
-
- if org_count == 0:
- self.stdout.write("Nothing to backfill.")
- return
-
- total_teams = 0
- processed_orgs = 0
-
- # Use iterator() to avoid loading all orgs into memory
- for org in orgs_queryset.only("id", "name", "default_experiment_stats_method").iterator(chunk_size=batch_size):
- team_count = (
- Team.objects.filter(organization_id=org.id).update(
- default_experiment_stats_method=org.default_experiment_stats_method
- )
- if not dry_run
- else Team.objects.filter(organization_id=org.id).count()
- )
-
- total_teams += team_count
- processed_orgs += 1
-
- if processed_orgs % batch_size == 0:
- self.stdout.write(f"Progress: {processed_orgs}/{org_count} orgs processed, {total_teams} teams updated")
-
- action = "Would update" if dry_run else "Updated"
- self.stdout.write(
- f"\n{'Dry run complete' if dry_run else 'Backfill complete'}. {action} {total_teams} teams across {processed_orgs} organizations."
- )
diff --git a/posthog/management/commands/populate_experiment_timeseries.py b/posthog/management/commands/populate_experiment_timeseries.py
deleted file mode 100644
index 676e842e063d..000000000000
--- a/posthog/management/commands/populate_experiment_timeseries.py
+++ /dev/null
@@ -1,175 +0,0 @@
-import traceback
-from datetime import date, datetime, timedelta
-from typing import Union
-from zoneinfo import ZoneInfo
-
-from django.core.management.base import BaseCommand
-from django.utils import timezone
-
-from posthog.schema import ExperimentFunnelMetric, ExperimentMeanMetric, ExperimentQuery, ExperimentRatioMetric
-
-from products.experiments.backend.hogql_queries.experiment_query_runner import ExperimentQueryRunner
-from products.experiments.backend.models.experiment import Experiment, ExperimentMetricResult
-
-
-class Command(BaseCommand):
- help = "Populate ExperimentMetricResult records for testing experiment timeseries functionality"
-
- def add_arguments(self, parser):
- parser.add_argument(
- "--experiment-id",
- type=int,
- required=True,
- help="Experiment ID to populate timeseries data for",
- )
- parser.add_argument(
- "--metric-uuid",
- type=str,
- required=True,
- help="Metric UUID to populate data for",
- )
- parser.add_argument(
- "--force",
- action="store_true",
- help="Force recalculation of existing records",
- )
-
- def handle(self, *args, **options):
- experiment_id = options["experiment_id"]
- metric_uuid = options["metric_uuid"]
- force = options["force"]
-
- try:
- self.populate_timeseries(
- experiment_id=experiment_id,
- metric_uuid=metric_uuid,
- force=force,
- )
- except Exception as e:
- error_msg = f"Error populating experiment timeseries: {e}\n\nFull traceback:\n{traceback.format_exc()}"
- self.stdout.write(self.style.ERROR(error_msg))
-
- def populate_timeseries(self, experiment_id: int, metric_uuid: str, force: bool) -> None:
- """
- Populate ExperimentMetricResult records for the entire experiment duration using real calculations
- """
- try:
- experiment = Experiment.objects.get(id=experiment_id, deleted=False)
- except Experiment.DoesNotExist:
- raise ValueError(f"Experiment {experiment_id} not found or deleted")
-
- all_metrics = (experiment.metrics or []) + (experiment.metrics_secondary or [])
- metric = next((m for m in all_metrics if m.get("uuid") == metric_uuid), None)
- if not metric:
- raise ValueError(f"Metric {metric_uuid} not found in experiment {experiment_id}")
-
- metric_type = metric.get("metric_type")
- metric_obj: Union[ExperimentMeanMetric, ExperimentFunnelMetric, ExperimentRatioMetric]
- if metric_type == "mean":
- metric_obj = ExperimentMeanMetric(**metric)
- elif metric_type == "funnel":
- metric_obj = ExperimentFunnelMetric(**metric)
- elif metric_type == "ratio":
- metric_obj = ExperimentRatioMetric(**metric)
- else:
- raise ValueError(f"Unknown metric type: {metric_type}")
-
- # Determine project timezone for display purposes
- project_tz = ZoneInfo(experiment.team.timezone) if experiment.team.timezone else ZoneInfo("UTC")
- utc_tz = ZoneInfo("UTC")
-
- start_date = experiment.start_date.date() if experiment.start_date else experiment.created_at.date()
- end_date = experiment.end_date.date() if experiment.end_date else date.today()
-
- self.stdout.write(f"Populating timeseries for experiment {experiment_id} ({experiment.name})")
- self.stdout.write(f"Metric: {metric.get('name', metric_uuid)}")
- self.stdout.write(f"Date range: {start_date} to {end_date}")
- self.stdout.write(f"Project timezone: {project_tz}")
-
- experiment_dates = []
- current_date = start_date
- while current_date <= end_date:
- experiment_dates.append(current_date)
- current_date += timedelta(days=1)
-
- self.stdout.write(f"Total days: {len(experiment_dates)}")
-
- created_count = 0
- updated_count = 0
- skipped_count = 0
-
- for experiment_date in experiment_dates:
- # For backfilling, use 2am UTC (consistent with daily recalculation schedule at "0 2 * * *")
- # This ensures backfilled data matches what would be calculated by the daily schedule
- query_to_utc = datetime.combine(experiment_date, datetime.min.time().replace(hour=2), tzinfo=utc_tz)
-
- # Cumulative calculation: always from experiment start to the query time
- query_from_utc = experiment.start_date if experiment.start_date else experiment.created_at
-
- if (
- not force
- and ExperimentMetricResult.objects.filter(
- experiment_id=experiment_id, metric_uuid=metric_uuid, query_to=query_to_utc
- ).exists()
- ):
- skipped_count += 1
- continue
-
- self.stdout.write(f"Calculating for {experiment_date} (up to {query_to_utc.strftime('%H:%M %Z')})...")
-
- status = "completed"
- result_data = None
- completed_at = None
- error_message = None
-
- try:
- experiment_query = ExperimentQuery(
- experiment_id=experiment_id,
- metric=metric_obj,
- )
-
- # Evaluate the experiment as of query_to_utc (clamped to end_date inside the runner).
- # error_event_context=None: an ops backfill is not user-visible pain.
- query_runner = ExperimentQueryRunner(
- query=experiment_query, team=experiment.team, as_of=query_to_utc, error_event_context=None
- )
- result = query_runner._calculate()
- result_data = result.model_dump()
-
- # Record when the calculation actually completed
- completed_at = timezone.now()
-
- except Exception as e:
- status = "failed"
- error_message = str(e)
- completed_at = None # Never completed
- self.stdout.write(self.style.WARNING(f" Failed: {error_message}"))
-
- metric_result, created = ExperimentMetricResult.objects.update_or_create(
- experiment_id=experiment_id,
- metric_uuid=metric_uuid,
- query_to=query_to_utc,
- defaults={
- "query_from": query_from_utc,
- "status": status,
- "result": result_data,
- "query_id": None,
- "completed_at": completed_at,
- "error_message": error_message,
- },
- )
-
- if created:
- created_count += 1
- else:
- updated_count += 1
-
- self.stdout.write(
- self.style.SUCCESS(
- f"Successfully populated timeseries data:\n"
- f" Created: {created_count} records\n"
- f" Updated: {updated_count} records\n"
- f" Skipped: {skipped_count} records\n"
- f" Total: {len(experiment_dates)} days"
- )
- )
diff --git a/posthog/models/resource_transfer/test/__snapshots__/test_visitor_field_snapshots.ambr b/posthog/models/resource_transfer/test/__snapshots__/test_visitor_field_snapshots.ambr
index 32a2ff8cbe68..29d11b29689a 100644
--- a/posthog/models/resource_transfer/test/__snapshots__/test_visitor_field_snapshots.ambr
+++ b/posthog/models/resource_transfer/test/__snapshots__/test_visitor_field_snapshots.ambr
@@ -721,7 +721,6 @@
'get_next_by_updated_at',
'get_previous_by_created_at',
'get_previous_by_updated_at',
- 'get_stats_config',
'get_status_display',
'get_type_display',
'holdout_id',
diff --git a/products/experiments/backend/experiment_service.py b/products/experiments/backend/experiment_service.py
index 9acaf99b32ac..f032881549a2 100644
--- a/products/experiments/backend/experiment_service.py
+++ b/products/experiments/backend/experiment_service.py
@@ -647,14 +647,6 @@ class ExperimentService:
return rendered[: cls._ERROR_VALUE_MAX_LEN] + "...(truncated)"
return rendered
- @classmethod
- def strip_unknown_exposure_criteria_keys(cls, exposure_criteria: dict | None) -> dict | None:
- """Drop unknown top-level keys from stored criteria (writes accepted them before
- the unknown-key rejection below existed)."""
- if not isinstance(exposure_criteria, dict):
- return exposure_criteria
- return {k: v for k, v in exposure_criteria.items() if k in ExperimentExposureCriteria.model_fields}
-
@classmethod
def validate_experiment_exposure_criteria(cls, exposure_criteria: object) -> None:
"""Validate experiment exposure criteria payloads.
@@ -672,8 +664,7 @@ class ExperimentService:
)
# Reject unknown top-level keys: they used to be silently saved, and the strict
- # read-side parse then broke every results/exposure query for the experiment
- # (reads now tolerate them, but new writes should fail fast with a pointer).
+ # read-side parse then broke every results/exposure query for the experiment.
unknown_keys = set(exposure_criteria) - set(ExperimentExposureCriteria.model_fields)
if unknown_keys:
hint = (
@@ -4192,9 +4183,7 @@ class ExperimentService:
"ensure_experience_continuity": bool(source_experiment.feature_flag.ensure_experience_continuity),
}
- # Stored criteria can carry unknown top-level keys accepted before writes rejected
- # them — strip those instead of failing the clone on data the user didn't write.
- cloned_exposure_criteria = self.strip_unknown_exposure_criteria_keys(source_experiment.exposure_criteria)
+ cloned_exposure_criteria = source_experiment.exposure_criteria
self.validate_experiment_exposure_criteria(cloned_exposure_criteria)
self.validate_experiment_metrics(source_experiment.metrics)
self.validate_experiment_metrics(source_experiment.metrics_secondary)
diff --git a/products/experiments/backend/hogql_queries/exposure_query_logic.py b/products/experiments/backend/hogql_queries/exposure_query_logic.py
index 5a005fbf719d..d904eb233d06 100644
--- a/products/experiments/backend/hogql_queries/exposure_query_logic.py
+++ b/products/experiments/backend/hogql_queries/exposure_query_logic.py
@@ -110,11 +110,7 @@ def normalize_to_exposure_criteria(
# Convert dict to typed object
if isinstance(exposure_criteria, dict):
- # Copy only known fields before the strict (extra="forbid") parse: the write-side
- # validator never rejected unknown top-level keys, so saved criteria can carry
- # stray ones (e.g. `properties`, which belongs at exposure_config.properties) —
- # erroring here would break every results/exposure query for that experiment.
- criteria_copy = {k: v for k, v in exposure_criteria.items() if k in ExperimentExposureCriteria.model_fields}
+ criteria_copy = dict(exposure_criteria)
# Also normalize nested configs if present
for config_key in ("exposure_config", "activation_config"):
config = criteria_copy.get(config_key)
diff --git a/products/experiments/backend/hogql_queries/test/data/customers.csv b/products/experiments/backend/hogql_queries/test/data/customers.csv
deleted file mode 100644
index 9d80cb84111b..000000000000
--- a/products/experiments/backend/hogql_queries/test/data/customers.csv
+++ /dev/null
@@ -1,6 +0,0 @@
-customer_id,customer_created_at,customer_name,customer_email
-user_control_0,"2023-01-01","John Doe","[email protected]"
-user_test_1,"2023-01-02","Jane Doe","[email protected]"
-user_test_2,"2023-01-03","John Smith","[email protected]"
-user_test_3,"2023-01-06","Jane Smith","[email protected]"
-user_extra,"2023-01-07","John Doe Jr","[email protected]"
\ No newline at end of file
diff --git a/products/experiments/backend/hogql_queries/test/data/subscriptions.csv b/products/experiments/backend/hogql_queries/test/data/subscriptions.csv
deleted file mode 100644
index 7c8fa86ddc42..000000000000
--- a/products/experiments/backend/hogql_queries/test/data/subscriptions.csv
+++ /dev/null
@@ -1,6 +0,0 @@
-subscription_id,subscription_created_at,subscription_customer_id,subscription_amount
-"1","2023-01-02","user_control_0",100
-"2","2023-01-03","user_test_1",50
-"3","2023-01-04","user_test_2",75
-"4","2023-01-05","user_test_3",80
-"5","2023-01-06","user_extra",90
\ No newline at end of file
diff --git a/products/experiments/backend/hogql_queries/test/data/usage.csv b/products/experiments/backend/hogql_queries/test/data/usage.csv
deleted file mode 100644
index 1d3f125d35a8..000000000000
--- a/products/experiments/backend/hogql_queries/test/data/usage.csv
+++ /dev/null
@@ -1,7 +0,0 @@
-id,ds,userid,usage
-1,"2023-01-01","user_control_0",1000
-2,"2023-01-02","user_test_1",500
-3,"2023-01-03","user_test_2",750
-4,"2023-01-04","internal_test_1",100000
-5,"2023-01-06","user_test_3",800
-6,"2023-01-07","user_extra",900
\ No newline at end of file
diff --git a/products/experiments/backend/hogql_queries/test/test_exposure_query_logic.py b/products/experiments/backend/hogql_queries/test/test_exposure_query_logic.py
index 2c44d3fb1548..959c8a034d15 100644
--- a/products/experiments/backend/hogql_queries/test/test_exposure_query_logic.py
+++ b/products/experiments/backend/hogql_queries/test/test_exposure_query_logic.py
@@ -122,20 +122,6 @@ class TestNormalizeToExposureCriteria:
# Should return the exact same object, not a copy
assert result is typed_criteria
- def test_drops_unknown_keys(self):
- # The write path historically accepted unknown top-level keys, so saved
- # criteria can carry e.g. a stray `properties` — the strict parse must not
- # break on them.
- input_dict = {
- "filterTestAccounts": True,
- "properties": [{"key": "email", "value": "test", "operator": "icontains", "type": "person"}],
- }
-
- result = normalize_to_exposure_criteria(input_dict)
-
- assert result is not None
- assert result.filterTestAccounts is True
-
class TestGetTestAccountsFilter:
_team_filter = {"key": "$host", "type": "event", "value": "localhost", "operator": "not_icontains"}
diff --git a/products/experiments/backend/models/experiment.py b/products/experiments/backend/models/experiment.py
index 9049fbcf9afb..792548e3c07e 100644
--- a/products/experiments/backend/models/experiment.py
+++ b/products/experiments/backend/models/experiment.py
@@ -295,9 +295,6 @@ class Experiment(FileSystemSyncMixin, ModelActivityMixin, RootTeamMixin, models.
"created_at": self.created_at,
}
- def get_stats_config(self, key: str):
- return self.stats_config.get(key) if self.stats_config else None
-
@classmethod
def get_file_system_unfiled(cls, team: "Team", surface: str = DEFAULT_SURFACE) -> QuerySet["Experiment"]:
base_qs = cls.objects.filter(team=team).exclude(deleted=True)
diff --git a/products/experiments/backend/test/test_experiment_service.py b/products/experiments/backend/test/test_experiment_service.py
index 139ed469a349..d67e642e1565 100644
--- a/products/experiments/backend/test/test_experiment_service.py
+++ b/products/experiments/backend/test/test_experiment_service.py
@@ -2518,26 +2518,6 @@ class TestExperimentService(APIBaseTest):
# Same flag key → reuses the existing flag
assert dup.feature_flag.id == source.feature_flag.id
- def test_duplicate_experiment_strips_legacy_unknown_exposure_criteria_keys(self):
- # Stored criteria can carry unknown keys accepted before write-side rejection;
- # duplicating such an experiment must succeed and drop them.
- self._create_flag(key="dup-legacy-criteria")
- service = self._service()
- source = service.create_experiment(
- name="Legacy criteria",
- feature_flag_key="dup-legacy-criteria",
- exposure_criteria={"filterTestAccounts": True},
- )
- source.exposure_criteria = {"filterTestAccounts": True, "properties": [{"key": "email"}]}
- source.save(update_fields=["exposure_criteria"])
-
- dup = service.duplicate_experiment(source)
-
- criteria = dup.exposure_criteria
- assert criteria is not None
- assert criteria.get("filterTestAccounts") is True
- assert "properties" not in criteria
-
def test_duplicate_experiment_generates_unique_name(self):
self._create_flag(key="dup-unique-1")
service = self._service()