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(autoresearch): base prediction segments on lift over the base rate (#114870)

posthog[bot]d77eadf8bbdd
diff --git a/frontend/snapshots.yml b/frontend/snapshots.yml
index fe7f0d5c9ee4..07a561139936 100644
--- a/frontend/snapshots.yml
+++ b/frontend/snapshots.yml
@@ -6535,17 +6535,17 @@ snapshots:
products-autoresearch-lifecycle-strip--validated-champion--light:
hash: v1.k794b7964.131ecc736b38defef5b8ba34fa9836f1d2d5132e1d109e4b995b9591a5d9255c.759giT71A_8sdMCqx-FasPgdZzZWHgRvaoUmqVtYYKw
products-autoresearch-model-detail-scene--accuracy--narrow--dark:
- hash: v1.k794b7964.3f8217187d3824bf7878aed9060ebd96a4afbbe3bd4dd57d6c50d040ad396780.d5Oe_Z7FJqsHeGA64EyYABDdWkPetbotTiGPnQV6U6k
+ hash: v1.k794b7964.bba5cd4781b922d63c9ec2892f96e47be92348f60b13c89e4c27589e1f9bc19f.1LLSE4lMVlwoDHZhRR1CV5rQPwOUbKaTil-AwyfPJF8
products-autoresearch-model-detail-scene--accuracy--narrow--light:
- hash: v1.k794b7964.c8eb64cb2728f6ee73094a5d2e5effdbdebb972cbe7a90e5942e153d8f625465.OQRwRbwNqDTXFmqHU6WfPJIsnTR0exRaoSyRf4-HNRw
+ hash: v1.k794b7964.d1cf885e94b7b5a8009a241e6c13566fe53e3b30c12a7a33488b2bafb72040a8.98ETMbotAyOoqoZT7kpGP1q4VY8iMc7Ex4tz2vOdhvw
products-autoresearch-model-detail-scene--accuracy--wide--dark:
- hash: v1.k794b7964.0fd3e76c74910c5e0017cb1a687bdc23e16807c956eab7c9d38800b588d2dc9c.V7437wGvm0FwZf22kWHip3bJcTzZkedIl7aEz329Hhs
+ hash: v1.k794b7964.a4dc11c6e77cbd7fcc56da0bed5d1510ddd037d12a3bb07a5eaa6f4362f3daa8.UON_fOX7Jn8GaEfs2Q8aXhxIT_ScAVBYzLfAP0neN34
products-autoresearch-model-detail-scene--accuracy--wide--light:
- hash: v1.k794b7964.937ed09f5202a79d41b2907a114a8d8a5479e9cd50ab992d5e1526244a026716.c8J1y77rve1oe6vz5ZMFqLIXEwMEiXbLMcbP_KoLkt4
+ hash: v1.k794b7964.d25c744b33325893085ff451db1857b0199ae81b31412d5cc10f4db4cb7fb78d.j8dOrAFot09FYopy_6ZgoV67BEQslHF1B5MkoowaZXw
products-autoresearch-model-detail-scene--accuracy-before-precision-recall--wide--dark:
- hash: v1.k794b7964.0b5c8f601ca997bcc047ac9433320f97ded3d77587b5d9a1d17d4efc14fe067a.HmMZQj_A1QVaOYN24p6cCzBTWJ0dxBghBe4vwKTshnE
+ hash: v1.k794b7964.f5a93a008ee426539faf447233438616f02063130e0c8379504b2230c7fdc100.ZixG8syKynNL_4Xoxgwnai_dbR6DrhLIXpxLpqkfX1c
products-autoresearch-model-detail-scene--accuracy-before-precision-recall--wide--light:
- hash: v1.k794b7964.cb4b85b471a78a1ad4c359c27692622fbf3bc29d133aa0d9a1c329b7eeba7723.AGhOQQd19cM-yzuU1A6HUYfsGLQf9gpLSuX1Y0OK8Bo
+ hash: v1.k794b7964.8889f1c4e0c4f7508bb25824f85c560042338ccba9cd9a92635b7ad7554cc7cb.lo2fwfoTjLpSjmz00TsOd2j-IousiuI0Ia3Xfr9wCZs
products-autoresearch-model-detail-scene--agent-research-narrow--narrow--dark:
hash: v1.k794b7964.052f6d0dba654432d5f12d65bc0f91bc3e2de64334dac07e62d6cf730f154820.7cPMLn00EY67HPH6ikgGBUlULYPQSAMVKLyE_cR3uTs
products-autoresearch-model-detail-scene--agent-research-narrow--narrow--light:
@@ -6555,41 +6555,45 @@ snapshots:
products-autoresearch-model-detail-scene--agent-research-wide--wide--light:
hash: v1.k794b7964.61a18ed53831b16b23b3f5c5bf5db2311a2a67c3237d339a9559de7dd488432c.jsOveKxB0FdFA8m-z9oDOUxV_z4mbAXK9Lra6HxBrr0
products-autoresearch-model-detail-scene--coverage-below-cap--narrow--dark:
- hash: v1.k794b7964.721530fcc755c7f3fdbd2ac8da72aeee7661e2cca2a594897bc63f0644c238ee.zJhue3x2e_jOlNhkf7MO1OaF4g1HG6E9ks29rkzZleE
+ hash: v1.k794b7964.4e43edc26f1f7617df0b9ab5a0461a452ffeaaac42866cf177de7d6a37ef9f57.HuUUWBynAYTLHQ0baecnM7XmuDjZK848f3l4QSwlyKA
products-autoresearch-model-detail-scene--coverage-below-cap--narrow--light:
- hash: v1.k794b7964.fe0a81a4119d2cac8a693099bd5316b2d3725f611f3dd6a5ac68dff184e8a82c.cC5aTKRX4gyM-IEoUjYC0PXBgBVOIJ_YxdKABqOPPVU
+ hash: v1.k794b7964.25c1e3a691cdce3afc6707117290f5f9baf78f32ea6665cc4fd314d46b2b8212.4lZJM_CKAmsI1z7VkYRae4ZyvdSGzJNhWH1bZhEB9h0
products-autoresearch-model-detail-scene--coverage-below-cap--wide--dark:
- hash: v1.k794b7964.44cd2d63e9cad9efe3147afe30f4c1094e19aea4bc000f29ceb9f4942374953c.8XtAEwpQ9G3eZlXhMeg-7PFH7doptrwHCWup1lvotu0
+ hash: v1.k794b7964.5625b06041f958263a883741de07e56e0ea22b9f3f600ea2e9952146fdfc7c1c.B3cnfe1hT3J2-vnea-5ImDGE_mVpyiwAsnJQMabJq_8
products-autoresearch-model-detail-scene--coverage-below-cap--wide--light:
- hash: v1.k794b7964.30bf170449b1e41729af4fdd359f203c575b61cd86a91d1404474f1e9ce04aa2.nHtmktQwmYtROwQlkvF0Wai2UweaJG08Vtxj1wclyOQ
+ hash: v1.k794b7964.1f350c2f315f0ca74330604ae35b7ccc2d77d52bc18da09a34a2d8b9c09eeba7.lo43kMkTZGhgkWNOd7Fz1Iaqq89uLS41teZFQ3yLS_c
products-autoresearch-model-detail-scene--coverage-rolling-mid-cycle--narrow--dark:
- hash: v1.k794b7964.66b9db1745b588df2a4c100c72773c8ed69e5b9c11bb06cee447e54c307add83.GupL02pHEAaRli9TEEU5xdNdWNYbzcYpb4MH3bQNnw0
+ hash: v1.k794b7964.1517002a8859c840f3d8e3c8b51dde48c0c0c8a74358a7b1e754bd0af324a176.UE5BH4Oult8tdMzFZGekiaFsTMS-9Ln4UIAiCj8CYWE
products-autoresearch-model-detail-scene--coverage-rolling-mid-cycle--narrow--light:
- hash: v1.k794b7964.8ec1ffa9de602b25d098cdb293fb245c4955c9ebc160224131db894519166017.P6ovEwupUpVHrf2cA_AfWooiNfwvMout6JT0PVwYqoU
+ hash: v1.k794b7964.f30ac4dfeb1017151451c962d7bf71fd7c3b83b3e320a0e2a15fae4d0fe3e496.9Mw-jnr4jRd339DlsAOgqYUwO7gB4QSYaRgpqr4Y8ko
products-autoresearch-model-detail-scene--coverage-rolling-mid-cycle--wide--dark:
- hash: v1.k794b7964.c3e6c9ab12890444266e6cb1325b36a939c7c055bd8f57ab9cb23bdce497bf48.BanqKFIn98OeGkPzXVy-XZGrA--UG1Wfpm5WIsVbId0
+ hash: v1.k794b7964.233b87d1bd3b880f00bbd5dd385bb225a1ef0725e5e9e946911584ab5a262919.ZeZSguEir_06IeQ6UJFGk3DmOX1opgTemvy0KlnExkU
products-autoresearch-model-detail-scene--coverage-rolling-mid-cycle--wide--light:
- hash: v1.k794b7964.64af60e40bb95efceb94be384ba8a674477bb36e9765984b4ec4cb7aeb4d5b98.s9GNvnmp8Wv4AnoMU5kJIudkpsQTykdkhNphYliExUM
+ hash: v1.k794b7964.9a390abbd9cd9129d3bb994ac0d7fba2c42f24c86772158913344485c49f4193.h4A9K-TQ4HjDqfrIN1XY3V3tQpgFlqb3T-7qngIEQeE
products-autoresearch-model-detail-scene--coverage-with-failed-runs--narrow--dark:
- hash: v1.k794b7964.dc648673de2261f42b22ff5b443cfcea886722003a27774013104f074ef0f1d8.DkJOzJlZyxUuT3r21GuO4ETvOR69_qYU7XSiSYz1LK8
+ hash: v1.k794b7964.dcfa2bfa839b6f5d53dffed1cb9ef1169e16609769bd6bf3fe0e539adb3e7d8d.9wEtUCYRaHsi-F7vzlHxY0EFCotO9CYzn0OOCz7j4aM
products-autoresearch-model-detail-scene--coverage-with-failed-runs--narrow--light:
- hash: v1.k794b7964.14148a60a3672401ff7c13adfc2d9a730570c1975d6d28b6c4a5a61b2fd4e2ae.-bDkliOWb6Eg1KB0N2tTf8RC3PAk47BKl5PYany8hBs
+ hash: v1.k794b7964.2f67bcc8bc73793f78e3924e3baeb8b9d3e4b0d636f28f215ad224738e915ef9.wiTTfZkL7qs10VhXsEW9a0FTsWIEEHeywcih7NVXdv8
products-autoresearch-model-detail-scene--coverage-with-failed-runs--wide--dark:
- hash: v1.k794b7964.be3ca41a134359e6bece640a965f9cfcc333941ae5869625c4914d343e50f1db.zKecG11ytYgkA28oOOj3b8XoSF8rByx4Xrxv4ri2lPw
+ hash: v1.k794b7964.243216a8469f3ff645764447f893ff8f2ab5559494ef6318ddf437bbd1006f23.2OdjhN4lHq_UEfdYlZindTaOHce4vh6IjSrllT7R3sI
products-autoresearch-model-detail-scene--coverage-with-failed-runs--wide--light:
- hash: v1.k794b7964.24f39e61b0e12e87c25873f586fe4d2353ae45ca15ab38182da8b6b9f4060ca5.23vLegDN9E_LgZmMW1R-X2B4CbdUbq2lvNy-Lq7YujY
+ hash: v1.k794b7964.ed9f0633f2e496a16e293b395f692fd69a5ba492a6d8b3296385b7e7368f12ab.ZeInQ-roAfD25wO3YNElEDBAH8nsa4Twq-kN1Yb4suM
products-autoresearch-model-detail-scene--narrow--narrow--dark:
- hash: v1.k794b7964.ccf500b86b8416ba6f5eb0585c4f2b1a651a7ee08197eb26acbf1159a98a5a9c.QZOCYtHGQLG2LxdHPOFSl3DEOeCQc2LhQJqnXabqih8
+ hash: v1.k794b7964.c3ef7f3a7938bef4e0d2e04069fdbeaeb4e7fdfeae799b961d157116e6462a08.J7paTdt4-VUAMfE_MVamn2piXgtLZF7XgWXmMA1xwwU
products-autoresearch-model-detail-scene--narrow--narrow--light:
- hash: v1.k794b7964.69ff7705b5a7a23f19da2825a77c0eaef3e99e4e59ee04f57a04a4529a39c6e6.eox1HduqmnWEHYcw9I6_McOvsjY3nTNRd1nm37Qrtd4
+ hash: v1.k794b7964.9c294b354388a47476fab373631d06c696fee66142f22e0a214abe72e79bfb7d.GPXydv4tanlj-nCL2fpFVDBlN6QbYb9GPsAQDoB25bA
products-autoresearch-model-detail-scene--wide--wide--dark:
- hash: v1.k794b7964.7ae6b811f9b09f8a9f518b758b008781c6f05ca0d0bea07c9e94b6c3e643e7af.p4p8au-9DAy6r2E5vQv0RUuUCak5FzUtNqSFCDdo9wA
+ hash: v1.k794b7964.666220372bba1865f19d61c88c6364aac2b1f19b07e97c45f4b2e55dcf96e0da.3dNk60c4eKV_ocxKLKSbNqw2VBot_GNxf5gRf9KhWqU
products-autoresearch-model-detail-scene--wide--wide--light:
- hash: v1.k794b7964.f93faffb29c817fc5d2b48b1cadeed596372e13c6870d0f695f90fb7b5a0f5ee.jr8VOYxzbK2nVfO08U2rOYdTytGsXuKT6WgXzi8Aqbc
+ hash: v1.k794b7964.614d0667fdb8e4c424f5054c49281725df8e5cb28f1e981f7476594adfd50510.0Y7BmV2ztuwUZWtNnISERLoQ-G7ukfSYOt5WaErWRwE
products-autoresearch-probability-histogram--bimodal--dark:
hash: v1.k794b7964.f95d3982e7c08f2e1b51655520f15e37293aa98e5ca87126a5653d2300bd776b.2G0LsuSx-SLqWn1Oxm_bUHSqfeDPFF6Pof0vDvhZEHM
products-autoresearch-probability-histogram--bimodal--light:
hash: v1.k794b7964.831315d68f8983a92a0f0e134a485f482ca6df6fa85f78301e926ce00e2e2ccb.TO-b36vQiw4ne1Fv45cDNBHKKKvDkBFK2C5I3PF-qmo
+ products-autoresearch-probability-histogram--rare-target--dark:
+ hash: v1.k794b7964.bc374b79f63aede5d6ddd282353fd329b2bdedbac2b279714abd812352666eb9.bhhMCiEP_ZhTIEPu03tDCOTvCHvfYjBXwxI2l0SuWIs
+ products-autoresearch-probability-histogram--rare-target--light:
+ hash: v1.k794b7964.1957744ad9d75b6b11b1926bea1ef119a5eb61fd27dbdebd7f3d740560c7a901.OPFTiit8TMJEdMor2yAX7IE3Evurbzl0QiRY9y29_3E
products-autoresearch-probability-histogram--single-bucket--dark:
hash: v1.k794b7964.164637ddca4c38e0f3fbcabd8c6abf6679cc52b8181e545d9d42faf7a6913377.-9jAhj26nqF75jfLBkjvFo7XuqmLPFvndCV1_30iCrg
products-autoresearch-probability-histogram--single-bucket--light:
diff --git a/products/autoresearch/backend/evaluation/AGENTS.md b/products/autoresearch/backend/evaluation/AGENTS.md
index 10c5cbce2a12..2e4f9df7b39f 100644
--- a/products/autoresearch/backend/evaluation/AGENTS.md
+++ b/products/autoresearch/backend/evaluation/AGENTS.md
@@ -20,13 +20,17 @@ It is the only honest number in the product. A holdout AUC of 0.93 says the mode
- **calibration bins** (`_quantile_calibration_bins`) — up to 10 bins cut at score quantiles, each with `n`, `mean_p_y` and `positive_rate`; equal scores share a bin. Equal-width bins put nearly every person in the first bin for a rare target, so read these instead
- **lift@k** (`_lift_at_k`) — how much better than random the top slice is; ties at the boundary score are split fractionally so the number does not depend on row order
- **average precision** — area under the precision-recall curve; null when the date has no positives
- - **confusion counts** (`confusion`, `_confusion_counts`) — `tp`, `fp`, `fn`, `tn`, `n_flagged`, `precision` and `recall` for three cutoffs: `top_10`, `top_20`, and `likely` (score at or above `LIKELY_THRESHOLD`). Top-k cutoffs flag every person tied at the boundary score, so the counts are whole people and `n_flagged` can be a little above k. `LIKELY_THRESHOLD` comes from `frontend/predictionSegmentThresholds.json`, the same file the frontend segments read
+ - **confusion counts** (`confusion`, `_confusion_counts`) — `tp`, `fp`, `fn`, `tn`, `n_flagged`, `precision` and `recall` for three cutoffs: `top_10`, `top_20`, and `likely` (score at or above `likely_threshold`, which is stored with them). Top-k cutoffs flag every person tied at the boundary score, so the counts are whole people and `n_flagged` can be a little above k. `likely_threshold` is the Likely cut point from the dates checked before this one, so the counts describe the group the Predictions tab showed
- **weekday** — the ISO weekday of the prediction date
Every model that emitted predictions on the date is scored, whatever its role now. Inference shadow-scores every model in the shadow set on the champion's people, and each records its own inference run, so their realized numbers land here. That is what makes challenger promotion decidable on evidence rather than on holdout alone. A shadow model's events carry the emitted role `shadow`.
Results land on `AutoresearchModel.realized_score` / `.calibration_error` / `.metrics["realized"]` via `_update_model_realized_metrics()`, and each validated date records an `AutoresearchRun` whose `metrics["per_model"]` keeps the emitted role next to the current one.
The model row keeps only the newest date. The history is on the runs: `latest_validation_runs()` in `history.py` reads them, for `online_performance()` in `../facade/api.py` (the pipeline's `online_performance` action and the `autoresearch-online-performance-retrieve` MCP tool) reads the newest completed run per (date, horizon) and returns one row per model per date, so an archived former champion keeps its evidence after a promotion. The training brief reads the same history (`../training/realized_context.py`).
+- `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.
+ A saved cohort, flag or workflow stores the absolute cut point, so it does not follow a later change in the base rate.
+
## Mental model
```text
diff --git a/products/autoresearch/backend/evaluation/history.py b/products/autoresearch/backend/evaluation/history.py
index ae92b90514ba..893bdea40880 100644
--- a/products/autoresearch/backend/evaluation/history.py
+++ b/products/autoresearch/backend/evaluation/history.py
@@ -10,15 +10,18 @@ from django.db.models.functions import DenseRank
from products.autoresearch.backend.models import AutoresearchPipeline, AutoresearchRun
-def latest_validation_runs(team_id: int, pipeline: AutoresearchPipeline, *, limit: int) -> list[AutoresearchRun]:
+def latest_validation_runs(
+ team_id: int, pipeline: AutoresearchPipeline, *, limit: int, before: date | None = None
+) -> list[AutoresearchRun]:
"""
The newest completed validation run per (prediction date, horizon), newest date first.
- ``limit`` bounds the number of groups. When a group was validated more than once, its
+ ``limit`` bounds the number of groups, and ``before`` keeps only prediction dates earlier
+ than it. When a group was validated more than once, its
newest completed run holds the current evidence. Each run keeps every model it scored in
``metrics["per_model"]``, so a former champion keeps its evidence after a promotion.
"""
- return list(
+ runs = (
AutoresearchRun.objects.for_team(team_id)
.filter(
pipeline=pipeline,
@@ -27,8 +30,14 @@ def latest_validation_runs(team_id: int, pipeline: AutoresearchPipeline, *, limi
metrics__has_key="prediction_date",
)
.annotate(prediction_date=KT("metrics__prediction_date"), horizon=KT("metrics__horizon_days"))
- .order_by("-prediction_date", "horizon", F("completed_at").desc(nulls_last=True), "-id")
- .distinct("prediction_date", "horizon")[:limit]
+ )
+ if before is not None:
+ # ISO dates sort as text in date order.
+ runs = runs.filter(prediction_date__lt=before.isoformat())
+ return list(
+ runs.order_by("-prediction_date", "horizon", F("completed_at").desc(nulls_last=True), "-id").distinct(
+ "prediction_date", "horizon"
+ )[:limit]
)
diff --git a/products/autoresearch/backend/evaluation/online_validation.py b/products/autoresearch/backend/evaluation/online_validation.py
index 90252a8730e0..1865541981c8 100644
--- a/products/autoresearch/backend/evaluation/online_validation.py
+++ b/products/autoresearch/backend/evaluation/online_validation.py
@@ -17,10 +17,8 @@ Architecture:
say was emitted.
"""
-import json
import math
from datetime import UTC, date, datetime, timedelta
-from pathlib import Path
from typing import Any
from django.db import transaction
@@ -44,6 +42,8 @@ from products.autoresearch.backend.dataset.labeling import (
_own_events_excluded_clause,
build_target_condition,
)
+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.inference.sandbox import SandboxInferenceError, _resolve_acting_user
from products.autoresearch.backend.models import AutoresearchModel, AutoresearchPipeline, AutoresearchRun
from products.autoresearch.backend.query import INTERACTIVE_QUERY, HogQLResult, QueryContext, run_hogql
@@ -347,11 +347,18 @@ def _validate_claimed_date(
user=user,
query_context=query_context,
)
+ # 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)
+ )
per_model = {
model_id: _ModelValidation(
emitted_role=model.emitted_role,
metrics=_compute_validation_metrics(
- model.p_y_by_person, realized, prediction_date=pending.prediction_date
+ model.p_y_by_person,
+ realized,
+ prediction_date=pending.prediction_date,
+ likely_threshold=thresholds.likely,
),
)
for model_id, model in predictions.items()
@@ -623,20 +630,18 @@ def _query(
# ── Metrics ────────────────────────────────────────────────────────────────────────
-# The frontend reads the same file for PREDICTION_SEGMENT_THRESHOLDS, so the Likely cutoff cannot drift.
-_SEGMENT_THRESHOLDS_PATH = Path(__file__).resolve().parents[2] / "frontend" / "predictionSegmentThresholds.json"
-LIKELY_THRESHOLD: float = float(json.loads(_SEGMENT_THRESHOLDS_PATH.read_text())["high"])
-
def _compute_validation_metrics(
predictions: dict[str, float],
realized_labels: frozenset[str],
*,
prediction_date: date,
+ likely_threshold: float,
) -> dict[str, Any]:
"""
AUC with its 95% interval, Brier score, ECE, quantile calibration bins, lift@k,
average precision, and confusion counts from scored predictions against realized labels.
+ The ``likely`` counts flag scores at or above ``likely_threshold``, which is kept with them.
Only the AUC and its interval need both classes, and average precision needs a positive.
The other metrics are computed for a single-class date too, because an all-negative day
@@ -681,8 +686,9 @@ def _compute_validation_metrics(
metrics["confusion"] = {
"top_10": _confusion_counts(y_true, _top_k_flags(y_score, k=0.10)),
"top_20": _confusion_counts(y_true, _top_k_flags(y_score, k=0.20)),
- "likely": _confusion_counts(y_true, y_score >= LIKELY_THRESHOLD),
+ "likely": _confusion_counts(y_true, y_score >= likely_threshold),
}
+ metrics["likely_threshold"] = likely_threshold
return metrics
diff --git a/products/autoresearch/backend/evaluation/segment_thresholds.py b/products/autoresearch/backend/evaluation/segment_thresholds.py
new file mode 100644
index 000000000000..fc54de33ab90
--- /dev/null
+++ b/products/autoresearch/backend/evaluation/segment_thresholds.py
@@ -0,0 +1,107 @@
+"""
+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
+endpoint returns the current pair, and the frontend reads it from there, so the Predictions tab,
+the Accuracy tab and online validation cannot disagree.
+"""
+
+from collections.abc import Iterable
+from dataclasses import replace
+from typing import Any
+
+from posthog.dataclasses import frozen
+
+from products.autoresearch.backend.models import AutoresearchRun
+
+LIKELY_LIFT = 3.0
+FIXED_LIKELY_THRESHOLD = 0.6
+FIXED_POSSIBLE_THRESHOLD = 0.2
+
+# The base rate pools the newest checked dates, so it follows a drifting target.
+BASE_RATE_DATES = 28
+# A base rate from fewer positives than this is too noisy to set cut points from.
+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
+
+
+@frozen
+class SegmentThresholds:
+ likely: float
+ possible: float
+ # None when the fixed pair applies.
+ base_rate: float | None
+ # Checked dates the base rate pools.
+ dates: int
+
+
+@frozen
+class ScoreCalibration:
+ """The champion's mean score against the realized rate, over the checked dates it emitted as champion."""
+
+ mean_p_y: float
+ base_rate: float
+
+ @property
+ def miscalibrated(self) -> bool:
+ return not (1 / MISCALIBRATION_FACTOR <= self.mean_p_y / self.base_rate <= MISCALIBRATION_FACTOR)
+
+
+def _significant(value: float, digits: int = 3) -> float:
+ return float(f"{value:.{digits}g}")
+
+
+def _champion_entries(runs: Iterable[AutoresearchRun]) -> Iterable[tuple[str, dict[str, Any]]]:
+ """The emitted champion's metrics on each checked date. Shadow models score the same people, so they are skipped."""
+ for run in runs:
+ for model_id, metrics in (run.metrics.get("per_model") or {}).items():
+ if metrics.get("emitted_role") == "champion":
+ yield model_id, metrics
+ break
+
+
+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)
+
+
+def segment_thresholds(runs: Iterable[AutoresearchRun]) -> SegmentThresholds:
+ """The cut points from the realized base rate of the given completed validation runs."""
+ scored = positives = dates = 0
+ for _, 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)
+
+
+def champion_score_calibration(runs: Iterable[AutoresearchRun], champion_id: str) -> ScoreCalibration | None:
+ """
+ Pooled mean score and realized rate of one champion. Null until its dates hold enough positives.
+
+ Class weighting or resampling in train.py leaves scores that are not probabilities, and no
+ correction at scoring time undoes it. Cut points from the base rate do not mean "N times as
+ likely" for such a model, so the UI warns about it.
+ """
+ scored = positives = 0
+ predicted = 0.0
+ for model_id, metrics in _champion_entries(runs):
+ mean_p_y = metrics.get("mean_p_y")
+ if model_id != champion_id or mean_p_y is None:
+ continue
+ n = int(metrics.get("n_scored") or 0)
+ scored += n
+ positives += int(metrics.get("n_positive") or 0)
+ predicted += float(mean_p_y) * n
+ if positives < MIN_BASE_RATE_POSITIVES or scored == 0:
+ return None
+ return ScoreCalibration(mean_p_y=round(predicted / scored, 4), base_rate=round(positives / scored, 4))
diff --git a/products/autoresearch/backend/evaluation/test_online_validation.py b/products/autoresearch/backend/evaluation/test_online_validation.py
index f066a25f4aab..c71aa5c8ec78 100644
--- a/products/autoresearch/backend/evaluation/test_online_validation.py
+++ b/products/autoresearch/backend/evaluation/test_online_validation.py
@@ -27,6 +27,11 @@ from products.autoresearch.backend.evaluation.online_validation import (
find_pending_validation_dates,
run_online_validation_for_pipeline,
)
+from products.autoresearch.backend.evaluation.segment_thresholds import (
+ FIXED_LIKELY_THRESHOLD,
+ champion_score_calibration,
+ segment_thresholds,
+)
from products.autoresearch.backend.models import AutoresearchModel, AutoresearchPipeline, AutoresearchRun
from products.autoresearch.backend.query import BATCH_QUERY, HogQLResult
from products.autoresearch.backend.testing import TeamScopedTestMixin
@@ -40,7 +45,10 @@ class TestComputeValidationMetrics(SimpleTestCase):
def test_returns_base_counts(self):
metrics = _compute_validation_metrics(
- self._predictions(), frozenset(["user-1", "user-2"]), prediction_date=date(2026, 9, 6)
+ self._predictions(),
+ frozenset(["user-1", "user-2"]),
+ prediction_date=date(2026, 9, 6),
+ likely_threshold=FIXED_LIKELY_THRESHOLD,
)
assert metrics["n_scored"] == 5
assert metrics["n_positive"] == 2
@@ -61,7 +69,12 @@ class TestComputeValidationMetrics(SimpleTestCase):
]
)
def test_realized_auc(self, _name, preds, expected_auc):
- metrics = _compute_validation_metrics(preds, frozenset(["high-1", "high-2"]), prediction_date=date(2026, 9, 1))
+ metrics = _compute_validation_metrics(
+ preds,
+ frozenset(["high-1", "high-2"]),
+ prediction_date=date(2026, 9, 1),
+ likely_threshold=FIXED_LIKELY_THRESHOLD,
+ )
assert metrics["realized_auc"] == expected_auc
@parameterized.expand(
@@ -71,7 +84,12 @@ class TestComputeValidationMetrics(SimpleTestCase):
]
)
def test_single_class_skips_only_the_auc(self, _name, labels):
- metrics = _compute_validation_metrics({"user-1": 0.5, "user-2": 0.6}, labels, prediction_date=date(2026, 9, 1))
+ metrics = _compute_validation_metrics(
+ {"user-1": 0.5, "user-2": 0.6},
+ labels,
+ prediction_date=date(2026, 9, 1),
+ likely_threshold=FIXED_LIKELY_THRESHOLD,
+ )
assert metrics["warning"] == "single_class_no_auc"
assert "realized_auc" not in metrics
assert "realized_auc_ci_low" not in metrics
@@ -103,9 +121,14 @@ class TestComputeValidationMetrics(SimpleTestCase):
preds = {f"user-{i}": score for i, score in enumerate(scores)}
positives = frozenset(["user-0", "user-3", "user-5"])
- metrics = _compute_validation_metrics(preds, positives, prediction_date=date(2026, 9, 1))
+ metrics = _compute_validation_metrics(
+ preds, positives, prediction_date=date(2026, 9, 1), likely_threshold=FIXED_LIKELY_THRESHOLD
+ )
reversed_metrics = _compute_validation_metrics(
- dict(reversed(list(preds.items()))), positives, prediction_date=date(2026, 9, 1)
+ dict(reversed(list(preds.items()))),
+ positives,
+ prediction_date=date(2026, 9, 1),
+ likely_threshold=FIXED_LIKELY_THRESHOLD,
)
assert metrics["confusion"] == reversed_metrics["confusion"]
@@ -134,6 +157,62 @@ class TestComputeValidationMetrics(SimpleTestCase):
assert 0.0 < metrics["average_precision"] <= 1.0
+def _checked_date(*entries: tuple[str, str, int, int, float | None]) -> AutoresearchRun:
+ return AutoresearchRun(
+ metrics={
+ "per_model": {
+ model_id: {"emitted_role": role, "n_scored": n_scored, "n_positive": n_positive, "mean_p_y": mean_p_y}
+ for model_id, role, n_scored, n_positive, mean_p_y in entries
+ }
+ }
+ )
+
+
+class TestSegmentThresholds(SimpleTestCase):
+ @parameterized.expand(
+ [
+ ("rare_target", [[("m", "champion", 2000, 30, None)]], (0.045, 0.015, 0.015)),
+ (
+ "pooled_over_dates",
+ [[("m", "champion", 1000, 10, None)], [("m", "champion", 1000, 30, None)]],
+ (0.06, 0.02, 0.02),
+ ),
+ ("high_base_rate_is_capped", [[("m", "champion", 100, 50, None)]], (0.75, 0.5, 0.5)),
+ (
+ "shadow_models_are_skipped",
+ [[("m", "champion", 1000, 20, None), ("s", "shadow", 1000, 900, None)]],
+ (0.06, 0.02, 0.02),
+ ),
+ ("too_few_positives_is_fixed", [[("m", "champion", 1000, 5, None)]], (0.6, 0.2, None)),
+ ("no_checked_dates_is_fixed", [], (0.6, 0.2, None)),
+ ]
+ )
+ def test_cut_points_follow_the_realized_base_rate(self, _name, dates, expected):
+ thresholds = segment_thresholds([_checked_date(*entries) for entries in dates])
+
+ assert (thresholds.likely, thresholds.possible, thresholds.base_rate) == expected
+ assert thresholds.dates == len(dates)
+
+ @parameterized.expand(
+ [
+ ("calibrated", 0.025, False),
+ ("class_weighted", 0.3, True),
+ ("under_predicting", 0.005, True),
+ ]
+ )
+ def test_champion_score_calibration(self, _name, mean_p_y, expect_miscalibrated):
+ runs = [
+ _checked_date(("champ", "champion", 1000, 20, mean_p_y)),
+ _checked_date(("former", "champion", 1000, 20, 0.9)),
+ ]
+
+ calibration = champion_score_calibration(runs, "champ")
+
+ assert calibration is not None
+ assert (calibration.mean_p_y, calibration.base_rate) == (mean_p_y, 0.02)
+ assert calibration.miscalibrated is expect_miscalibrated
+
+
class TestAucConfidenceInterval(SimpleTestCase):
def test_interval_narrows_as_the_classes_grow(self):
few = _auc_confidence_interval(0.75, n_pos=20, n_neg=200)
@@ -486,6 +565,39 @@ class TestRunOnlineValidationForPipeline(TeamScopedTestMixin, BaseTest):
assert label_call.kwargs["query"].values["limit"] == 5
assert "LIMIT {limit}" in label_call.kwargs["query"].query
+ @parameterized.expand(
+ [
+ ("no_earlier_dates_use_the_fixed_cut_point", [], FIXED_LIKELY_THRESHOLD),
+ ("earlier_dates_set_it_by_lift", [(date(2026, 8, 31), 10)], 0.15),
+ ("later_dates_are_ignored", [(date(2026, 8, 31), 10), (date(2026, 9, 2), 100)], 0.15),
+ ]
+ )
+ def test_the_likely_counts_use_the_cut_point_from_earlier_dates(self, _name, checked, expected_threshold):
+ for prediction_date, n_positive in checked:
+ AutoresearchRun.objects.create(
+ pipeline=self.pipeline,
+ run_type=AutoresearchRun.RunType.VALIDATION,
+ status=AutoresearchRun.Status.COMPLETED,
+ completed_at=django_timezone.now(),
+ metrics={
+ "prediction_date": prediction_date.isoformat(),
+ "horizon_days": 7,
+ "per_model": {
+ str(self.champion.pk): {"emitted_role": "champion", "n_scored": 200, "n_positive": n_positive}
+ },
+ },
+ )
+ hogql = _fake_hogql(predictions=self._prediction_rows(4), labels=[["user-0"]])
+
+ with patch.object(online_validation, "run_hogql", hogql):
+ runs = run_online_validation_for_pipeline(self.pipeline)
+
+ per_model = runs[0].metrics["per_model"][str(self.champion.pk)]
+ assert per_model["likely_threshold"] == expected_threshold
+ assert per_model["confusion"]["likely"]["n_flagged"] == sum(
+ score >= expected_threshold for score in (0.9, 0.8, 0.2, 0.1)
+ )
+
@parameterized.expand(
[
("fewer_rows_than_emitted", 3, "Found 3 of the 4 predictions"),
diff --git a/products/autoresearch/backend/facade/api.py b/products/autoresearch/backend/facade/api.py
index 05e46931d1aa..335ad2275bfb 100644
--- a/products/autoresearch/backend/facade/api.py
+++ b/products/autoresearch/backend/facade/api.py
@@ -40,7 +40,13 @@ from ..dataset.validation import (
validate_pipeline_definition as _validate_pipeline_definition,
)
from ..evaluation.history import latest_validation_runs, realized_auc_trends
-from ..evaluation.online_validation import LIKELY_THRESHOLD as LIKELY_THRESHOLD
+from ..evaluation.segment_thresholds import (
+ BASE_RATE_DATES,
+ FIXED_LIKELY_THRESHOLD,
+ LIKELY_LIFT,
+ champion_score_calibration,
+ segment_thresholds,
+)
from ..models import (
AutoresearchIteration,
AutoresearchModel,
@@ -82,6 +88,7 @@ from .contracts import (
PipelineValidation,
PipelineWrite,
PredictionCoverage,
+ PredictionSegmentThresholds,
RealizedAucPoint,
ResolvedTemplate,
Run,
@@ -1079,12 +1086,39 @@ def online_performance(
)
if confusion is not None
else None,
+ # Dates checked before the cut point was stored used the fixed one.
+ likely_threshold=m.get("likely_threshold", FIXED_LIKELY_THRESHOLD)
+ if confusion is not None
+ else None,
calibration_bins=[CalibrationBin(**b) for b in bins] if bins is not None else None,
warning=m.get("warning"),
validated_at=run.completed_at,
)
)
- return OnlinePerformance(rows=rows)
+ return OnlinePerformance(rows=rows, segment_thresholds=_segment_thresholds(team_id, pipeline))
+
+
+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 = (
+ AutoresearchModel.objects.for_team(team_id)
+ .filter(pipeline=pipeline, role=AutoresearchModel.Role.CHAMPION)
+ .values_list("id", flat=True)
+ .first()
+ )
+ calibration = champion_score_calibration(runs, str(champion_id)) if champion_id is not None else None
+ return PredictionSegmentThresholds(
+ likely_threshold=thresholds.likely,
+ possible_threshold=thresholds.possible,
+ likely_lift=LIKELY_LIFT,
+ base_rate=thresholds.base_rate,
+ base_rate_dates=thresholds.dates,
+ 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,
+ )
# ── Training runs ──────────────────────────────────────────────────────────
diff --git a/products/autoresearch/backend/facade/contracts.py b/products/autoresearch/backend/facade/contracts.py
index 549313800eeb..982574b2ab03 100644
--- a/products/autoresearch/backend/facade/contracts.py
+++ b/products/autoresearch/backend/facade/contracts.py
@@ -436,14 +436,30 @@ class OnlinePerformanceRow:
lift_at_20: float | None
average_precision: float | None
confusion: ConfusionByCutoff | None
+ likely_threshold: float | None
calibration_bins: list[CalibrationBin] | None
warning: str | None
validated_at: datetime | None
+@dataclass(frozen=True)
+class PredictionSegmentThresholds:
+ """The pipeline's current cut points between the Likely, Possible and Unlikely segments."""
+
+ likely_threshold: float
+ possible_threshold: float
+ likely_lift: float
+ base_rate: float | None
+ base_rate_dates: int
+ champion_mean_p_y: float | None
+ champion_base_rate: float | None
+ scores_miscalibrated: bool
+
+
@dataclass(frozen=True)
class OnlinePerformance:
rows: list[OnlinePerformanceRow]
+ segment_thresholds: PredictionSegmentThresholds
# ── Artifact bundle ────────────────────────────────────────────────────────
diff --git a/products/autoresearch/backend/presentation/views/serializers.py b/products/autoresearch/backend/presentation/views/serializers.py
index 8c9509320a1e..91f0c32c1b00 100644
--- a/products/autoresearch/backend/presentation/views/serializers.py
+++ b/products/autoresearch/backend/presentation/views/serializers.py
@@ -1357,7 +1357,7 @@ class ConfusionByCutoffSerializer(serializers.Serializer):
top_10 = ConfusionCountsSerializer(help_text="Counts when the top 10% of users by score are flagged.")
top_20 = ConfusionCountsSerializer(help_text="Counts when the top 20% of users by score are flagged.")
likely = ConfusionCountsSerializer(
- help_text=f"Counts when users with a score of {api.LIKELY_THRESHOLD} or higher (the Likely segment) are flagged."
+ help_text=("Counts when users in the Likely segment, with a score of likely_threshold or higher, are flagged.")
)
@@ -1426,6 +1426,13 @@ class OnlinePerformanceRowSerializer(serializers.Serializer):
"Null for dates validated before this metric existed."
),
)
+ likely_threshold = serializers.FloatField(
+ allow_null=True,
+ help_text=(
+ "The Likely cut point the 'likely' confusion counts used for this date, from the base rate of the "
+ "dates checked before it. Null when confusion is null."
+ ),
+ )
calibration_bins = CalibrationBinSerializer(
many=True,
allow_null=True,
@@ -1442,6 +1449,50 @@ class OnlinePerformanceRowSerializer(serializers.Serializer):
validated_at = serializers.DateTimeField(allow_null=True, help_text="When the validation run completed.")
+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."
+ )
+ )
+ 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."
+ )
+ )
+ likely_lift = serializers.FloatField(
+ help_text="How many times the base rate a score must reach to be in the Likely segment."
+ )
+ 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."
+ ),
+ )
+ base_rate_dates = serializers.IntegerField(help_text="Number of checked prediction dates the base rate pools.")
+ champion_mean_p_y = serializers.FloatField(
+ allow_null=True,
+ help_text=(
+ "The current champion's mean predicted probability over the checked dates it scored as champion. "
+ "Null until those dates hold enough positives."
+ ),
+ )
+ champion_base_rate = serializers.FloatField(
+ allow_null=True,
+ help_text="The real rate of the target event over the same dates as champion_mean_p_y.",
+ )
+ scores_miscalibrated = serializers.BooleanField(
+ help_text=(
+ "True when champion_mean_p_y is far above or below champion_base_rate. The scores "
+ "are then not probabilities (for example after class weighting in train.py), so a score of likely_lift "
+ "times the base rate does not mean the user is that many times as likely to convert."
+ )
+ )
+
+
class OnlinePerformanceSerializer(serializers.Serializer):
rows = OnlinePerformanceRowSerializer(
many=True,
@@ -1450,6 +1501,12 @@ class OnlinePerformanceSerializer(serializers.Serializer):
"Empty until a prediction horizon has elapsed and online validation has run."
),
)
+ segment_thresholds = PredictionSegmentThresholdsSerializer(
+ help_text=(
+ "The current cut points between the Likely, Possible and Unlikely segments, set by lift over the "
+ "realized base rate. They do not depend on limit."
+ )
+ )
@extend_schema_serializer(component_name="AutoresearchRun")
diff --git a/products/autoresearch/backend/tests/test_api.py b/products/autoresearch/backend/tests/test_api.py
index f158b8f0945d..f929c238bf4e 100644
--- a/products/autoresearch/backend/tests/test_api.py
+++ b/products/autoresearch/backend/tests/test_api.py
@@ -1154,8 +1154,20 @@ class TestAutoresearchPipelineAPI(TeamScopedTestMixin, APIBaseTest):
"precision": 1.0,
"recall": 0.5,
}
+ assert rows[1]["likely_threshold"] == 0.6
assert rows[0]["realized_auc_ci_low"] is None and rows[0]["calibration_bins"] is None
assert rows[0]["average_precision"] is None and rows[0]["confusion"] is None
+ assert rows[0]["likely_threshold"] is None
+ assert resp.json()["segment_thresholds"] == {
+ "likely_threshold": 0.6,
+ "possible_threshold": 0.2,
+ "likely_lift": 3.0,
+ "base_rate": None,
+ "base_rate_dates": 2,
+ "champion_mean_p_y": None,
+ "champion_base_rate": None,
+ "scores_miscalibrated": False,
+ }
limited = self.client.get(f"{self.base_url}/{pipeline.id}/online_performance/?limit=1").json()["rows"]
assert [r["prediction_date"] for r in limited] == ["2026-09-03"]
diff --git a/products/autoresearch/frontend/AGENTS.md b/products/autoresearch/frontend/AGENTS.md
index fc0cce21612c..d5afa5490105 100644
--- a/products/autoresearch/frontend/AGENTS.md
+++ b/products/autoresearch/frontend/AGENTS.md
@@ -21,7 +21,7 @@ The product is mostly a backend, and the UI is deliberately thin — it reads st
| `agentSearch.ts` | The agent's search across training runs: chart points, best score so far, AUC change per experiment, log groups and the latest agent notes. |
| `onlinePerformance.ts` | Accuracy tab helpers over the `online_performance` endpoint: the headline, the realized AUC series, predicted against actual by segment. |
| `predictionCoverage.ts` | Predictions tab coverage from the runs list: the measured summary and the coverage and score age per day. |
-| `predictionSegments.ts` | The likelihood segment thresholds, from `predictionSegmentThresholds.json`. Online validation reads the same file for its Likely cutoff. |
+| `predictionSegments.ts` | The likelihood segments from the cut points the `online_performance` endpoint returns: lift over the base rate, or a fixed pair until then. |
| `PipelineStatusTag.tsx` | Status tag + tooltip shared by the list and detail scenes. |
| `ProbabilityHistogram.tsx` | Decile histogram of the latest scoring run's probabilities. |
| `DailyVolumeChart.tsx` | Bar-per-day chart of scoring volume. |
diff --git a/products/autoresearch/frontend/AutoresearchPipelineScene.stories.tsx b/products/autoresearch/frontend/AutoresearchPipelineScene.stories.tsx
index 76d4e1ea0268..b2a52f6db997 100644
--- a/products/autoresearch/frontend/AutoresearchPipelineScene.stories.tsx
+++ b/products/autoresearch/frontend/AutoresearchPipelineScene.stories.tsx
@@ -145,8 +145,9 @@ const onlinePerformance = {
confusion: {
top_10: { tp: 480, fp: 4220, fn: 930, tn: 41370, n_flagged: 4700, precision: 0.1021, recall: 0.3404 },
top_20: { tp: 735, fp: 8665, fn: 675, tn: 36925, n_flagged: 9400, precision: 0.0782, recall: 0.5213 },
- likely: { tp: 0, fp: 0, fn: 1410, tn: 45590, n_flagged: 0, precision: null, recall: 0 },
+ likely: { tp: 700, fp: 3700, fn: 710, tn: 41890, n_flagged: 4400, precision: 0.1591, recall: 0.4965 },
},
+ likely_threshold: 0.09,
calibration_bins: [
{ n: 37600, mean_p_y: 0.01, positive_rate: 0.008 },
{ n: 4700, mean_p_y: 0.08, positive_rate: 0.07 },
@@ -157,6 +158,16 @@ const onlinePerformance = {
validated_at: '2026-02-21T03:00:00Z',
}))
.reverse(),
+ segment_thresholds: {
+ likely_threshold: 0.09,
+ possible_threshold: 0.03,
+ likely_lift: 3,
+ base_rate: 0.03,
+ base_rate_dates: 5,
+ champion_mean_p_y: 0.033,
+ champion_base_rate: 0.03,
+ scores_miscalibrated: false,
+ },
}
const trainingRuns = [
@@ -282,7 +293,13 @@ export const AccuracyBeforePrecisionRecall: Story = {
mswDecorator({
get: {
[`/api/projects/:team_id/autoresearch/${PIPELINE_ID}/online_performance/`]: {
- rows: onlinePerformance.rows.map((row) => ({ ...row, average_precision: null, confusion: null })),
+ ...onlinePerformance,
+ rows: onlinePerformance.rows.map((row) => ({
+ ...row,
+ average_precision: null,
+ confusion: null,
+ likely_threshold: null,
+ })),
},
},
}),
diff --git a/products/autoresearch/frontend/ProbabilityHistogram.stories.tsx b/products/autoresearch/frontend/ProbabilityHistogram.stories.tsx
index 32b5d4d52bf9..20f7547c9d3a 100644
--- a/products/autoresearch/frontend/ProbabilityHistogram.stories.tsx
+++ b/products/autoresearch/frontend/ProbabilityHistogram.stories.tsx
@@ -12,14 +12,25 @@ type Story = StoryObj<typeof ProbabilityHistogram>
const USERS_PER_DECILE = [30, 1, 4, 3, 0, 1, 3, 2, 3, 81]
+const FIXED_THRESHOLDS = { likely_threshold: 0.6, possible_threshold: 0.2, base_rate: null }
+
export const Bimodal: Story = {
args: {
buckets: USERS_PER_DECILE.map((users, decile) => ({ lower: decile / 10, users })),
+ thresholds: FIXED_THRESHOLDS,
+ },
+}
+
+export const RareTarget: Story = {
+ args: {
+ buckets: [940, 31, 12, 6, 4, 3, 2, 1, 1, 0].map((users, decile) => ({ lower: decile / 10, users })),
+ thresholds: { likely_threshold: 0.045, possible_threshold: 0.015, base_rate: 0.015 },
},
}
export const SingleBucket: Story = {
args: {
buckets: Array.from({ length: 10 }, (_, decile) => ({ lower: decile / 10, users: decile === 9 ? 128 : 0 })),
+ thresholds: FIXED_THRESHOLDS,
},
}
diff --git a/products/autoresearch/frontend/ProbabilityHistogram.tsx b/products/autoresearch/frontend/ProbabilityHistogram.tsx
index 71cdaea4a935..d182c6604c36 100644
--- a/products/autoresearch/frontend/ProbabilityHistogram.tsx
+++ b/products/autoresearch/frontend/ProbabilityHistogram.tsx
@@ -1,13 +1,22 @@
import { Tooltip } from '@posthog/lemon-ui'
import { ProbabilityBucket } from './autoresearchPipelineLogic'
-import { predictionSegmentFor } from './predictionSegments'
+import { PredictionSegmentThresholds, predictionSegmentForRange } from './predictionSegments'
// The h-40 track minus room for the count label above the tallest bar.
const BAR_MAX_HEIGHT_PX = 136
-/** Fixed-decile histogram of a scoring run's predicted probabilities, colored by segment. No chart deps, like MetricSparkline. */
-export function ProbabilityHistogram({ buckets }: { buckets: ProbabilityBucket[] }): JSX.Element {
+/**
+ * Fixed-decile histogram of a scoring run's predicted probabilities, colored by segment. A bar that a cut
+ * point splits, or every bar before the cut points load, is neutral. No chart deps, like MetricSparkline.
+ */
+export function ProbabilityHistogram({
+ buckets,
+ thresholds,
+}: {
+ buckets: ProbabilityBucket[]
+ thresholds: PredictionSegmentThresholds | null
+}): JSX.Element {
const totalUsers = buckets.reduce((sum, bucket) => sum + bucket.users, 0)
const maxUsers = Math.max(...buckets.map((bucket) => bucket.users), 1)
return (
@@ -15,11 +24,14 @@ export function ProbabilityHistogram({ buckets }: { buckets: ProbabilityBucket[]
{buckets.map((bucket) => {
const label = `${Math.round(bucket.lower * 100)}-${Math.round((bucket.lower + 0.1) * 100)}%`
const share = totalUsers > 0 ? (100 * bucket.users) / totalUsers : 0
- const segment = predictionSegmentFor(bucket.lower)
+ const segment = thresholds
+ ? predictionSegmentForRange(bucket.lower, bucket.lower + 0.1, thresholds)
+ : null
+ const segmentLabel = segment ? segment.label.toLowerCase() : thresholds ? 'more than one segment' : null
return (
<Tooltip
key={bucket.lower}
- title={`${label} (${segment.label.toLowerCase()}): ${bucket.users.toLocaleString()} users (${share.toFixed(1)}% of ${totalUsers.toLocaleString()} scored)`}
+ title={`${label}${segmentLabel ? ` (${segmentLabel})` : ''}: ${bucket.users.toLocaleString()} users (${share.toFixed(1)}% of ${totalUsers.toLocaleString()} scored)`}
>
<div className="flex-1 min-w-0 flex flex-col items-center gap-1">
<div className="w-full h-40 flex flex-col items-center justify-end gap-0.5">
@@ -29,7 +41,7 @@ export function ProbabilityHistogram({ buckets }: { buckets: ProbabilityBucket[]
{bucket.users.toLocaleString()}
</span>
<div
- className={`w-full rounded-t hover:opacity-80 ${segment.colorClassName}`}
+ className={`w-full rounded-t hover:opacity-80 ${segment?.colorClassName ?? 'bg-border-primary'}`}
style={{
height: Math.round((BAR_MAX_HEIGHT_PX * bucket.users) / maxUsers),
minHeight: bucket.users > 0 ? 3 : 0,
diff --git a/products/autoresearch/frontend/autoresearchPipelineLogic.ts b/products/autoresearch/frontend/autoresearchPipelineLogic.ts
index 7f361e3abc45..6b8f08019ff0 100644
--- a/products/autoresearch/frontend/autoresearchPipelineLogic.ts
+++ b/products/autoresearch/frontend/autoresearchPipelineLogic.ts
@@ -55,6 +55,7 @@ import {
CreateSuggestionPriorityEnumApi,
type ModelExplanationFieldApi,
type OnlinePerformanceRowApi,
+ type PredictionSegmentThresholdsApi,
} from './generated/api.schemas'
import type { ConfusionByCutoffApi } from './generated/api.schemas'
import {
@@ -72,12 +73,13 @@ import {
import { LifecycleStep, pipelineLifecycle } from './pipelineLifecycle'
import { type CoveragePoint, type CoverageSummary, coverageHistory, coverageSummary } from './predictionCoverage'
import {
- PREDICTION_SEGMENTS,
- PREDICTION_SEGMENT_THRESHOLDS,
+ PREDICTION_SEGMENT_KEYS,
type PredictionLinkDestination,
type PredictionSegmentCounts,
+ type PredictionSegmentDefinition,
type PredictionSegmentKey,
predictionSegmentCohortFilters,
+ predictionSegmentDefinitions,
} from './predictionSegments'
import type { PredictionsPeopleView } from './predictionsPeopleQuery'
@@ -328,6 +330,8 @@ export interface autoresearchPipelineLogicValues {
scoreResultLoading: boolean
scoringCoverage: ScoringCoverage | null
segmentCalibration: SegmentCalibration[]
+ segmentDefinitions: PredictionSegmentDefinition[] | null
+ segmentThresholds: PredictionSegmentThresholdsApi | null
selectedTab: AutoresearchPipelineTab | null
startTrainingResult: AutoresearchTrainingRunApi | null
startTrainingResultLoading: boolean
@@ -456,10 +460,10 @@ export interface autoresearchPipelineLogicActions {
errorObject?: any
}
loadPredictionSegmentsSuccess: (
- predictionSegments: PredictionSegmentCounts,
+ predictionSegments: PredictionSegmentCounts | null,
payload?: any
) => {
- predictionSegments: PredictionSegmentCounts
+ predictionSegments: PredictionSegmentCounts | null
payload?: any
}
loadProbabilityDistribution: () => any
@@ -654,6 +658,9 @@ export interface autoresearchPipelineLogicActions {
setPredictionsPeopleView: (view: PredictionsPeopleView) => {
view: PredictionsPeopleView
}
+ setSegmentThresholds: (thresholds: PredictionSegmentThresholdsApi) => {
+ thresholds: PredictionSegmentThresholdsApi
+ }
setSuggestionDraft: (draft: string) => {
draft: string
}
@@ -760,7 +767,13 @@ export interface autoresearchPipelineLogicMeta {
coverageHistory: (runs: AutoresearchRunApi[]) => CoveragePoint[]
latestChampionPerformance: (onlinePerformance: OnlinePerformanceRowApi[]) => OnlinePerformanceRowApi | null
realizedAucPoints: (onlinePerformance: OnlinePerformanceRowApi[]) => RealizedAucPoint[]
- segmentCalibration: (latestChampionPerformance: OnlinePerformanceRowApi | null) => SegmentCalibration[]
+ segmentDefinitions: (
+ segmentThresholds: PredictionSegmentThresholdsApi | null
+ ) => PredictionSegmentDefinition[] | null
+ segmentCalibration: (
+ latestChampionPerformance: OnlinePerformanceRowApi | null,
+ segmentThresholds: PredictionSegmentThresholdsApi | null
+ ) => SegmentCalibration[]
championConfusion: (
onlinePerformance: OnlinePerformanceRowApi[],
accuracyCutoff: keyof ConfusionByCutoffApi
@@ -827,6 +840,7 @@ export const autoresearchPipelineLogic = kea<autoresearchPipelineLogicType>([
searchPointClicked: (point: SearchPoint) => ({ point }),
saveSegmentCohort: (segment: PredictionSegmentKey) => ({ segment }),
saveSegmentCohortFinished: true,
+ setSegmentThresholds: (thresholds: PredictionSegmentThresholdsApi) => ({ thresholds }),
}),
reducers({
detailRequested: [
@@ -904,11 +918,19 @@ export const autoresearchPipelineLogic = kea<autoresearchPipelineLogicType>([
saveSegmentCohortFinished: () => null,
},
],
+ segmentThresholds: [
+ null as PredictionSegmentThresholdsApi | null,
+ {
+ setSegmentThresholds: (_, { thresholds }) => thresholds,
+ },
+ ],
predictionSegmentsError: [
false,
{
loadPredictionSegments: () => false,
loadPredictionSegmentsFailure: () => true,
+ // The segments cannot be counted without the cut points.
+ loadOnlinePerformanceFailure: () => true,
},
],
probabilityDistributionError: [
@@ -981,7 +1003,7 @@ export const autoresearchPipelineLogic = kea<autoresearchPipelineLogicType>([
},
],
}),
- loaders(({ values, props }) => ({
+ loaders(({ actions, values, props }) => ({
pipeline: [
null as AutoresearchPipelineApi | null,
{
@@ -1050,7 +1072,11 @@ export const autoresearchPipelineLogic = kea<autoresearchPipelineLogicType>([
if (!values.currentTeamId) {
return []
}
- const { rows } = await autoresearchOnlinePerformanceRetrieve(String(values.currentTeamId), props.id)
+ const { rows, segment_thresholds } = await autoresearchOnlinePerformanceRetrieve(
+ String(values.currentTeamId),
+ props.id
+ )
+ actions.setSegmentThresholds(segment_thresholds)
return rows
},
},
@@ -1193,11 +1219,15 @@ export const autoresearchPipelineLogic = kea<autoresearchPipelineLogicType>([
null as PredictionSegmentCounts | null,
{
loadPredictionSegments: async () => {
+ const thresholds = values.segmentThresholds
+ if (!thresholds) {
+ return null
+ }
// The same per-person scores as the probability distribution, so the segments add up to its total.
const response = await api.queryHogQL(
hogql`
SELECT
- multiIf(p >= ${PREDICTION_SEGMENT_THRESHOLDS.high}, 'likely', p >= ${PREDICTION_SEGMENT_THRESHOLDS.low}, 'possible', 'unlikely') AS segment,
+ multiIf(p >= ${thresholds.likely_threshold}, 'likely', p >= ${thresholds.possible_threshold}, 'possible', 'unlikely') AS segment,
count() AS people,
sum(p) AS expected_conversions
FROM (
@@ -1226,7 +1256,7 @@ export const autoresearchPipelineLogic = kea<autoresearchPipelineLogicType>([
(response.results ?? []).map((row: any[]) => [String(row[0]), row])
)
return Object.fromEntries(
- PREDICTION_SEGMENTS.map(({ key }) => {
+ PREDICTION_SEGMENT_KEYS.map((key) => {
const row = rows.get(key)
return [key, { people: Number(row?.[1] ?? 0), expectedConversions: Number(row?.[2] ?? 0) }]
})
@@ -1330,10 +1360,20 @@ export const autoresearchPipelineLogic = kea<autoresearchPipelineLogicType>([
(s) => [s.onlinePerformance],
(onlinePerformance: OnlinePerformanceRowApi[]): RealizedAucPoint[] => realizedAucSeries(onlinePerformance),
],
+ segmentDefinitions: [
+ (s) => [s.segmentThresholds],
+ (segmentThresholds: PredictionSegmentThresholdsApi | null): PredictionSegmentDefinition[] | null =>
+ segmentThresholds ? predictionSegmentDefinitions(segmentThresholds) : null,
+ ],
segmentCalibration: [
- (s) => [s.latestChampionPerformance],
- (latestChampionPerformance: OnlinePerformanceRowApi | null): SegmentCalibration[] =>
- calibrationBySegment(latestChampionPerformance?.calibration_bins ?? []),
+ (s) => [s.latestChampionPerformance, s.segmentThresholds],
+ (
+ latestChampionPerformance: OnlinePerformanceRowApi | null,
+ segmentThresholds: PredictionSegmentThresholdsApi | null
+ ): SegmentCalibration[] =>
+ segmentThresholds
+ ? calibrationBySegment(latestChampionPerformance?.calibration_bins ?? [], segmentThresholds)
+ : [],
],
championConfusion: [
(s) => [s.onlinePerformance, s.accuracyCutoff],
@@ -1441,7 +1481,12 @@ export const autoresearchPipelineLogic = kea<autoresearchPipelineLogicType>([
if (pipeline?.last_scored_at && !values.probabilityDistribution && !values.probabilityDistributionLoading) {
actions.loadProbabilityDistribution()
}
- if (pipeline?.last_scored_at && !values.predictionSegments && !values.predictionSegmentsLoading) {
+ if (
+ pipeline?.last_scored_at &&
+ values.segmentThresholds &&
+ !values.predictionSegments &&
+ !values.predictionSegmentsLoading
+ ) {
actions.loadPredictionSegments()
}
if (pipeline?.last_scored_at && !values.dailyVolume && !values.dailyVolumeLoading) {
@@ -1625,29 +1670,35 @@ export const autoresearchPipelineLogic = kea<autoresearchPipelineLogicType>([
setPredictionsPeopleView: ({ view }) => {
posthog.capture('autoresearch model predictions view changed', { pipeline_id: props.id, view })
},
+ setSegmentThresholds: () => {
+ if (values.pipeline?.last_scored_at) {
+ actions.loadPredictionSegments()
+ }
+ },
setAccuracyCutoff: ({ cutoff }) => {
posthog.capture('autoresearch model accuracy cutoff changed', { pipeline_id: props.id, cutoff })
},
saveSegmentCohort: async ({ segment }) => {
- const { pipeline, currentProjectId } = values
- const definition = PREDICTION_SEGMENTS.find(({ key }) => key === segment)
+ const { pipeline, currentProjectId, segmentThresholds } = values
+ const definition = values.segmentDefinitions?.find(({ key }) => key === segment)
const outputProperty = pipeline?.output_person_property
- if (!pipeline || !outputProperty || !currentProjectId || !definition) {
+ if (!pipeline || !outputProperty || !currentProjectId || !definition || !segmentThresholds) {
actions.saveSegmentCohortFinished()
return
}
try {
const cohort = await cohortsCreate(String(currentProjectId), {
- name: `${pipeline.name}: ${definition.label.toLowerCase()} (${definition.range.toLowerCase()})`,
- description: `People whose ${outputProperty} score is ${definition.range.toLowerCase()}. Updates each time the model scores.`,
+ name: `${pipeline.name}: ${definition.label.toLowerCase()} (${definition.probabilityRange.toLowerCase()})`,
+ description: `People whose ${outputProperty} score is ${definition.probabilityRange.toLowerCase()}. The members update each time the model scores, but the cut point stays at the value it had when the cohort was saved.`,
is_static: false,
- filters: predictionSegmentCohortFilters(segment, outputProperty),
+ filters: predictionSegmentCohortFilters(segment, outputProperty, segmentThresholds),
})
posthog.capture('autoresearch model cohort saved', {
pipeline_id: props.id,
segment,
cohort_id: cohort.id,
people: values.predictionSegments?.[segment].people,
+ cut_points: segmentThresholds.base_rate != null ? 'base_rate' : 'fixed',
})
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.ts
index 6f6c04349235..d7eef482b131 100644
--- a/products/autoresearch/frontend/generated/api.schemas.ts
+++ b/products/autoresearch/frontend/generated/api.schemas.ts
@@ -1476,7 +1476,7 @@ export interface ConfusionByCutoffApi {
top_10: ConfusionCountsApi
/** Counts when the top 20% of users by score are flagged. */
top_20: ConfusionCountsApi
- /** Counts when users with a score of 0.6 or higher (the Likely segment) are flagged. */
+ /** Counts when users in the Likely segment, with a score of likely_threshold or higher, are flagged. */
likely: ConfusionCountsApi
}
@@ -1557,6 +1557,11 @@ export interface OnlinePerformanceRowApi {
average_precision: number | null
/** Confusion counts, precision and recall at three cutoffs: top 10%, top 20%, and the Likely segment. Null for dates validated before this metric existed. */
confusion: ConfusionByCutoffApi | null
+ /**
+ * The Likely cut point the 'likely' confusion counts used for this date, from the base rate of the dates checked before it. Null when confusion is null.
+ * @nullable
+ */
+ likely_threshold: number | null
/**
* Calibration table with up to 10 bins cut at score quantiles, lowest scores first. Users with equal scores share a bin, so heavy ties give fewer bins. Null for dates validated before this metric existed.
* @nullable
@@ -1574,9 +1579,39 @@ export interface OnlinePerformanceRowApi {
validated_at: string | null
}
+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. */
+ 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. */
+ 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.
+ * @nullable
+ */
+ base_rate: number | null
+ /** Number of checked prediction dates the base rate pools. */
+ base_rate_dates: number
+ /**
+ * The current champion's mean predicted probability over the checked dates it scored as champion. Null until those dates hold enough positives.
+ * @nullable
+ */
+ champion_mean_p_y: number | null
+ /**
+ * The real rate of the target event over the same dates as champion_mean_p_y.
+ * @nullable
+ */
+ champion_base_rate: number | null
+ /** True when champion_mean_p_y is far above or below champion_base_rate. The scores are then not probabilities (for example after class weighting in train.py), so a score of likely_lift times the base rate does not mean the user is that many times as likely to convert. */
+ scores_miscalibrated: boolean
+}
+
export interface OnlinePerformanceApi {
/** One row per model per validated prediction date, newest date first. Empty until a prediction horizon has elapsed and online validation has run. */
rows: OnlinePerformanceRowApi[]
+ /** The current cut points between the Likely, Possible and Unlikely segments, set by lift over the realized base rate. They do not depend on limit. */
+ segment_thresholds: PredictionSegmentThresholdsApi
}
export interface StartTrainingRequestApi {
diff --git a/products/autoresearch/frontend/onlinePerformance.test.ts b/products/autoresearch/frontend/onlinePerformance.test.ts
index 01c33900051d..18366e2a5c01 100644
--- a/products/autoresearch/frontend/onlinePerformance.test.ts
+++ b/products/autoresearch/frontend/onlinePerformance.test.ts
@@ -19,11 +19,14 @@ function counts(tp: number, fp: number, fn: number, tn: number): ConfusionByCuto
describe('onlinePerformance', () => {
test('calibrationBySegment weights each bin by its people and drops empty segments', () => {
- const segments = calibrationBySegment([
- { n: 300, mean_p_y: 0.05, positive_rate: 0.04 },
- { n: 100, mean_p_y: 0.15, positive_rate: 0.2 },
- { n: 50, mean_p_y: 0.7, positive_rate: 0.6 },
- ])
+ const segments = calibrationBySegment(
+ [
+ { n: 300, mean_p_y: 0.05, positive_rate: 0.04 },
+ { n: 100, mean_p_y: 0.15, positive_rate: 0.2 },
+ { n: 50, mean_p_y: 0.7, positive_rate: 0.6 },
+ ],
+ { likely_threshold: 0.6, possible_threshold: 0.2, base_rate: null }
+ )
expect(
segments.map(({ segment, people, predicted, actual }) => [segment.key, people, predicted, actual])
diff --git a/products/autoresearch/frontend/onlinePerformance.ts b/products/autoresearch/frontend/onlinePerformance.ts
index 392e8195b8e8..25d29ddf5467 100644
--- a/products/autoresearch/frontend/onlinePerformance.ts
+++ b/products/autoresearch/frontend/onlinePerformance.ts
@@ -8,10 +8,10 @@ import {
} from './generated/api.schemas'
import { modelQuality } from './modelQuality'
import {
- PREDICTION_SEGMENTS,
- PREDICTION_SEGMENT_THRESHOLDS,
PredictionSegmentDefinition,
+ PredictionSegmentThresholds,
predictionSegmentFor,
+ predictionSegmentDefinitions,
} from './predictionSegments'
export interface RealizedAucPoint {
@@ -103,17 +103,20 @@ export function realizedAucSeries(rows: OnlinePerformanceRowApi[]): RealizedAucP
* Predicted against actual rate per likelihood segment. The quantile bins do not align with the
* segment cut points, so each bin goes to the segment of its mean predicted probability.
*/
-export function calibrationBySegment(bins: CalibrationBinApi[]): SegmentCalibration[] {
+export function calibrationBySegment(
+ bins: CalibrationBinApi[],
+ thresholds: PredictionSegmentThresholds
+): SegmentCalibration[] {
const totals = new Map<string, { people: number; predicted: number; actual: number }>()
for (const bin of bins) {
- const key = predictionSegmentFor(bin.mean_p_y).key
+ const key = predictionSegmentFor(bin.mean_p_y, thresholds).key
const total = totals.get(key) ?? { people: 0, predicted: 0, actual: 0 }
total.people += bin.n
total.predicted += bin.n * bin.mean_p_y
total.actual += bin.n * bin.positive_rate
totals.set(key, total)
}
- return PREDICTION_SEGMENTS.flatMap((segment) => {
+ return predictionSegmentDefinitions(thresholds).flatMap((segment) => {
const total = totals.get(segment.key)
return total && total.people > 0
? [
@@ -172,7 +175,7 @@ function cutoffGroup(cutoff: AccuracyCutoff): string {
case 'top_20':
return 'the top 20% the model flagged'
case 'likely':
- return `the people the model scored ${PREDICTION_SEGMENT_THRESHOLDS.high * 100}% or higher`
+ return 'the people the model scored as likely'
}
}
diff --git a/products/autoresearch/frontend/pipeline/ConfusionMatrixCard.tsx b/products/autoresearch/frontend/pipeline/ConfusionMatrixCard.tsx
index 2cadbcee35e7..73183728fa9d 100644
--- a/products/autoresearch/frontend/pipeline/ConfusionMatrixCard.tsx
+++ b/products/autoresearch/frontend/pipeline/ConfusionMatrixCard.tsx
@@ -6,7 +6,6 @@ import { dayjs } from 'lib/dayjs'
import { autoresearchPipelineLogic } from '../autoresearchPipelineLogic'
import { ACCURACY_CUTOFFS, PooledConfusion, percent } from '../onlinePerformance'
-import { PREDICTION_SEGMENT_THRESHOLDS } from '../predictionSegments'
import { MetricCard } from './MetricCard'
function dateRange({ firstDate, lastDate }: PooledConfusion): string {
@@ -57,8 +56,8 @@ export function ConfusionMatrixCard(): JSX.Element {
)}
{confusion.flagged === 0 ? (
<LemonBanner type="info">
- No one scored {PREDICTION_SEGMENT_THRESHOLDS.high * 100}% or higher in this period. Pick Top
- 10% to see how the people with the highest scores did.
+ No one scored as likely in this period. Pick Top 10% to see how the people with the highest
+ scores did.
</LemonBanner>
) : (
<div className="flex flex-wrap items-start gap-4">
diff --git a/products/autoresearch/frontend/pipeline/PredictionActionsPanel.tsx b/products/autoresearch/frontend/pipeline/PredictionActionsPanel.tsx
index 72fc779529eb..5d225fedacc4 100644
--- a/products/autoresearch/frontend/pipeline/PredictionActionsPanel.tsx
+++ b/products/autoresearch/frontend/pipeline/PredictionActionsPanel.tsx
@@ -5,21 +5,21 @@ import { LemonButton } from '@posthog/lemon-ui'
import { autoresearchPipelineLogic } from '../autoresearchPipelineLogic'
import {
- PREDICTION_SEGMENTS,
likelySegmentFeatureFlagUrl,
likelySegmentWorkflowUrl,
predictionBreakdownInsightUrl,
} from '../predictionSegments'
export function PredictionActionsPanel(): JSX.Element | null {
- const { pipeline } = useValues(autoresearchPipelineLogic)
+ const { pipeline, segmentThresholds, segmentDefinitions } = useValues(autoresearchPipelineLogic)
const { reportPredictionLinkClicked } = useActions(autoresearchPipelineLogic)
const outputProperty = pipeline?.output_person_property
if (!pipeline || !outputProperty) {
return null
}
- const likelyRange = PREDICTION_SEGMENTS[0].range.toLowerCase()
+ const likelyRange = segmentDefinitions?.[0].probabilityRange.toLowerCase() ?? 'as likely'
+ const segmentsLoading = !segmentThresholds ? 'Segments are still loading' : undefined
return (
<div className="border rounded p-4 bg-surface-primary">
@@ -28,7 +28,8 @@ export function PredictionActionsPanel(): JSX.Element | null {
<div className="flex flex-col gap-1">
<LemonButton
icon={<IconFlag />}
- to={likelySegmentFeatureFlagUrl(outputProperty)}
+ to={segmentThresholds ? likelySegmentFeatureFlagUrl(outputProperty, segmentThresholds) : undefined}
+ disabledReason={segmentsLoading}
onClick={() => reportPredictionLinkClicked('feature_flag')}
data-attr="autoresearch-predictions-create-flag"
fullWidth
@@ -37,7 +38,8 @@ export function PredictionActionsPanel(): JSX.Element | null {
</LemonButton>
<LemonButton
icon={<IconDecisionTree />}
- to={likelySegmentWorkflowUrl(outputProperty)}
+ to={segmentThresholds ? likelySegmentWorkflowUrl(outputProperty, segmentThresholds) : undefined}
+ disabledReason={segmentsLoading}
onClick={() => reportPredictionLinkClicked('workflow')}
data-attr="autoresearch-predictions-create-workflow"
fullWidth
diff --git a/products/autoresearch/frontend/pipeline/PredictionSegmentCards.tsx b/products/autoresearch/frontend/pipeline/PredictionSegmentCards.tsx
index 230601484111..3c67e9fa5310 100644
--- a/products/autoresearch/frontend/pipeline/PredictionSegmentCards.tsx
+++ b/products/autoresearch/frontend/pipeline/PredictionSegmentCards.tsx
@@ -1,14 +1,15 @@
import { useActions, useValues } from 'kea'
-import { LemonButton, LemonSkeleton, Tooltip } from '@posthog/lemon-ui'
+import { LemonBanner, LemonButton, LemonSkeleton, Tooltip } from '@posthog/lemon-ui'
import { humanFriendlyNumber } from 'lib/utils/numbers'
import { autoresearchPipelineLogic } from '../autoresearchPipelineLogic'
-import { PREDICTION_SEGMENTS, PredictionSegmentDefinition, predictionSegmentPeopleUrl } from '../predictionSegments'
+import { PredictionSegmentDefinition, formatProbability, predictionSegmentPeopleUrl } from '../predictionSegments'
function SegmentCard({ segment }: { segment: PredictionSegmentDefinition }): JSX.Element {
- const { pipeline, predictionSegments, savingCohortSegment } = useValues(autoresearchPipelineLogic)
+ const { pipeline, predictionSegments, savingCohortSegment, segmentThresholds } =
+ useValues(autoresearchPipelineLogic)
const { saveSegmentCohort } = useActions(autoresearchPipelineLogic)
const stats = predictionSegments?.[segment.key]
@@ -62,8 +63,18 @@ function SegmentCard({ segment }: { segment: PredictionSegmentDefinition }): JSX
type="tertiary"
size="small"
data-attr={`autoresearch-segment-view-people-${segment.key}`}
- to={predictionSegmentPeopleUrl(segment.key, outputProperty)}
- disabledReason={!outputProperty ? 'The model has no output property' : undefined}
+ to={
+ segmentThresholds
+ ? predictionSegmentPeopleUrl(segment.key, outputProperty, segmentThresholds)
+ : undefined
+ }
+ disabledReason={
+ !outputProperty
+ ? 'The model has no output property'
+ : !segmentThresholds
+ ? 'Segments are still loading'
+ : undefined
+ }
>
View people
</LemonButton>
@@ -72,17 +83,51 @@ function SegmentCard({ segment }: { segment: PredictionSegmentDefinition }): JSX
)
}
+function SegmentCutPoints(): JSX.Element | null {
+ const { pipeline, segmentThresholds: thresholds } = useValues(autoresearchPipelineLogic)
+ if (!thresholds) {
+ return null
+ }
+ const target = pipeline?.target_event ?? 'the target event'
+ return (
+ <>
+ <p className="text-sm text-secondary mb-0">
+ {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.'}
+ </p>
+ {thresholds.scores_miscalibrated &&
+ thresholds.champion_mean_p_y != null &&
+ thresholds.champion_base_rate != null && (
+ <LemonBanner type="warning">
+ This model's scores are not true probabilities. It predicted{' '}
+ {formatProbability(thresholds.champion_mean_p_y)} on average, and{' '}
+ {formatProbability(thresholds.champion_base_rate)} of people did {target}. The segments still
+ rank people, but a score of {thresholds.likely_lift}× average may not mean{' '}
+ {thresholds.likely_lift}× as likely. Check the Accuracy tab before you act on the percentages.
+ </LemonBanner>
+ )}
+ </>
+ )
+}
+
export function PredictionSegmentCards(): JSX.Element {
- const { predictionSegmentsError } = useValues(autoresearchPipelineLogic)
+ const { predictionSegmentsError, segmentDefinitions } = useValues(autoresearchPipelineLogic)
if (predictionSegmentsError) {
return <p className="text-sm text-muted mb-0">Couldn't load the segments. Refresh the page to try again.</p>
}
+ if (!segmentDefinitions) {
+ return <LemonSkeleton className="h-40" />
+ }
return (
- <div className="flex flex-wrap gap-4">
- {PREDICTION_SEGMENTS.map((segment) => (
- <SegmentCard key={segment.key} segment={segment} />
- ))}
+ <div className="space-y-3">
+ <SegmentCutPoints />
+ <div className="flex flex-wrap gap-4">
+ {segmentDefinitions.map((segment) => (
+ <SegmentCard key={segment.key} segment={segment} />
+ ))}
+ </div>
</div>
)
}
diff --git a/products/autoresearch/frontend/pipeline/PredictionsTab.tsx b/products/autoresearch/frontend/pipeline/PredictionsTab.tsx
index 9fc66cfc6623..37a5bd01e2c4 100644
--- a/products/autoresearch/frontend/pipeline/PredictionsTab.tsx
+++ b/products/autoresearch/frontend/pipeline/PredictionsTab.tsx
@@ -33,7 +33,8 @@ function DailyVolumePanel(): JSX.Element {
}
function ProbabilityDistributionPanel(): JSX.Element {
- const { probabilityHistogram, probabilityDistributionError } = useValues(autoresearchPipelineLogic)
+ const { probabilityHistogram, probabilityDistributionError, segmentThresholds } =
+ useValues(autoresearchPipelineLogic)
if (probabilityDistributionError) {
return (
@@ -52,7 +53,7 @@ function ProbabilityDistributionPanel(): JSX.Element {
</p>
)
}
- return <ProbabilityHistogram buckets={probabilityHistogram} />
+ return <ProbabilityHistogram buckets={probabilityHistogram} thresholds={segmentThresholds} />
}
export function PredictionsTab(): JSX.Element {
diff --git a/products/autoresearch/frontend/predictionSegmentThresholds.json b/products/autoresearch/frontend/predictionSegmentThresholds.json
deleted file mode 100644
index 486ff20a19d0..000000000000
--- a/products/autoresearch/frontend/predictionSegmentThresholds.json
+++ /dev/null
@@ -1 +0,0 @@
-{ "high": 0.6, "low": 0.2 }
diff --git a/products/autoresearch/frontend/predictionSegments.test.ts b/products/autoresearch/frontend/predictionSegments.test.ts
index 414ba690cabf..376e1d108d73 100644
--- a/products/autoresearch/frontend/predictionSegments.test.ts
+++ b/products/autoresearch/frontend/predictionSegments.test.ts
@@ -1,12 +1,18 @@
import { parseWorkflowTriggerPrefill } from 'products/workflows/frontend/Workflows/workflowTriggerPrefill'
import {
- PREDICTION_SEGMENTS,
+ PredictionSegmentThresholds,
likelySegmentWorkflowUrl,
predictionSegmentCohortFilters,
+ predictionSegmentDefinitions,
predictionSegmentFor,
+ predictionSegmentForRange,
} from './predictionSegments'
+const FIXED: PredictionSegmentThresholds = { likely_threshold: 0.6, possible_threshold: 0.2, base_rate: null }
+const RARE: PredictionSegmentThresholds = { likely_threshold: 0.045, possible_threshold: 0.015, base_rate: 0.015 }
+const CAPPED: PredictionSegmentThresholds = { likely_threshold: 0.75, possible_threshold: 0.5, base_rate: 0.5 }
+
function cohortMatches(filters: ReturnType<typeof predictionSegmentCohortFilters>, probability: number): boolean {
return filters.properties.values.every((group) =>
'values' in group
@@ -19,23 +25,60 @@ function cohortMatches(filters: ReturnType<typeof predictionSegmentCohortFilters
}
describe('predictionSegments', () => {
- test.each(Array.from({ length: 21 }, (_, step) => step / 20))(
- 'a %s score lands in exactly one segment cohort, the one its histogram bar is colored as',
- (probability) => {
- const matching = PREDICTION_SEGMENTS.filter(({ key }) =>
- cohortMatches(predictionSegmentCohortFilters(key, 'p_signed_up'), probability)
- )
-
- expect(matching.map(({ key }) => key)).toEqual([predictionSegmentFor(probability).key])
+ test.each([
+ ['fixed', FIXED],
+ ['rare target', RARE],
+ ['capped', CAPPED],
+ ])(
+ 'with %s cut points, every score lands in exactly one segment cohort, the one its card counts',
+ (_, thresholds) => {
+ const { likely_threshold: high, possible_threshold: low } = thresholds
+ const scores = [...Array.from({ length: 21 }, (_, step) => step / 20), high, low, high - 1e-9, low - 1e-9]
+ for (const probability of scores) {
+ const matching = predictionSegmentDefinitions(thresholds).filter(({ key }) =>
+ cohortMatches(predictionSegmentCohortFilters(key, 'p_signed_up', thresholds), probability)
+ )
+
+ expect(matching.map(({ key }) => key)).toEqual([predictionSegmentFor(probability, thresholds).key])
+ }
}
)
+ test.each([
+ ['fixed', FIXED, ['60% and above', '20% to 60%', 'Below 20%'], ['60% and above', '20% to 60%', 'Below 20%']],
+ [
+ 'rare target',
+ RARE,
+ ['3× average or higher (4.5%+)', 'Average to 3× (1.5% to 4.5%)', 'Below average (under 1.5%)'],
+ ['4.5% and above', '1.5% to 4.5%', 'Below 1.5%'],
+ ],
+ [
+ 'capped',
+ CAPPED,
+ ['1.5× average or higher (75%+)', 'Average to 1.5× (50% to 75%)', 'Below average (under 50%)'],
+ ['75% and above', '50% to 75%', 'Below 50%'],
+ ],
+ ])('%s cut points state the lift and the probabilities', (_, thresholds, ranges, probabilityRanges) => {
+ const segments = predictionSegmentDefinitions(thresholds)
+
+ expect(segments.map(({ range }) => range)).toEqual(ranges)
+ expect(segments.map(({ probabilityRange }) => probabilityRange)).toEqual(probabilityRanges)
+ })
+
+ test.each([
+ ['a bar inside one segment keeps its color', 0.6, 0.7, FIXED, 'likely'],
+ ['a bar a cut point splits is neutral', 0.0, 0.1, RARE, null],
+ ['a bar starting at a cut point is not split', 0.5, 0.6, CAPPED, 'possible'],
+ ])('%s', (_, lower, upper, thresholds, expected) => {
+ expect(predictionSegmentForRange(lower, upper, thresholds)?.key ?? null).toEqual(expected)
+ })
+
test('the workflow link opens a batch workflow whose audience is the likely segment', () => {
- const raw = new URLSearchParams(likelySegmentWorkflowUrl('p_signed_up').split('?')[1]).get('trigger')
+ const raw = new URLSearchParams(likelySegmentWorkflowUrl('p_signed_up', RARE).split('?')[1]).get('trigger')
expect(parseWorkflowTriggerPrefill(raw ?? undefined)).toEqual({
type: 'batch',
- filters: { properties: [{ type: 'person', key: 'p_signed_up', operator: 'gte', value: 0.6 }] },
+ filters: { properties: [{ type: 'person', key: 'p_signed_up', operator: 'gte', value: 0.045 }] },
})
})
})
diff --git a/products/autoresearch/frontend/predictionSegments.ts b/products/autoresearch/frontend/predictionSegments.ts
index 73998f8b26c4..d968f04ca979 100644
--- a/products/autoresearch/frontend/predictionSegments.ts
+++ b/products/autoresearch/frontend/predictionSegments.ts
@@ -10,33 +10,87 @@ import { BaseMathType, PersonPropertyFilter, PropertyFilterType, PropertyOperato
import type { CohortFiltersApi, PersonFilterApi } from 'products/cohorts/frontend/generated/api.schemas'
import { urlForNewWorkflowWithTrigger } from 'products/workflows/frontend/Workflows/workflowTriggerPrefill'
-import type { AutoresearchPipelineApi } from './generated/api.schemas'
-import thresholds from './predictionSegmentThresholds.json'
+import type { AutoresearchPipelineApi, PredictionSegmentThresholdsApi } from './generated/api.schemas'
/**
- * Probability cut points between the segments. Both sit on a histogram decile boundary,
- * so every histogram bar belongs to exactly one segment. Online validation reads the same
- * JSON file for its Likely cutoff.
+ * The cut points come from the online_performance endpoint: lift over the model's realized base rate,
+ * or a fixed pair until enough predictions are checked. Online validation counts its Likely flags
+ * with the same cut point.
*/
-export const PREDICTION_SEGMENT_THRESHOLDS: { readonly high: number; readonly low: number } = thresholds
+export type PredictionSegmentThresholds = Pick<
+ PredictionSegmentThresholdsApi,
+ 'likely_threshold' | 'possible_threshold' | 'base_rate'
+>
export type PredictionSegmentKey = 'likely' | 'possible' | 'unlikely'
+export const PREDICTION_SEGMENT_KEYS: PredictionSegmentKey[] = ['likely', 'possible', 'unlikely']
+
export interface PredictionSegmentDefinition {
key: PredictionSegmentKey
label: string
+ /** The range as the cards show it, relative to the average when there is a base rate. */
range: string
+ /** The range in probabilities only. Saved cohorts keep this cut point, so their names state it. */
+ probabilityRange: string
/** Tailwind background class for the segment's card accent and histogram bars. */
colorClassName: string
}
-const { high, low } = PREDICTION_SEGMENT_THRESHOLDS
+/** A probability as a percentage with up to three significant digits, so a rare target's 0.045 reads 4.5%. */
+export function formatProbability(probability: number): string {
+ return `${parseFloat((probability * 100).toPrecision(3))}%`
+}
+
+function formatLift(lift: number): string {
+ return `${parseFloat(lift.toFixed(1))}×`
+}
-export const PREDICTION_SEGMENTS: PredictionSegmentDefinition[] = [
- { key: 'likely', label: 'Likely', range: `${high * 100}% and above`, colorClassName: 'bg-success' },
- { key: 'possible', label: 'Possible', range: `${low * 100}% to ${high * 100}%`, colorClassName: 'bg-warning' },
- { key: 'unlikely', label: 'Unlikely', range: `Below ${low * 100}%`, colorClassName: 'bg-muted' },
-]
+export function predictionSegmentDefinitions({
+ likely_threshold: high,
+ possible_threshold: low,
+ base_rate: baseRate,
+}: PredictionSegmentThresholds): PredictionSegmentDefinition[] {
+ const highText = formatProbability(high)
+ const lowText = formatProbability(low)
+ const probabilityRanges: Record<PredictionSegmentKey, string> = {
+ likely: `${highText} and above`,
+ possible: `${lowText} to ${highText}`,
+ unlikely: `Below ${lowText}`,
+ }
+ // A high base rate caps the Likely cut point, so the lift is read off the cut point, not the configured one.
+ const lift = baseRate ? formatLift(high / baseRate) : null
+ const ranges: Record<PredictionSegmentKey, string> = lift
+ ? {
+ likely: `${lift} average or higher (${highText}+)`,
+ possible: `Average to ${lift} (${lowText} to ${highText})`,
+ unlikely: `Below average (under ${lowText})`,
+ }
+ : probabilityRanges
+ return [
+ {
+ key: 'likely',
+ label: 'Likely',
+ range: ranges.likely,
+ probabilityRange: probabilityRanges.likely,
+ colorClassName: 'bg-success',
+ },
+ {
+ key: 'possible',
+ label: 'Possible',
+ range: ranges.possible,
+ probabilityRange: probabilityRanges.possible,
+ colorClassName: 'bg-warning',
+ },
+ {
+ key: 'unlikely',
+ label: 'Unlikely',
+ range: ranges.unlikely,
+ probabilityRange: probabilityRanges.unlikely,
+ colorClassName: 'bg-muted',
+ },
+ ]
+}
/** People and expected conversions of one segment in the latest scoring run. */
export interface PredictionSegmentStats {
@@ -47,14 +101,42 @@ export interface PredictionSegmentStats {
export type PredictionSegmentCounts = Record<PredictionSegmentKey, PredictionSegmentStats>
-export function predictionSegmentFor(probability: number): PredictionSegmentDefinition {
- const [likely, possible, unlikely] = PREDICTION_SEGMENTS
- return probability >= high ? likely : probability >= low ? possible : unlikely
+function segmentKeyFor(probability: number, thresholds: PredictionSegmentThresholds): PredictionSegmentKey {
+ return probability >= thresholds.likely_threshold
+ ? 'likely'
+ : probability >= thresholds.possible_threshold
+ ? 'possible'
+ : 'unlikely'
+}
+
+export function predictionSegmentFor(
+ probability: number,
+ thresholds: PredictionSegmentThresholds
+): PredictionSegmentDefinition {
+ const key = segmentKeyFor(probability, thresholds)
+ return predictionSegmentDefinitions(thresholds).find(
+ (segment) => segment.key === key
+ ) as PredictionSegmentDefinition
+}
+
+/** The segment of every score in [lower, upper), or null when a cut point splits the range. */
+export function predictionSegmentForRange(
+ lower: number,
+ upper: number,
+ thresholds: PredictionSegmentThresholds
+): PredictionSegmentDefinition | null {
+ const split = [thresholds.likely_threshold, thresholds.possible_threshold].some(
+ (cutPoint) => cutPoint > lower && cutPoint < upper
+ )
+ return split ? null : predictionSegmentFor(lower, thresholds)
}
type SegmentBound = { operator: PropertyOperator.GreaterThanOrEqual | PropertyOperator.LessThan; value: number }
-function segmentBounds(key: PredictionSegmentKey): SegmentBound[] {
+function segmentBounds(
+ key: PredictionSegmentKey,
+ { likely_threshold: high, possible_threshold: low }: PredictionSegmentThresholds
+): SegmentBound[] {
switch (key) {
case 'likely':
return [{ operator: PropertyOperator.GreaterThanOrEqual, value: high }]
@@ -69,8 +151,12 @@ function segmentBounds(key: PredictionSegmentKey): SegmentBound[] {
}
/** A dynamic cohort of the people whose output property puts them in the segment. */
-export function predictionSegmentCohortFilters(key: PredictionSegmentKey, property: string): CohortFiltersApi {
- const values: PersonFilterApi[] = segmentBounds(key).map(({ operator, value }) => ({
+export function predictionSegmentCohortFilters(
+ key: PredictionSegmentKey,
+ property: string,
+ thresholds: PredictionSegmentThresholds
+): CohortFiltersApi {
+ const values: PersonFilterApi[] = segmentBounds(key, thresholds).map(({ operator, value }) => ({
type: 'person',
key: property,
operator,
@@ -79,8 +165,12 @@ export function predictionSegmentCohortFilters(key: PredictionSegmentKey, proper
return { properties: { type: 'OR', values: [{ type: 'AND', values }] } }
}
-function segmentPropertyFilters(key: PredictionSegmentKey, property: string): PersonPropertyFilter[] {
- return segmentBounds(key).map(({ operator, value }) => ({
+function segmentPropertyFilters(
+ key: PredictionSegmentKey,
+ property: string,
+ thresholds: PredictionSegmentThresholds
+): PersonPropertyFilter[] {
+ return segmentBounds(key, thresholds).map(({ operator, value }) => ({
type: PropertyFilterType.Person,
key: property,
operator,
@@ -89,8 +179,12 @@ function segmentPropertyFilters(key: PredictionSegmentKey, property: string): Pe
}
/** The persons list, filtered with the same conditions as the segment's cohort. */
-export function predictionSegmentPeopleUrl(key: PredictionSegmentKey, property: string): string {
- const properties = segmentPropertyFilters(key, property)
+export function predictionSegmentPeopleUrl(
+ key: PredictionSegmentKey,
+ property: string,
+ thresholds: PredictionSegmentThresholds
+): string {
+ const properties = segmentPropertyFilters(key, property, thresholds)
const query: DataTableNode = {
kind: NodeKind.DataTableNode,
source: {
@@ -110,15 +204,15 @@ export function predictionSegmentPeopleUrl(key: PredictionSegmentKey, property:
export type PredictionLinkDestination = 'feature_flag' | 'workflow' | 'insight'
/** A new feature flag released to the likely segment. */
-export function likelySegmentFeatureFlagUrl(property: string): string {
- return urls.featureFlagNew({ properties: segmentPropertyFilters('likely', property) })
+export function likelySegmentFeatureFlagUrl(property: string, thresholds: PredictionSegmentThresholds): string {
+ return urls.featureFlagNew({ properties: segmentPropertyFilters('likely', property, thresholds) })
}
/** A new batch workflow whose audience is the likely segment. */
-export function likelySegmentWorkflowUrl(property: string): string {
+export function likelySegmentWorkflowUrl(property: string, thresholds: PredictionSegmentThresholds): string {
return urlForNewWorkflowWithTrigger({
type: 'batch',
- filters: { properties: segmentPropertyFilters('likely', property) },
+ filters: { properties: segmentPropertyFilters('likely', property, thresholds) },
})
}
diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.ts
index a8a3fceabce5..7940c5bbf132 100644
--- a/services/mcp/src/api/generated.ts
+++ b/services/mcp/src/api/generated.ts
@@ -24624,7 +24624,7 @@ export namespace Schemas {
top_10: ConfusionCounts;
/** Counts when the top 20% of users by score are flagged. */
top_20: ConfusionCounts;
- /** Counts when users with a score of 0.6 or higher (the Likely segment) are flagged. */
+ /** Counts when users in the Likely segment, with a score of likely_threshold or higher, are flagged. */
likely: ConfusionCounts;
}
@@ -67876,6 +67876,11 @@ export namespace Schemas {
average_precision: number | null;
/** Confusion counts, precision and recall at three cutoffs: top 10%, top 20%, and the Likely segment. Null for dates validated before this metric existed. */
confusion: ConfusionByCutoff | null;
+ /**
+ * The Likely cut point the 'likely' confusion counts used for this date, from the base rate of the dates checked before it. Null when confusion is null.
+ * @nullable
+ */
+ likely_threshold: number | null;
/**
* Calibration table with up to 10 bins cut at score quantiles, lowest scores first. Users with equal scores share a bin, so heavy ties give fewer bins. Null for dates validated before this metric existed.
* @nullable
@@ -67893,9 +67898,39 @@ export namespace Schemas {
validated_at: string | null;
}
+ 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. */
+ 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. */
+ 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.
+ * @nullable
+ */
+ base_rate: number | null;
+ /** Number of checked prediction dates the base rate pools. */
+ base_rate_dates: number;
+ /**
+ * The current champion's mean predicted probability over the checked dates it scored as champion. Null until those dates hold enough positives.
+ * @nullable
+ */
+ champion_mean_p_y: number | null;
+ /**
+ * The real rate of the target event over the same dates as champion_mean_p_y.
+ * @nullable
+ */
+ champion_base_rate: number | null;
+ /** True when champion_mean_p_y is far above or below champion_base_rate. The scores are then not probabilities (for example after class weighting in train.py), so a score of likely_lift times the base rate does not mean the user is that many times as likely to convert. */
+ scores_miscalibrated: boolean;
+ }
+
export interface OnlinePerformance {
/** One row per model per validated prediction date, newest date first. Empty until a prediction horizon has elapsed and online validation has run. */
rows: OnlinePerformanceRow[];
+ /** The current cut points between the Likely, Possible and Unlikely segments, set by lift over the realized base rate. They do not depend on limit. */
+ segment_thresholds: PredictionSegmentThresholds;
}
/**