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(logs): browse per-service series band charts on the anomalies tab (#87889)

Jon McCallum0187cdf50f93
diff --git a/frontend/snapshots.yml b/frontend/snapshots.yml
index d708193e9b7d..763c76de1741 100644
--- a/frontend/snapshots.yml
+++ b/frontend/snapshots.yml
@@ -4600,6 +4600,10 @@ snapshots:
hash: v1.k794b7964.ff05bda7e439902c963d4cee0889351a3cace04ef2e149494544b1bc60794347.JKw0gsl8CIiVdeLk4DndxZFLr2oZ7kYNBIxNotCuVCQ
lemon-ui-visual-image-diff-viewer--small-image--light:
hash: v1.k794b7964.ed31587820d0216f2281ec8e610da8cb9fe8cb45f9c13e0280f17771cf84994a.spusB2C8AKwu5Tv0KOr8pkjDxgEZw5jcOlEikYAzKWI
+ logs-anomalybandchart--observed-vs-expected--dark:
+ hash: v1.k794b7964.69fc4d5a1cb9c712e52a149c23362f59d4f48afb519f127887c09f5179ff8ee6.dcZ-OsCW3daVlEr1DTJuJ2sg7v51vbf5cOVBiTZFEe0
+ logs-anomalybandchart--observed-vs-expected--light:
+ hash: v1.k794b7964.77210b7387e77246bdfecedb643c69d2e05057c1a8f50c803e09e7372bcfd3fe.65EXHskPNsbGnTZ3-_lm9qkMFE7wfhTc1_yHlA-1TNo
mcp-apps-actions--list--light:
hash: v1.k794b7964.780ee2787e03d18e28952f15ba1063d3561bf506c3f27370e111aa00b6840480.kyd4ZfOZOnVnvs4zzuHttn7iaRk1OSRVc4UGm-myJEA
mcp-apps-actions--multi-step--light:
diff --git a/products/logs/frontend/LogsAnomalies.tsx b/products/logs/frontend/LogsAnomalies.tsx
index 6408eead85fa..4c312958efee 100644
--- a/products/logs/frontend/LogsAnomalies.tsx
+++ b/products/logs/frontend/LogsAnomalies.tsx
@@ -1,296 +1,135 @@
import { useActions, useValues } from 'kea'
-import { combineUrl, router } from 'kea-router'
+import { memo } from 'react'
-import { IconUndo } from '@posthog/icons'
-import { LemonBanner, LemonButton, LemonSelect, LemonTag, LemonTagType } from '@posthog/lemon-ui'
+import { LemonBanner, LemonButton, LemonTag } 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 { urls } from 'scenes/urls'
+import { Spinner } from 'lib/lemon-ui/Spinner'
import type { LogMessage } from '~/queries/schema/schema-general'
import { AnomalyBandChart } from 'products/logs/frontend/components/AnomalyBandChart'
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, type ScanRange, 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'),
- },
-]
+import type { LogsSeriesBandSeriesApi } from 'products/logs/frontend/generated/api.schemas'
+import { logsAnomaliesLogic } from 'products/logs/frontend/logsAnomaliesLogic'
export function LogsAnomalies(): JSX.Element {
- const { serviceName, windowHours, scanResult, scanResultLoading, scanDisabledReason } =
- useValues(logsAnomaliesLogic)
- const { setServiceName, setWindowHours, runScan } = useActions(logsAnomaliesLogic)
+ const { serviceName } = useValues(logsAnomaliesLogic)
+ const { setServiceName } = useActions(logsAnomaliesLogic)
return (
- <div className="flex flex-col gap-4">
+ <div className="flex flex-col gap-4 flex-1 min-h-0">
<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.
+ // Match the band baseline lookback so a service that recently went
+ // silent still shows up as a 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."
- />
- )}
+ <SeriesBands />
</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>
- )}
- <BandCharts series={result.series} serviceName={result.service_name} />
- <LearningStatus series={result.series} lookbackDays={result.lookback_days} />
- </div>
- )
-}
+function SeriesBands(): JSX.Element {
+ const { serviceName, seriesBands, seriesBandsError, seriesBandsLoading, visibleSeries, hiddenSeriesCount } =
+ useValues(logsAnomaliesLogic)
+ const { loadSeriesBands, showMoreSeries } = useActions(logsAnomaliesLogic)
-function BandCharts({
- series,
- serviceName,
-}: {
- series: LogsAnomalyScanSeriesApi[]
- serviceName: string
-}): JSX.Element | null {
- const { zoomedRange, scanDisabledReason } = useValues(logsAnomaliesLogic)
- const { zoomToRange, resetZoom } = useActions(logsAnomaliesLogic)
- const withBuckets = series.filter((s) => s.buckets.length > 0)
- if (withBuckets.length === 0) {
- return null
+ if (!serviceName) {
+ return (
+ <EmptyMessage
+ title="Log volume by series"
+ description="See a week of log volume for each series a service emits, with the expected range learned from previous weeks. Choose a service to start."
+ />
+ )
}
- return (
- <div className="flex flex-col gap-2" data-attr="logs-anomalies-band-charts">
- <h3 className="mb-0">Observed vs expected</h3>
- <div className="text-secondary text-sm">
- Log volume per 5 minute bucket against the learned band. Marked points fell outside the band. Drag
- across a chart to scan a narrower window, or click a bucket to read its logs.
+
+ if (seriesBandsError) {
+ // LemonBanner takes a fixed prop set, so a data-attr on it would never reach the DOM.
+ return (
+ <div data-attr="logs-anomalies-error">
+ <LemonBanner type="error" action={{ children: 'Try again', onClick: loadSeriesBands }}>
+ Couldn't load the charts for {serviceName}. {seriesBandsError}
+ </LemonBanner>
</div>
- {withBuckets.map((s) => (
- <div key={s.severity} className="rounded border bg-surface-primary p-3">
- <div className="mb-2 flex items-center gap-2">
- <LogTag level={s.severity as LogMessage['severity_text']} />
- <span className="text-secondary text-xs">{s.stage ? STAGE_LABEL[s.stage] : 'Not scored'}</span>
- {/* Per chart rather than in the toolbar: you drag on a chart, so the way back
- has to be next to the chart you dragged on. */}
- {zoomedRange && (
- <LemonButton
- className="ml-auto"
- size="xsmall"
- type="secondary"
- icon={<IconUndo />}
- onClick={resetZoom}
- disabledReason={scanDisabledReason}
- data-attr="logs-anomalies-reset-zoom"
- >
- Reset zoom
- </LemonButton>
- )}
- </div>
- <AnomalyBandChart
- buckets={s.buckets}
- onZoom={zoomToRange}
- onBucketClick={(range) => openLogsForBucket(serviceName, s.severity, range)}
- />
- </div>
- ))}
- </div>
- )
-}
+ )
+ }
-function openLogsForBucket(serviceName: string, severity: string, range: ScanRange): void {
- router.actions.push(
- combineUrl(urls.logs(), {
- activeTab: 'viewer',
- serviceNames: serviceName,
- severityLevels: severity,
- dateRange: { date_from: range.dateFrom, date_to: range.dateTo },
- }).url
- )
-}
+ if (seriesBandsLoading || !seriesBands) {
+ return (
+ <div className="flex items-center justify-center py-16">
+ <Spinner className="text-2xl" />
+ </div>
+ )
+ }
-function ConstraintsBanner({ result }: { result: LogsAnomalyScanResponseApi }): JSX.Element | null {
- if (!result.degraded && !result.eval_clipped && result.binding_constraints.length === 0) {
- return null
+ if (seriesBands.series.length === 0) {
+ // A service that logged earlier in the baseline window still returns zero-filled series,
+ // so an empty list means nothing was logged across the baseline either.
+ return (
+ <EmptyMessage
+ title="No logs to chart"
+ description={`${seriesBands.service_name} has no recent log volume. Choose another service, or check back once it logs again.`}
+ />
+ )
}
- 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="flex flex-col gap-2 flex-1 min-h-0 overflow-y-auto" data-attr="logs-anomalies-band-charts">
<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')}
+ Log volume per hour over the last 7 days, against the range seen at the same time of week in the
+ previous weeks. Marked points fell outside that range. Click a bucket to read its logs.
</div>
+ {seriesBands.series_truncated ? (
+ <div data-attr="logs-anomalies-truncated">
+ <LemonBanner type="warning">
+ This service emits more series than one page can chart. The quietest series were left out.
+ </LemonBanner>
+ </div>
+ ) : null}
+ {visibleSeries.map((series) => (
+ <SeriesCard key={`${series.namespace}/${series.environment}/${series.severity}`} series={series} />
+ ))}
+ {hiddenSeriesCount > 0 ? (
+ <LemonButton type="secondary" center onClick={showMoreSeries} data-attr="logs-anomalies-show-more">
+ Show more ({hiddenSeriesCount} hidden)
+ </LemonButton>
+ ) : null}
</div>
)
}
-function LearningStatus({
- series,
- lookbackDays,
-}: {
- series: LogsAnomalyScanSeriesApi[]
- lookbackDays: number
-}): JSX.Element {
+// "Show more" grows the visible slice without touching the cards already on screen, so the charts
+// they hold should not reconcile again.
+const SeriesCard = memo(function SeriesCard({ series }: { series: LogsSeriesBandSeriesApi }): JSX.Element {
+ const { openLogsForBucket } = useActions(logsAnomaliesLogic)
+ // A banded series carries a band on every bucket, so their absence is the backend's own
+ // "still learning" verdict. Restating its week threshold here would let the two drift.
+ const learning = series.buckets.length > 0 && series.buckets.every((bucket) => bucket.lower == null)
return (
- <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 className="rounded border bg-surface-primary p-3" data-attr="logs-anomalies-series">
+ <div className="mb-2 flex items-center gap-2">
+ <LogTag level={series.severity as LogMessage['severity_text']} />
+ {series.namespace ? <LemonTag>{series.namespace}</LemonTag> : null}
+ {series.environment ? <LemonTag>{series.environment}</LemonTag> : null}
+ {learning ? (
+ <LemonTag type="caution" title="This series has too little history for an expected range yet.">
+ Learning baseline
+ </LemonTag>
+ ) : null}
</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"
+ <AnomalyBandChart
+ buckets={series.buckets}
+ onBucketClick={(dateRange) => openLogsForBucket(series.severity, dateRange)}
/>
</div>
)
-}
+})
diff --git a/products/logs/frontend/components/AnomalyBandChart.stories.tsx b/products/logs/frontend/components/AnomalyBandChart.stories.tsx
index 7ae7c96b8690..d88dadb22cd9 100644
--- a/products/logs/frontend/components/AnomalyBandChart.stories.tsx
+++ b/products/logs/frontend/components/AnomalyBandChart.stories.tsx
@@ -1,39 +1,28 @@
import { Meta, StoryObj } from '@storybook/react'
-import type { LogsAnomalyScanBucketApi } from 'products/logs/frontend/generated/api.schemas'
+import type { LogsSeriesBandBucketApi } from 'products/logs/frontend/generated/api.schemas'
import { AnomalyBandChart } from './AnomalyBandChart'
-const BUCKET_MINUTES = 5
+const BUCKET_MINUTES = 60
const BUCKETS = 72
-const FIRST_BUCKET = Date.parse('2026-08-06T04:00:00Z')
+const FIRST_BUCKET = Date.parse('2026-08-03T04:00:00Z')
-/** Buckets that exercise every state the chart draws: a learned band, an anomalous spike and drop
- * against it, a silence, and a trailing unscored stretch where the band has to break. */
-function buildBuckets(): LogsAnomalyScanBucketApi[] {
+/** Buckets that exercise every state the chart draws: a banded stretch, an out-of-band spike and
+ * drop against it, and a trailing learning stretch where the band has to break. */
+function buildBuckets(): LogsSeriesBandBucketApi[] {
return Array.from({ length: BUCKETS }, (_, index) => {
const time = new Date(FIRST_BUCKET + index * BUCKET_MINUTES * 60_000).toISOString()
// A slow sine keeps the baseline uneven without a random source.
- const expected = Math.round(400 + 120 * Math.sin(index / 5))
- const scored = index < BUCKETS - 8
- const verdict = index === 24 ? 'spike' : index === 44 ? 'drop' : index === 52 ? 'silence' : null
- const observed =
- verdict === 'spike'
- ? expected * 4
- : verdict === 'drop'
- ? Math.round(expected * 0.2)
- : verdict === 'silence'
- ? 0
- : expected
+ const typical = Math.round(400 + 120 * Math.sin(index / 5))
+ const banded = index < BUCKETS - 8
+ const observed = index === 24 ? typical * 4 : index === 44 ? Math.round(typical * 0.1) : typical
return {
time,
observed,
- expected: scored ? expected : null,
- lower: scored ? Math.round(expected * 0.6) : null,
- upper: scored ? Math.round(expected * 1.4) : null,
- stage: scored ? 'mature' : null,
- verdict,
+ lower: banded ? Math.round(typical * 0.6) : null,
+ upper: banded ? Math.round(typical * 1.4) : null,
}
})
}
@@ -61,6 +50,6 @@ const meta: Meta<typeof AnomalyBandChart> = {
export default meta
-/** What `LogsAnomalies` renders per severity: observed volume against the learned band, with the
- * anomalous buckets marked and the unscored tail left as a gap. */
+/** What `LogsAnomalies` renders per series: observed volume against the time-of-week band, with
+ * out-of-band buckets marked and the unbanded tail left as a gap. */
export const ObservedVsExpected: StoryObj<typeof AnomalyBandChart> = {}
diff --git a/products/logs/frontend/components/AnomalyBandChart.test.ts b/products/logs/frontend/components/AnomalyBandChart.test.ts
index 7be03b03979f..563af40ae4dc 100644
--- a/products/logs/frontend/components/AnomalyBandChart.test.ts
+++ b/products/logs/frontend/components/AnomalyBandChart.test.ts
@@ -1,70 +1,64 @@
-import type { LogsAnomalyScanBucketApi } from 'products/logs/frontend/generated/api.schemas'
+import type { LogsSeriesBandBucketApi } from 'products/logs/frontend/generated/api.schemas'
-import { bucketRange, buildBandChartData } from './AnomalyBandChart'
+import { buildBandChartData, clickableBucketTimes } from './AnomalyBandChart'
-function bucket(overrides: Partial<LogsAnomalyScanBucketApi>): LogsAnomalyScanBucketApi {
+function bucket(overrides: Partial<LogsSeriesBandBucketApi>): LogsSeriesBandBucketApi {
return {
time: '2026-08-06T10:00:00Z',
observed: 12,
- expected: 11,
lower: 4,
upper: 21,
- stage: 'mature',
- verdict: null,
...overrides,
}
}
describe('AnomalyBandChart', () => {
describe('buildBandChartData', () => {
- it('leaves unscored band values non-finite instead of coercing to zero', () => {
- // A null band coerced to 0 would render every unscored region as a
+ it('leaves unbanded values non-finite instead of coercing to zero', () => {
+ // A null band coerced to 0 would render every unbanded region as a
// drop to zero, which is exactly the misreading the chart must avoid.
// The band breaks at a non-finite value, which is how the gap is drawn.
const data = buildBandChartData([
bucket({}),
- bucket({ time: '2026-08-06T10:05:00Z', expected: null, lower: null, upper: null, stage: null }),
+ bucket({ time: '2026-08-06T11:00:00Z', lower: null, upper: null }),
])
expect(data.lower).toEqual([4, NaN])
expect(data.upper).toEqual([21, NaN])
expect(data.observed).toEqual([12, 12])
})
- it('carries verdicts positionally so anomalous points can be highlighted', () => {
+ it('marks points outside the band, and never marks unbanded points', () => {
const data = buildBandChartData([
bucket({}),
- bucket({ time: '2026-08-06T10:05:00Z', observed: 47, verdict: 'spike' }),
+ bucket({ time: '2026-08-06T11:00:00Z', observed: 47 }),
+ bucket({ time: '2026-08-06T12:00:00Z', observed: 1 }),
+ bucket({ time: '2026-08-06T13:00:00Z', observed: 47, lower: null, upper: null }),
])
- expect(data.verdicts).toEqual([null, 'spike'])
+ expect(data.outOfBand).toEqual([null, 'above', 'below', null])
})
it('labels buckets with their raw times so the time axis can format them', () => {
// Pre-formatted display strings would be printed verbatim by the time axis, which
// costs the interval-aware ticks and the tooltip's date header.
- const data = buildBandChartData([bucket({}), bucket({ time: '2026-08-06T10:05:00Z' })])
- expect(data.labels).toEqual(['2026-08-06T10:00:00Z', '2026-08-06T10:05:00Z'])
+ const data = buildBandChartData([bucket({}), bucket({ time: '2026-08-06T11:00:00Z' })])
+ expect(data.labels).toEqual(['2026-08-06T10:00:00Z', '2026-08-06T11:00:00Z'])
})
})
- describe('bucketRange', () => {
- const buckets = ['10:00', '10:05', '10:10', '10:15'].map((time) => bucket({ time: `2026-08-06T${time}:00Z` }))
-
- // Every index names a bucket start. A range ending at the last bucket's start would scan
- // and link to everything except the bucket the user actually picked, and a single-bucket
- // click would resolve to an empty window.
- it.each([
- { name: 'a drag across buckets', start: 0, end: 2, from: '10:00:00Z', to: '10:15:00.000Z' },
- { name: 'a click on one bucket', start: 1, end: 1, from: '10:05:00Z', to: '10:10:00.000Z' },
- { name: 'a right-to-left drag', start: 2, end: 0, from: '10:00:00Z', to: '10:15:00.000Z' },
- ])('covers whole buckets for $name', ({ start, end, from, to }) => {
- expect(bucketRange(buckets, start, end)).toEqual({
- dateFrom: `2026-08-06T${from}`,
- dateTo: `2026-08-06T${to}`,
- })
+ describe('clickableBucketTimes', () => {
+ // Every charted bucket is a complete interval. Without the appended end, a click on the
+ // newest one would open a range running to "now", covering the current uncharted interval
+ // on top of the one that was clicked.
+ it('closes the last bucket at its own end', () => {
+ expect(clickableBucketTimes(['2026-08-06T10:00:00Z', '2026-08-06T11:00:00Z'])).toEqual([
+ '2026-08-06T10:00:00Z',
+ '2026-08-06T11:00:00Z',
+ '2026-08-06T12:00:00.000Z',
+ ])
})
- it('returns null when the bucket width cannot be derived', () => {
- expect(bucketRange([bucket({})], 0, 0)).toBeNull()
+ it('leaves a single bucket alone, having no width to measure', () => {
+ expect(clickableBucketTimes(['2026-08-06T10:00:00Z'])).toEqual(['2026-08-06T10:00:00Z'])
})
})
})
diff --git a/products/logs/frontend/components/AnomalyBandChart.tsx b/products/logs/frontend/components/AnomalyBandChart.tsx
index 8aa3617e9f65..e70ffb3f3bd4 100644
--- a/products/logs/frontend/components/AnomalyBandChart.tsx
+++ b/products/logs/frontend/components/AnomalyBandChart.tsx
@@ -6,7 +6,6 @@ import {
DefaultTooltip,
TimeSeriesLineChart,
type AnomalyMarker,
- type DateRangeZoomData,
type PointClickData,
type Series,
type TimeSeriesLineChartConfig,
@@ -17,22 +16,26 @@ import { useChartConfig, useChartTheme } from 'lib/charts/hooks'
import { dayjs } from 'lib/dayjs'
import { humanFriendlyNumber } from 'lib/utils/numbers'
-import type { LogsAnomalyScanBucketApi, LogsAnomalyVerdictEnumApi } from 'products/logs/frontend/generated/api.schemas'
-import type { ScanRange } from 'products/logs/frontend/logsAnomaliesLogic'
+import type { DateRange } from '~/queries/schema/schema-general'
+
+import { selectedDateRange } from 'products/logs/frontend/components/LogsViewer/LogsViewerSparkline/bucketRanges'
+import type { LogsSeriesBandBucketApi } from 'products/logs/frontend/generated/api.schemas'
const OBSERVED_KEY = 'observed'
+export type OutOfBand = 'above' | 'below'
+
export interface BandChartData {
labels: string[]
observed: number[]
lower: number[]
upper: number[]
- verdicts: (LogsAnomalyVerdictEnumApi | null)[]
+ outOfBand: (OutOfBand | null)[]
}
-// Band values stay NaN for unscored buckets so the chart shows a gap there. Coercing them to 0
-// would render every unscored region as a drop to zero.
-export function buildBandChartData(buckets: LogsAnomalyScanBucketApi[]): BandChartData {
+// Band values stay NaN for unbanded buckets so the chart shows a gap there. Coercing them to 0
+// would render every unbanded region as a drop to zero.
+export function buildBandChartData(buckets: LogsSeriesBandBucketApi[]): BandChartData {
return {
// Raw bucket times: the time axis formats the ticks, so it can switch to day boundaries on a
// multi-day window without every label being baked at one width.
@@ -40,45 +43,51 @@ export function buildBandChartData(buckets: LogsAnomalyScanBucketApi[]): BandCha
observed: buckets.map((bucket) => bucket.observed),
lower: buckets.map((bucket) => bucket.lower ?? NaN),
upper: buckets.map((bucket) => bucket.upper ?? NaN),
- verdicts: buckets.map((bucket) => bucket.verdict),
+ outOfBand: buckets.map((bucket) => {
+ if (bucket.lower == null || bucket.upper == null) {
+ return null
+ }
+ if (bucket.observed > bucket.upper) {
+ return 'above'
+ }
+ if (bucket.observed < bucket.lower) {
+ return 'below'
+ }
+ return null
+ }),
}
}
-/** Matches the verdict tags above each chart, and follows the theme rather than pinning one shade. */
-const VERDICT_POINT_COLOR: Record<LogsAnomalyVerdictEnumApi, string> = {
- spike: 'var(--danger)',
- drop: 'var(--warning)',
- silence: 'var(--danger-dark)',
+/** Follows the theme rather than pinning one shade. */
+const OUT_OF_BAND_POINT_COLOR: Record<OutOfBand, string> = {
+ above: 'var(--danger)',
+ below: 'var(--warning)',
}
-/** Both indices name a bucket *start*, so the range has to run to the end of the last one. A range
- * ending at its start would exclude the very bucket the user dragged over or clicked. Bucket width
- * comes from the first gap rather than the scan's constant, so the two can't drift. */
-export function bucketRange(
- buckets: LogsAnomalyScanBucketApi[],
- startIndex: number,
- endIndex: number
-): ScanRange | null {
- const [from, to] = startIndex <= endIndex ? [startIndex, endIndex] : [endIndex, startIndex]
- const start = buckets[from]?.time
- const end = buckets[to]?.time
- if (!start || !end || buckets.length < 2) {
- return null
- }
- const bucketMs = Date.parse(buckets[1].time) - Date.parse(buckets[0].time)
- if (!(bucketMs > 0)) {
- return null
+const OUT_OF_BAND_LABEL: Record<OutOfBand, string> = {
+ above: 'spike',
+ below: 'drop',
+}
+
+/** `selectedDateRange` reads a bucket's end off the next bucket's start, and leaves the last one
+ * open-ended at "now". That suits the viewer's sparkline, whose newest bucket is still filling,
+ * but every bucket here is a complete interval: an open end would pull in the current, uncharted
+ * interval on top of the one the user clicked. Appending the exclusive window end closes it. */
+export function clickableBucketTimes(times: string[]): string[] {
+ const last = times[times.length - 1]
+ const step = times.length > 1 ? Date.parse(times[1]) - Date.parse(times[0]) : 0
+ if (!(step > 0)) {
+ return times
}
- return { dateFrom: start, dateTo: new Date(Date.parse(end) + bucketMs).toISOString() }
+ return [...times, new Date(Date.parse(last) + step).toISOString()]
}
export interface AnomalyBandChartProps {
- buckets: LogsAnomalyScanBucketApi[]
- onZoom?: (range: ScanRange) => void
- onBucketClick?: (range: ScanRange) => void
+ buckets: LogsSeriesBandBucketApi[]
+ onBucketClick?: (dateRange: DateRange) => void
}
-export function AnomalyBandChart({ buckets, onZoom, onBucketClick }: AnomalyBandChartProps): JSX.Element {
+export function AnomalyBandChart({ buckets, onBucketClick }: AnomalyBandChartProps): JSX.Element {
const theme = useChartTheme()
const data = useMemo(() => buildBandChartData(buckets), [buckets])
@@ -87,76 +96,66 @@ export function AnomalyBandChart({ buckets, onZoom, onBucketClick }: AnomalyBand
[data.observed]
)
- // A verdict's color varies per bucket, which an area fill can't express, so the anomalous points
- // are their own overlay rather than a second series.
+ // A marker's color varies per bucket, which an area fill can't express, so the out-of-band
+ // points are their own overlay rather than a second series.
const markers = useMemo<AnomalyMarker[]>(
() =>
- buckets.flatMap((bucket, index) =>
- bucket.verdict
+ data.outOfBand.flatMap((state, index) =>
+ state
? [
{
dataIndex: index,
- value: bucket.observed,
- color: VERDICT_POINT_COLOR[bucket.verdict],
+ value: data.observed[index],
+ color: OUT_OF_BAND_POINT_COLOR[state],
yAxisId: DEFAULT_Y_AXIS_ID,
},
]
: []
),
- [buckets]
+ [data.outOfBand, data.observed]
)
const config = useChartConfig<TimeSeriesLineChartConfig>(
() => ({
- // Bucket times are UTC, and the scan's own timestamps around this chart render in the
- // viewer's zone, so the axis reads there too. The scan buckets at a fixed few minutes.
- xAxis: { timezone: dayjs.tz.guess(), interval: 'minute' },
+ // Bucket times are UTC, and the timestamps around this chart render in the viewer's
+ // zone, so the axis reads there too. The grain has to be stated: without it the axis
+ // builds no date formatter and prints raw ISO labels. The endpoint is hourly-only.
+ xAxis: { timezone: dayjs.tz.guess(), interval: 'hour' },
yAxis: { tickFormatter: humanFriendlyNumber },
confidenceIntervals: [{ seriesKey: OBSERVED_KEY, lower: data.lower, upper: data.upper }],
}),
[data.lower, data.upper]
)
- const onDateRangeZoom = useMemo(
- () =>
- onZoom
- ? ({ startIndex, endIndex }: DateRangeZoomData) => {
- const range = bucketRange(buckets, startIndex, endIndex)
- if (range) {
- onZoom(range)
- }
- }
- : undefined,
- [buckets, onZoom]
- )
-
- const onPointClick = useMemo(
- () =>
- onBucketClick
- ? ({ dataIndex }: PointClickData) => {
- const range = bucketRange(buckets, dataIndex, dataIndex)
- if (range) {
- onBucketClick(range)
- }
- }
- : undefined,
- [buckets, onBucketClick]
- )
+ const onPointClick = useMemo(() => {
+ if (!onBucketClick) {
+ return undefined
+ }
+ const clickTimes = clickableBucketTimes(data.labels)
+ return ({ dataIndex }: PointClickData) => {
+ const dateRange = selectedDateRange(clickTimes, dataIndex, dataIndex)
+ if (dateRange) {
+ onBucketClick(dateRange)
+ }
+ }
+ }, [data.labels, onBucketClick])
const renderTooltip = useCallback(
(ctx: TooltipContext): JSX.Element => {
const bucket = buckets[ctx.dataIndex]
- const verdict = bucket?.verdict
+ const outOfBand = data.outOfBand[ctx.dataIndex]
return (
<DefaultTooltip
{...ctx}
labelFormatter={(label) => dayjs(label).format('MMM D, HH:mm')}
- valueFormatter={(value) => `${humanFriendlyNumber(value)}${verdict ? ` (${verdict})` : ''}`}
+ valueFormatter={(value) =>
+ `${humanFriendlyNumber(value)}${outOfBand ? ` (${OUT_OF_BAND_LABEL[outOfBand]})` : ''}`
+ }
footer={bucket ? bandSummary(bucket) : null}
/>
)
},
- [buckets]
+ [buckets, data.outOfBand]
)
return (
@@ -168,7 +167,6 @@ export function AnomalyBandChart({ buckets, onZoom, onBucketClick }: AnomalyBand
theme={theme}
config={config}
tooltip={renderTooltip}
- onDateRangeZoom={onDateRangeZoom}
onPointClick={onPointClick}
dataAttr="logs-anomaly-band-chart"
>
@@ -178,11 +176,9 @@ export function AnomalyBandChart({ buckets, onZoom, onBucketClick }: AnomalyBand
)
}
-function bandSummary(bucket: LogsAnomalyScanBucketApi): string {
- if (bucket.expected == null || bucket.lower == null || bucket.upper == null) {
- return 'Not scored'
+function bandSummary(bucket: LogsSeriesBandBucketApi): string {
+ if (bucket.lower == null || bucket.upper == null) {
+ return 'No baseline yet'
}
- return `Expected ${humanFriendlyNumber(bucket.expected)} (band ${humanFriendlyNumber(
- bucket.lower
- )} to ${humanFriendlyNumber(bucket.upper)})`
+ return `Expected ${humanFriendlyNumber(bucket.lower)} to ${humanFriendlyNumber(bucket.upper)}`
}
diff --git a/products/logs/frontend/components/LogsServices/serviceViewerUrl.ts b/products/logs/frontend/components/LogsServices/serviceViewerUrl.ts
index e90c169f65b3..729953dd139f 100644
--- a/products/logs/frontend/components/LogsServices/serviceViewerUrl.ts
+++ b/products/logs/frontend/components/LogsServices/serviceViewerUrl.ts
@@ -4,15 +4,25 @@ import { lemonToast } from '@posthog/lemon-ui'
import { urls } from 'scenes/urls'
+import type { DateRange } from '~/queries/schema/schema-general'
+
+/** Extra viewer filters to pin alongside the service. Keys are the URL params logsSceneLogic reads. */
+export interface ServiceViewerFilters {
+ severityLevels?: string[]
+ dateRange?: DateRange
+}
+
/**
* Viewer tab scoped to one service. logsSceneLogic reads `serviceNames` back off the URL, and
* the list has to go in as a list: a scalar comes back through `parseTagsFilter`'s
- * comma-separated path, so `checkout,v2` would arrive as two services.
+ * comma-separated path, so `checkout,v2` would arrive as two services. Any severity list passed
+ * alongside it goes in the same way.
*/
-export function serviceViewerUrl(serviceName: string): string {
+export function serviceViewerUrl(serviceName: string, filters: ServiceViewerFilters = {}): string {
return combineUrl(urls.currentProject(urls.logs()), {
activeTab: 'viewer',
serviceNames: [serviceName],
+ ...filters,
}).url
}
diff --git a/products/logs/frontend/logsAnomaliesLogic.test.ts b/products/logs/frontend/logsAnomaliesLogic.test.ts
index a0923bd3306a..c7175e109ada 100644
--- a/products/logs/frontend/logsAnomaliesLogic.test.ts
+++ b/products/logs/frontend/logsAnomaliesLogic.test.ts
@@ -1,24 +1,34 @@
+import { router } from 'kea-router'
import { expectLogic } from 'kea-test-utils'
import { initKeaTests } from '~/test/init'
-import { logsAnomaliesScanCreate } from 'products/logs/frontend/generated/api'
+import { logsAnomaliesSeriesBandsCreate } from 'products/logs/frontend/generated/api'
+import type { LogsSeriesBandsResponseApi } from 'products/logs/frontend/generated/api.schemas'
-import { logsAnomaliesLogic } from './logsAnomaliesLogic'
+import { DEFAULT_VISIBLE_SERIES, logsAnomaliesLogic } from './logsAnomaliesLogic'
+
+function seriesBandsResponse(seriesCount: number): LogsSeriesBandsResponseApi {
+ return {
+ service_name: 'checkout',
+ window_start: '2026-08-10T10:00:00Z',
+ window_end: '2026-08-17T10:00:00Z',
+ interval_minutes: 60,
+ series_truncated: false,
+ series: Array.from({ length: seriesCount }, (_, index) => ({
+ namespace: 'ns',
+ environment: 'prod',
+ severity: `severity-${index}`,
+ total_count: 100 - index,
+ baseline_weeks: 5,
+ buckets: [],
+ })),
+ }
+}
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: [],
- }),
+ logsAnomaliesSeriesBandsCreate: jest.fn(),
}))
describe('logsAnomaliesLogic', () => {
@@ -26,49 +36,93 @@ describe('logsAnomaliesLogic', () => {
beforeEach(() => {
initKeaTests()
+ ;(logsAnomaliesSeriesBandsCreate as jest.Mock).mockResolvedValue(seriesBandsResponse(3))
logic = logsAnomaliesLogic()
logic.mount()
})
afterEach(() => {
logic.unmount()
+ jest.clearAllMocks()
})
- it('does not call the scan endpoint without a service', async () => {
+ it('does not call the endpoint without a service', async () => {
await expectLogic(logic, () => {
- logic.actions.runScan()
+ logic.actions.loadSeriesBands({})
}).toFinishAllListeners()
- expect(logsAnomaliesScanCreate).not.toHaveBeenCalled()
- expect(logic.values.scanDisabledReason).toBe('Pick a service to scan first')
+ expect(logsAnomaliesSeriesBandsCreate).not.toHaveBeenCalled()
+ expect(logic.values.seriesBands).toBeNull()
})
- it('scans with an absolute UTC window derived from the selected width', async () => {
- logic.actions.setServiceName('checkout')
- logic.actions.setWindowHours(6)
+ it('loads bands when a service is picked, and clears them on switch', async () => {
await expectLogic(logic, () => {
- logic.actions.runScan()
+ logic.actions.setServiceName('checkout')
}).toFinishAllListeners()
- expect(logsAnomaliesScanCreate).toHaveBeenCalledTimes(1)
- const [, body] = (logsAnomaliesScanCreate as jest.Mock).mock.calls[0]
+ expect(logsAnomaliesSeriesBandsCreate).toHaveBeenCalledTimes(1)
+ const [, body] = (logsAnomaliesSeriesBandsCreate 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')
+ expect(logic.values.seriesBands?.series).toHaveLength(3)
+
+ // The previous service's charts must not linger under the new selection.
+ await expectLogic(logic, () => {
+ logic.actions.setServiceName(null)
+ }).toFinishAllListeners()
+ expect(logic.values.seriesBands).toBeNull()
+ expect(logsAnomaliesSeriesBandsCreate).toHaveBeenCalledTimes(1)
})
- it('keeps the previous result until a new scan succeeds', async () => {
+ it('drops a slow response for a service the user has already left', async () => {
+ // The charts carry no service name of their own, so a late response landing under the
+ // new selection would be read as that service's volume.
+ let finishFirst: (response: LogsSeriesBandsResponseApi) => void = () => {}
+ ;(logsAnomaliesSeriesBandsCreate as jest.Mock)
+ .mockReturnValueOnce(new Promise<LogsSeriesBandsResponseApi>((resolve) => (finishFirst = resolve)))
+ .mockResolvedValueOnce(seriesBandsResponse(1))
+
logic.actions.setServiceName('checkout')
+ logic.actions.setServiceName('worker')
+ finishFirst(seriesBandsResponse(9))
+ await expectLogic(logic).toFinishAllListeners()
+
+ expect(logic.values.seriesBands?.series).toHaveLength(1)
+ })
+
+ it('sends a clicked bucket to the viewer as list filters', async () => {
+ // A scalar `serviceNames` or `severityLevels` is re-split on commas by the viewer's
+ // `parseTagsFilter`, so both have to arrive as lists.
+ await expectLogic(logic, () => {
+ logic.actions.setServiceName('checkout')
+ }).toFinishAllListeners()
+
+ await expectLogic(logic, () => {
+ logic.actions.openLogsForBucket('error', {
+ date_from: '2026-08-17T09:00:00Z',
+ date_to: '2026-08-17T10:00:00Z',
+ })
+ }).toFinishAllListeners()
+
+ expect(router.values.searchParams).toMatchObject({
+ activeTab: 'viewer',
+ serviceNames: ['checkout'],
+ severityLevels: ['error'],
+ dateRange: { date_from: '2026-08-17T09:00:00Z', date_to: '2026-08-17T10:00:00Z' },
+ })
+ })
+
+ it('slices visible series and grows the window on show more', async () => {
+ ;(logsAnomaliesSeriesBandsCreate as jest.Mock).mockResolvedValue(
+ seriesBandsResponse(DEFAULT_VISIBLE_SERIES + 3)
+ )
await expectLogic(logic, () => {
- logic.actions.runScan()
+ logic.actions.setServiceName('checkout')
}).toFinishAllListeners()
- const firstResult = logic.values.scanResult
- logic.actions.setServiceName('other-service')
- expect(logic.values.scanResult).toBe(firstResult)
+ expect(logic.values.visibleSeries).toHaveLength(DEFAULT_VISIBLE_SERIES)
+ expect(logic.values.hiddenSeriesCount).toBe(3)
+
+ logic.actions.showMoreSeries()
+ expect(logic.values.visibleSeries).toHaveLength(DEFAULT_VISIBLE_SERIES + 3)
+ expect(logic.values.hiddenSeriesCount).toBe(0)
})
})
diff --git a/products/logs/frontend/logsAnomaliesLogic.tsx b/products/logs/frontend/logsAnomaliesLogic.tsx
index e308eb02bb23..85a0ec5343b3 100644
--- a/products/logs/frontend/logsAnomaliesLogic.tsx
+++ b/products/logs/frontend/logsAnomaliesLogic.tsx
@@ -1,78 +1,69 @@
import { MakeLogicType, actions, connect, kea, listeners, path, reducers, selectors } from 'kea'
import { loaders } from 'kea-loaders'
+import { router } from 'kea-router'
-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' },
-]
+import type { DateRange } from '~/queries/schema/schema-general'
-export const DEFAULT_SCAN_WINDOW_HOURS = 24
+import { serviceViewerUrl } from 'products/logs/frontend/components/LogsServices/serviceViewerUrl'
+import { logsAnomaliesSeriesBandsCreate } from 'products/logs/frontend/generated/api'
+import type { LogsSeriesBandSeriesApi, LogsSeriesBandsResponseApi } from 'products/logs/frontend/generated/api.schemas'
-/** An explicit window dragged out on a chart, which overrides the preset until it is cleared. */
-export interface ScanRange {
- dateFrom: string
- dateTo: string
-}
+export const DEFAULT_VISIBLE_SERIES = 12
// 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
+ hiddenSeriesCount: number
+ seriesBands: LogsSeriesBandsResponseApi | null
+ seriesBandsError: string | null
+ seriesBandsLoading: boolean
serviceName: string | null
- windowHours: number
- zoomedRange: ScanRange | null
+ visibleSeries: LogsSeriesBandSeriesApi[]
+ visibleSeriesCount: number
}
// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface logsAnomaliesLogicActions {
- resetZoom: () => {
- value: true
- }
- runScan: () => any
- runScanFailure: (
+ loadSeriesBands: (_: any) => any
+ loadSeriesBandsFailure: (
error: string,
errorObject?: any
) => {
error: string
errorObject?: any
}
- runScanSuccess: (
- scanResult: LogsAnomalyScanResponseApi | null,
+ loadSeriesBandsSuccess: (
+ seriesBands: LogsSeriesBandsResponseApi | null,
payload?: any
) => {
- scanResult: LogsAnomalyScanResponseApi | null
+ seriesBands: LogsSeriesBandsResponseApi | null
payload?: any
}
+ openLogsForBucket: (
+ severity: string,
+ dateRange: DateRange
+ ) => {
+ dateRange: DateRange
+ severity: string
+ }
setServiceName: (serviceName: string | null) => {
serviceName: string | null
}
- setWindowHours: (windowHours: number) => {
- windowHours: number
- }
- zoomToRange: (range: ScanRange) => {
- range: ScanRange
+ showMoreSeries: () => {
+ value: true
}
}
// 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
+ visibleSeries: (
+ seriesBands: LogsSeriesBandsResponseApi | null,
+ visibleSeriesCount: number
+ ) => LogsSeriesBandSeriesApi[]
+ hiddenSeriesCount: (seriesBands: LogsSeriesBandsResponseApi | null, visibleSeriesCount: number) => number
}
}
@@ -88,27 +79,24 @@ export const logsAnomaliesLogic = kea<logsAnomaliesLogicType>([
connect(() => ({ values: [teamLogic, ['currentTeamId']] })),
actions({
setServiceName: (serviceName: string | null) => ({ serviceName }),
- setWindowHours: (windowHours: number) => ({ windowHours }),
- zoomToRange: (range: ScanRange) => ({ range }),
- resetZoom: true,
+ showMoreSeries: true,
+ openLogsForBucket: (severity: string, dateRange: DateRange) => ({ severity, dateRange }),
}),
loaders(({ values }) => ({
- scanResult: [
- null as LogsAnomalyScanResponseApi | null,
+ seriesBands: [
+ null as LogsSeriesBandsResponseApi | null,
{
- runScan: async () => {
+ loadSeriesBands: async (_, breakpoint) => {
if (!values.serviceName || !values.currentTeamId) {
- return values.scanResult
+ return null
}
- const now = dayjs.utc()
- const { zoomedRange } = values
- return await logsAnomaliesScanCreate(String(values.currentTeamId), {
+ const response = await logsAnomaliesSeriesBandsCreate(String(values.currentTeamId), {
serviceName: values.serviceName,
- dateRange: {
- date_from: zoomedRange?.dateFrom ?? now.subtract(values.windowHours, 'hour').toISOString(),
- date_to: zoomedRange?.dateTo ?? now.toISOString(),
- },
})
+ // A slow service can resolve after the user has moved to another one. Without
+ // this the late response would chart itself under the new service's name.
+ breakpoint()
+ return response
},
},
],
@@ -120,44 +108,53 @@ export const logsAnomaliesLogic = kea<logsAnomaliesLogicType>([
setServiceName: (_, { serviceName }) => serviceName,
},
],
- windowHours: [
- DEFAULT_SCAN_WINDOW_HOURS as number,
+ // Charts from the previous service would misread as the new one, so a
+ // service switch drops straight to the loading state.
+ seriesBands: {
+ setServiceName: () => null,
+ },
+ // The loader leaves the value null on failure, which reads the same as "still loading",
+ // so the failure needs its own value for the tab to show a retry instead of a spinner.
+ seriesBandsError: [
+ null as string | null,
{
- setWindowHours: (_, { windowHours }) => windowHours,
+ setServiceName: () => null,
+ loadSeriesBands: () => null,
+ loadSeriesBandsSuccess: () => null,
+ loadSeriesBandsFailure: (_, { error }) => error || 'The request did not complete.',
},
],
- zoomedRange: [
- null as ScanRange | null,
+ visibleSeriesCount: [
+ DEFAULT_VISIBLE_SERIES as number,
{
- zoomToRange: (_, { range }) => range,
- resetZoom: () => null,
- // Picking a preset is the other way back out of a zoom.
- setWindowHours: () => null,
+ setServiceName: () => DEFAULT_VISIBLE_SERIES,
+ showMoreSeries: (state) => state + DEFAULT_VISIBLE_SERIES,
},
],
}),
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
- },
+ visibleSeries: [
+ (s) => [s.seriesBands, s.visibleSeriesCount],
+ (seriesBands: LogsSeriesBandsResponseApi | null, visibleSeriesCount: number): LogsSeriesBandSeriesApi[] =>
+ seriesBands ? seriesBands.series.slice(0, visibleSeriesCount) : [],
+ ],
+ hiddenSeriesCount: [
+ (s) => [s.seriesBands, s.visibleSeriesCount],
+ (seriesBands: LogsSeriesBandsResponseApi | null, visibleSeriesCount: number): number =>
+ seriesBands ? Math.max(0, seriesBands.series.length - visibleSeriesCount) : 0,
],
}),
- listeners(({ actions }) => ({
- runScanFailure: ({ error }) => {
- // ApiError already extracts the endpoint's { error } body into the message.
- lemonToast.error(error || 'The anomaly scan failed. Try a shorter window.')
+ listeners(({ actions, values }) => ({
+ setServiceName: ({ serviceName }) => {
+ if (serviceName) {
+ actions.loadSeriesBands({})
+ }
+ },
+ openLogsForBucket: ({ severity, dateRange }) => {
+ if (!values.serviceName) {
+ return
+ }
+ router.actions.push(serviceViewerUrl(values.serviceName, { severityLevels: [severity], dateRange }))
},
- // Zooming rescans on its own, because a drag that left the previous window on screen would
- // read as having done nothing. The preset select keeps its explicit Scan button.
- zoomToRange: () => actions.runScan(),
- resetZoom: () => actions.runScan(),
})),
])