: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(logs): anomaly scan UI in the anomalies tab (#78707)
Jon McCallum0e1e989ee52f
diff --git a/products/logs/frontend/LogsAnomalies.tsx b/products/logs/frontend/LogsAnomalies.tsxindex f17dc6fd21d2..229fa79d92b4 100644--- a/products/logs/frontend/LogsAnomalies.tsx+++ b/products/logs/frontend/LogsAnomalies.tsx@@ -1,11 +1,228 @@+import { useActions, useValues } from 'kea'++import { LemonBanner, LemonButton, LemonSelect, LemonTag, LemonTagType } from '@posthog/lemon-ui'+import { EmptyMessage } from 'lib/components/EmptyMessage/EmptyMessage'+import { TZLabel } from 'lib/components/TZLabel'+import { LemonTable, LemonTableColumns } from 'lib/lemon-ui/LemonTable'+import { pluralize } from 'lib/utils/strings'++import type { LogMessage } from '~/queries/schema/schema-general'++import { ServiceFilter } from 'products/logs/frontend/components/LogsViewer/Filters/ServiceFilter'+import { LogTag } from 'products/logs/frontend/components/LogTag'+import {+ BindingConstraintsEnumApi,+ type LimitedByEnumApi,+ type LogsAnomalyBaselineStageEnumApi,+ type LogsAnomalyScanIssueApi,+ type LogsAnomalyScanResponseApi,+ type LogsAnomalyScanSeriesApi,+ type LogsAnomalyVerdictEnumApi,+} from 'products/logs/frontend/generated/api.schemas'+import { SCAN_WINDOW_OPTIONS, logsAnomaliesLogic } from 'products/logs/frontend/logsAnomaliesLogic'++const VERDICT_TAG: Record<LogsAnomalyVerdictEnumApi, { label: string; type: LemonTagType }> = {+ spike: { label: 'Spike', type: 'danger' },+ drop: { label: 'Drop', type: 'warning' },+ silence: { label: 'Silence', type: 'danger' },+}++const STATE_TAG: Record<LogsAnomalyScanIssueApi['state'], { label: string; type: LemonTagType }> = {+ active: { label: 'Ongoing', type: 'danger' },+ resolved: { label: 'Resolved', type: 'success' },+ // A resolved issue whose anomaly recurred near the end of the window,+ // without enough consecutive buckets to reopen yet.+ pending: { label: 'Recurring', type: 'warning' },+}++const STAGE_LABEL: Record<LogsAnomalyBaselineStageEnumApi, string> = {+ insufficient: 'Not enough history',+ cold_start: 'Cold start',+ developing: 'Developing',+ mature: 'Mature',+}++const LIMIT_LABEL: Record<LimitedByEnumApi, string> = {+ series_history: 'Limited by series history (young series, or trimmed by a retention rule)',+ team_retention: 'Limited by the project log retention setting',+ byte_budget: 'Limited by the scan read budget',+}++const CONSTRAINT_MESSAGE: Record<BindingConstraintsEnumApi, string> = {+ [BindingConstraintsEnumApi.ByteBudget]:+ 'The scan degraded to stay inside its read budget, so baselines are less mature than usual.',+ [BindingConstraintsEnumApi.TeamRetention]:+ 'The project log retention setting is shorter than the full lookback, so baselines are less mature than usual.',+}++const LEARNING_COLUMNS: LemonTableColumns<LogsAnomalyScanSeriesApi> = [+ {+ title: 'Severity',+ render: (_, record) => <LogTag level={record.severity as LogMessage['severity_text']} />,+ },+ {+ title: 'Baseline',+ render: (_, record) => (record.stage ? STAGE_LABEL[record.stage] : 'Not scored'),+ },+ {+ title: 'First seen',+ render: (_, record) => (record.history_start ? <TZLabel time={record.history_start} /> : '—'),+ },+ {+ title: 'Limits',+ render: (_, record) => (record.limited_by ? LIMIT_LABEL[record.limited_by] : 'Full baseline'),+ },+]-// Intentionally bare: the learning-status surface lands here in a later change.export function LogsAnomalies(): JSX.Element {+ const { serviceName, windowHours, scanResult, scanResultLoading, scanDisabledReason } =+ useValues(logsAnomaliesLogic)+ const { setServiceName, setWindowHours, runScan } = useActions(logsAnomaliesLogic)++ return (+ <div className="flex flex-col gap-4">+ <div className="flex flex-wrap items-center gap-2">+ <span data-attr="logs-anomalies-service">+ <ServiceFilter+ value={serviceName ? [serviceName] : []}+ onChange={(serviceNames) => setServiceName(serviceNames?.[0] ?? null)}+ // Match the scan's baseline lookback so a service that recently went+ // silent still shows up as a scannable suggestion.+ dateRange={{ date_from: '-42d' }}+ selectionMode="single"+ emptyButtonLabel="Choose a service"+ />+ </span>+ <LemonSelect+ value={windowHours}+ onChange={(value) => value !== null && setWindowHours(value)}+ options={SCAN_WINDOW_OPTIONS}+ data-attr="logs-anomalies-window"+ />+ <LemonButton+ type="primary"+ onClick={runScan}+ loading={scanResultLoading}+ disabledReason={scanDisabledReason}+ data-attr="logs-anomalies-scan"+ >+ Scan for anomalies+ </LemonButton>+ </div>++ {scanResult ? (+ <ScanResults result={scanResult} />+ ) : scanResultLoading ? null : (+ <EmptyMessage+ title="Anomaly detection"+ description="PostHog learns each service's normal log volume and flags spikes, drops, and silences. Choose a service and a time window, then run a scan."+ />+ )}+ </div>+ )+}++function ScanResults({ result }: { result: LogsAnomalyScanResponseApi }): JSX.Element {+ return (+ <div className="flex flex-col gap-4" data-attr="logs-anomalies-results">+ <ConstraintsBanner result={result} />+ {result.issues.length > 0 ? (+ <div className="flex flex-col gap-2">+ {result.issues.map((issue, index) => (+ <IssueCard key={index} issue={issue} />+ ))}+ </div>+ ) : (+ <LemonBanner type="success">+ No anomalies in this window. Log volume for {result.service_name} stayed inside its expected bands+ from <TZLabel time={result.eval_start} /> to <TZLabel time={result.eval_end} />.+ </LemonBanner>+ )}+ <LearningStatus series={result.series} lookbackDays={result.lookback_days} />+ </div>+ )+}++function ConstraintsBanner({ result }: { result: LogsAnomalyScanResponseApi }): JSX.Element | null {+ if (!result.degraded && !result.eval_clipped && result.binding_constraints.length === 0) {+ return null+ }+ return (+ <LemonBanner type="warning" data-attr="logs-anomalies-constraints">+ <div className="flex flex-col gap-1">+ <span>+ This scan used {result.lookback_days.toFixed(1)} days of baseline history+ {result.eval_clipped ? (+ <>+ {' '}+ and was clipped to the window from <TZLabel time={result.eval_start} /> to{' '}+ <TZLabel time={result.eval_end} />+ </>+ ) : null}+ .+ </span>+ {result.binding_constraints.length > 0 ? (+ <ul className="list-disc pl-4">+ {result.binding_constraints.map((constraint) => (+ <li key={constraint}>{CONSTRAINT_MESSAGE[constraint]}</li>+ ))}+ </ul>+ ) : null}+ </div>+ </LemonBanner>+ )+}++function IssueCard({ issue }: { issue: LogsAnomalyScanIssueApi }): JSX.Element {+ const verdict = VERDICT_TAG[issue.kind]+ const state = STATE_TAG[issue.state]+ return (+ <div className="rounded border bg-surface-primary p-3 flex flex-col gap-2" data-attr="logs-anomalies-issue">+ <div className="flex items-center gap-2">+ <LemonTag type={verdict.type}>{verdict.label}</LemonTag>+ {issue.severity ? <LogTag level={issue.severity as LogMessage['severity_text']} /> : null}+ {state ? <LemonTag type={state.type}>{state.label}</LemonTag> : null}+ </div>+ <div className="text-secondary text-sm">+ Opened <TZLabel time={issue.opened_at} />+ {issue.resolved_at ? (+ <>+ , resolved <TZLabel time={issue.resolved_at} />+ </>+ ) : (+ <>+ , last anomalous <TZLabel time={issue.last_anomalous_at} />+ </>+ )}+ {' · '}+ {pluralize(issue.anomalous_bucket_times.length, 'anomalous bucket')}+ </div>+ </div>+ )+}++function LearningStatus({+ series,+ lookbackDays,+}: {+ series: LogsAnomalyScanSeriesApi[]+ lookbackDays: number+}): JSX.Element {return (- <EmptyMessage- title="Anomaly detection"- description="PostHog learns each service's normal log volume and surfaces spikes, drops, and silences here, so there's nothing to configure."- />+ <div className="flex flex-col gap-1">+ <h3 className="mb-0">What the detector has learned</h3>+ <div className="text-secondary text-sm">+ Baselines built from {lookbackDays.toFixed(1)} days of history.+ </div>+ <LemonTable+ dataSource={series}+ columns={LEARNING_COLUMNS}+ rowKey="severity"+ size="small"+ emptyState="No log series found for this service in the scanned window."+ data-attr="logs-anomalies-learning"+ />+ </div>)}diff --git a/products/logs/frontend/logsAnomaliesLogic.test.ts b/products/logs/frontend/logsAnomaliesLogic.test.tsnew file mode 100644index 000000000000..a0923bd3306a--- /dev/null+++ b/products/logs/frontend/logsAnomaliesLogic.test.ts@@ -0,0 +1,74 @@+import { expectLogic } from 'kea-test-utils'++import { initKeaTests } from '~/test/init'++import { logsAnomaliesScanCreate } from 'products/logs/frontend/generated/api'++import { logsAnomaliesLogic } from './logsAnomaliesLogic'++jest.mock('products/logs/frontend/generated/api', () => ({+ __esModule: true,+ logsAnomaliesScanCreate: jest.fn().mockResolvedValue({+ service_name: 'checkout',+ eval_start: '2026-08-05T00:00:00Z',+ eval_end: '2026-08-06T00:00:00Z',+ lookback_days: 42,+ eval_clipped: false,+ degraded: false,+ binding_constraints: [],+ series: [],+ issues: [],+ }),+}))++describe('logsAnomaliesLogic', () => {+ let logic: ReturnType<typeof logsAnomaliesLogic.build>++ beforeEach(() => {+ initKeaTests()+ logic = logsAnomaliesLogic()+ logic.mount()+ })++ afterEach(() => {+ logic.unmount()+ })++ it('does not call the scan endpoint without a service', async () => {+ await expectLogic(logic, () => {+ logic.actions.runScan()+ }).toFinishAllListeners()+ expect(logsAnomaliesScanCreate).not.toHaveBeenCalled()+ expect(logic.values.scanDisabledReason).toBe('Pick a service to scan first')+ })++ it('scans with an absolute UTC window derived from the selected width', async () => {+ logic.actions.setServiceName('checkout')+ logic.actions.setWindowHours(6)+ await expectLogic(logic, () => {+ logic.actions.runScan()+ }).toFinishAllListeners()++ expect(logsAnomaliesScanCreate).toHaveBeenCalledTimes(1)+ const [, body] = (logsAnomaliesScanCreate as jest.Mock).mock.calls[0]+ expect(body.serviceName).toBe('checkout')+ const from = new Date(body.dateRange.date_from)+ const to = new Date(body.dateRange.date_to)+ // The endpoint requires absolute ISO datetimes; relative expressions+ // like "-6h" would be rejected.+ expect(Number.isNaN(from.getTime())).toBe(false)+ expect(to.getTime() - from.getTime()).toBe(6 * 60 * 60 * 1000)+ expect(logic.values.scanResult?.service_name).toBe('checkout')+ })++ it('keeps the previous result until a new scan succeeds', async () => {+ logic.actions.setServiceName('checkout')+ await expectLogic(logic, () => {+ logic.actions.runScan()+ }).toFinishAllListeners()+ const firstResult = logic.values.scanResult++ logic.actions.setServiceName('other-service')+ expect(logic.values.scanResult).toBe(firstResult)+ })+})diff --git a/products/logs/frontend/logsAnomaliesLogic.tsx b/products/logs/frontend/logsAnomaliesLogic.tsxnew file mode 100644index 000000000000..550ca1d91a59--- /dev/null+++ b/products/logs/frontend/logsAnomaliesLogic.tsx@@ -0,0 +1,134 @@+import { MakeLogicType, actions, connect, kea, listeners, path, reducers, selectors } from 'kea'+import { loaders } from 'kea-loaders'++import { lemonToast } from '@posthog/lemon-ui'++import { dayjs } from 'lib/dayjs'+import type { LemonSelectOption } from 'lib/lemon-ui/LemonSelect'+import { teamLogic } from 'scenes/teamLogic'++import { logsAnomaliesScanCreate } from 'products/logs/frontend/generated/api'+import type { LogsAnomalyScanResponseApi } from 'products/logs/frontend/generated/api.schemas'++// The endpoint accepts at most 7 days per scan.+export const SCAN_WINDOW_OPTIONS: LemonSelectOption<number>[] = [+ { value: 1, label: 'Last hour' },+ { value: 6, label: 'Last 6 hours' },+ { value: 24, label: 'Last 24 hours' },+ { value: 72, label: 'Last 3 days' },+ { value: 168, label: 'Last 7 days' },+]++export const DEFAULT_SCAN_WINDOW_HOURS = 24++// Generated by kea-typegen. Update if you're an agent, ignore if you're human.+export interface logsAnomaliesLogicValues {+ currentTeamId: number | null // teamLogic+ scanDisabledReason: string | null+ scanResult: LogsAnomalyScanResponseApi | null+ scanResultLoading: boolean+ serviceName: string | null+ windowHours: number+}++// Generated by kea-typegen. Update if you're an agent, ignore if you're human.+export interface logsAnomaliesLogicActions {+ runScan: () => any+ runScanFailure: (+ error: string,+ errorObject?: any+ ) => {+ error: string+ errorObject?: any+ }+ runScanSuccess: (+ scanResult: LogsAnomalyScanResponseApi | null,+ payload?: any+ ) => {+ scanResult: LogsAnomalyScanResponseApi | null+ payload?: any+ }+ setServiceName: (serviceName: string | null) => {+ serviceName: string | null+ }+ setWindowHours: (windowHours: number) => {+ windowHours: number+ }+}++// Generated by kea-typegen. Update if you're an agent, ignore if you're human.+export interface logsAnomaliesLogicMeta {+ __keaTypeGenInternalSelectorTypes: {+ scanDisabledReason: (serviceName: string | null, scanResultLoading: boolean) => string | null+ }+}++export type logsAnomaliesLogicType = MakeLogicType<+ logsAnomaliesLogicValues,+ logsAnomaliesLogicActions,+ Record<string, any>,+ logsAnomaliesLogicMeta+>++export const logsAnomaliesLogic = kea<logsAnomaliesLogicType>([+ path(['products', 'logs', 'frontend', 'logsAnomaliesLogic']),+ connect(() => ({ values: [teamLogic, ['currentTeamId']] })),+ actions({+ setServiceName: (serviceName: string | null) => ({ serviceName }),+ setWindowHours: (windowHours: number) => ({ windowHours }),+ }),+ loaders(({ values }) => ({+ scanResult: [+ null as LogsAnomalyScanResponseApi | null,+ {+ runScan: async () => {+ if (!values.serviceName || !values.currentTeamId) {+ return values.scanResult+ }+ const now = dayjs.utc()+ return await logsAnomaliesScanCreate(String(values.currentTeamId), {+ serviceName: values.serviceName,+ dateRange: {+ date_from: now.subtract(values.windowHours, 'hour').toISOString(),+ date_to: now.toISOString(),+ },+ })+ },+ },+ ],+ })),+ reducers({+ serviceName: [+ null as string | null,+ {+ setServiceName: (_, { serviceName }) => serviceName,+ },+ ],+ windowHours: [+ DEFAULT_SCAN_WINDOW_HOURS as number,+ {+ setWindowHours: (_, { windowHours }) => windowHours,+ },+ ],+ }),+ selectors({+ scanDisabledReason: [+ (s) => [s.serviceName, s.scanResultLoading],+ (serviceName: string | null, scanResultLoading: boolean): string | null => {+ if (!serviceName) {+ return 'Pick a service to scan first'+ }+ if (scanResultLoading) {+ return 'A scan is already running'+ }+ return null+ },+ ],+ }),+ listeners(() => ({+ runScanFailure: ({ error }) => {+ // ApiError already extracts the endpoint's { error } body into the message.+ lemonToast.error(error || 'The anomaly scan failed. Try a shorter window.')+ },+ })),+])