: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(autoresearch): use the training base rate for segment cut points (#115977)
posthog[bot]9d9b86014873
diff --git a/products/autoresearch/backend/evaluation/AGENTS.md b/products/autoresearch/backend/evaluation/AGENTS.mdindex b85bde745321..6883521496d7 100644--- a/products/autoresearch/backend/evaluation/AGENTS.md+++ b/products/autoresearch/backend/evaluation/AGENTS.md@@ -31,7 +31,7 @@ It is the only honest number in the product. A holdout AUC of 0.93 says the mode`OUTCOME_INGESTION_GRACE` and `matures_at()`, the first instant a prediction date can be checked. `find_pending_validation_dates()` uses it, and the pipeline's `first_check_expected_at` applies it to the champion's earliest scored date, so the two cannot disagree. It imports nothing heavy, so the facade reads it without loading this package's sandbox code.- `segment_thresholds.py`- The cut points between the Likely, Possible and Unlikely segments. Possible starts at the base rate, and Likely starts at `LIKELY_LIFT` times it, capped halfway between the base rate and 1. The base rate pools the emitted champion's `n_positive` / `n_scored` over the newest `BASE_RATE_DATES` checked dates. Until those dates hold `MIN_BASE_RATE_POSITIVES`, the fixed pair applies. `online_performance()` returns the current pair, which every frontend surface reads, and `champion_score_calibration()` flags a champion whose mean score is far from the realized rate. Class weighting or resampling in `train.py` leaves scores that are not probabilities, and nothing at scoring time corrects it.+ The cut points between the Likely, Possible and Unlikely segments. Possible starts at the base rate, and Likely starts at `LIKELY_LIFT` times it, capped halfway between the base rate and 1. The base rate pools the emitted champion's `n_positive` / `n_scored` over the newest `BASE_RATE_DATES` checked dates. Until those dates hold `MIN_BASE_RATE_POSITIVES`, the champion's training base rate applies: `fit_champion_model()` records the population and positives from before case-control sampling in the model's `metrics` (`training_population`, `training_positives`), and the same floor applies to them. The training window is in the past, so this rate can differ from the realized rate, which replaces it as soon as it is available. A champion fit before the counts were recorded falls back to the fixed pair. `base_rate_source` on the response tells `realized`, `training` and `fixed` apart. `online_performance()` returns the current pair, which every frontend surface reads, and `champion_score_calibration()` flags a champion whose mean score is far from the realized rate. Class weighting or resampling in `train.py` leaves scores that are not probabilities, and nothing at scoring time corrects it.A saved cohort, flag or workflow stores the absolute cut point, so it does not follow a later change in the base rate.## Mental modeldiff --git a/products/autoresearch/backend/evaluation/online_validation.py b/products/autoresearch/backend/evaluation/online_validation.pyindex 83a1157460a1..bc5c60eed3f5 100644--- a/products/autoresearch/backend/evaluation/online_validation.py+++ b/products/autoresearch/backend/evaluation/online_validation.py@@ -44,7 +44,11 @@ from products.autoresearch.backend.dataset.labeling import ()from products.autoresearch.backend.evaluation.history import latest_validation_runsfrom products.autoresearch.backend.evaluation.maturity import matures_at-from products.autoresearch.backend.evaluation.segment_thresholds import BASE_RATE_DATES, segment_thresholds+from products.autoresearch.backend.evaluation.segment_thresholds import (+ BASE_RATE_DATES,+ champion_training_base_rate,+ segment_thresholds,+)from products.autoresearch.backend.inference.failures import INFERENCE_WORKFLOW_TIMEOUTfrom products.autoresearch.backend.inference.sandbox import SandboxInferenceError, _resolve_acting_userfrom products.autoresearch.backend.models import AutoresearchModel, AutoresearchPipeline, AutoresearchRun@@ -347,7 +351,8 @@ def _validate_claimed_date()# The cut point the Predictions tab showed for this date comes from the dates checked before it.thresholds = segment_thresholds(- latest_validation_runs(team.pk, pipeline, limit=BASE_RATE_DATES, before=pending.prediction_date)+ latest_validation_runs(team.pk, pipeline, limit=BASE_RATE_DATES, before=pending.prediction_date),+ training_rate=champion_training_base_rate(team.pk, pipeline),)per_model = {model_id: _ModelValidation(diff --git a/products/autoresearch/backend/evaluation/segment_thresholds.py b/products/autoresearch/backend/evaluation/segment_thresholds.pyindex fc54de33ab90..076b20b053c7 100644--- a/products/autoresearch/backend/evaluation/segment_thresholds.py+++ b/products/autoresearch/backend/evaluation/segment_thresholds.py@@ -2,8 +2,9 @@The cut points between the Likely, Possible and Unlikely segments.A pipeline's cut points follow lift over its realized base rate: Unlikely is below the base rate,-Likely is ``LIKELY_LIFT`` times the base rate or more, and Possible is in between. A fixed pair-applies until the checked dates hold enough positives for a stable rate. The online_performance+Likely is ``LIKELY_LIFT`` times the base rate or more, and Possible is in between. Until the checked+dates hold enough positives for a stable rate, the base rate of the champion's training population+applies, and a fixed pair applies when the champion has no recorded training counts. The online_performanceendpoint returns the current pair, and the frontend reads it from there, so the Predictions tab,the Accuracy tab and online validation cannot disagree."""@@ -12,9 +13,11 @@ from collections.abc import Iterablefrom dataclasses import replacefrom typing import Any+from django.db import models+from posthog.dataclasses import frozen-from products.autoresearch.backend.models import AutoresearchRun+from products.autoresearch.backend.models import AutoresearchModel, AutoresearchPipeline, AutoresearchRunLIKELY_LIFT = 3.0FIXED_LIKELY_THRESHOLD = 0.6@@ -27,6 +30,16 @@ MIN_BASE_RATE_POSITIVES = 10# A mean score this many times above or below the realized rate means the scores are not probabilities.MISCALIBRATION_FACTOR = 2.0+# The unsampled training counts the champion fit records in AutoresearchModel.metrics.+TRAINING_POPULATION_KEY = "training_population"+TRAINING_POSITIVES_KEY = "training_positives"+++class BaseRateSource(models.TextChoices):+ REALIZED = "realized"+ TRAINING = "training"+ FIXED = "fixed"+@frozenclass SegmentThresholds:@@ -36,6 +49,7 @@ class SegmentThresholds:base_rate: float | None# Checked dates the base rate pools.dates: int+ source: BaseRateSource@frozen@@ -67,21 +81,60 @@ def thresholds_for_base_rate(base_rate: float) -> SegmentThresholds:rate = _significant(base_rate)# The cap keeps Likely reachable when LIKELY_LIFT times a high base rate is near or above 100%.likely = min(LIKELY_LIFT * rate, rate + (1 - rate) / 2)- return SegmentThresholds(likely=_significant(likely), possible=rate, base_rate=rate, dates=0)+ return SegmentThresholds(+ likely=_significant(likely), possible=rate, base_rate=rate, dates=0, source=BaseRateSource.REALIZED+ )+++def _stable_rate(positives: int, population: int) -> float | None:+ if positives < MIN_BASE_RATE_POSITIVES or positives >= population:+ return None+ return positives / population+++def training_base_rate(model_metrics: dict[str, Any] | None) -> float | None:+ """+ The base rate of the population a model was fit on, from the counts before case-control sampling.++ The sampled rows overstate the rate by ``1 / negative_sample_rate``, so the fit records the+ unsampled counts. Null for a model fit before the counts were recorded.+ """+ metrics = model_metrics or {}+ return _stable_rate(int(metrics.get(TRAINING_POSITIVES_KEY) or 0), int(metrics.get(TRAINING_POPULATION_KEY) or 0))-def segment_thresholds(runs: Iterable[AutoresearchRun]) -> SegmentThresholds:- """The cut points from the realized base rate of the given completed validation runs."""+def champion_training_base_rate(team_id: int, pipeline: AutoresearchPipeline) -> float | None:+ metrics = (+ AutoresearchModel.objects.for_team(team_id)+ .filter(pipeline=pipeline, role=AutoresearchModel.Role.CHAMPION)+ .values_list("metrics", flat=True)+ .first()+ )+ return training_base_rate(metrics)+++def segment_thresholds(runs: Iterable[AutoresearchRun], *, training_rate: float | None = None) -> SegmentThresholds:+ """+ The cut points from the realized base rate of the given completed validation runs. Until those+ runs hold enough positives, ``training_rate`` sets them, and the fixed pair applies without it.+ """scored = positives = dates = 0for _, metrics in _champion_entries(runs):scored += int(metrics.get("n_scored") or 0)positives += int(metrics.get("n_positive") or 0)dates += 1- if positives < MIN_BASE_RATE_POSITIVES or positives >= scored:- return SegmentThresholds(- likely=FIXED_LIKELY_THRESHOLD, possible=FIXED_POSSIBLE_THRESHOLD, base_rate=None, dates=dates- )- return replace(thresholds_for_base_rate(positives / scored), dates=dates)+ realized_rate = _stable_rate(positives, scored)+ if realized_rate is not None:+ return replace(thresholds_for_base_rate(realized_rate), dates=dates)+ if training_rate is not None:+ return replace(thresholds_for_base_rate(training_rate), dates=dates, source=BaseRateSource.TRAINING)+ return SegmentThresholds(+ likely=FIXED_LIKELY_THRESHOLD,+ possible=FIXED_POSSIBLE_THRESHOLD,+ base_rate=None,+ dates=dates,+ source=BaseRateSource.FIXED,+ )def champion_score_calibration(runs: Iterable[AutoresearchRun], champion_id: str) -> ScoreCalibration | None:diff --git a/products/autoresearch/backend/evaluation/test_online_validation.py b/products/autoresearch/backend/evaluation/test_online_validation.pyindex c2a4f8e18e76..396594f80c61 100644--- a/products/autoresearch/backend/evaluation/test_online_validation.py+++ b/products/autoresearch/backend/evaluation/test_online_validation.py@@ -31,6 +31,7 @@ from products.autoresearch.backend.evaluation.segment_thresholds import (FIXED_LIKELY_THRESHOLD,champion_score_calibration,segment_thresholds,+ training_base_rate,)from products.autoresearch.backend.models import AutoresearchModel, AutoresearchPipeline, AutoresearchRunfrom products.autoresearch.backend.query import BATCH_QUERY, HogQLResult@@ -193,6 +194,40 @@ class TestSegmentThresholds(SimpleTestCase):assert (thresholds.likely, thresholds.possible, thresholds.base_rate) == expectedassert thresholds.dates == len(dates)+ @parameterized.expand(+ [+ ("no_checked_dates_uses_training", [], 0.004, (0.012, 0.004, 0.004, "training")),+ (+ "too_few_realized_positives_uses_training",+ [[("m", "champion", 1000, 5, None)]],+ 0.004,+ (0.012, 0.004, 0.004, "training"),+ ),+ (+ "realized_rate_wins_over_training",+ [[("m", "champion", 2000, 30, None)]],+ 0.004,+ (0.045, 0.015, 0.015, "realized"),+ ),+ ("no_training_rate_is_fixed", [], None, (0.6, 0.2, None, "fixed")),+ ]+ )+ def test_training_rate_applies_until_the_realized_rate_is_stable(self, _name, dates, training_rate, expected):+ thresholds = segment_thresholds([_checked_date(*entries) for entries in dates], training_rate=training_rate)++ assert (thresholds.likely, thresholds.possible, thresholds.base_rate, thresholds.source) == expected++ @parameterized.expand(+ [+ ("recorded_counts", {"training_population": 50_000, "training_positives": 200}, 0.004),+ ("fit_before_counts_were_recorded", {"holdout_auc": 0.7}, None),+ ("too_few_positives", {"training_population": 50_000, "training_positives": 9}, None),+ ("no_metrics", None, None),+ ]+ )+ def test_training_base_rate(self, _name, metrics, expected):+ assert training_base_rate(metrics) == expected+@parameterized.expand([("calibrated", 0.025, False),diff --git a/products/autoresearch/backend/facade/api.py b/products/autoresearch/backend/facade/api.pyindex 46bd042a9bd4..25c95003978e 100644--- a/products/autoresearch/backend/facade/api.py+++ b/products/autoresearch/backend/facade/api.py@@ -45,8 +45,10 @@ from ..evaluation.segment_thresholds import (BASE_RATE_DATES,FIXED_LIKELY_THRESHOLD,LIKELY_LIFT,+ BaseRateSource,champion_score_calibration,segment_thresholds,+ training_base_rate,)from ..inference.failures import INFERENCE_WORKFLOW_TIMEOUTfrom ..models import (@@ -1187,20 +1189,21 @@ def online_performance(def _segment_thresholds(team_id: int, pipeline: AutoresearchPipeline) -> PredictionSegmentThresholds:"""The current cut points, from a fixed window of checked dates so the request's ``limit`` cannot move them."""runs = latest_validation_runs(team_id, pipeline, limit=BASE_RATE_DATES)- thresholds = segment_thresholds(runs)- champion_id = (+ champion = (AutoresearchModel.objects.for_team(team_id).filter(pipeline=pipeline, role=AutoresearchModel.Role.CHAMPION)- .values_list("id", flat=True)+ .values("id", "metrics").first())- calibration = champion_score_calibration(runs, str(champion_id)) if champion_id is not None else None+ thresholds = segment_thresholds(runs, training_rate=training_base_rate(champion["metrics"]) if champion else None)+ calibration = champion_score_calibration(runs, str(champion["id"])) if champion is not None else Nonereturn PredictionSegmentThresholds(likely_threshold=thresholds.likely,possible_threshold=thresholds.possible,likely_lift=LIKELY_LIFT,base_rate=thresholds.base_rate,base_rate_dates=thresholds.dates,+ base_rate_source=thresholds.source,champion_mean_p_y=calibration.mean_p_y if calibration else None,champion_base_rate=calibration.base_rate if calibration else None,scores_miscalibrated=calibration.miscalibrated if calibration else False,@@ -1918,6 +1921,7 @@ SUGGESTION_PRIORITY_CHOICES = AutoresearchSuggestion.Priority.choicesSUGGESTION_STATUS_CHOICES = AutoresearchSuggestion.Status.choicesSUGGESTION_SOURCE_CHOICES = AutoresearchSuggestion.Source.choicesRUN_TYPE_CHOICES = AutoresearchRun.RunType.choices+BASE_RATE_SOURCE_CHOICES = BaseRateSource.choicesRUN_STATUS_CHOICES = AutoresearchRun.Status.choicesFEATURE_DIRECTION_CHOICES = _FeatureDirection.choicesMAX_TOP_FEATURES = _MAX_TOP_FEATURESdiff --git a/products/autoresearch/backend/facade/contracts.py b/products/autoresearch/backend/facade/contracts.pyindex 67842039477c..6dc28c8fb7d8 100644--- a/products/autoresearch/backend/facade/contracts.py+++ b/products/autoresearch/backend/facade/contracts.py@@ -466,6 +466,7 @@ class PredictionSegmentThresholds:likely_lift: floatbase_rate: float | Nonebase_rate_dates: int+ base_rate_source: strchampion_mean_p_y: float | Nonechampion_base_rate: float | Nonescores_miscalibrated: booldiff --git a/products/autoresearch/backend/inference/sandbox.py b/products/autoresearch/backend/inference/sandbox.pyindex 1a8f301d062f..928b05238564 100644--- a/products/autoresearch/backend/inference/sandbox.py+++ b/products/autoresearch/backend/inference/sandbox.py@@ -47,6 +47,7 @@ from datetime import UTC, datetimefrom decimal import Decimalfrom typing import Any, Protocol+from django.db import transactionfrom django.utils import timezone as django_timezoneimport pandas as pd@@ -78,6 +79,7 @@ from products.autoresearch.backend.dataset.labeling import (rolling_selection,scored_lookback_days,)+from products.autoresearch.backend.evaluation.segment_thresholds import TRAINING_POPULATION_KEY, TRAINING_POSITIVES_KEYfrom products.autoresearch.backend.models import AutoresearchModel, AutoresearchPipelinefrom products.autoresearch.backend.query import (BATCH_QUERY,@@ -173,6 +175,9 @@ class MaterializedData:holdout_rows: list[dict[str, Any]] = field(default_factory=list)# The rate the rows were drawn at; the fitted model's scores need its prior correction.negative_sample_rate: float = 1.0+ # The labeled population and its positives before the sample, so the training base rate is not inflated.+ population: int = 0+ positives: int = 0@frozen@@ -225,12 +230,14 @@ def fit_champion_model(Pass the training run's ``anchor_ts`` so the fit sees the anchor set the agent scored.The fit's negative sample rate is saved on the ``model_id`` row before ``model.pkl`` is- written, so no scoring run can load the model without the rate its correction needs.+ written, so no scoring run can load the model without the rate its correction needs. The+ unsampled training counts go into the row's metrics, so the segment cut points can use the+ training base rate before any prediction is checked.``predict.py`` runs once against the holdout features before the model is persisted,so a bundle whose two scripts disagree fails here rather than on the first cadence.- Returns train.py's metrics (holdout_auc, n_train, n_features). Raises+ Returns train.py's metrics (holdout_auc, n_train, n_features) and the training counts. RaisesSandboxInferenceError on any materialization or sandbox failure."""if bundle is None:@@ -250,11 +257,10 @@ def fit_champion_model(raise SandboxInferenceError("No numeric feature columns produced by feature SQL")model_bytes, metrics = _run_train_in_sandbox(bundle=bundle, data=data, pipeline=pipeline)- metrics = {**metrics, "negative_sample_rate": data.negative_sample_rate}+ training_counts = {TRAINING_POPULATION_KEY: data.population, TRAINING_POSITIVES_KEY: data.positives}+ metrics = {**metrics, "negative_sample_rate": data.negative_sample_rate, **training_counts}if model_id is not None:- AutoresearchModel.objects.for_team(team.pk).filter(pk=model_id).update(- negative_sample_rate=data.negative_sample_rate- )+ _record_fit_sample(team_id=team.pk, model_id=model_id, data=data, training_counts=training_counts)write_model(prefix, model_bytes)write_artifact(prefix, _FEATURE_COLUMNS_JSON, json.dumps(data.feature_cols).encode("utf-8"))logger.info(@@ -268,6 +274,16 @@ def fit_champion_model(return metrics+def _record_fit_sample(*, team_id: int, model_id: str, data: MaterializedData, training_counts: dict[str, int]) -> None:+ with transaction.atomic():+ model = AutoresearchModel.objects.for_team(team_id).select_for_update().filter(pk=model_id).first()+ if model is None:+ return+ model.negative_sample_rate = data.negative_sample_rate+ model.metrics = {**(model.metrics or {}), **training_counts}+ model.save(update_fields=["negative_sample_rate", "metrics"])++def score_via_sandbox(*,team: Team,@@ -511,6 +527,8 @@ def materialize_training_data(train_rows=train_rows,holdout_rows=holdout_rows,negative_sample_rate=sample.negative_sample_rate,+ population=sample.population,+ positives=sample.positives,)diff --git a/products/autoresearch/backend/inference/scoring.py b/products/autoresearch/backend/inference/scoring.pyindex 5815ff9529d2..b1b4470953a0 100644--- a/products/autoresearch/backend/inference/scoring.py+++ b/products/autoresearch/backend/inference/scoring.py@@ -68,7 +68,11 @@ from products.autoresearch.backend.dataset.labeling import (rolling_selection,)from products.autoresearch.backend.evaluation.history import latest_validation_runs-from products.autoresearch.backend.evaluation.segment_thresholds import BASE_RATE_DATES, segment_thresholds+from products.autoresearch.backend.evaluation.segment_thresholds import (+ BASE_RATE_DATES,+ champion_training_base_rate,+ segment_thresholds,+)from products.autoresearch.backend.inference.failures import classify_failurefrom products.autoresearch.backend.inference.sandbox import (_FOLD_COL,@@ -395,7 +399,10 @@ def _likely_segment(*, team_id: int, pipeline: AutoresearchPipeline, scored: ScoThe run keeps the count because its score distribution stores only quantiles, and the modellist must not query the prediction events for every pipeline."""- threshold = segment_thresholds(latest_validation_runs(team_id, pipeline, limit=BASE_RATE_DATES)).likely+ threshold = segment_thresholds(+ latest_validation_runs(team_id, pipeline, limit=BASE_RATE_DATES),+ training_rate=champion_training_base_rate(team_id, pipeline),+ ).likelyreturn {"likely_count": sum(1 for row in scored.rows if row["p_y"] >= threshold),"likely_threshold": threshold,diff --git a/products/autoresearch/backend/inference/test_sandbox_inference.py b/products/autoresearch/backend/inference/test_sandbox_inference.pyindex 2711df02dc54..decd40ed6702 100644--- a/products/autoresearch/backend/inference/test_sandbox_inference.py+++ b/products/autoresearch/backend/inference/test_sandbox_inference.py@@ -2,6 +2,7 @@ import ioimport jsonimport base64from decimal import Decimal+from typing import Anyfrom posthog.test.base import BaseTestfrom unittest.mock import MagicMock, patch@@ -16,6 +17,7 @@ from posthog.hogql_queries.query_runner import ExecutionModefrom posthog.models.user import Userfrom products.autoresearch.backend.dataset.labeling import ROLLING_SCORE_LIMIT+from products.autoresearch.backend.evaluation.segment_thresholds import training_base_ratefrom products.autoresearch.backend.inference import sandbox as sandbox_inferencefrom products.autoresearch.backend.inference.sandbox import (_FEATURE_COLUMNS_JSON,@@ -65,11 +67,12 @@ _SCORE_ROWS = [_METRICS_JSON = '{"holdout_auc": 0.73, "n_train": 2, "n_features": 2}'-def _training_materialized() -> sandbox_inference.MaterializedData:+def _training_materialized(**sample: Any) -> sandbox_inference.MaterializedData:return sandbox_inference.MaterializedData(feature_cols=["events_total", "pageviews"],train_rows=[r for r in _TRAINING_ROWS if r["__fold"] != 0],holdout_rows=[r for r in _TRAINING_ROWS if r["__fold"] == 0],+ **sample,)@@ -653,7 +656,11 @@ class TestScoreViaSandbox(TeamScopedTestMixin, BaseTest):stored: dict = {}with (patch.object(sandbox_inference, "read_bundle", return_value=self._bundle()),- patch.object(sandbox_inference, "materialize_training_data", return_value=_training_materialized()),+ patch.object(+ sandbox_inference,+ "materialize_training_data",+ return_value=_training_materialized(negative_sample_rate=0.1, population=50_000, positives=200),+ ),patch.object(sandbox_inference, "write_model", side_effect=lambda prefix, content: stored.update(model=content)),@@ -664,9 +671,15 @@ class TestScoreViaSandbox(TeamScopedTestMixin, BaseTest):),patch.object(sandbox_inference.Sandbox, "create", return_value=fake),):- metrics = fit_champion_model(team=self.team, pipeline=pipeline, prefix=model.artifact_prefix)+ metrics = fit_champion_model(+ team=self.team, pipeline=pipeline, prefix=model.artifact_prefix, model_id=str(model.pk)+ )assert metrics["holdout_auc"] == 0.73+ model.refresh_from_db()+ assert model.negative_sample_rate == 0.1+ # The unsampled counts, so the rate is not inflated by 1 / negative_sample_rate.+ assert training_base_rate(model.metrics) == 0.004assert stored["model"] == b"FITTED" # the fitted model.pkl read back + persistedassert json.loads(stored[_FEATURE_COLUMNS_JSON]) == ["events_total", "pageviews"]assert any(p.endswith("data/train_features.parquet") for p in fake.written) # train run materializes trainingdiff --git a/products/autoresearch/backend/presentation/views/serializers.py b/products/autoresearch/backend/presentation/views/serializers.pyindex 8638b4a99403..12ca750235e3 100644--- a/products/autoresearch/backend/presentation/views/serializers.py+++ b/products/autoresearch/backend/presentation/views/serializers.py@@ -40,6 +40,7 @@ VALIDATION_WARNING_CODES = api.VALIDATION_WARNING_CODESMODEL_ROLE_CHOICES = api.MODEL_ROLE_CHOICESRUN_STATUS_CHOICES = api.RUN_STATUS_CHOICESRUN_TYPE_CHOICES = api.RUN_TYPE_CHOICES+BASE_RATE_SOURCE_CHOICES = api.BASE_RATE_SOURCE_CHOICESTRAINING_RUN_STATUS_CHOICES = api.TRAINING_RUN_STATUS_CHOICESITERATION_STATUS_CHOICES = api.ITERATION_STATUS_CHOICESSUGGESTION_PRIORITY_CHOICES = api.SUGGESTION_PRIORITY_CHOICES@@ -1544,13 +1545,13 @@ class PredictionSegmentThresholdsSerializer(serializers.Serializer):likely_threshold = serializers.FloatField(help_text=("Users with a score at or above this probability are in the Likely segment: likely_lift times the "- "base rate, capped halfway between the base rate and 1. A fixed cut point when base_rate is null."+ "base rate, capped halfway between the base rate and 1. A fixed cut point when base_rate_source is fixed."))possible_threshold = serializers.FloatField(help_text=("Users with a score at or above this probability and below likely_threshold are in the Possible "- "segment, and users below it are Unlikely. Equal to base_rate, or a fixed cut point when base_rate is null."+ "segment, and users below it are Unlikely. Equal to base_rate, or a fixed cut point when base_rate_source is fixed."))likely_lift = serializers.FloatField(@@ -1559,11 +1560,20 @@ class PredictionSegmentThresholdsSerializer(serializers.Serializer):base_rate = serializers.FloatField(allow_null=True,help_text=(- "Fraction of the champion's scored users who did the target event, pooled over the newest checked "- "dates. Null, and the fixed cut points apply, until those dates hold enough positives."+ "The base rate the cut points use. When base_rate_source is realized, the fraction of the champion's scored "+ "users who did the target event, pooled over the newest checked dates. When base_rate_source is training, the "+ "fraction of the champion's training population that did it. Null when base_rate_source is fixed."),)base_rate_dates = serializers.IntegerField(help_text="Number of checked prediction dates the base rate pools.")+ base_rate_source = serializers.ChoiceField(+ choices=BASE_RATE_SOURCE_CHOICES,+ help_text=(+ "Where the cut points come from. realized: the checked dates hold enough positives. training: no "+ "realized base rate yet, so the champion's training population sets it. fixed: neither is available, "+ "so fixed cut points apply."+ ),+ )champion_mean_p_y = serializers.FloatField(allow_null=True,help_text=(diff --git a/products/autoresearch/backend/tests/test_api.py b/products/autoresearch/backend/tests/test_api.pyindex 146ee0057dad..59c070edc96c 100644--- a/products/autoresearch/backend/tests/test_api.py+++ b/products/autoresearch/backend/tests/test_api.py@@ -1228,6 +1228,7 @@ class TestAutoresearchPipelineAPI(TeamScopedTestMixin, APIBaseTest):"likely_lift": 3.0,"base_rate": None,"base_rate_dates": 2,+ "base_rate_source": "fixed","champion_mean_p_y": None,"champion_base_rate": None,"scores_miscalibrated": False,diff --git a/products/autoresearch/frontend/AutoresearchPipelineScene.stories.tsx b/products/autoresearch/frontend/AutoresearchPipelineScene.stories.tsxindex b2a52f6db997..6e3698dfe7e2 100644--- a/products/autoresearch/frontend/AutoresearchPipelineScene.stories.tsx+++ b/products/autoresearch/frontend/AutoresearchPipelineScene.stories.tsx@@ -164,6 +164,7 @@ const onlinePerformance = {likely_lift: 3,base_rate: 0.03,base_rate_dates: 5,+ base_rate_source: 'realized',champion_mean_p_y: 0.033,champion_base_rate: 0.03,scores_miscalibrated: false,diff --git a/products/autoresearch/frontend/autoresearchPipelineLogic.ts b/products/autoresearch/frontend/autoresearchPipelineLogic.tsindex ab40becf4eb7..45312781ab75 100644--- a/products/autoresearch/frontend/autoresearchPipelineLogic.ts+++ b/products/autoresearch/frontend/autoresearchPipelineLogic.ts@@ -1710,7 +1710,10 @@ export const autoresearchPipelineLogic = kea<autoresearchPipelineLogicType>([segment,cohort_id: cohort.id,people: values.predictionSegments?.[segment].people,- cut_points: segmentThresholds.base_rate != null ? 'base_rate' : 'fixed',+ cut_points:+ segmentThresholds.base_rate_source === 'realized'+ ? 'base_rate'+ : segmentThresholds.base_rate_source,})lemonToast.success('Cohort saved', {button: { label: 'View cohort', action: () => router.actions.push(urls.cohort(cohort.id)) },diff --git a/products/autoresearch/frontend/generated/api.schemas.ts b/products/autoresearch/frontend/generated/api.schemas.tsindex f59b60aaad92..fbb12982a378 100644--- a/products/autoresearch/frontend/generated/api.schemas.ts+++ b/products/autoresearch/frontend/generated/api.schemas.ts@@ -1652,20 +1652,39 @@ export interface OnlinePerformanceRowApi {validated_at: string | null}+/**+ * * `realized` - Realized+ * * `training` - Training+ * * `fixed` - Fixed+ */+export type BaseRateSourceEnumApi = (typeof BaseRateSourceEnumApi)[keyof typeof BaseRateSourceEnumApi]++export const BaseRateSourceEnumApi = {+ Realized: 'realized',+ Training: 'training',+ Fixed: 'fixed',+} as const+export interface PredictionSegmentThresholdsApi {- /** Users with a score at or above this probability are in the Likely segment: likely_lift times the base rate, capped halfway between the base rate and 1. A fixed cut point when base_rate is null. */+ /** Users with a score at or above this probability are in the Likely segment: likely_lift times the base rate, capped halfway between the base rate and 1. A fixed cut point when base_rate_source is fixed. */likely_threshold: number- /** Users with a score at or above this probability and below likely_threshold are in the Possible segment, and users below it are Unlikely. Equal to base_rate, or a fixed cut point when base_rate is null. */+ /** Users with a score at or above this probability and below likely_threshold are in the Possible segment, and users below it are Unlikely. Equal to base_rate, or a fixed cut point when base_rate_source is fixed. */possible_threshold: number/** How many times the base rate a score must reach to be in the Likely segment. */likely_lift: number/**- * Fraction of the champion's scored users who did the target event, pooled over the newest checked dates. Null, and the fixed cut points apply, until those dates hold enough positives.+ * The base rate the cut points use. When base_rate_source is realized, the fraction of the champion's scored users who did the target event, pooled over the newest checked dates. When base_rate_source is training, the fraction of the champion's training population that did it. Null when base_rate_source is fixed.* @nullable*/base_rate: number | null/** Number of checked prediction dates the base rate pools. */base_rate_dates: number+ /** Where the cut points come from. realized: the checked dates hold enough positives. training: no realized base rate yet, so the champion's training population sets it. fixed: neither is available, so fixed cut points apply.+ *+ * * `realized` - Realized+ * * `training` - Training+ * * `fixed` - Fixed */+ base_rate_source: BaseRateSourceEnumApi/*** The current champion's mean predicted probability over the checked dates it scored as champion. Null until those dates hold enough positives.* @nullablediff --git a/products/autoresearch/frontend/pipeline/PredictionSegmentCards.tsx b/products/autoresearch/frontend/pipeline/PredictionSegmentCards.tsxindex 899f47d2447c..beae077c0ae1 100644--- a/products/autoresearch/frontend/pipeline/PredictionSegmentCards.tsx+++ b/products/autoresearch/frontend/pipeline/PredictionSegmentCards.tsx@@ -93,9 +93,11 @@ function SegmentCutPoints(): JSX.Element | null {return (<><p className="text-sm text-secondary mb-0">- {thresholds.base_rate != null+ {thresholds.base_rate_source === 'realized' && thresholds.base_rate != null? `Segments compare each score with the average: ${formatProbability(thresholds.base_rate)} of scored people did ${target} over the last ${thresholds.base_rate_dates} checked dates.`- : 'Segments use fixed cut points until enough predictions are checked against what people did.'}+ : thresholds.base_rate_source === 'training' && thresholds.base_rate != null+ ? `Segments compare each score with the average in the training data: ${formatProbability(thresholds.base_rate)} of people did ${target}. They switch to measured outcomes once enough predictions are checked against what people did.`+ : 'Segments use fixed cut points until enough predictions are checked against what people did.'}</p>{thresholds.scores_miscalibrated &&thresholds.champion_mean_p_y != null &&diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.tsindex af181f9a1960..e4a7ba9fa40e 100644--- a/services/mcp/src/api/generated.ts+++ b/services/mcp/src/api/generated.ts@@ -15479,6 +15479,20 @@ export namespace Schemas {Zmw: 'ZMW',} as const;+ /**+ * * `realized` - Realized+ * * `training` - Training+ * * `fixed` - Fixed+ */+ export type BaseRateSourceEnum = typeof BaseRateSourceEnum[keyof typeof BaseRateSourceEnum];+++ export const BaseRateSourceEnum = {+ Realized: 'realized',+ Training: 'training',+ Fixed: 'fixed',+ } as const;+export interface UserBasicInfo {id: number;first_name: string;@@ -68752,19 +68766,25 @@ export namespace Schemas {}export interface PredictionSegmentThresholds {- /** Users with a score at or above this probability are in the Likely segment: likely_lift times the base rate, capped halfway between the base rate and 1. A fixed cut point when base_rate is null. */+ /** Users with a score at or above this probability are in the Likely segment: likely_lift times the base rate, capped halfway between the base rate and 1. A fixed cut point when base_rate_source is fixed. */likely_threshold: number;- /** Users with a score at or above this probability and below likely_threshold are in the Possible segment, and users below it are Unlikely. Equal to base_rate, or a fixed cut point when base_rate is null. */+ /** Users with a score at or above this probability and below likely_threshold are in the Possible segment, and users below it are Unlikely. Equal to base_rate, or a fixed cut point when base_rate_source is fixed. */possible_threshold: number;/** How many times the base rate a score must reach to be in the Likely segment. */likely_lift: number;/**- * Fraction of the champion's scored users who did the target event, pooled over the newest checked dates. Null, and the fixed cut points apply, until those dates hold enough positives.+ * The base rate the cut points use. When base_rate_source is realized, the fraction of the champion's scored users who did the target event, pooled over the newest checked dates. When base_rate_source is training, the fraction of the champion's training population that did it. Null when base_rate_source is fixed.* @nullable*/base_rate: number | null;/** Number of checked prediction dates the base rate pools. */base_rate_dates: number;+ /** Where the cut points come from. realized: the checked dates hold enough positives. training: no realized base rate yet, so the champion's training population sets it. fixed: neither is available, so fixed cut points apply.+ *+ * * `realized` - Realized+ * * `training` - Training+ * * `fixed` - Fixed */+ base_rate_source: BaseRateSourceEnum;/*** The current champion's mean predicted probability over the checked dates it scored as champion. Null until those dates hold enough positives.* @nullable