:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
feat(autoresearch): bound the predictions people query and add views (#113104)
posthog[bot]d243a60e7923
diff --git a/products/autoresearch/frontend/autoresearchPipelineLogic.ts b/products/autoresearch/frontend/autoresearchPipelineLogic.tsindex 19a50f0327ff..92197ff6fcb1 100644--- a/products/autoresearch/frontend/autoresearchPipelineLogic.ts+++ b/products/autoresearch/frontend/autoresearchPipelineLogic.ts@@ -38,6 +38,7 @@ import {type AutoresearchTrainingRunApi,CreateSuggestionPriorityEnumApi,} from './generated/api.schemas'+import type { PredictionsPeopleView } from './predictionsPeopleQuery'export interface AutoresearchPipelineLogicProps {id: string@@ -244,6 +245,7 @@ export interface autoresearchPipelineLogicValues {pipeline: AutoresearchPipelineApi | nullpipelineError: booleanpipelineLoading: boolean+ predictionsPeopleView: PredictionsPeopleViewprobabilityDistribution: ProbabilityBucket[] | nullprobabilityDistributionError: booleanprobabilityDistributionLoading: boolean@@ -528,6 +530,9 @@ export interface autoresearchPipelineLogicActions {setActiveTab: (tab: AutoresearchPipelineTab) => {tab: AutoresearchPipelineTab}+ setPredictionsPeopleView: (view: PredictionsPeopleView) => {+ view: PredictionsPeopleView+ }setSuggestionDraft: (draft: string) => {draft: string}@@ -638,6 +643,7 @@ export const autoresearchPipelineLogic = kea<autoresearchPipelineLogicType>([}),actions({setActiveTab: (tab: AutoresearchPipelineTab) => ({ tab }),+ setPredictionsPeopleView: (view: PredictionsPeopleView) => ({ view }),loadDetail: true,toggleRunArtifacts: (runId: string) => ({ runId }),reportNotebookOpened: (runId: string) => ({ runId }),@@ -661,6 +667,12 @@ export const autoresearchPipelineLogic = kea<autoresearchPipelineLogicType>([setActiveTab: (_, { tab }) => tab,},],+ predictionsPeopleView: [+ 'most_likely' as PredictionsPeopleView,+ {+ setPredictionsPeopleView: (_, { view }) => view,+ },+ ],activeScoreRun: [null as AutoresearchRunApi | null,{@@ -1208,6 +1220,9 @@ export const autoresearchPipelineLogic = kea<autoresearchPipelineLogicType>([reportNotebookOpened: ({ runId }) => {posthog.capture('autoresearch model report notebook opened', { pipeline_id: props.id, run_id: runId })},+ setPredictionsPeopleView: ({ view }) => {+ posthog.capture('autoresearch model predictions view changed', { pipeline_id: props.id, view })+ },})),actionToUrl(({ values }) => ({// Reflect the active tab in the URL (?tab=…) so each tab is deep-linkable.diff --git a/products/autoresearch/frontend/pipeline/PredictionsTab.tsx b/products/autoresearch/frontend/pipeline/PredictionsTab.tsxindex 0e02d275d5b4..45593d1f69bc 100644--- a/products/autoresearch/frontend/pipeline/PredictionsTab.tsx+++ b/products/autoresearch/frontend/pipeline/PredictionsTab.tsx@@ -96,7 +96,7 @@ export function PredictionsTab(): JSX.Element {<LemonCollapsemultiple- defaultActiveKeys={['distribution', 'highest']}+ defaultActiveKeys={['distribution', 'people']}panels={[{key: 'distribution',@@ -104,14 +104,9 @@ export function PredictionsTab(): JSX.Element {content: <ProbabilityDistributionPanel />,},{- key: 'highest',- header: 'Highest-probability users (latest scoring run)',- content: <ProbabilityUsersTable pipelineId={pipeline.id} direction="DESC" />,- },- {- key: 'lowest',- header: 'Lowest-probability users (latest scoring run)',- content: <ProbabilityUsersTable pipelineId={pipeline.id} direction="ASC" />,+ key: 'people',+ header: 'People (latest scoring run)',+ content: <ProbabilityUsersTable pipelineId={pipeline.id} />,},{key: 'volume',diff --git a/products/autoresearch/frontend/pipeline/ProbabilityUsersTable.tsx b/products/autoresearch/frontend/pipeline/ProbabilityUsersTable.tsxindex 276ecc0b445f..48bbb81ccc6a 100644--- a/products/autoresearch/frontend/pipeline/ProbabilityUsersTable.tsx+++ b/products/autoresearch/frontend/pipeline/ProbabilityUsersTable.tsx@@ -1,11 +1,14 @@-import { Link } from '@posthog/lemon-ui'+import { useActions, useValues } from 'kea'++import { LemonSegmentedButton, Link } from '@posthog/lemon-ui'import { urls } from 'scenes/urls'import { Query } from '~/queries/Query/Query'import { NodeKind } from '~/queries/schema/schema-general'-import { LATEST_BATCH_LOOKBACK_DAYS } from '../autoresearchPipelineLogic'+import { autoresearchPipelineLogic } from '../autoresearchPipelineLogic'+import { PREDICTIONS_PEOPLE_VIEWS, predictionsPeopleQuery } from '../predictionsPeopleQuery'/** Links to the person's page. The value is a (person UUID, display name) tuple; the display name falls back to the UUID. */function PersonCell({ value }: { value: unknown }): JSX.Element {@@ -22,66 +25,55 @@ function PercentCell({ value }: { value: unknown }): JSX.Element {return value == null ? <>—</> : <>{String(value)}%</>}-/** Top/bottom-N users by predicted probability for a pipeline, grouped by person. */-export function ProbabilityUsersTable({- pipelineId,- direction,-}: {- pipelineId: string- direction: 'DESC' | 'ASC'-}): JSX.Element {+function ChangeCell({ value }: { value: unknown }): JSX.Element {+ const change = Number(value)+ if (!change) {+ return <span className="text-muted">No change</span>+ }+ return (+ <span className={change > 0 ? 'text-success' : 'text-danger'}>+ {change > 0 ? '+' : ''}+ {change} pts+ </span>+ )+}++/** The top people of the latest scoring run, in the selected view. */+export function ProbabilityUsersTable({ pipelineId }: { pipelineId: string }): JSX.Element {+ const { predictionsPeopleView } = useValues(autoresearchPipelineLogic)+ const { setPredictionsPeopleView } = useActions(autoresearchPipelineLogic)+return (- <Query- readOnly- context={{- columns: {- person: { title: 'Person', render: PersonCell },- probability: { title: 'Probability', render: PercentCell },- last_scored: { title: 'Last scored' },- },- }}- query={{- kind: NodeKind.DataTableNode,- source: {- kind: NodeKind.HogQLQuery,- query: `- -- Capture can shift the timestamps of one batch apart, so the latest batch is its prediction date.- WITH latest AS (- SELECT max(properties.$autoresearch_prediction_date) AS prediction_date- FROM events- WHERE event = 'autoresearch_prediction'- AND properties.$autoresearch_pipeline_id = {pipeline_id}- AND timestamp >= now() - INTERVAL ${LATEST_BATCH_LOOKBACK_DAYS} DAY- ),- scored AS (- SELECT- coalesce(nullIf(properties.$autoresearch_person_id, ''), distinct_id) AS person_id,- round(100 * argMax(toFloat(properties.$autoresearch_p_y), timestamp), 1) AS probability,- max(timestamp) AS last_scored- FROM events- WHERE event = 'autoresearch_prediction'- AND properties.$autoresearch_pipeline_id = {pipeline_id}- AND timestamp >= now() - INTERVAL ${LATEST_BATCH_LOOKBACK_DAYS} DAY- AND properties.$autoresearch_prediction_date = (SELECT prediction_date FROM latest)- GROUP BY person_id- )- -- LEFT JOIN persons directly on the person UUID: the implicit person join goes via- -- distinct_id, which drops scored people whose prediction events aren't person-mapped.- SELECT- tuple(s.person_id, coalesce(- nullIf(toString(p.properties.email), ''),- nullIf(toString(p.properties.name), '')- )) AS person,- s.probability AS probability,- s.last_scored AS last_scored- FROM scored s- LEFT JOIN persons p ON toString(p.id) = s.person_id- ORDER BY probability ${direction}- LIMIT 50- `,- values: { pipeline_id: pipelineId },- },- }}- />+ <div className="space-y-2">+ <LemonSegmentedButton+ size="small"+ value={predictionsPeopleView}+ onChange={setPredictionsPeopleView}+ options={PREDICTIONS_PEOPLE_VIEWS.map(({ value, label }) => ({+ value,+ label,+ 'data-attr': `autoresearch-predictions-view-${value}`,+ }))}+ />+ <Query+ readOnly+ context={{+ columns: {+ person: { title: 'Person', render: PersonCell },+ probability: { title: 'Probability', render: PercentCell },+ change: { title: 'Change since last score', render: ChangeCell },+ last_scored: { title: 'Last scored' },+ },+ }}+ query={{+ kind: NodeKind.DataTableNode,+ source: {+ kind: NodeKind.HogQLQuery,+ query: predictionsPeopleQuery(predictionsPeopleView),+ values: { pipeline_id: pipelineId },+ },+ }}+ />+ </div>)}diff --git a/products/autoresearch/frontend/predictionsPeopleQuery.test.ts b/products/autoresearch/frontend/predictionsPeopleQuery.test.tsnew file mode 100644index 000000000000..60e6618f0f31--- /dev/null+++ b/products/autoresearch/frontend/predictionsPeopleQuery.test.ts@@ -0,0 +1,15 @@+import { PREDICTIONS_PEOPLE_LIMIT, PREDICTIONS_PEOPLE_VIEWS, predictionsPeopleQuery } from './predictionsPeopleQuery'++describe('predictionsPeopleQuery', () => {+ test.each(PREDICTIONS_PEOPLE_VIEWS.map(({ value }) => value))(+ '%s reads display names only for the top people, never joining persons over the batch',+ (view) => {+ const query = predictionsPeopleQuery(view).replace(/\s+/g, ' ')++ expect(query).not.toMatch(/JOIN persons\b/i)+ expect(query).toContain(`LIMIT ${PREDICTIONS_PEOPLE_LIMIT} ), names AS`)+ expect(query).toContain('FROM raw_persons WHERE id IN (SELECT toUUID(person_id) FROM top)')+ expect(query).toContain('FROM top t LEFT JOIN names n')+ }+ )+})diff --git a/products/autoresearch/frontend/predictionsPeopleQuery.ts b/products/autoresearch/frontend/predictionsPeopleQuery.tsnew file mode 100644index 000000000000..46a2406ea680--- /dev/null+++ b/products/autoresearch/frontend/predictionsPeopleQuery.ts@@ -0,0 +1,81 @@+import { LATEST_BATCH_LOOKBACK_DAYS } from './autoresearchPipelineLogic'++export type PredictionsPeopleView = 'most_likely' | 'biggest_movers' | 'least_likely'++export const PREDICTIONS_PEOPLE_VIEWS: { value: PredictionsPeopleView; label: string }[] = [+ { value: 'most_likely', label: 'Most likely' },+ { value: 'biggest_movers', label: 'Biggest movers' },+ { value: 'least_likely', label: 'Least likely' },+]++export const PREDICTIONS_PEOPLE_LIMIT = 50++const ORDER_BY: Record<PredictionsPeopleView, string> = {+ most_likely: 'p_latest DESC',+ biggest_movers: 'abs(change) DESC, p_latest DESC',+ least_likely: 'p_latest ASC',+}++/**+ * HogQL for the top people of the latest prediction batch, with the `{pipeline_id}` placeholder.+ * The query picks the top person ids first and reads display names for only those ids,+ * so the persons read never grows with the batch size.+ */+export function predictionsPeopleQuery(view: PredictionsPeopleView): string {+ return `+ -- Capture can shift the timestamps of one batch apart, so the latest batch is its prediction date.+ WITH latest AS (+ SELECT max(properties.$autoresearch_prediction_date) AS prediction_date+ FROM events+ WHERE event = 'autoresearch_prediction'+ AND properties.$autoresearch_pipeline_id = {pipeline_id}+ AND timestamp >= now() - INTERVAL ${LATEST_BATCH_LOOKBACK_DAYS} DAY+ ),+ scored AS (+ SELECT+ coalesce(nullIf(properties.$autoresearch_person_id, ''), distinct_id) AS person_id,+ properties.$autoresearch_prediction_date = (SELECT prediction_date FROM latest) AS in_latest,+ toFloat(properties.$autoresearch_p_y) AS p,+ timestamp+ FROM events+ WHERE event = 'autoresearch_prediction'+ AND properties.$autoresearch_pipeline_id = {pipeline_id}+ AND timestamp >= now() - INTERVAL ${LATEST_BATCH_LOOKBACK_DAYS} DAY+ ),+ top AS (+ SELECT+ person_id,+ argMaxIf(p, timestamp, in_latest) AS p_latest,+ -- A person with one score has no previous score, so their change is 0.+ if(countIf(not in_latest) > 0, p_latest - argMaxIf(p, timestamp, not in_latest), 0) AS change,+ maxIf(timestamp, in_latest) AS last_scored+ FROM scored+ GROUP BY person_id+ HAVING countIf(in_latest) > 0+ ORDER BY ${ORDER_BY[view]}+ LIMIT ${PREDICTIONS_PEOPLE_LIMIT}+ ),+ names AS (+ SELECT+ toString(id) AS person_id,+ argMax(coalesce(+ nullIf(toString(properties.email), ''),+ nullIf(toString(properties.name), '')+ ), version) AS display_name+ FROM raw_persons+ WHERE id IN (SELECT toUUID(person_id) FROM top)+ GROUP BY id+ HAVING argMax(is_deleted, version) = 0+ )+ -- Join on the person UUID: the implicit person join goes via distinct_id,+ -- which drops scored people whose prediction events are not person-mapped.+ SELECT+ tuple(t.person_id, n.display_name) AS person,+ round(100 * t.p_latest, 1) AS probability,+ round(100 * t.change, 1) AS change,+ t.last_scored AS last_scored+ FROM top t+ LEFT JOIN names n ON n.person_id = t.person_id+ ORDER BY ${ORDER_BY[view]}+ `+}