: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
refactor(signals): read experiment orientation through the facade (#126283)
Anders7b70b0710e94
diff --git a/products/experiments/backend/facade/contracts.py b/products/experiments/backend/facade/contracts.pyindex 0e0b0c2e3432..5037868c6e72 100644--- a/products/experiments/backend/facade/contracts.py+++ b/products/experiments/backend/facade/contracts.py@@ -552,6 +552,30 @@ class RunningExperiment:flag_key: str+@frozen+class RecentExperiment:+ """One of a team's most recently modified experiments."""++ id: int+ name: str+ archived: bool+ start_date: datetime | None+ end_date: datetime | None+ feature_flag_key: str+ updated_at: datetime+++@frozen+class ExperimentOrientation:+ """A team's experiment counts and its most recently modified experiments. Deleted experiments are left out."""++ total_count: int+ # Started, not ended, and not archived.+ running_count: int+ # Most recently modified first.+ recent: tuple[RecentExperiment, ...]++@frozenclass ExperimentChanged:"""One save or delete of an experiment, as `connect_experiment_changed` receivers get it."""diff --git a/products/experiments/backend/facade/scout.py b/products/experiments/backend/facade/scout.pynew file mode 100644index 000000000000..1ab0f4771a12--- /dev/null+++ b/products/experiments/backend/facade/scout.py@@ -0,0 +1,29 @@+"""Experiment reads for the signals scout harness, which orients its agents on a team's experiments."""++from products.experiments.backend.facade.contracts import ExperimentOrientation, RecentExperiment+from products.experiments.backend.models.experiment import Experiment+++def experiment_orientation(*, team_id: int, recent_limit: int) -> ExperimentOrientation:+ """The team's experiment counts and its `recent_limit` most recently modified experiments."""+ # `team=` matches this team only. RootTeamQuerySet rewrites `team_id=` to the parent team when the team has one.+ experiments = Experiment.objects.filter(team=team_id).exclude(deleted=True)+ recent = experiments.order_by("-updated_at").values(+ "id", "name", "archived", "start_date", "end_date", "feature_flag__key", "updated_at"+ )[:recent_limit]+ return ExperimentOrientation(+ total_count=experiments.count(),+ running_count=experiments.filter(archived=False, start_date__isnull=False, end_date__isnull=True).count(),+ recent=tuple(+ RecentExperiment(+ id=row["id"],+ name=row["name"],+ archived=row["archived"],+ start_date=row["start_date"],+ end_date=row["end_date"],+ feature_flag_key=row["feature_flag__key"],+ updated_at=row["updated_at"],+ )+ for row in recent+ ),+ )diff --git a/products/experiments/backend/test/test_facade_scout.py b/products/experiments/backend/test/test_facade_scout.pynew file mode 100644index 000000000000..3a15790b6daa--- /dev/null+++ b/products/experiments/backend/test/test_facade_scout.py@@ -0,0 +1,59 @@+from datetime import UTC, datetime, timedelta++from posthog.test.base import BaseTest++from posthog.models.team import Team++from products.experiments.backend.facade import testing+from products.experiments.backend.facade.contracts import RecentExperiment+from products.experiments.backend.facade.scout import experiment_orientation+from products.experiments.backend.models.experiment import Experiment+from products.feature_flags.backend.models.feature_flag import FeatureFlag+++class TestExperimentOrientation(BaseTest):+ def test_counts_and_lists_the_live_experiments_of_the_team(self) -> None:+ other_team = Team.objects.create(organization=self.organization, name="Other")+ updated = datetime(2026, 10, 1, tzinfo=UTC)+ day = timedelta(days=1)+ started = updated - 10 * day+ ids: dict[str, int] = {}+ for key, team, end_date, archived, deleted, days_before_update in [+ ("running", self.team, None, False, False, 1),+ ("archived", self.team, None, True, False, 2),+ ("stopped", self.team, updated - 5 * day, False, False, 3),+ ("deleted_unset", self.team, None, False, False, 4),+ ("deleted", self.team, None, False, True, 0),+ ("other_team", other_team, None, False, False, 0),+ ]:+ flag = FeatureFlag.objects.create(team=team, key=f"flag-{key}", created_by=self.user)+ ids[key] = testing.create_experiment(+ team_id=team.id,+ feature_flag_id=flag.id,+ name=key,+ start_date=started,+ end_date=end_date,+ archived=archived,+ deleted=deleted,+ updated_at=updated - days_before_update * day,+ )+ Experiment.objects.filter(id=ids["deleted_unset"]).update(deleted=None)+ draft_flag = FeatureFlag.objects.create(team=self.team, key="flag-draft", created_by=self.user)+ testing.create_experiment(+ team_id=self.team.id, feature_flag_id=draft_flag.id, name="draft", updated_at=updated - 9 * day+ )++ orientation = experiment_orientation(team_id=self.team.id, recent_limit=3)++ assert orientation.total_count == 5+ assert orientation.running_count == 2+ assert [experiment.id for experiment in orientation.recent] == [ids["running"], ids["archived"], ids["stopped"]]+ assert orientation.recent[2] == RecentExperiment(+ id=ids["stopped"],+ name="stopped",+ archived=False,+ start_date=started,+ end_date=updated - 5 * day,+ feature_flag_key="flag-stopped",+ updated_at=updated - 3 * day,+ )diff --git a/products/signals/backend/scout_harness/profile/builders.py b/products/signals/backend/scout_harness/profile/builders.pyindex ba9a4279f1a0..880ba1f2bf46 100644--- a/products/signals/backend/scout_harness/profile/builders.py+++ b/products/signals/backend/scout_harness/profile/builders.py@@ -57,13 +57,8 @@ from products.business_knowledge.backend.models.knowledge_source import Knowledgfrom products.cdp.backend.models.hog_functions.hog_function import HogFunctionfrom products.cohorts.backend.models.cohort import Cohortfrom products.dashboards.backend.models.dashboard import Dashboard--# `products.experiments` ships a facade (api.py + contracts.py) but the contract is-# not yet enforced by CI (no `backend:contract-check` script in package.json). The-# facade exposes `create_experiment` but no list/query helpers, so the read-only-# orientation reader here imports the model directly. When experiments isolation is-# enforced, migrate this to a facade `list_recent_experiments(team, limit)` helper.-from products.experiments.backend.models.experiment import Experiment+from products.experiments.backend.facade import scout as experiments_scout+from products.experiments.backend.facade.contracts import RecentExperimentfrom products.feature_flags.backend.models.feature_flag import FeatureFlagfrom products.notebooks.backend.facade import api as notebooksfrom products.signals.backend.constants import SYSTEM_SCOUT_NAMES@@ -541,27 +536,24 @@ def _recent_experiments(team: Team) -> dict[str, Any]:the model's own `is_running` property. `feature_flag_key` is the cross-ref theagent uses to correlate experiments with the `recent_feature_flags` section."""- qs = Experiment.objects.filter(team=team).filter(Q(deleted=False) | Q(deleted__isnull=True))- total = qs.count()- running = qs.filter(archived=False, start_date__isnull=False, end_date__isnull=True).count()- recent = qs.select_related("feature_flag").order_by("-updated_at")[:RECENT_ENTITY_LIMIT]+ orientation = experiments_scout.experiment_orientation(team_id=team.id, recent_limit=RECENT_ENTITY_LIMIT)return {- "total_count": total,- "running_count": running,+ "total_count": orientation.total_count,+ "running_count": orientation.running_count,"recent": [{"id": exp.id,"name": exp.name,"status": _experiment_status(exp),- "feature_flag_key": exp.feature_flag.key if exp.feature_flag_id else None,- "updated_at": exp.updated_at.isoformat() if exp.updated_at else None,+ "feature_flag_key": exp.feature_flag_key,+ "updated_at": exp.updated_at.isoformat(),}- for exp in recent+ for exp in orientation.recent],}-def _experiment_status(exp: Experiment) -> str:+def _experiment_status(exp: RecentExperiment) -> str:"""Derive single-word experiment status from archive/start/end fields."""if exp.archived:return "archived"diff --git a/products/signals/backend/test/test_scout_harness_profile.py b/products/signals/backend/test/test_scout_harness_profile.pyindex 48b329e4fbad..37d7ec51b3e9 100644--- a/products/signals/backend/test/test_scout_harness_profile.py+++ b/products/signals/backend/test/test_scout_harness_profile.py@@ -36,7 +36,7 @@ from products.business_knowledge.backend.models.knowledge_source import Knowledgfrom products.cdp.backend.models.hog_functions.hog_function import HogFunctionfrom products.cohorts.backend.models.cohort import Cohortfrom products.dashboards.backend.models.dashboard import Dashboard-from products.experiments.backend.models.experiment import Experiment+from products.experiments.backend.facade.testing import create_experimentfrom products.feature_flags.backend.models.feature_flag import FeatureFlagfrom products.notebooks.backend.models import Notebookfrom products.product_analytics.backend.facade.models import Insight@@ -640,19 +640,22 @@ class TestRecentExperiments(BaseTest):def test_running_count_only_counts_started_unfinished_unarchived(self) -> None:now = timezone.now()- Experiment.objects.create(- team=self.team, name="running", feature_flag=self._flag("ff-r"), start_date=now - timedelta(days=1)+ create_experiment(+ team_id=self.team.id,+ name="running",+ feature_flag_id=self._flag("ff-r").id,+ start_date=now - timedelta(days=1),)- Experiment.objects.create(team=self.team, name="draft", feature_flag=self._flag("ff-d"))- Experiment.objects.create(- team=self.team,+ create_experiment(team_id=self.team.id, name="draft", feature_flag_id=self._flag("ff-d").id)+ create_experiment(+ team_id=self.team.id,name="stopped",- feature_flag=self._flag("ff-s"),+ feature_flag_id=self._flag("ff-s").id,start_date=now - timedelta(days=10),end_date=now - timedelta(days=1),)- Experiment.objects.create(- team=self.team, name="archived", feature_flag=self._flag("ff-a"), start_date=now, archived=True+ create_experiment(+ team_id=self.team.id, name="archived", feature_flag_id=self._flag("ff-a").id, start_date=now, archived=True)result = _recent_experiments(self.team)assert result["total_count"] == 4@@ -666,14 +669,16 @@ class TestRecentExperiments(BaseTest):}def test_carries_feature_flag_key_for_cross_reference(self) -> None:- Experiment.objects.create(team=self.team, name="exp", feature_flag=self._flag("my-exp-flag"))+ create_experiment(team_id=self.team.id, name="exp", feature_flag_id=self._flag("my-exp-flag").id)result = _recent_experiments(self.team)assert result["recent"][0]["feature_flag_key"] == "my-exp-flag"def test_team_isolated(self) -> None:other = self.organization.teams.create(name="other")- Experiment.objects.create(- team=other, name="x", feature_flag=FeatureFlag.objects.create(team=other, key="o", created_by=self.user)+ create_experiment(+ team_id=other.id,+ name="x",+ feature_flag_id=FeatureFlag.objects.create(team=other, key="o", created_by=self.user).id,)result = _recent_experiments(self.team)assert result["total_count"] == 0diff --git a/products/signals/backend/test/test_scout_precheck.py b/products/signals/backend/test/test_scout_precheck.pyindex 6c429e8912aa..6efa21110599 100644--- a/products/signals/backend/test/test_scout_precheck.py+++ b/products/signals/backend/test/test_scout_precheck.py@@ -23,6 +23,7 @@ from posthog.models.scoping import team_scopefrom posthog.session_recordings.queries.test.session_replay_sql import produce_replay_summaryfrom products.customer_analytics.backend.facade.testing import create_account+from products.experiments.backend.facade.testing import create_experimentfrom products.signals.backend.models import SignalReport, SignalScoutConfig, SignalScoutRunfrom products.signals.backend.scout_harness.lazy_seed import HARNESS_SEEDED_BYfrom products.signals.backend.scout_harness.precheck import (@@ -348,12 +349,14 @@ class TestSystemTableSkillDefaults(ClickhouseTestMixin, NonAtomicBaseTest):def _seed_experiment(self, *, started: bool, days_since_update: int) -> None:FeatureFlag = apps.get_model("feature_flags", "FeatureFlag")- Experiment = apps.get_model("experiments", "Experiment")flag = FeatureFlag.objects.create(team=self.team, key=f"exp_flag_{started}_{days_since_update}")- experiment = Experiment.objects.create(- team=self.team, name="e", feature_flag=flag, start_date=NOW - timedelta(days=60) if started else None+ create_experiment(+ team_id=self.team.id,+ name="e",+ feature_flag_id=flag.id,+ start_date=NOW - timedelta(days=60) if started else None,+ updated_at=NOW - timedelta(days=days_since_update),)- Experiment.objects.filter(pk=experiment.pk).update(updated_at=NOW - timedelta(days=days_since_update))def _seed_report(self, status: str, *, days_since_update: int) -> None:report = SignalReport.objects.create(team=self.team, status=status, title="r")