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): add a ready-to-train checklist and start training (#113149)

posthog[bot]01dc17c8fbaa
diff --git a/products/autoresearch/frontend/AGENTS.md b/products/autoresearch/frontend/AGENTS.md
index a9beac03c9d3..a84cb0a109ed 100644
--- a/products/autoresearch/frontend/AGENTS.md
+++ b/products/autoresearch/frontend/AGENTS.md
@@ -14,8 +14,8 @@ The product is mostly a backend, and the UI is deliberately thin — it reads st
| `AutoresearchNewScene.tsx` | `/autoresearch/new` — the create form. Its parts live in `newModel/`. |
| `AutoresearchPipelineScene.tsx` | `/autoresearch/:id` — the detail shell: title bar actions and the tab strip. Each tab lives in `pipeline/`. |
| `autoresearchLogic.ts` | List logic — loads pipelines, lifecycle actions, and setup-status detection for the empty-state gate. |
-| `autoresearchNewLogic.ts` | Create form — a `kea-forms` form that validates the target, then calls the generated `autoresearchCreate`. |
-| `newModel/` | Create-form parts: template chips, the definition sentence (population, target, horizon), and the collapsed Advanced section. |
+| `autoresearchNewLogic.ts` | Create form: a `kea-forms` form that validates the definition, then creates the model and optionally starts training. |
+| `newModel/` | Create-form parts: template chips, definition sentence, Advanced section, readiness checklist, "What happens next". |
| `autoresearchPipelineLogic.ts` | Detail logic. |
| `PipelineStatusTag.tsx` | Status tag + tooltip shared by the list and detail scenes. |
| `ProbabilityHistogram.tsx` | Decile histogram of the latest scoring run's probabilities. |
@@ -47,7 +47,7 @@ Follow `frontend/src/AGENTS.md` — it applies to product frontends too.
- TypeScript with explicit return types; Tailwind utilities rather than inline styles.
- Reuse Lemon / quill components instead of hand-rolling tables, badges, or tags.
- Any button that fires a request must guard against double-submission — `loading` / `disabledReason` on `LemonButton`, reset on both success and error paths. The lifecycle actions here (train, score, archive, pause, resume) are all network calls, and several are expensive: firing `train` twice starts two sandbox agent runs and spends the budget twice.
-- Usage events are part of the API: renaming one breaks every insight built on it. The list logic captures `autoresearch model list viewed`, `autoresearch model list load failed`, `autoresearch model deleted` / `paused` / `resumed`, `autoresearch model training started` (with `source: 'list'` from a card), `autoresearch model card clicked`, and `autoresearch model action failed` (with `action`). The create logic captures `autoresearch model template selected` (with `template_key`), `autoresearch model custom chosen`, and `autoresearch model advanced opened`. Buttons carry a `data-attr` for autocapture. Extend the same names when you add a scene.
+- Usage events are part of the API: renaming one breaks every insight built on it. The list logic captures `autoresearch model list viewed`, `autoresearch model list load failed`, `autoresearch model deleted` / `paused` / `resumed`, `autoresearch model training started` (with `source: 'list'` from a card), `autoresearch model card clicked`, and `autoresearch model action failed` (with `action`). The create logic captures `autoresearch model template selected` (with `template_key`), `autoresearch model custom chosen`, `autoresearch model advanced opened`, `autoresearch model created` (with `action`: `start_training` or `save_draft`), and `autoresearch model training started` / `training start failed`. Buttons carry a `data-attr` for autocapture. Extend the same names when you add a scene.
## Copy
diff --git a/products/autoresearch/frontend/AutoresearchNewScene.tsx b/products/autoresearch/frontend/AutoresearchNewScene.tsx
index c7d10f93b6de..83f75184ffc8 100644
--- a/products/autoresearch/frontend/AutoresearchNewScene.tsx
+++ b/products/autoresearch/frontend/AutoresearchNewScene.tsx
@@ -2,8 +2,8 @@ import { useActions, useValues } from 'kea'
import { Form } from 'kea-forms'
import { router } from 'kea-router'
-import { IconArrowLeft, IconInfo } from '@posthog/icons'
-import { LemonBanner, LemonButton, LemonInput, LemonSkeleton, Spinner, Tooltip } from '@posthog/lemon-ui'
+import { IconArrowLeft } from '@posthog/icons'
+import { LemonButton, LemonInput } from '@posthog/lemon-ui'
import { NotFound } from 'lib/components/NotFound'
import { useFeatureFlag } from 'lib/hooks/useFeatureFlag'
@@ -14,160 +14,28 @@ import { urls } from 'scenes/urls'
import { SceneContent } from '~/layout/scenes/components/SceneContent'
import { SceneTitleSection } from '~/layout/scenes/components/SceneTitleSection'
-import { autoresearchNewLogic, hasTarget } from './autoresearchNewLogic'
+import { autoresearchNewLogic } from './autoresearchNewLogic'
import { AdvancedSettings } from './newModel/AdvancedSettings'
import { DefinitionSentence } from './newModel/DefinitionSentence'
+import { ReadinessChecklist } from './newModel/ReadinessChecklist'
import { TemplateChips } from './newModel/TemplateChips'
+import { WhatHappensNext } from './newModel/WhatHappensNext'
export const scene: SceneExport = {
component: AutoresearchNewScene,
logic: autoresearchNewLogic,
}
-function formatPercent(value: number | null | undefined): string {
- if (value === null || value === undefined) {
- return '—'
- }
- return `${(value * 100).toFixed(2)}%`
-}
-
-function formatNumber(value: number | null | undefined): string {
- if (value === null || value === undefined) {
- return '—'
- }
- return value.toLocaleString()
-}
-
-function ValidationPanel(): JSX.Element {
- const { validation, validationLoading, validationFailed, newPipeline, newPipelineValidationErrors } =
- useValues(autoresearchNewLogic)
- const { runValidate } = useActions(autoresearchNewLogic)
- // The form hides field errors until the first submit, and the validate loader skips invalid day values.
- // So this panel is the only place that says why no estimate appears.
- const dayError = newPipelineValidationErrors.training_lookback_days ?? newPipelineValidationErrors.horizon_days
-
- if (validationFailed && !validationLoading) {
- return (
- <LemonBanner
- type="error"
- action={{
- children: 'Retry',
- onClick: () => runValidate(null),
- 'data-attr': 'autoresearch-new-validate-retry',
- }}
- >
- Couldn't check this model definition. Retry, or change a field to check again.
- </LemonBanner>
- )
- }
-
- if (dayError) {
- return (
- <div className="border rounded p-4 bg-bg-light text-muted text-sm">
- {dayError}. Fix it to see live training estimates.
- </div>
- )
- }
-
- if (!validation && !validationLoading && !hasTarget(newPipeline)) {
- return (
- <div className="border rounded p-4 bg-bg-light text-muted text-sm">
- Pick a target event to see live training estimates.
- </div>
- )
- }
-
- return (
- <div className="border rounded p-4 flex flex-col gap-3">
- <div className="flex items-center justify-between">
- <h3 className="text-base font-semibold mb-0">Live estimate</h3>
- {validationLoading && <Spinner className="text-sm" />}
- </div>
-
- {validation ? (
- <>
- <div className="grid grid-cols-2 gap-2 text-sm">
- <div>
- <div className="text-muted">Training rows</div>
- <div className="font-mono">{formatNumber(validation.estimated_training_rows)}</div>
- </div>
- <div>
- <div className="text-muted">Prediction users</div>
- <div className="font-mono">{formatNumber(validation.inference_population_size)}</div>
- </div>
- <div>
- <div className="text-muted">Positives</div>
- <div className="font-mono">{formatNumber(validation.positive_count)}</div>
- </div>
- <div>
- <div className="text-muted">Negatives</div>
- <div className="font-mono">{formatNumber(validation.negative_count)}</div>
- </div>
- <div className="col-span-2">
- <div className="text-muted flex items-center gap-1">
- Base rate
- <Tooltip
- title={
- <span>
- For each user in the training population we pick a random reference point in
- their history and check whether the target event fired in the following
- "Prediction horizon" days. Base rate is the fraction labeled positive: the
- conversion rate the model is trained to predict.
- <br />
- <br />
- Computed from a sample of up to 5,000 users for speed; the sampled rate is
- an unbiased estimate of what the trainer sees unsampled.
- </span>
- }
- >
- <IconInfo className="text-sm cursor-help" />
- </Tooltip>
- </div>
- <div className="font-mono">{formatPercent(validation.base_rate)}</div>
- </div>
- </div>
-
- {validation.warnings.length > 0 && (
- <div className="flex flex-col gap-2 mt-2">
- {validation.warnings.map((w, i) => (
- <LemonBanner
- key={`${w.code}-${i}`}
- type={
- w.severity === 'error' ? 'error' : w.severity === 'warning' ? 'warning' : 'info'
- }
- >
- {w.message}
- </LemonBanner>
- ))}
- </div>
- )}
-
- {validation.error && (
- <LemonBanner type="error">Validation failed to run: {validation.error}</LemonBanner>
- )}
- </>
- ) : (
- <>
- <LemonSkeleton className="h-4 w-full" />
- <LemonSkeleton className="h-4 w-3/4" />
- <LemonSkeleton className="h-4 w-1/2" />
- </>
- )}
- </div>
- )
-}
-
export function AutoresearchNewScene(): JSX.Element {
const isEnabled = useFeatureFlag('AUTORESEARCH')
- const { validation, isNewPipelineSubmitting, resolvedTemplateLoading } = useValues(autoresearchNewLogic)
- const { submitNewPipeline } = useActions(autoresearchNewLogic)
+ const { isNewPipelineSubmitting, submitIntent, startTrainingDisabledReason, saveDraftDisabledReason } =
+ useValues(autoresearchNewLogic)
+ const { submitWithIntent } = useActions(autoresearchNewLogic)
if (!isEnabled) {
return <NotFound object="Autoresearch" caption="This feature is not enabled for your project." />
}
- const blockingError = validation?.warnings.some((w) => w.severity === 'error') ?? false
-
return (
<SceneContent>
<div className="mb-2">
@@ -205,25 +73,31 @@ export function AutoresearchNewScene(): JSX.Element {
>
Cancel
</LemonButton>
+ <LemonButton
+ type="secondary"
+ loading={isNewPipelineSubmitting && submitIntent === 'draft'}
+ disabledReason={saveDraftDisabledReason}
+ onClick={() => submitWithIntent('draft')}
+ data-attr="autoresearch-new-save-draft"
+ >
+ Save as draft
+ </LemonButton>
<LemonButton
type="primary"
- loading={isNewPipelineSubmitting}
- disabledReason={
- blockingError
- ? 'Resolve blocking warnings before creating'
- : resolvedTemplateLoading
- ? 'Wait for the template to load'
- : undefined
- }
- onClick={() => submitNewPipeline()}
- data-attr="autoresearch-new-create"
+ loading={isNewPipelineSubmitting && submitIntent === 'train'}
+ disabledReason={startTrainingDisabledReason}
+ onClick={() => submitWithIntent('train')}
+ data-attr="autoresearch-new-start-training"
>
- Create model
+ Start training
</LemonButton>
</div>
</Form>
- <ValidationPanel />
+ <div className="flex flex-col gap-4">
+ <ReadinessChecklist />
+ <WhatHappensNext />
+ </div>
</div>
</SceneContent>
)
diff --git a/products/autoresearch/frontend/autoresearchNewLogic.test.ts b/products/autoresearch/frontend/autoresearchNewLogic.test.ts
index 39f8db212325..a632db26047e 100644
--- a/products/autoresearch/frontend/autoresearchNewLogic.test.ts
+++ b/products/autoresearch/frontend/autoresearchNewLogic.test.ts
@@ -1,5 +1,10 @@
+import { router } from 'kea-router'
import { expectLogic } from 'kea-test-utils'
+import { ApiError } from 'lib/api-error'
+import { lemonToast } from 'lib/lemon-ui/LemonToast/LemonToast'
+import { urls } from 'scenes/urls'
+
import { initKeaTests } from '~/test/init'
import { PersonPropertyFilter, PropertyFilterType, PropertyOperator } from '~/types'
@@ -8,11 +13,13 @@ import {
autoresearchCreate,
autoresearchResolveTemplateCreate,
autoresearchTemplatesList,
+ autoresearchTrainCreate,
autoresearchValidateCreate,
} from './generated/api'
jest.mock('./generated/api', () => ({
autoresearchCreate: jest.fn(),
+ autoresearchTrainCreate: jest.fn(),
autoresearchValidateCreate: jest.fn(),
autoresearchTemplatesList: jest.fn(),
autoresearchResolveTemplateCreate: jest.fn(),
@@ -22,6 +29,25 @@ const mockCreate = autoresearchCreate as jest.Mock
const mockValidate = autoresearchValidateCreate as jest.Mock
const mockTemplates = autoresearchTemplatesList as jest.Mock
const mockResolve = autoresearchResolveTemplateCreate as jest.Mock
+const mockTrain = autoresearchTrainCreate as jest.Mock
+
+function validation(
+ warnings: { code: string; severity: string }[],
+ overrides: Record<string, unknown> = {}
+): Record<string, unknown> {
+ return {
+ can_proceed: !warnings.some((w) => w.severity === 'error'),
+ requires_acknowledgement: false,
+ estimated_training_rows: 1000,
+ positive_count: 100,
+ negative_count: 900,
+ base_rate: 0.1,
+ inference_population_size: 2000,
+ warnings: warnings.map((w) => ({ ...w, message: w.code })),
+ error: null,
+ ...overrides,
+ }
+}
const TEMPLATES = [
{
@@ -241,4 +267,142 @@ describe('autoresearchNewLogic', () => {
await settle(logic)
expect(mockCreate).toHaveBeenCalledTimes(1)
})
+
+ it.each([
+ ['no warnings', [], {}, 'ready', ['pass', 'pass', 'pass', 'pass'], false],
+ [
+ 'a non-blocking warning',
+ [{ code: 'extreme_imbalance', severity: 'warning' }],
+ {},
+ 'warnings',
+ ['pass', 'warning', 'pass', 'pass'],
+ false,
+ ],
+ [
+ 'a blocking data warning',
+ [{ code: 'low_negatives', severity: 'error' }],
+ {},
+ 'blocked',
+ ['pass', 'pass', 'fail', 'pass'],
+ true,
+ ],
+ [
+ 'a horizon longer than the lookback, which skips the data queries',
+ [{ code: 'horizon_exceeds_lookback', severity: 'error' }],
+ {
+ estimated_training_rows: 0,
+ positive_count: 0,
+ negative_count: 0,
+ base_rate: 0,
+ inference_population_size: null,
+ },
+ 'blocked',
+ ['skipped', 'skipped', 'skipped', 'fail'],
+ true,
+ ],
+ ])(
+ 'builds the readiness checklist from a response with %s',
+ async (_, warnings, overrides, readiness, statuses, startTrainingDisabled) => {
+ mockValidate.mockResolvedValue(validation(warnings, overrides))
+ const logic = autoresearchNewLogic()
+ logic.mount()
+
+ logic.actions.setNewPipelineValues({ target_event: '$pageview' })
+ await settle(logic)
+
+ expect(logic.values.readiness).toBe(readiness)
+ expect(logic.values.readinessChecks.map((check) => check.status)).toEqual(statuses)
+ expect(!!logic.values.startTrainingDisabledReason).toBe(startTrainingDisabled)
+ expect(logic.values.saveDraftDisabledReason).toBeUndefined()
+ }
+ )
+
+ it.each([
+ ['train', 'blocked', 0, 0],
+ ['draft', 'blocked', 1, 0],
+ ['train', 'ready', 1, 1],
+ ['draft', 'ready', 1, 0],
+ ] as const)(
+ 'with the %s action on a %s definition, creates %d model and starts %d run',
+ async (intent, readiness, expectedCreates, expectedTrains) => {
+ mockValidate.mockResolvedValue(
+ validation(readiness === 'blocked' ? [{ code: 'low_volume', severity: 'error' }] : [])
+ )
+ mockCreate.mockResolvedValue({ id: 'pipeline-1', name: 'Sharing' })
+ mockTrain.mockResolvedValue({ id: 'run-1', status: 'running' })
+ const logic = autoresearchNewLogic()
+ logic.mount()
+
+ logic.actions.setNewPipelineValues({ name: 'Sharing', target_event: 'file_shared' })
+ await settle(logic)
+ logic.actions.submitWithIntent(intent)
+ await settle(logic)
+
+ expect(mockCreate).toHaveBeenCalledTimes(expectedCreates)
+ expect(mockTrain.mock.calls.map((call) => call[1])).toEqual(expectedTrains ? ['pipeline-1'] : [])
+ expect(router.values.location.pathname.endsWith(urls.autoresearchPipeline('pipeline-1'))).toBe(
+ expectedCreates === 1
+ )
+ }
+ )
+
+ it.each([
+ ['creates the model', 0],
+ ['starts training', 1],
+ ])(
+ 'neither trains nor navigates late when the person leaves while the form %s',
+ async (pendingStep, expectedTrains) => {
+ let finishPendingStep: () => void = () => {}
+ const pending = new Promise<void>((resolve) => {
+ finishPendingStep = resolve
+ })
+ const created = { id: 'pipeline-1', name: 'Sharing' }
+ if (pendingStep === 'creates the model') {
+ mockCreate.mockReturnValue(pending.then(() => created))
+ } else {
+ mockCreate.mockResolvedValue(created)
+ }
+ mockTrain.mockReturnValue(pending.then(() => ({ id: 'run-1', status: 'running' })))
+ const logic = autoresearchNewLogic()
+ logic.mount()
+
+ logic.actions.setNewPipelineValues({ name: 'Sharing', target_event: 'file_shared' })
+ await settle(logic)
+ logic.actions.submitWithIntent('train')
+ await jest.advanceTimersByTimeAsync(0)
+ logic.unmount()
+ finishPendingStep()
+ await jest.advanceTimersByTimeAsync(0)
+
+ expect(mockTrain).toHaveBeenCalledTimes(expectedTrains)
+ expect(router.values.location.pathname).not.toContain(urls.autoresearchPipeline('pipeline-1'))
+ }
+ )
+
+ it.each([
+ ['a validation error', { detail: 'A training run is already running' }, 'A training run is already running'],
+ [
+ 'a usage limit',
+ new ApiError("You've reached your usage limit.", 429, undefined, {
+ code: 'usage_limit_exceeded',
+ error: "You've reached your usage limit.",
+ }),
+ "You've reached your usage limit.",
+ ],
+ ])('opens the created model and shows the reason when training fails with %s', async (_, error, reason) => {
+ const toastError = jest.spyOn(lemonToast, 'error').mockReturnValue('' as any)
+ mockCreate.mockResolvedValue({ id: 'pipeline-1', name: 'Sharing' })
+ mockTrain.mockRejectedValue(error)
+ const logic = autoresearchNewLogic()
+ logic.mount()
+
+ logic.actions.setNewPipelineValues({ name: 'Sharing', target_event: 'file_shared' })
+ await settle(logic)
+ logic.actions.submitWithIntent('train')
+ await settle(logic)
+
+ expect(mockTrain).toHaveBeenCalledTimes(1)
+ expect(toastError).toHaveBeenCalledWith(expect.stringContaining(reason))
+ expect(router.values.location.pathname).toContain(urls.autoresearchPipeline('pipeline-1'))
+ })
})
diff --git a/products/autoresearch/frontend/autoresearchNewLogic.ts b/products/autoresearch/frontend/autoresearchNewLogic.ts
index 90153969ee5d..582ea745eac9 100644
--- a/products/autoresearch/frontend/autoresearchNewLogic.ts
+++ b/products/autoresearch/frontend/autoresearchNewLogic.ts
@@ -30,15 +30,18 @@ import {
autoresearchCreate,
autoresearchResolveTemplateCreate,
autoresearchTemplatesList,
+ autoresearchTrainCreate,
autoresearchValidateCreate,
} from './generated/api'
import {
+ AutoresearchPipelineApi,
AutoresearchPipelineCreateApi,
ResolvedTemplateApi,
TemplateInfoApi,
TemplateKeyEnumApi,
ValidatePipelineRequestApi,
ValidatePipelineResponseApi,
+ ValidationWarningApi,
} from './generated/api.schemas'
type TargetType = 'event' | 'action'
@@ -86,6 +89,27 @@ const DEFAULTS: NewPipelineFormValues = {
export const HORIZON_PRESETS = [7, 14, 30, 90]
+/** Start training creates the model and runs it. Save as draft only creates it. */
+export type SubmitIntent = 'train' | 'draft'
+
+export type Readiness = 'ready' | 'warnings' | 'blocked'
+
+export type ReadinessCheckStatus = 'pass' | 'warning' | 'fail' | 'skipped'
+
+export interface ReadinessCheck {
+ key: 'population' | 'positives' | 'negatives' | 'other'
+ label: string
+ value: string
+ status: ReadinessCheckStatus
+ warnings: ValidationWarningApi[]
+}
+
+const CHECK_WARNING_CODES: Record<Exclude<ReadinessCheck['key'], 'other'>, string[]> = {
+ population: ['low_volume', 'moderate_volume', 'mostly_anonymous_population', 'population_too_large'],
+ positives: ['low_positives', 'extreme_imbalance'],
+ negatives: ['low_negatives', 'near_universal'],
+}
+
const VALIDATE_DEBOUNCE_MS = 500
const RESOLVE_DEBOUNCE_MS = 300
@@ -157,6 +181,67 @@ export function populationSummary(kind: PopulationKind | null, filters: AnyPrope
return `${base} matching ${filters.length} ${filters.length === 1 ? 'filter' : 'filters'}`
}
+function formatCount(value: number | null | undefined): string {
+ return value === null || value === undefined ? 'Unknown' : value.toLocaleString()
+}
+
+function checkStatus(warnings: ValidationWarningApi[]): ReadinessCheckStatus {
+ if (warnings.some((w) => w.severity === 'error')) {
+ return 'fail'
+ }
+ return warnings.some((w) => w.severity === 'warning') ? 'warning' : 'pass'
+}
+
+function readinessChecks(validation: ValidatePipelineResponseApi): ReadinessCheck[] {
+ const forCodes = (codes: string[]): ValidationWarningApi[] =>
+ validation.warnings.filter((w) => codes.includes(w.code))
+ const grouped = Object.values(CHECK_WARNING_CODES).flat()
+ const population = forCodes(CHECK_WARNING_CODES.population)
+ const positives = forCodes(CHECK_WARNING_CODES.positives)
+ const negatives = forCodes(CHECK_WARNING_CODES.negatives)
+ const other = validation.warnings.filter((w) => !grouped.includes(w.code))
+ const baseRate = validation.base_rate === null ? '' : ` (${(validation.base_rate * 100).toFixed(1)}% base rate)`
+ const checks: ReadinessCheck[] = [
+ {
+ key: 'population',
+ label: 'Population size',
+ value: `${formatCount(validation.estimated_training_rows)} to train on, ${formatCount(
+ validation.inference_population_size
+ )} to score`,
+ status: checkStatus(population),
+ warnings: population,
+ },
+ {
+ key: 'positives',
+ label: 'People who did it',
+ value: `${formatCount(validation.positive_count)}${baseRate}`,
+ status: checkStatus(positives),
+ warnings: positives,
+ },
+ {
+ key: 'negatives',
+ label: "People who didn't",
+ value: formatCount(validation.negative_count),
+ status: checkStatus(negatives),
+ warnings: negatives,
+ },
+ {
+ key: 'other',
+ label: 'Other warnings',
+ value: other.length === 0 ? 'None' : String(other.length),
+ status: checkStatus(other),
+ warnings: other,
+ },
+ ]
+ // The backend refuses this definition before it runs the data queries, so its counts are placeholders.
+ if (!validation.warnings.some((w) => w.code === 'horizon_exceeds_lookback')) {
+ return checks
+ }
+ return checks.map((check) =>
+ check.key === 'other' ? check : { ...check, value: 'Not checked', status: 'skipped' }
+ )
+}
+
/** The form values a resolve-template response sets. Fields the user edited keep their value. */
function valuesFromResolvedTemplate(
resolved: ResolvedTemplateApi,
@@ -198,10 +283,15 @@ export interface autoresearchNewLogicValues {
newPipelineTouched: boolean
newPipelineTouches: Record<string, boolean>
newPipelineValidationErrors: DeepPartialMap<NewPipelineFormValues, ValidationErrorType>
+ readiness: Readiness | null
+ readinessChecks: ReadinessCheck[]
resolvedTemplate: ResolvedTemplateApi | null
resolvedTemplateLoading: boolean
resolvedTemplateStale: boolean
+ saveDraftDisabledReason: string | undefined
showNewPipelineErrors: boolean
+ startTrainingDisabledReason: string | undefined
+ submitIntent: SubmitIntent
templates: TemplateInfoApi[]
templatesLoading: boolean
validation: ValidatePipelineResponseApi | null
@@ -297,6 +387,9 @@ export interface autoresearchNewLogicActions {
submitNewPipelineSuccess: (newPipeline: NewPipelineFormValues) => {
newPipeline: NewPipelineFormValues
}
+ submitWithIntent: (intent: SubmitIntent) => {
+ intent: SubmitIntent
+ }
touchNewPipelineField: (key: string) => {
key: string
}
@@ -309,6 +402,21 @@ export interface autoresearchNewLogicMeta {
newPipeline: NewPipelineFormValues,
resolvedTemplate: ResolvedTemplateApi | null
) => boolean
+ readiness: (validation: ValidatePipelineResponseApi | null) => Readiness | null
+ readinessChecks: (validation: ValidatePipelineResponseApi | null) => ReadinessCheck[]
+ startTrainingDisabledReason: (
+ resolvedTemplateLoading: boolean,
+ isNewPipelineSubmitting: boolean,
+ submitIntent: SubmitIntent,
+ validationFailed: boolean,
+ validationLoading: boolean,
+ validation: ValidatePipelineResponseApi | null
+ ) => string | undefined
+ saveDraftDisabledReason: (
+ resolvedTemplateLoading: boolean,
+ isNewPipelineSubmitting: boolean,
+ submitIntent: SubmitIntent
+ ) => string | undefined
}
}
@@ -335,6 +443,7 @@ export const autoresearchNewLogic = kea<autoresearchNewLogicType>([
resolveTemplateSuccess: (resolved: ResolvedTemplateApi) => ({ resolved }),
resolveTemplateFailure: true,
setAdvancedOpen: (open: boolean) => ({ open }),
+ submitWithIntent: (intent: SubmitIntent) => ({ intent }),
}),
loaders(({ values }) => ({
templates: [
@@ -431,6 +540,12 @@ export const autoresearchNewLogic = kea<autoresearchNewLogicType>([
setAdvancedOpen: (_, { open }) => open,
},
],
+ submitIntent: [
+ 'train' as SubmitIntent,
+ {
+ submitWithIntent: (_, { intent }) => intent,
+ },
+ ],
}),
forms(({ actions, values }) => ({
newPipeline: {
@@ -470,7 +585,7 @@ export const autoresearchNewLogic = kea<autoresearchNewLogicType>([
? 'Experiment budget must be a whole number'
: undefined,
}),
- submit: async (payload: NewPipelineFormValues) => {
+ submit: async (payload: NewPipelineFormValues, breakpoint) => {
if (!values.currentTeamId) {
lemonToast.error('Select a project before creating a model')
return
@@ -485,19 +600,23 @@ export const autoresearchNewLogic = kea<autoresearchNewLogicType>([
)
return
}
- if (values.validationFailed) {
- lemonToast.error('Validation failed to run. Retry it, then create.')
- return
- }
- if (values.validationLoading || !values.validation) {
- // The form clears its validation on every change and re-runs it debounced, so a
- // null or in-flight result means these values have never been checked.
- lemonToast.error('Validation is still running. Wait for it to finish, then create.')
- return
- }
- if (!values.validation.can_proceed) {
- lemonToast.error('Validation found blocking errors. Fix them before creating.')
- return
+ const intent = values.submitIntent
+ // A draft does not train, so only Start training needs a passing check.
+ if (intent === 'train') {
+ if (values.validationFailed) {
+ lemonToast.error("Couldn't check this model. Retry the check, then start training.")
+ return
+ }
+ if (values.validationLoading || !values.validation) {
+ // The form clears its validation on every change and re-runs it debounced, so a
+ // null or in-flight result means these values have never been checked.
+ lemonToast.error('The check is still running. Wait for it to finish, then start training.')
+ return
+ }
+ if (!values.validation.can_proceed) {
+ lemonToast.error("This model can't train yet. Fix the failed checks first.")
+ return
+ }
}
const { target_event, target_definition } = targetRequestFields(payload)
const { training_population, inference_population } = populationRequestFields(payload)
@@ -515,21 +634,18 @@ export const autoresearchNewLogic = kea<autoresearchNewLogicType>([
? { output_person_property: payload.output_person_property }
: {}),
}
+ const eventProperties = {
+ target_type: payload.target_type,
+ template_key: payload.template_key,
+ action: intent === 'train' ? 'start_training' : 'save_draft',
+ readiness: values.readiness,
+ }
+ const teamId = String(values.currentTeamId)
+ let created: AutoresearchPipelineApi
try {
- const created = await autoresearchCreate(String(values.currentTeamId), body)
- posthog.capture('autoresearch model created', {
- pipeline_id: created.id,
- target_type: payload.target_type,
- template_key: payload.template_key,
- })
- lemonToast.success(`Created "${created.name}"`)
- actions.resetNewPipeline()
- router.actions.push(urls.autoresearch())
+ created = await autoresearchCreate(teamId, body)
} catch (error: any) {
- posthog.capture('autoresearch model create failed', {
- target_type: payload.target_type,
- template_key: payload.template_key,
- })
+ posthog.capture('autoresearch model create failed', eventProperties)
lemonToast.error(
error?.detail ??
error?.data?.detail ??
@@ -537,6 +653,39 @@ export const autoresearchNewLogic = kea<autoresearchNewLogicType>([
)
throw error
}
+ posthog.capture('autoresearch model created', { ...eventProperties, pipeline_id: created.id })
+ if (intent === 'train') {
+ // A person who left the form during creation keeps the model as a draft, without a paid run.
+ breakpoint()
+ try {
+ await autoresearchTrainCreate(teamId, created.id)
+ posthog.capture('autoresearch model training started', {
+ ...eventProperties,
+ pipeline_id: created.id,
+ })
+ lemonToast.success(`Started training "${created.name}"`)
+ } catch (error: any) {
+ // The model exists, so open it anyway. Its page can start training again.
+ posthog.capture('autoresearch model training start failed', {
+ ...eventProperties,
+ pipeline_id: created.id,
+ })
+ // The access and usage gates put their reason in `error`, not in DRF's `detail`.
+ lemonToast.error(
+ `Saved "${created.name}" as a draft, but training didn't start. ${
+ error?.detail ??
+ error?.data?.detail ??
+ error?.data?.error ??
+ 'Start it from the model page.'
+ }`
+ )
+ }
+ } else {
+ lemonToast.success(`Saved "${created.name}" as a draft`)
+ }
+ breakpoint()
+ actions.resetNewPipeline()
+ router.actions.push(urls.autoresearchPipeline(created.id))
},
},
})),
@@ -549,8 +698,73 @@ export const autoresearchNewLogic = kea<autoresearchNewLogicType>([
resolved.target_event !== newPipeline.target_event.trim() ||
resolved.horizon_days !== newPipeline.horizon_days),
],
+ readiness: [
+ (s) => [s.validation],
+ (validation: ValidatePipelineResponseApi | null): Readiness | null => {
+ if (!validation) {
+ return null
+ }
+ if (!validation.can_proceed) {
+ return 'blocked'
+ }
+ return validation.warnings.some((w) => w.severity === 'warning') ? 'warnings' : 'ready'
+ },
+ ],
+ readinessChecks: [
+ (s) => [s.validation],
+ (validation: ValidatePipelineResponseApi | null): ReadinessCheck[] =>
+ validation && !validation.error ? readinessChecks(validation) : [],
+ ],
+ startTrainingDisabledReason: [
+ (s) => [
+ s.resolvedTemplateLoading,
+ s.isNewPipelineSubmitting,
+ s.submitIntent,
+ s.validationFailed,
+ s.validationLoading,
+ s.validation,
+ ],
+ (
+ resolvedTemplateLoading: boolean,
+ isSubmitting: boolean,
+ submitIntent: SubmitIntent,
+ validationFailed: boolean,
+ validationLoading: boolean,
+ validation: ValidatePipelineResponseApi | null
+ ): string | undefined => {
+ if (resolvedTemplateLoading) {
+ return 'Wait for the template to load'
+ }
+ if (isSubmitting && submitIntent === 'draft') {
+ return 'Saving the draft'
+ }
+ if (validationFailed) {
+ return "Couldn't check this model. Retry the check first."
+ }
+ if (validation && !validation.can_proceed) {
+ return "This model can't train yet. Fix the failed checks first."
+ }
+ return validationLoading ? 'Checking your data' : undefined
+ },
+ ],
+ saveDraftDisabledReason: [
+ (s) => [s.resolvedTemplateLoading, s.isNewPipelineSubmitting, s.submitIntent],
+ (
+ resolvedTemplateLoading: boolean,
+ isSubmitting: boolean,
+ submitIntent: SubmitIntent
+ ): string | undefined => {
+ if (resolvedTemplateLoading) {
+ return 'Wait for the template to load'
+ }
+ return isSubmitting && submitIntent === 'train' ? 'Starting training' : undefined
+ },
+ ],
}),
listeners(({ actions, values }) => ({
+ submitWithIntent: () => {
+ actions.submitNewPipeline()
+ },
runValidateSuccess: ({ validation }) => {
if (validation) {
posthog.capture('autoresearch model validated', {
diff --git a/products/autoresearch/frontend/newModel/ReadinessChecklist.tsx b/products/autoresearch/frontend/newModel/ReadinessChecklist.tsx
new file mode 100644
index 000000000000..b0319c4d5dcc
--- /dev/null
+++ b/products/autoresearch/frontend/newModel/ReadinessChecklist.tsx
@@ -0,0 +1,147 @@
+import { useActions, useValues } from 'kea'
+
+import { IconCheckCircle, IconCircleDashed, IconInfo, IconWarning, IconX } from '@posthog/icons'
+import { LemonBanner, LemonSkeleton, Spinner, Tooltip } from '@posthog/lemon-ui'
+
+import { Readiness, ReadinessCheck, autoresearchNewLogic, hasTarget } from '../autoresearchNewLogic'
+import { ValidationWarningApi } from '../generated/api.schemas'
+
+const WARNING_TEXT_CLASS: Record<ValidationWarningApi['severity'], string> = {
+ error: 'text-danger',
+ warning: 'text-warning-dark',
+ info: 'text-muted',
+}
+
+const HEADINGS: Record<Readiness, string> = {
+ ready: 'Ready to train',
+ warnings: 'Ready, with warnings',
+ blocked: "Can't train yet",
+}
+
+function CheckIcon({ status }: { status: ReadinessCheck['status'] }): JSX.Element {
+ if (status === 'fail') {
+ return <IconX className="text-danger text-lg shrink-0" />
+ }
+ if (status === 'warning') {
+ return <IconWarning className="text-warning text-lg shrink-0" />
+ }
+ if (status === 'skipped') {
+ return <IconCircleDashed className="text-muted text-lg shrink-0" />
+ }
+ return <IconCheckCircle className="text-success text-lg shrink-0" />
+}
+
+function CheckRow({ check }: { check: ReadinessCheck }): JSX.Element {
+ return (
+ <li className="flex gap-2">
+ <CheckIcon status={check.status} />
+ <div className="flex flex-col gap-1 min-w-0">
+ <div className="flex flex-wrap items-center gap-x-2">
+ <span className="font-semibold flex items-center gap-1">
+ {check.label}
+ {check.key === 'positives' && (
+ <Tooltip title="Base rate is the share of the training population that did the target event within the horizon. It is estimated from a sample of up to 5,000 users.">
+ <IconInfo className="text-sm text-muted cursor-help" />
+ </Tooltip>
+ )}
+ </span>
+ <span className="font-mono text-muted">{check.value}</span>
+ </div>
+ {check.warnings.map((warning, index) => (
+ <div key={`${warning.code}-${index}`} className={WARNING_TEXT_CLASS[warning.severity]}>
+ {warning.message}
+ </div>
+ ))}
+ </div>
+ </li>
+ )
+}
+
+export function ReadinessChecklist(): JSX.Element {
+ const {
+ validation,
+ validationLoading,
+ validationFailed,
+ newPipeline,
+ newPipelineValidationErrors,
+ readiness,
+ readinessChecks,
+ } = useValues(autoresearchNewLogic)
+ const { runValidate } = useActions(autoresearchNewLogic)
+ // The form hides field errors until the first submit, and the validate loader skips invalid day values.
+ // So this panel is the only place that says why no check appears.
+ const dayError = newPipelineValidationErrors.training_lookback_days ?? newPipelineValidationErrors.horizon_days
+
+ if (validationFailed && !validationLoading) {
+ return (
+ <LemonBanner
+ type="error"
+ action={{
+ children: 'Retry',
+ onClick: () => runValidate(null),
+ 'data-attr': 'autoresearch-new-validate-retry',
+ }}
+ >
+ Couldn't check this model definition. Retry, or change a field to check again.
+ </LemonBanner>
+ )
+ }
+
+ if (dayError) {
+ return (
+ <div className="border rounded p-4 bg-bg-light text-muted text-sm">
+ {dayError}. Fix it to check if this model is ready to train.
+ </div>
+ )
+ }
+
+ if (!validation && !validationLoading && !hasTarget(newPipeline)) {
+ return (
+ <div className="border rounded p-4 bg-bg-light text-muted text-sm">
+ Pick a target event to check if this model is ready to train.
+ </div>
+ )
+ }
+
+ return (
+ <div className="border rounded p-4 flex flex-col gap-3" data-attr="autoresearch-new-readiness">
+ <div className="flex items-center justify-between">
+ <h3 className="text-base font-semibold mb-0">
+ {readiness ? HEADINGS[readiness] : 'Checking your data'}
+ </h3>
+ {validationLoading && <Spinner className="text-sm" />}
+ </div>
+
+ {validation ? (
+ <>
+ {validation.error && (
+ <LemonBanner
+ type="error"
+ action={{
+ children: 'Retry',
+ onClick: () => runValidate(null),
+ loading: validationLoading,
+ 'data-attr': 'autoresearch-new-validate-retry',
+ }}
+ >
+ Couldn't check this model: {validation.error}
+ </LemonBanner>
+ )}
+ {readinessChecks.length > 0 && (
+ <ul className="flex flex-col gap-3 text-sm">
+ {readinessChecks.map((check) => (
+ <CheckRow key={check.key} check={check} />
+ ))}
+ </ul>
+ )}
+ </>
+ ) : (
+ <>
+ <LemonSkeleton className="h-4 w-full" />
+ <LemonSkeleton className="h-4 w-3/4" />
+ <LemonSkeleton className="h-4 w-1/2" />
+ </>
+ )}
+ </div>
+ )
+}
diff --git a/products/autoresearch/frontend/newModel/WhatHappensNext.tsx b/products/autoresearch/frontend/newModel/WhatHappensNext.tsx
new file mode 100644
index 000000000000..d1c325a80ebd
--- /dev/null
+++ b/products/autoresearch/frontend/newModel/WhatHappensNext.tsx
@@ -0,0 +1,24 @@
+const STEPS = [
+ 'An agent builds features from your events and trains candidate models on past data.',
+ 'It keeps the model with the best holdout score, and stops when the score stops improving or the experiment budget runs out.',
+ 'The best model scores your population every day and saves each score as a person property.',
+ 'When the prediction horizon passes, Autoresearch compares the predictions with what people did.',
+]
+
+export function WhatHappensNext(): JSX.Element {
+ return (
+ <div className="border rounded p-4 flex flex-col gap-3">
+ <h3 className="text-base font-semibold mb-0">What happens next</h3>
+ <ol className="flex flex-col gap-2 text-sm list-none p-0 m-0">
+ {STEPS.map((step, index) => (
+ <li key={index} className="flex gap-2">
+ <span className="flex items-center justify-center shrink-0 size-5 rounded-full bg-fill-highlight-100 text-xs font-semibold">
+ {index + 1}
+ </span>
+ <span>{step}</span>
+ </li>
+ ))}
+ </ol>
+ </div>
+ )
+}