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): lead the predictions tab with likelihood segments (#113111)

posthog[bot]31f5d5ba2a46
diff --git a/frontend/snapshots.yml b/frontend/snapshots.yml
index 0f53bf04d729..7bb8acf91767 100644
--- a/frontend/snapshots.yml
+++ b/frontend/snapshots.yml
@@ -6427,13 +6427,13 @@ snapshots:
products-autoresearch-daily-volume-chart--two-weeks--light:
hash: v1.k794b7964.657b4864698965984216442d166b797580c2400a075a32a666088955114b6e26.5aBdQrW6RrKJjUXMDizdh6cpFHYQ1hqWTxPzdc2duvk
products-autoresearch-probability-histogram--bimodal--dark:
- hash: v1.k794b7964.54848640bbeba7e0c519e2a4f939bd58aff008ea7f48b96c38f95c825859e29c.8bwWwevDVdQFiWK4kusQ_xTaxhGSYIyHuH6qZFWC18U
+ hash: v1.k794b7964.f95d3982e7c08f2e1b51655520f15e37293aa98e5ca87126a5653d2300bd776b.2G0LsuSx-SLqWn1Oxm_bUHSqfeDPFF6Pof0vDvhZEHM
products-autoresearch-probability-histogram--bimodal--light:
- hash: v1.k794b7964.7465c08474c8046d542766f38638d29b338aa735187618003250a820305a7f0a.E5Z0ct7fsOPeVK172KqNscasD4VWpkZqHNkAdPwxb0w
+ hash: v1.k794b7964.831315d68f8983a92a0f0e134a485f482ca6df6fa85f78301e926ce00e2e2ccb.TO-b36vQiw4ne1Fv45cDNBHKKKvDkBFK2C5I3PF-qmo
products-autoresearch-probability-histogram--single-bucket--dark:
- hash: v1.k794b7964.47dc280e27c512035ac74d86134e2b5771f84b1454556c492f6319d9d3ffa29f.l0n9noDhYfjTrpN-tlvi5TJq4RJCDIkUCFKse51o1O4
+ hash: v1.k794b7964.164637ddca4c38e0f3fbcabd8c6abf6679cc52b8181e545d9d42faf7a6913377.-9jAhj26nqF75jfLBkjvFo7XuqmLPFvndCV1_30iCrg
products-autoresearch-probability-histogram--single-bucket--light:
- hash: v1.k794b7964.492095448990e600a399d4212b8fb96e8f95c2e7bdafb3f84d8bdc10467fbf4e.1OfZFFoGzmeH8sxtbwrD-H9bR_n08l9kV63NB2Sv1jU
+ hash: v1.k794b7964.7087a0c145f21f4ad346356f61768cfe3c158fcaf680e2bfd46135bcb39985a5.DRfvEC1xadIFDKaZCGZtNj1jj7vYSW_jF1U97K7QrBI
products-autoresearch-training-run-row--compared-with-champion-narrow--dark:
hash: v1.k794b7964.9830e6048bce43800723ca6bee037bb1a91ec500aec423893be9b3c55659df14.fmdX0m_Qvg0f3TJFplwoR0u44C8RtyPj1NgmVoqP9Fk
products-autoresearch-training-run-row--compared-with-champion-narrow--light:
diff --git a/products/autoresearch/frontend/ProbabilityHistogram.tsx b/products/autoresearch/frontend/ProbabilityHistogram.tsx
index d45fdf9bff50..71cdaea4a935 100644
--- a/products/autoresearch/frontend/ProbabilityHistogram.tsx
+++ b/products/autoresearch/frontend/ProbabilityHistogram.tsx
@@ -1,11 +1,12 @@
import { Tooltip } from '@posthog/lemon-ui'
import { ProbabilityBucket } from './autoresearchPipelineLogic'
+import { predictionSegmentFor } 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. No chart deps, like MetricSparkline. */
+/** 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 {
const totalUsers = buckets.reduce((sum, bucket) => sum + bucket.users, 0)
const maxUsers = Math.max(...buckets.map((bucket) => bucket.users), 1)
@@ -14,10 +15,11 @@ 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)
return (
<Tooltip
key={bucket.lower}
- title={`${label}: ${bucket.users.toLocaleString()} users (${share.toFixed(1)}% of ${totalUsers.toLocaleString()} scored)`}
+ title={`${label} (${segment.label.toLowerCase()}): ${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">
@@ -27,7 +29,7 @@ export function ProbabilityHistogram({ buckets }: { buckets: ProbabilityBucket[]
{bucket.users.toLocaleString()}
</span>
<div
- className="w-full rounded-t bg-[var(--data-color-1)] hover:bg-[var(--data-color-1-hover)]"
+ className={`w-full rounded-t hover:opacity-80 ${segment.colorClassName}`}
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 3013b4ac046d..695990bd2b66 100644
--- a/products/autoresearch/frontend/autoresearchPipelineLogic.ts
+++ b/products/autoresearch/frontend/autoresearchPipelineLogic.ts
@@ -7,6 +7,7 @@ import api from 'lib/api'
import { FEATURE_FLAGS } from 'lib/constants'
import { lemonToast } from 'lib/lemon-ui/LemonToast'
import { featureFlagLogic } from 'lib/logic/featureFlagLogic'
+import { projectLogic } from 'scenes/projectLogic'
import { Scene } from 'scenes/sceneTypes'
import { teamLogic } from 'scenes/teamLogic'
import { urls } from 'scenes/urls'
@@ -14,6 +15,8 @@ import { urls } from 'scenes/urls'
import { hogql } from '~/queries/utils'
import { Breadcrumb } from '~/types'
+import { cohortsCreate } from 'products/cohorts/frontend/generated/api'
+
import type { FeatureFlagsSet } from '../../../frontend/src/lib/logic/featureFlagLogic'
import {
autoresearchModelsList,
@@ -40,6 +43,13 @@ import {
CreateSuggestionPriorityEnumApi,
type ModelExplanationFieldApi,
} from './generated/api.schemas'
+import {
+ PREDICTION_SEGMENTS,
+ PREDICTION_SEGMENT_THRESHOLDS,
+ type PredictionSegmentCounts,
+ type PredictionSegmentKey,
+ predictionSegmentCohortFilters,
+} from './predictionSegments'
import type { PredictionsPeopleView } from './predictionsPeopleQuery'
export interface AutoresearchPipelineLogicProps {
@@ -83,10 +93,10 @@ function findRunningScoreRun(runs: AutoresearchRunApi[]): AutoresearchRunApi | n
)
}
-/** One decile of the latest scoring run's predicted probabilities: `lower` ≤ p < `lower` + 0.1. */
/** How far back the Predictions tab looks for the latest scoring batch, so it never scans the full history. */
export const LATEST_BATCH_LOOKBACK_DAYS = 90
+/** One decile of the latest scoring run's predicted probabilities: `lower` ≤ p < `lower` + 0.1. */
export interface ProbabilityBucket {
lower: number
users: number
@@ -255,6 +265,7 @@ export interface OnlinePerformanceRow {
// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface autoresearchPipelineLogicValues {
featureFlags: FeatureFlagsSet // featureFlagLogic
+ currentProjectId: number | null // projectLogic
currentTeamId: number | null // teamLogic
activeScoreRun: AutoresearchRunApi | null
activeTab: AutoresearchPipelineTab
@@ -275,6 +286,9 @@ export interface autoresearchPipelineLogicValues {
pipeline: AutoresearchPipelineApi | null
pipelineError: boolean
pipelineLoading: boolean
+ predictionSegments: PredictionSegmentCounts | null
+ predictionSegmentsError: boolean
+ predictionSegmentsLoading: boolean
predictionsPeopleView: PredictionsPeopleView
probabilityDistribution: ProbabilityBucket[] | null
probabilityDistributionError: boolean
@@ -285,6 +299,7 @@ export interface autoresearchPipelineLogicValues {
runs: AutoresearchRunApi[]
runsError: boolean
runsLoading: boolean
+ savingCohortSegment: PredictionSegmentKey | null
scoreResult: AutoresearchRunApi | null
scoreResultLoading: boolean
scoringCoverage: ScoringCoverage | null
@@ -392,6 +407,21 @@ export interface autoresearchPipelineLogicActions {
pipeline: AutoresearchPipelineApi | null
payload?: any
}
+ loadPredictionSegments: () => any
+ loadPredictionSegmentsFailure: (
+ error: string,
+ errorObject?: any
+ ) => {
+ error: string
+ errorObject?: any
+ }
+ loadPredictionSegmentsSuccess: (
+ predictionSegments: PredictionSegmentCounts,
+ payload?: any
+ ) => {
+ predictionSegments: PredictionSegmentCounts
+ payload?: any
+ }
loadProbabilityDistribution: () => any
loadProbabilityDistributionFailure: (
error: string,
@@ -536,6 +566,12 @@ export interface autoresearchPipelineLogicActions {
pipeline: AutoresearchPipelineApi | null
payload?: any
}
+ saveSegmentCohort: (segment: PredictionSegmentKey) => {
+ segment: PredictionSegmentKey
+ }
+ saveSegmentCohortFinished: () => {
+ value: true
+ }
scoreNow: () => any
scoreNowFailure: (
error: string,
@@ -670,7 +706,7 @@ export const autoresearchPipelineLogic = kea<autoresearchPipelineLogicType>([
props({} as AutoresearchPipelineLogicProps),
key((props) => props.id),
connect({
- values: [teamLogic, ['currentTeamId'], featureFlagLogic, ['featureFlags']],
+ values: [teamLogic, ['currentTeamId'], projectLogic, ['currentProjectId'], featureFlagLogic, ['featureFlags']],
actions: [teamLogic, ['loadCurrentTeamSuccess'], featureFlagLogic, ['setFeatureFlags']],
}),
actions({
@@ -685,6 +721,8 @@ export const autoresearchPipelineLogic = kea<autoresearchPipelineLogicType>([
startScorePolling: true,
pollScoreRun: true,
scoreRunFinished: (run: AutoresearchRunApi) => ({ run }),
+ saveSegmentCohort: (segment: PredictionSegmentKey) => ({ segment }),
+ saveSegmentCohortFinished: true,
}),
reducers({
detailRequested: [
@@ -733,6 +771,20 @@ export const autoresearchPipelineLogic = kea<autoresearchPipelineLogicType>([
setSuggestionPriority: (_, { priority }) => priority,
},
],
+ savingCohortSegment: [
+ null as PredictionSegmentKey | null,
+ {
+ saveSegmentCohort: (_, { segment }) => segment,
+ saveSegmentCohortFinished: () => null,
+ },
+ ],
+ predictionSegmentsError: [
+ false,
+ {
+ loadPredictionSegments: () => false,
+ loadPredictionSegmentsFailure: () => true,
+ },
+ ],
probabilityDistributionError: [
false,
{
@@ -957,6 +1009,7 @@ export const autoresearchPipelineLogic = kea<autoresearchPipelineLogicType>([
FROM events
WHERE event = 'autoresearch_prediction'
AND properties.$autoresearch_pipeline_id = ${props.id}
+ AND properties.$autoresearch_model_role != 'shadow'
AND timestamp >= now() - INTERVAL ${LATEST_BATCH_LOOKBACK_DAYS} DAY
AND properties.$autoresearch_prediction_date = (
SELECT max(properties.$autoresearch_prediction_date)
@@ -979,6 +1032,51 @@ export const autoresearchPipelineLogic = kea<autoresearchPipelineLogicType>([
},
},
],
+ predictionSegments: [
+ null as PredictionSegmentCounts | null,
+ {
+ loadPredictionSegments: async () => {
+ // 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,
+ count() AS people,
+ sum(p) AS expected_conversions
+ FROM (
+ SELECT
+ coalesce(nullIf(properties.$autoresearch_person_id, ''), distinct_id) AS person_id,
+ argMax(toFloat(properties.$autoresearch_p_y), timestamp) AS p
+ FROM events
+ WHERE event = 'autoresearch_prediction'
+ AND properties.$autoresearch_pipeline_id = ${props.id}
+ AND properties.$autoresearch_model_role != 'shadow'
+ AND timestamp >= now() - INTERVAL ${LATEST_BATCH_LOOKBACK_DAYS} DAY
+ AND properties.$autoresearch_prediction_date = (
+ SELECT max(properties.$autoresearch_prediction_date)
+ FROM events
+ WHERE event = 'autoresearch_prediction'
+ AND properties.$autoresearch_pipeline_id = ${props.id}
+ AND timestamp >= now() - INTERVAL ${LATEST_BATCH_LOOKBACK_DAYS} DAY
+ )
+ GROUP BY person_id
+ )
+ GROUP BY segment
+ `,
+ { productKey: 'autoresearch', name: 'autoresearch_prediction_segments' }
+ )
+ const rows = new Map<string, any[]>(
+ (response.results ?? []).map((row: any[]) => [String(row[0]), row])
+ )
+ return Object.fromEntries(
+ PREDICTION_SEGMENTS.map(({ key }) => {
+ const row = rows.get(key)
+ return [key, { people: Number(row?.[1] ?? 0), expectedConversions: Number(row?.[2] ?? 0) }]
+ })
+ ) as PredictionSegmentCounts
+ },
+ },
+ ],
dailyVolume: [
null as DailyVolumePoint[] | null,
{
@@ -1141,6 +1239,9 @@ 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) {
+ actions.loadPredictionSegments()
+ }
if (pipeline?.last_scored_at && !values.dailyVolume && !values.dailyVolumeLoading) {
actions.loadDailyVolume()
}
@@ -1231,6 +1332,7 @@ export const autoresearchPipelineLogic = kea<autoresearchPipelineLogicType>([
rows_scored: run.rows_scored,
})
actions.loadProbabilityDistribution()
+ actions.loadPredictionSegments()
actions.loadDailyVolume()
const scored = run.rows_scored ?? 0
lemonToast.success(`Scored ${scored.toLocaleString()} users`)
@@ -1274,6 +1376,41 @@ export const autoresearchPipelineLogic = kea<autoresearchPipelineLogicType>([
setPredictionsPeopleView: ({ view }) => {
posthog.capture('autoresearch model predictions view changed', { pipeline_id: props.id, view })
},
+ saveSegmentCohort: async ({ segment }) => {
+ const { pipeline, currentProjectId } = values
+ const definition = PREDICTION_SEGMENTS.find(({ key }) => key === segment)
+ const outputProperty = pipeline?.output_person_property
+ if (!pipeline || !outputProperty || !currentProjectId || !definition) {
+ 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.`,
+ is_static: false,
+ filters: predictionSegmentCohortFilters(segment, outputProperty),
+ })
+ posthog.capture('autoresearch model cohort saved', {
+ pipeline_id: props.id,
+ segment,
+ cohort_id: cohort.id,
+ people: values.predictionSegments?.[segment].people,
+ })
+ lemonToast.success('Cohort saved', {
+ button: { label: 'View cohort', action: () => router.actions.push(urls.cohort(cohort.id)) },
+ })
+ } catch {
+ posthog.capture('autoresearch model action failed', {
+ action: 'save_cohort',
+ pipeline_id: props.id,
+ segment,
+ })
+ lemonToast.error("Couldn't save the cohort. Try again.")
+ } finally {
+ actions.saveSegmentCohortFinished()
+ }
+ },
})),
actionToUrl(({ values }) => ({
// Reflect the active tab in the URL (?tab=…) so each tab is deep-linkable.
diff --git a/products/autoresearch/frontend/pipeline/PredictionSegmentCards.tsx b/products/autoresearch/frontend/pipeline/PredictionSegmentCards.tsx
new file mode 100644
index 000000000000..230601484111
--- /dev/null
+++ b/products/autoresearch/frontend/pipeline/PredictionSegmentCards.tsx
@@ -0,0 +1,88 @@
+import { useActions, useValues } from 'kea'
+
+import { LemonButton, LemonSkeleton, Tooltip } from '@posthog/lemon-ui'
+
+import { humanFriendlyNumber } from 'lib/utils/numbers'
+
+import { autoresearchPipelineLogic } from '../autoresearchPipelineLogic'
+import { PREDICTION_SEGMENTS, PredictionSegmentDefinition, predictionSegmentPeopleUrl } from '../predictionSegments'
+
+function SegmentCard({ segment }: { segment: PredictionSegmentDefinition }): JSX.Element {
+ const { pipeline, predictionSegments, savingCohortSegment } = useValues(autoresearchPipelineLogic)
+ const { saveSegmentCohort } = useActions(autoresearchPipelineLogic)
+
+ const stats = predictionSegments?.[segment.key]
+ const totalPeople = predictionSegments
+ ? Object.values(predictionSegments).reduce((sum, { people }) => sum + people, 0)
+ : 0
+ const share = stats && totalPeople > 0 ? (100 * stats.people) / totalPeople : 0
+ const outputProperty = pipeline?.output_person_property ?? ''
+
+ return (
+ <div className="flex-1 min-w-60 border rounded p-4 flex flex-col gap-2 bg-surface-primary">
+ <div className="flex items-center gap-2">
+ <span className={`size-2.5 rounded-full shrink-0 ${segment.colorClassName}`} />
+ <span className="font-semibold">{segment.label}</span>
+ <span className="text-xs text-muted">{segment.range}</span>
+ </div>
+ {stats ? (
+ <>
+ <div className="text-2xl font-semibold tabular-nums">
+ {stats.people.toLocaleString()}{' '}
+ <span className="text-sm font-normal text-muted">people ({share.toFixed(1)}%)</span>
+ </div>
+ <Tooltip title="The sum of this segment's predicted probabilities">
+ <span className="text-sm text-secondary">
+ About {humanFriendlyNumber(Math.round(stats.expectedConversions))} expected to convert
+ {pipeline?.horizon_days ? ` within ${pipeline.horizon_days} days` : ''}
+ </span>
+ </Tooltip>
+ </>
+ ) : (
+ <LemonSkeleton className="h-12" />
+ )}
+ <div className="flex flex-wrap gap-2 mt-auto pt-2">
+ <LemonButton
+ type="secondary"
+ size="small"
+ data-attr={`autoresearch-segment-save-cohort-${segment.key}`}
+ loading={savingCohortSegment === segment.key}
+ disabledReason={
+ !stats
+ ? 'Segments are still loading'
+ : savingCohortSegment
+ ? 'A cohort is being saved'
+ : undefined
+ }
+ onClick={() => saveSegmentCohort(segment.key)}
+ >
+ Save as cohort
+ </LemonButton>
+ <LemonButton
+ 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}
+ >
+ View people
+ </LemonButton>
+ </div>
+ </div>
+ )
+}
+
+export function PredictionSegmentCards(): JSX.Element {
+ const { predictionSegmentsError } = 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>
+ }
+ return (
+ <div className="flex flex-wrap gap-4">
+ {PREDICTION_SEGMENTS.map((segment) => (
+ <SegmentCard key={segment.key} segment={segment} />
+ ))}
+ </div>
+ )
+}
diff --git a/products/autoresearch/frontend/pipeline/PredictionsTab.tsx b/products/autoresearch/frontend/pipeline/PredictionsTab.tsx
index 45593d1f69bc..a341fd338ee6 100644
--- a/products/autoresearch/frontend/pipeline/PredictionsTab.tsx
+++ b/products/autoresearch/frontend/pipeline/PredictionsTab.tsx
@@ -9,6 +9,7 @@ import { autoresearchPipelineLogic } from '../autoresearchPipelineLogic'
import { DailyVolumeChart } from '../DailyVolumeChart'
import { ProbabilityHistogram } from '../ProbabilityHistogram'
import { EmptyTab } from './EmptyTab'
+import { PredictionSegmentCards } from './PredictionSegmentCards'
import { ProbabilityUsersTable } from './ProbabilityUsersTable'
import { ScoreNowButton } from './ScoreNowButton'
@@ -92,7 +93,7 @@ export function PredictionsTab(): JSX.Element {
<code>autoresearch_prediction</code> event. These views read straight from those events.
</p>
- <ScoringCoverageBanner />
+ <PredictionSegmentCards />
<LemonCollapse
multiple
@@ -115,6 +116,8 @@ export function PredictionsTab(): JSX.Element {
},
]}
/>
+
+ <ScoringCoverageBanner />
</div>
)
}
diff --git a/products/autoresearch/frontend/predictionSegments.test.ts b/products/autoresearch/frontend/predictionSegments.test.ts
new file mode 100644
index 000000000000..b7031e69d95c
--- /dev/null
+++ b/products/autoresearch/frontend/predictionSegments.test.ts
@@ -0,0 +1,25 @@
+import { PREDICTION_SEGMENTS, predictionSegmentCohortFilters, predictionSegmentFor } from './predictionSegments'
+
+function cohortMatches(filters: ReturnType<typeof predictionSegmentCohortFilters>, probability: number): boolean {
+ return filters.properties.values.every((group) =>
+ 'values' in group
+ ? group.values.every((condition) => {
+ const { operator, value } = condition as { operator: string; value: number }
+ return operator === 'gte' ? probability >= value : probability < value
+ })
+ : false
+ )
+}
+
+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])
+ }
+ )
+})
diff --git a/products/autoresearch/frontend/predictionSegments.ts b/products/autoresearch/frontend/predictionSegments.ts
new file mode 100644
index 000000000000..458595b910a6
--- /dev/null
+++ b/products/autoresearch/frontend/predictionSegments.ts
@@ -0,0 +1,99 @@
+import { combineUrl } from 'kea-router'
+
+import { urls } from 'scenes/urls'
+
+import { defaultDataTableColumns } from '~/queries/nodes/DataTable/utils'
+import { DataTableNode, NodeKind } from '~/queries/schema/schema-general'
+import { escapePropertyAsHogQLIdentifier } from '~/queries/utils'
+import { PersonPropertyFilter, PropertyFilterType, PropertyOperator } from '~/types'
+
+import type { CohortFiltersApi, PersonFilterApi } from 'products/cohorts/frontend/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.
+ */
+export const PREDICTION_SEGMENT_THRESHOLDS = { high: 0.6, low: 0.2 } as const
+
+export type PredictionSegmentKey = 'likely' | 'possible' | 'unlikely'
+
+export interface PredictionSegmentDefinition {
+ key: PredictionSegmentKey
+ label: string
+ range: string
+ /** Tailwind background class for the segment's card accent and histogram bars. */
+ colorClassName: string
+}
+
+const { high, low } = PREDICTION_SEGMENT_THRESHOLDS
+
+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' },
+]
+
+/** People and expected conversions of one segment in the latest scoring run. */
+export interface PredictionSegmentStats {
+ people: number
+ /** The sum of the segment's probabilities: how many of its people the model expects to convert. */
+ expectedConversions: number
+}
+
+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
+}
+
+type SegmentBound = { operator: PropertyOperator.GreaterThanOrEqual | PropertyOperator.LessThan; value: number }
+
+function segmentBounds(key: PredictionSegmentKey): SegmentBound[] {
+ switch (key) {
+ case 'likely':
+ return [{ operator: PropertyOperator.GreaterThanOrEqual, value: high }]
+ case 'possible':
+ return [
+ { operator: PropertyOperator.GreaterThanOrEqual, value: low },
+ { operator: PropertyOperator.LessThan, value: high },
+ ]
+ case 'unlikely':
+ return [{ operator: PropertyOperator.LessThan, value: low }]
+ }
+}
+
+/** 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 }) => ({
+ type: 'person',
+ key: property,
+ operator,
+ value,
+ }))
+ return { properties: { type: 'OR', values: [{ type: 'AND', values }] } }
+}
+
+/** The persons list, filtered with the same conditions as the segment's cohort. */
+export function predictionSegmentPeopleUrl(key: PredictionSegmentKey, property: string): string {
+ const properties: PersonPropertyFilter[] = segmentBounds(key).map(({ operator, value }) => ({
+ type: PropertyFilterType.Person,
+ key: property,
+ operator,
+ value,
+ }))
+ const query: DataTableNode = {
+ kind: NodeKind.DataTableNode,
+ source: {
+ kind: NodeKind.ActorsQuery,
+ select: [
+ ...defaultDataTableColumns(NodeKind.ActorsQuery),
+ `properties.${escapePropertyAsHogQLIdentifier(property)}`,
+ ],
+ properties,
+ },
+ full: true,
+ propertiesViaUrl: true,
+ }
+ return combineUrl(urls.persons(), {}, { q: query }).url
+}
diff --git a/products/autoresearch/frontend/predictionsPeopleQuery.ts b/products/autoresearch/frontend/predictionsPeopleQuery.ts
index 46a2406ea680..bb59fd8dfad9 100644
--- a/products/autoresearch/frontend/predictionsPeopleQuery.ts
+++ b/products/autoresearch/frontend/predictionsPeopleQuery.ts
@@ -40,6 +40,7 @@ export function predictionsPeopleQuery(view: PredictionsPeopleView): string {
FROM events
WHERE event = 'autoresearch_prediction'
AND properties.$autoresearch_pipeline_id = {pipeline_id}
+ AND properties.$autoresearch_model_role != 'shadow'
AND timestamp >= now() - INTERVAL ${LATEST_BATCH_LOOKBACK_DAYS} DAY
),
top AS (