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): preview matched volume and projected storage in retention rules (#77166)

Frank Hamand24d86e300ad5
diff --git a/products/logs/frontend/components/LogsFilterPreview/LogsFilterVolumeSparkline.test.tsx b/products/logs/frontend/components/LogsFilterPreview/LogsFilterVolumeSparkline.test.tsx
new file mode 100644
index 000000000000..58fb8ecf4bde
--- /dev/null
+++ b/products/logs/frontend/components/LogsFilterPreview/LogsFilterVolumeSparkline.test.tsx
@@ -0,0 +1,91 @@
+import { cleanup, render, screen, waitFor } from '@testing-library/react'
+
+import { useMocks } from '~/mocks/jest'
+import { initKeaTests } from '~/test/init'
+import { FilterLogicalOperator, UniversalFiltersGroup } from '~/types'
+
+import { LogsFilterVolumeSparkline } from './LogsFilterVolumeSparkline'
+
+// The chart itself is Chart.js/quill and needs a canvas; we only care about which state the
+// component decides to render and what it hands the chart.
+jest.mock('lib/components/Sparkline', () => ({
+ Sparkline: ({ loading, data }: { loading?: boolean; data: unknown[] }) => (
+ <div data-attr="sparkline" data-loading={loading ? 'true' : 'false'} data-series={data.length} />
+ ),
+}))
+
+const EMPTY_GROUP: UniversalFiltersGroup = { type: FilterLogicalOperator.And, values: [] }
+const NON_EMPTY_GROUP: UniversalFiltersGroup = {
+ type: FilterLogicalOperator.And,
+ values: [{ key: 'service.name', type: 'log_resource_attribute', operator: 'exact', value: 'api' } as never],
+}
+
+describe('LogsFilterVolumeSparkline', () => {
+ let sparklineCalls: number
+
+ beforeEach(() => {
+ sparklineCalls = 0
+ useMocks({
+ post: {
+ '/api/environments/:team_id/logs/sparkline/': () => {
+ sparklineCalls += 1
+ return [
+ 200,
+ [
+ { time: '2026-08-04T11:00:00Z', service: 'api', count: 3, bytes_uncompressed: 2048 },
+ { time: '2026-08-04T11:30:00Z', service: 'api', count: 4, bytes_uncompressed: 4096 },
+ ],
+ ]
+ },
+ },
+ })
+ initKeaTests()
+ })
+
+ // This suite's jest setup doesn't auto-cleanup, so unmount explicitly or `screen` queries
+ // match leftover trees from earlier tests.
+ afterEach(cleanup)
+
+ it('prompts for a filter and does not query when the group is empty', async () => {
+ render(<LogsFilterVolumeSparkline filterGroup={EMPTY_GROUP} metric="bytes" />)
+
+ expect(screen.getByText('Add a filter above to preview matching log volume')).toBeTruthy()
+ await waitFor(() => expect(sparklineCalls).toEqual(0))
+ })
+
+ it('loads on mount for a pre-filled group and renders the chart with the total', async () => {
+ render(<LogsFilterVolumeSparkline filterGroup={NON_EMPTY_GROUP} metric="bytes" />)
+
+ await waitFor(() => expect(screen.getByTestId('sparkline').dataset.loading).toEqual('false'))
+ expect(sparklineCalls).toEqual(1)
+ expect(screen.getByText('6.1 KB')).toBeTruthy()
+ })
+
+ it('formats the header total as a log count for the count metric', async () => {
+ render(<LogsFilterVolumeSparkline filterGroup={NON_EMPTY_GROUP} metric="count" />)
+
+ await waitFor(() => expect(screen.getByText('7 logs')).toBeTruthy())
+ })
+
+ it('does not refetch when a re-render passes an equal-but-new filter group object', async () => {
+ const { rerender } = render(<LogsFilterVolumeSparkline filterGroup={NON_EMPTY_GROUP} metric="bytes" />)
+ await waitFor(() => expect(sparklineCalls).toEqual(1))
+
+ rerender(<LogsFilterVolumeSparkline filterGroup={{ ...NON_EMPTY_GROUP }} metric="bytes" />)
+
+ await waitFor(() => expect(screen.getByTestId('sparkline')).toBeTruthy())
+ expect(sparklineCalls).toEqual(1)
+ })
+
+ it('renders the caption from the loaded points', async () => {
+ render(
+ <LogsFilterVolumeSparkline
+ filterGroup={NON_EMPTY_GROUP}
+ metric="bytes"
+ renderCaption={({ points, total }) => <div>{`${points?.length} points, ${total} bytes`}</div>}
+ />
+ )
+
+ await waitFor(() => expect(screen.getByText('2 points, 6144 bytes')).toBeTruthy())
+ })
+})
diff --git a/products/logs/frontend/components/LogsFilterPreview/LogsFilterVolumeSparkline.tsx b/products/logs/frontend/components/LogsFilterPreview/LogsFilterVolumeSparkline.tsx
new file mode 100644
index 000000000000..6fc270296f0d
--- /dev/null
+++ b/products/logs/frontend/components/LogsFilterPreview/LogsFilterVolumeSparkline.tsx
@@ -0,0 +1,121 @@
+import { useActions, useValues } from 'kea'
+import { useEffect, useId, useMemo } from 'react'
+
+import { LemonButton } from '@posthog/lemon-ui'
+
+import { Sparkline, SparklineReferenceLine } from 'lib/components/Sparkline'
+
+import { UniversalFiltersGroup } from '~/types'
+
+import {
+ LogsFilterPreviewMetric,
+ LogsFilterPreviewPoint,
+ LogsFilterPreviewSeriesData,
+ SPARKLINE_ROW_LIMIT,
+ TOP_SERVICES_LIMIT,
+ buildSparklineSeries,
+ formatBytes,
+} from './logsFilterVolumePreview'
+import { logsFilterVolumePreviewLogic } from './logsFilterVolumePreviewLogic'
+
+export interface LogsFilterVolumeSparklineRenderInfo extends LogsFilterPreviewSeriesData {
+ points: LogsFilterPreviewPoint[] | null
+ /** The response hit the backend row cap, so the newest buckets are missing. */
+ truncated: boolean
+}
+
+export interface LogsFilterVolumeSparklineProps {
+ filterGroup: UniversalFiltersGroup
+ metric: LogsFilterPreviewMetric
+ /** Overrides the auto-generated logic key; only needed by stories and tests. */
+ previewKey?: string
+ /** Threshold lines in the chart's own units, which depend on the resolved bucket width. */
+ buildReferenceLines?: (info: LogsFilterVolumeSparklineRenderInfo) => SparklineReferenceLine[] | undefined
+ /** Rendered under the chart once data has loaded (rate-limit note, retention projection). */
+ renderCaption?: (info: LogsFilterVolumeSparklineRenderInfo) => JSX.Element | null
+}
+
+/**
+ * Live preview of the log volume a filter group matches over the last 24h, broken down by service.
+ * Shared by the drop-rule and retention-rule editors — one request serves both metrics, since each
+ * row carries `count` and `bytes_uncompressed`.
+ */
+export function LogsFilterVolumeSparkline({
+ filterGroup,
+ metric,
+ previewKey,
+ buildReferenceLines,
+ renderCaption,
+}: LogsFilterVolumeSparklineProps): JSX.Element {
+ const generatedKey = useId()
+ const logic = logsFilterVolumePreviewLogic({ previewKey: previewKey ?? generatedKey })
+ const { filterPreview, filterPreviewLoading } = useValues(logic)
+ const { setFilterGroup, refreshFilterPreview } = useActions(logic)
+
+ const hasFilters = filterGroup.values.length > 0
+
+ // Serialized so a re-render handing us a fresh-but-equal object doesn't re-fire the request.
+ // Mounting runs this too, which covers the edit-mode case of opening a form with filters already set.
+ const serializedFilterGroup = useMemo(() => JSON.stringify(filterGroup), [filterGroup])
+ useEffect(() => {
+ setFilterGroup(filterGroup)
+ // eslint-disable-next-line react-hooks/exhaustive-deps
+ }, [serializedFilterGroup])
+
+ const seriesData = useMemo(() => buildSparklineSeries(filterPreview, metric), [filterPreview, metric])
+ const renderInfo = useMemo<LogsFilterVolumeSparklineRenderInfo>(
+ () => ({
+ ...seriesData,
+ points: filterPreview,
+ truncated: (filterPreview?.length ?? 0) >= SPARKLINE_ROW_LIMIT,
+ }),
+ [seriesData, filterPreview]
+ )
+
+ const formattedTotal =
+ metric === 'bytes' ? formatBytes(seriesData.total) : `${seriesData.total.toLocaleString()} logs`
+ const referenceLines = buildReferenceLines?.(renderInfo)
+ const caption = filterPreview && !filterPreviewLoading ? renderCaption?.(renderInfo) : null
+
+ return (
+ <div className="mt-3 flex flex-col gap-1">
+ <div className="flex items-center justify-between text-xs text-muted">
+ <span>
+ Volume preview by service (last 24h, top {TOP_SERVICES_LIMIT}
+ {metric === 'bytes' ? ', bytes' : ''})
+ </span>
+ {hasFilters && !filterPreviewLoading ? <span>{formattedTotal}</span> : null}
+ </div>
+ <div className="relative h-24 border border-border rounded-md bg-bg-light px-2 py-1">
+ {!hasFilters ? (
+ <div className="h-full flex items-center justify-center text-muted text-xs">
+ Add a filter above to preview matching log volume
+ </div>
+ ) : filterPreviewLoading ? (
+ <Sparkline data={[]} labels={[]} loading className="w-full h-full" maximumIndicator={false} />
+ ) : !filterPreview ? (
+ <div className="h-full flex flex-col gap-1 items-center justify-center text-muted text-xs">
+ <span>Couldn't load the volume preview.</span>
+ <LemonButton size="xsmall" type="secondary" onClick={refreshFilterPreview}>
+ Retry
+ </LemonButton>
+ </div>
+ ) : seriesData.series.length === 0 ? (
+ <div className="h-full flex items-center justify-center text-muted text-xs">
+ No logs match these filters in the last 24h
+ </div>
+ ) : (
+ <Sparkline
+ data={seriesData.series}
+ labels={seriesData.labels}
+ className="w-full h-full"
+ maximumIndicator={false}
+ referenceLines={referenceLines}
+ renderTooltipValue={metric === 'bytes' ? formatBytes : undefined}
+ />
+ )}
+ </div>
+ {caption}
+ </div>
+ )
+}
diff --git a/products/logs/frontend/components/LogsFilterPreview/logsFilterVolumePreview.test.ts b/products/logs/frontend/components/LogsFilterPreview/logsFilterVolumePreview.test.ts
new file mode 100644
index 000000000000..dacdcec8959a
--- /dev/null
+++ b/products/logs/frontend/components/LogsFilterPreview/logsFilterVolumePreview.test.ts
@@ -0,0 +1,84 @@
+import { LogsFilterPreviewPoint, buildSparklineSeries, formatBytes } from './logsFilterVolumePreview'
+
+const point = (time: string, service: string, count: number, bytes?: number): LogsFilterPreviewPoint => ({
+ time,
+ service,
+ count,
+ bytes_uncompressed: bytes,
+})
+
+const T1 = '2026-08-04T11:00:00Z'
+const T2 = '2026-08-04T11:30:00Z'
+
+describe('buildSparklineSeries', () => {
+ it('stacks one series per service in bucket order', () => {
+ const data = buildSparklineSeries([point(T1, 'api', 3), point(T1, 'worker', 1), point(T2, 'api', 5)], 'count')
+
+ expect(data.series).toEqual([
+ expect.objectContaining({ name: 'api', values: [3, 5] }),
+ expect.objectContaining({ name: 'worker', values: [1, 0] }),
+ ])
+ expect(data.total).toEqual(9)
+ expect(data.chartMax).toEqual(5)
+ expect(data.bucketSeconds).toEqual(1800)
+ expect(data.bucketCount).toEqual(2)
+ expect(data.firstBucketTime).toEqual(T1)
+ })
+
+ it('rolls the long tail past the top 10 into one Others series, preserving the total', () => {
+ const points = Array.from({ length: 13 }, (_, i) => point(T1, `svc-${i}`, 13 - i))
+ const data = buildSparklineSeries(points, 'count')
+
+ expect(data.series).toHaveLength(11)
+ expect(data.series[10].name).toEqual('Others (3 services)')
+ // svc-10..svc-12 rank last, contributing 3 + 2 + 1.
+ expect(data.series[10].values).toEqual([6])
+ expect(data.truncatedServiceCount).toEqual(3)
+ expect(data.series.reduce((sum, s) => sum + s.values[0], 0)).toEqual(data.total)
+ })
+
+ it('reads bytes_uncompressed for the bytes metric and treats a missing value as zero', () => {
+ const points = [point(T1, 'api', 100, 2048), point(T2, 'api', 100)]
+
+ expect(buildSparklineSeries(points, 'bytes').total).toEqual(2048)
+ expect(buildSparklineSeries(points, 'count').total).toEqual(200)
+ })
+
+ it.each(['__proto__', 'constructor', 'toString'])(
+ 'handles an ingested service name of %p without crashing',
+ (service) => {
+ // Service names come from ingested logs. With a plain-object accumulator these keys
+ // resolve to inherited values instead of a bucket and throw on `.set`.
+ const data = buildSparklineSeries([point(T1, service, 2), point(T2, service, 3)], 'count')
+
+ expect(data.series).toEqual([expect.objectContaining({ name: service, values: [2, 3] })])
+ expect(data.total).toEqual(5)
+ }
+ )
+
+ it('labels a blank service as unknown', () => {
+ expect(buildSparklineSeries([point(T1, '', 1)], 'count').series[0].name).toEqual('unknown')
+ })
+
+ it('returns an empty shape for no data', () => {
+ for (const points of [null, []]) {
+ const data = buildSparklineSeries(points, 'bytes')
+ expect(data.series).toEqual([])
+ expect(data.total).toEqual(0)
+ expect(data.bucketCount).toEqual(0)
+ expect(data.firstBucketTime).toBeNull()
+ }
+ })
+})
+
+describe('formatBytes', () => {
+ it('scales through to PB so multi-week retained totals stay readable', () => {
+ expect(formatBytes(512)).toEqual('512 B')
+ expect(formatBytes(2048)).toEqual('2.0 KB')
+ expect(formatBytes(5_500_000)).toEqual('5.5 MB')
+ expect(formatBytes(15_000_000_000)).toEqual('15.00 GB')
+ expect(formatBytes(450_000_000_000)).toEqual('450.00 GB')
+ expect(formatBytes(13_500_000_000_000)).toEqual('13.50 TB')
+ expect(formatBytes(2_500_000_000_000_000)).toEqual('2.50 PB')
+ })
+})
diff --git a/products/logs/frontend/components/LogsFilterPreview/logsFilterVolumePreview.ts b/products/logs/frontend/components/LogsFilterPreview/logsFilterVolumePreview.ts
new file mode 100644
index 000000000000..21dcd0cfcad2
--- /dev/null
+++ b/products/logs/frontend/components/LogsFilterPreview/logsFilterVolumePreview.ts
@@ -0,0 +1,125 @@
+import { dataColorVars } from 'lib/colors'
+import { SparklineTimeSeries } from 'lib/components/Sparkline'
+import { dayjs } from 'lib/dayjs'
+
+export const TOP_SERVICES_LIMIT = 10
+
+/**
+ * Mirrors the `LIMIT 1000` in `products/logs/backend/sparkline_query_runner.py`. Rows are
+ * (bucket × service), and the query orders by time ascending — so once the cap is hit it's the
+ * *newest* buckets that get dropped, and any total derived from the response is an undercount.
+ */
+export const SPARKLINE_ROW_LIMIT = 1000
+
+export type LogsFilterPreviewMetric = 'count' | 'bytes'
+
+export interface LogsFilterPreviewPoint {
+ time: string
+ service: string
+ count: number
+ bytes_uncompressed?: number
+}
+
+export interface LogsFilterPreviewSeriesData {
+ labels: string[]
+ series: SparklineTimeSeries[]
+ total: number
+ truncatedServiceCount: number
+ /** Width of one bar/bucket in seconds; needed to translate a per-second rate limit into per-bucket units. */
+ bucketSeconds: number
+ /** Tallest stacked total across buckets; used to position the rate-limit reference line. */
+ chartMax: number
+ bucketCount: number
+ firstBucketTime: string | null
+}
+
+export function buildSparklineSeries(
+ points: LogsFilterPreviewPoint[] | null,
+ metric: LogsFilterPreviewMetric
+): LogsFilterPreviewSeriesData {
+ const timeOrder: string[] = []
+ const seenTimes = new Set<string>()
+ // A Map, not a plain object: service names come from ingested logs, so a log claiming
+ // `service.name: "__proto__"` would otherwise resolve to an inherited value instead of a
+ // bucket and throw on `.set`, taking the whole editor down.
+ const byService = new Map<string, Map<string, number>>()
+ const serviceTotals = new Map<string, number>()
+ const bucketTotals = new Map<string, number>()
+ let total = 0
+ // No early return for the empty case — the accumulators below already yield the zeroed shape,
+ // so a separate literal would just be a second copy of it to keep in sync.
+ for (const point of points ?? []) {
+ if (!seenTimes.has(point.time)) {
+ seenTimes.add(point.time)
+ timeOrder.push(point.time)
+ }
+ const svc = point.service || 'unknown'
+ const value = metric === 'bytes' ? (point.bytes_uncompressed ?? 0) : point.count
+ let bucket = byService.get(svc)
+ if (!bucket) {
+ bucket = new Map()
+ byService.set(svc, bucket)
+ }
+ bucket.set(point.time, (bucket.get(point.time) ?? 0) + value)
+ serviceTotals.set(svc, (serviceTotals.get(svc) ?? 0) + value)
+ bucketTotals.set(point.time, (bucketTotals.get(point.time) ?? 0) + value)
+ total += value
+ }
+ const labels = timeOrder.map((t) => dayjs(t).format('D MMM HH:mm'))
+ const rankedServices = Array.from(serviceTotals.entries()).sort(([, a], [, b]) => b - a)
+ const topServices = rankedServices.slice(0, TOP_SERVICES_LIMIT)
+ const otherServices = rankedServices.slice(TOP_SERVICES_LIMIT)
+ const truncatedServiceCount = otherServices.length
+ const series: SparklineTimeSeries[] = topServices.map(([service], index) => ({
+ name: service,
+ color: dataColorVars[index % dataColorVars.length],
+ values: timeOrder.map((t) => byService.get(service)?.get(t) ?? 0),
+ }))
+ if (otherServices.length > 0) {
+ // Roll up the long tail into a single "Others" series so the chart still adds up to total volume,
+ // and the rate-limit reference line lines up against an honest stacked max.
+ const othersValues = timeOrder.map((t) =>
+ otherServices.reduce((sum, [service]) => sum + (byService.get(service)?.get(t) ?? 0), 0)
+ )
+ series.push({
+ name: `Others (${otherServices.length} services)`,
+ color: 'muted',
+ values: othersValues,
+ })
+ }
+ const bucketSeconds = timeOrder.length >= 2 ? dayjs(timeOrder[1]).diff(dayjs(timeOrder[0]), 'second') : 0
+ const chartMax = Math.max(0, ...Array.from(bucketTotals.values()))
+ return {
+ labels,
+ series,
+ total,
+ truncatedServiceCount,
+ bucketSeconds,
+ chartMax,
+ bucketCount: timeOrder.length,
+ firstBucketTime: timeOrder[0] ?? null,
+ }
+}
+
+/**
+ * Decimal (1000-based) units, matching how logs usage is billed in `posthog/tasks/usage_report.py`.
+ * Goes up to PB because a multi-week retained total is routinely several TB.
+ */
+export function formatBytes(bytes: number): string {
+ if (bytes < 1000) {
+ return `${bytes.toLocaleString()} B`
+ }
+ if (bytes < 1_000_000) {
+ return `${(bytes / 1000).toFixed(1)} KB`
+ }
+ if (bytes < 1_000_000_000) {
+ return `${(bytes / 1_000_000).toFixed(1)} MB`
+ }
+ if (bytes < 1_000_000_000_000) {
+ return `${(bytes / 1_000_000_000).toFixed(2)} GB`
+ }
+ if (bytes < 1_000_000_000_000_000) {
+ return `${(bytes / 1_000_000_000_000).toFixed(2)} TB`
+ }
+ return `${(bytes / 1_000_000_000_000_000).toFixed(2)} PB`
+}
diff --git a/products/logs/frontend/components/LogsFilterPreview/logsFilterVolumePreviewLogic.test.ts b/products/logs/frontend/components/LogsFilterPreview/logsFilterVolumePreviewLogic.test.ts
new file mode 100644
index 000000000000..55f1389198d0
--- /dev/null
+++ b/products/logs/frontend/components/LogsFilterPreview/logsFilterVolumePreviewLogic.test.ts
@@ -0,0 +1,91 @@
+import { expectLogic } from 'kea-test-utils'
+
+import { useMocks } from '~/mocks/jest'
+import { initKeaTests } from '~/test/init'
+import { FilterLogicalOperator, UniversalFiltersGroup } from '~/types'
+
+import { logsFilterVolumePreviewLogic } from './logsFilterVolumePreviewLogic'
+
+const SPARKLINE_ROWS = [{ time: '2026-08-04T11:00:00Z', service: 'api', count: 3, bytes_uncompressed: 2048 }]
+
+const nonEmptyGroup: UniversalFiltersGroup = {
+ type: FilterLogicalOperator.And,
+ values: [{ key: 'service.name', type: 'log_resource_attribute', operator: 'exact', value: 'api' } as never],
+}
+
+describe('logsFilterVolumePreviewLogic', () => {
+ let logic: ReturnType<typeof logsFilterVolumePreviewLogic.build>
+ let sparklineCalls: number
+ let sparklineFails: boolean
+
+ beforeEach(() => {
+ sparklineCalls = 0
+ sparklineFails = false
+ useMocks({
+ post: {
+ '/api/environments/:team_id/logs/sparkline/': () => {
+ sparklineCalls += 1
+ return sparklineFails ? [500, { detail: 'boom' }] : [200, SPARKLINE_ROWS]
+ },
+ },
+ })
+ initKeaTests()
+ logic = logsFilterVolumePreviewLogic({ previewKey: 'test' })
+ logic.mount()
+ })
+
+ afterEach(() => {
+ logic.unmount()
+ })
+
+ it('does not query for an empty filter group', async () => {
+ await expectLogic(logic, () => {
+ logic.actions.setFilterGroup({ type: FilterLogicalOperator.And, values: [] })
+ }).toFinishAllListeners()
+
+ expect(logic.values.filterPreview).toBeNull()
+ expect(sparklineCalls).toEqual(0)
+ })
+
+ it('loads the preview for a non-empty filter group', async () => {
+ await expectLogic(logic, () => {
+ logic.actions.setFilterGroup(nonEmptyGroup)
+ })
+ .toDispatchActions(['loadFilterPreviewSuccess'])
+ .toFinishAllListeners()
+
+ expect(logic.values.filterPreview).toEqual(SPARKLINE_ROWS)
+ expect(sparklineCalls).toEqual(1)
+ })
+
+ it('drops the previous result when a later filter fails to load', async () => {
+ await expectLogic(logic, () => {
+ logic.actions.setFilterGroup(nonEmptyGroup)
+ })
+ .toDispatchActions(['loadFilterPreviewSuccess'])
+ .toFinishAllListeners()
+ expect(logic.values.filterPreview).toEqual(SPARKLINE_ROWS)
+
+ // Without clearing on failure, this stale value would be charted — and projected from —
+ // as if it described the newly selected filter.
+ sparklineFails = true
+ await expectLogic(logic, () => {
+ logic.actions.setFilterGroup({ ...nonEmptyGroup, type: FilterLogicalOperator.Or })
+ })
+ .toDispatchActions(['loadFilterPreviewFailure'])
+ .toFinishAllListeners()
+
+ expect(logic.values.filterPreview).toBeNull()
+ })
+
+ it('debounces rapid filter edits into a single request', async () => {
+ await expectLogic(logic, () => {
+ logic.actions.setFilterGroup(nonEmptyGroup)
+ logic.actions.setFilterGroup({ ...nonEmptyGroup, type: FilterLogicalOperator.Or })
+ })
+ .toDispatchActions(['loadFilterPreviewSuccess'])
+ .toFinishAllListeners()
+
+ expect(sparklineCalls).toEqual(1)
+ })
+})
diff --git a/products/logs/frontend/components/LogsFilterPreview/logsFilterVolumePreviewLogic.ts b/products/logs/frontend/components/LogsFilterPreview/logsFilterVolumePreviewLogic.ts
new file mode 100644
index 000000000000..e8c656312c8a
--- /dev/null
+++ b/products/logs/frontend/components/LogsFilterPreview/logsFilterVolumePreviewLogic.ts
@@ -0,0 +1,133 @@
+import { MakeLogicType, actions, kea, key, listeners, path, props, reducers } from 'kea'
+import { loaders } from 'kea-loaders'
+
+import api from 'lib/api'
+
+import { FilterLogicalOperator, PropertyGroupFilter, UniversalFiltersGroup } from '~/types'
+
+import { LogsFilterPreviewPoint } from './logsFilterVolumePreview'
+
+const EMPTY_FILTER_GROUP: UniversalFiltersGroup = {
+ type: FilterLogicalOperator.And,
+ values: [],
+}
+
+/** Wrap inner group as the alerts / logs-viewer wire format expects. */
+function wrapFilterGroup(inner: UniversalFiltersGroup): UniversalFiltersGroup {
+ return { type: FilterLogicalOperator.And, values: [inner] as never }
+}
+
+function isFilterGroupNonEmpty(group: UniversalFiltersGroup): boolean {
+ return Array.isArray(group.values) && group.values.length > 0
+}
+
+export interface LogsFilterVolumePreviewLogicProps {
+ /** Isolates one mounted preview from another. Callers normally pass a `useId()`. */
+ previewKey: string
+}
+
+// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
+export interface logsFilterVolumePreviewLogicValues {
+ filterGroup: UniversalFiltersGroup
+ filterPreview: LogsFilterPreviewPoint[] | null
+ filterPreviewLoading: boolean
+}
+
+// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
+export interface logsFilterVolumePreviewLogicActions {
+ loadFilterPreview: (_: any) => any
+ loadFilterPreviewFailure: (
+ error: string,
+ errorObject?: any
+ ) => {
+ error: string
+ errorObject?: any
+ }
+ loadFilterPreviewSuccess: (
+ filterPreview: LogsFilterPreviewPoint[] | null,
+ payload?: any
+ ) => {
+ filterPreview: LogsFilterPreviewPoint[] | null
+ payload?: any
+ }
+ refreshFilterPreview: () => {
+ value: true
+ }
+ setFilterGroup: (filterGroup: UniversalFiltersGroup) => {
+ filterGroup: UniversalFiltersGroup
+ }
+}
+
+// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
+export interface logsFilterVolumePreviewLogicMeta {
+ key: string
+}
+
+export type logsFilterVolumePreviewLogicType = MakeLogicType<
+ logsFilterVolumePreviewLogicValues,
+ logsFilterVolumePreviewLogicActions,
+ LogsFilterVolumePreviewLogicProps,
+ logsFilterVolumePreviewLogicMeta
+>
+
+export const logsFilterVolumePreviewLogic = kea<logsFilterVolumePreviewLogicType>([
+ path(['products', 'logs', 'frontend', 'components', 'LogsFilterPreview', 'logsFilterVolumePreviewLogic']),
+ props({} as LogsFilterVolumePreviewLogicProps),
+ key(({ previewKey }) => previewKey),
+
+ actions({
+ setFilterGroup: (filterGroup: UniversalFiltersGroup) => ({ filterGroup }),
+ refreshFilterPreview: true,
+ }),
+
+ reducers({
+ filterGroup: [
+ EMPTY_FILTER_GROUP as UniversalFiltersGroup,
+ {
+ setFilterGroup: (_, { filterGroup }) => filterGroup,
+ },
+ ],
+ // kea-loaders keeps the last successful value when a request fails. Consumers treat any
+ // non-null value as describing the current filter, so a failed refresh would otherwise
+ // chart the *previous* filter's volume and project storage from it. Dropping the value
+ // routes the UI to its error-and-retry state instead.
+ filterPreview: {
+ loadFilterPreviewFailure: () => null,
+ },
+ }),
+
+ loaders(({ values }) => ({
+ filterPreview: [
+ null as LogsFilterPreviewPoint[] | null,
+ {
+ loadFilterPreview: async (_, breakpoint) => {
+ await breakpoint(400)
+ if (!isFilterGroupNonEmpty(values.filterGroup)) {
+ return null
+ }
+ const response = await api.logs.sparkline({
+ query: {
+ dateRange: { date_from: '-24h', date_to: null },
+ filterGroup: wrapFilterGroup(values.filterGroup) as PropertyGroupFilter,
+ severityLevels: [],
+ serviceNames: [],
+ sparklineBreakdownBy: 'service',
+ },
+ })
+ // The backend returns each row keyed by the breakdown value ('service' here),
+ // not by the underlying column name (service_name).
+ return response as LogsFilterPreviewPoint[]
+ },
+ },
+ ],
+ })),
+
+ listeners(({ actions }) => ({
+ setFilterGroup: () => {
+ actions.loadFilterPreview(null)
+ },
+ refreshFilterPreview: () => {
+ actions.loadFilterPreview(null)
+ },
+ })),
+])
diff --git a/products/logs/frontend/components/LogsRetention/LogsRetentionForm.tsx b/products/logs/frontend/components/LogsRetention/LogsRetentionForm.tsx
index 704c02a683b2..71560e0a650c 100644
--- a/products/logs/frontend/components/LogsRetention/LogsRetentionForm.tsx
+++ b/products/logs/frontend/components/LogsRetention/LogsRetentionForm.tsx
@@ -1,6 +1,7 @@
import { useActions, useValues } from 'kea'
-import { LemonInput, LemonSegmentedButton, LemonSegmentedButtonOption, LemonSwitch } from '@posthog/lemon-ui'
+import { IconInfo } from '@posthog/icons'
+import { LemonInput, LemonSegmentedButton, LemonSegmentedButtonOption, LemonSwitch, Tooltip } from '@posthog/lemon-ui'
import { LemonField } from 'lib/lemon-ui/LemonField'
import { userLogic } from 'scenes/userLogic'
@@ -8,9 +9,11 @@ import { userLogic } from 'scenes/userLogic'
import { SceneSection } from '~/layout/scenes/components/SceneSection'
import { AvailableFeature } from '~/types'
+import { LogsFilterVolumeSparkline } from 'products/logs/frontend/components/LogsFilterPreview/LogsFilterVolumeSparkline'
import { DropRuleFilterEditor } from 'products/logs/frontend/components/LogsSampling/DropRuleFilterEditor'
import { RETENTION_DAYS_OPTIONS, logsRetentionFormLogic } from './logsRetentionFormLogic'
+import { buildRetentionProjection, retentionProjectionText } from './retentionStorageProjection'
export function LogsRetentionForm(): JSX.Element {
const { retentionForm, retentionFormErrors } = useValues(logsRetentionFormLogic)
@@ -69,6 +72,24 @@ export function LogsRetentionForm(): JSX.Element {
onChange={(group) => setRetentionFormValue('filter_group', group)}
/>
{!hasFilters && <p className="text-danger text-xs mt-1 mb-0">Add at least one filter to match logs.</p>}
+ <LogsFilterVolumeSparkline
+ filterGroup={retentionForm.filter_group}
+ metric="bytes"
+ renderCaption={({ points }) => {
+ const projection = buildRetentionProjection(points, retentionForm.retention_days)
+ if (!projection) {
+ return null
+ }
+ return (
+ <div className="flex items-center gap-1 text-xs text-muted">
+ <span>{retentionProjectionText(projection, retentionForm.retention_days)}</span>
+ <Tooltip title="Estimated from uncompressed ingested bytes over the last 24 hours — the same measure logs usage is billed on. Batch-level byte counts are spread evenly across records, so this is an approximation.">
+ <IconInfo className="shrink-0" />
+ </Tooltip>
+ </div>
+ )
+ }}
+ />
</SceneSection>
</div>
)
diff --git a/products/logs/frontend/components/LogsRetention/retentionStorageProjection.test.ts b/products/logs/frontend/components/LogsRetention/retentionStorageProjection.test.ts
new file mode 100644
index 000000000000..fead0a70261b
--- /dev/null
+++ b/products/logs/frontend/components/LogsRetention/retentionStorageProjection.test.ts
@@ -0,0 +1,111 @@
+import { LogsFilterPreviewPoint } from 'products/logs/frontend/components/LogsFilterPreview/logsFilterVolumePreview'
+
+import { buildRetentionProjection, retentionProjectionText } from './retentionStorageProjection'
+
+const HALF_HOUR_MS = 30 * 60 * 1000
+const GB = 1_000_000_000
+
+/** 48 half-hour buckets ending at `lastBucketMs`, splitting `totalBytes` evenly between them. */
+const buckets = (lastBucketMs: number, totalBytes: number, count = 48): LogsFilterPreviewPoint[] =>
+ Array.from({ length: count }, (_, i) => ({
+ time: new Date(lastBucketMs - (count - 1 - i) * HALF_HOUR_MS).toISOString(),
+ service: 'api',
+ count: 10,
+ bytes_uncompressed: totalBytes / count,
+ }))
+
+describe('buildRetentionProjection', () => {
+ it('projects bytes/day and the steady-state retained total from a full 24h window', () => {
+ const lastBucketMs = Date.UTC(2026, 7, 4, 12, 0, 0)
+ // First bucket is 47 half-hours before the last; `now` is the end of the last bucket,
+ // so the window is exactly 24h.
+ const nowMs = lastBucketMs + HALF_HOUR_MS
+ const projection = buildRetentionProjection(buckets(lastBucketMs, 15 * GB), 30, nowMs)!
+
+ expect(projection.windowSeconds).toEqual(86400)
+ expect(projection.bytesPerDay).toBeCloseTo(15 * GB, -3)
+ expect(projection.retainedBytes).toBeCloseTo(30 * 15 * GB, -3)
+ expect(projection.truncated).toBe(false)
+ })
+
+ it('divides by the real window when the backend floors date_from past 24h', () => {
+ // The sparkline query floors `now - 24h` to the bucket interval, so at 12:29 the window
+ // starts at 12:00 the previous day — 49 buckets spanning 24h29m. Assuming 86400s would
+ // over-project the daily rate by ~2%.
+ const lastBucketMs = Date.UTC(2026, 7, 4, 12, 0, 0)
+ const nowMs = lastBucketMs + 29 * 60 * 1000
+ const projection = buildRetentionProjection(buckets(lastBucketMs, 15 * GB, 49), 30, nowMs)!
+
+ expect(projection.windowSeconds).toEqual(88140)
+ expect(projection.bytesPerDay).toBeLessThan(15 * GB)
+ expect(projection.bytesPerDay).toBeCloseTo((15 * GB * 86400) / 88140, -3)
+ })
+
+ it('measures to the end of the last received bucket when the row cap truncated the response', () => {
+ const lastBucketMs = Date.UTC(2026, 7, 4, 6, 0, 0)
+ // Row cap hit, so `now` is hours past the newest bucket we got back — using it would
+ // stretch the window and understate the daily rate.
+ const nowMs = Date.UTC(2026, 7, 4, 12, 0, 0)
+ const points = buckets(lastBucketMs, 10 * GB, 1000)
+ const projection = buildRetentionProjection(points, 14, nowMs)!
+
+ expect(projection.truncated).toBe(true)
+ expect(projection.windowSeconds).toEqual(1000 * 1800)
+ expect(retentionProjectionText(projection, 14)).toContain('actual volume may be higher')
+ })
+
+ it('falls back to a one-day window when only one bucket came back', () => {
+ const projection = buildRetentionProjection(
+ [{ time: '2026-08-04T12:00:00Z', service: 'api', count: 1, bytes_uncompressed: 5 * GB }],
+ 30,
+ Date.UTC(2026, 7, 4, 12, 1, 0)
+ )!
+
+ expect(projection.windowSeconds).toEqual(86400)
+ expect(projection.bytesPerDay).toEqual(5 * GB)
+ })
+
+ it('returns null when there is nothing to project from', () => {
+ expect(buildRetentionProjection(null, 30)).toBeNull()
+ expect(buildRetentionProjection([], 30)).toBeNull()
+ })
+
+ it('scales the retained total with the tier but not the daily rate', () => {
+ const lastBucketMs = Date.UTC(2026, 7, 4, 12, 0, 0)
+ const nowMs = lastBucketMs + HALF_HOUR_MS
+ const points = buckets(lastBucketMs, 15 * GB)
+
+ const fourteen = buildRetentionProjection(points, 14, nowMs)!
+ const thirty = buildRetentionProjection(points, 30, nowMs)!
+
+ expect(thirty.bytesPerDay).toEqual(fourteen.bytesPerDay)
+ expect(thirty.retainedBytes / fourteen.retainedBytes).toBeCloseTo(30 / 14)
+ })
+})
+
+describe('retentionProjectionText', () => {
+ it('reads as a storage projection naming the tier', () => {
+ const lastBucketMs = Date.UTC(2026, 7, 4, 12, 0, 0)
+ const projection = buildRetentionProjection(buckets(lastBucketMs, 15 * GB), 30, lastBucketMs + HALF_HOUR_MS)!
+
+ expect(retentionProjectionText(projection, 30)).toEqual(
+ 'Based on the last 24 hours, this rule would store ~15.00 GB/day for 30 days (~450.00 GB retained at steady state).'
+ )
+ })
+
+ it('says nothing would be stored when rows came back with no bytes', () => {
+ const projection = buildRetentionProjection(
+ [
+ { time: '2026-08-04T11:30:00Z', service: '', count: 0 },
+ { time: '2026-08-04T12:00:00Z', service: '', count: 0 },
+ ],
+ 30,
+ Date.UTC(2026, 7, 4, 12, 30, 0)
+ )!
+
+ expect(projection.totalBytes).toEqual(0)
+ expect(retentionProjectionText(projection, 30)).toEqual(
+ "No logs matched these filters in the last 24 hours, so this rule wouldn't store anything today."
+ )
+ })
+})
diff --git a/products/logs/frontend/components/LogsRetention/retentionStorageProjection.ts b/products/logs/frontend/components/LogsRetention/retentionStorageProjection.ts
new file mode 100644
index 000000000000..6752dca8ffae
--- /dev/null
+++ b/products/logs/frontend/components/LogsRetention/retentionStorageProjection.ts
@@ -0,0 +1,84 @@
+import {
+ LogsFilterPreviewPoint,
+ SPARKLINE_ROW_LIMIT,
+ formatBytes,
+} from 'products/logs/frontend/components/LogsFilterPreview/logsFilterVolumePreview'
+
+const SECONDS_PER_DAY = 86400
+
+export interface RetentionStorageProjection {
+ totalBytes: number
+ /** Actual span the preview covers, derived from the data rather than assumed to be 24h. */
+ windowSeconds: number
+ bytesPerDay: number
+ /** What the rule holds once every day in the retention window is populated. */
+ retainedBytes: number
+ /** The preview hit the backend row cap, so the newest buckets are missing and this is an undercount. */
+ truncated: boolean
+}
+
+/**
+ * Project how much storage a retention rule would hold, from the volume its filter matched
+ * over the previewed window.
+ *
+ * The window is deliberately derived from the returned buckets instead of being assumed to be
+ * exactly 24h: the sparkline query floors `now - 24h` to the bucket interval, so it really covers
+ * 24h plus up to one bucket, and the trailing bucket is only partially elapsed. Measuring
+ * `now - firstBucket` is self-correcting — the partial bucket contributes partial bytes *and*
+ * partial span — and it survives a change to the backend's bucket sizing.
+ */
+export function buildRetentionProjection(
+ points: LogsFilterPreviewPoint[] | null,
+ retentionDays: number,
+ nowMs: number = Date.now()
+): RetentionStorageProjection | null {
+ if (!points || points.length === 0) {
+ return null
+ }
+
+ let totalBytes = 0
+ const bucketTimes: number[] = []
+ const seenTimes = new Set<string>()
+ for (const point of points) {
+ totalBytes += point.bytes_uncompressed ?? 0
+ if (!seenTimes.has(point.time)) {
+ seenTimes.add(point.time)
+ bucketTimes.push(new Date(point.time).getTime())
+ }
+ }
+
+ const truncated = points.length >= SPARKLINE_ROW_LIMIT
+ const firstBucketMs = Math.min(...bucketTimes)
+ const lastBucketMs = Math.max(...bucketTimes)
+ const bucketSeconds = bucketTimes.length >= 2 ? (bucketTimes[1] - bucketTimes[0]) / 1000 : 0
+
+ // When rows were dropped by the row cap, `now` is no longer the end of the data we got back,
+ // so measure to the end of the last bucket we actually received instead.
+ let windowSeconds = truncated
+ ? (lastBucketMs - firstBucketMs) / 1000 + bucketSeconds
+ : (nowMs - firstBucketMs) / 1000
+ if (!Number.isFinite(windowSeconds) || windowSeconds <= 0 || bucketSeconds <= 0) {
+ // A single bucket gives us no interval to reason about — fall back to treating the
+ // response as one day rather than dividing by ~0 and reporting an absurd rate.
+ windowSeconds = SECONDS_PER_DAY
+ }
+
+ const bytesPerDay = (totalBytes * SECONDS_PER_DAY) / windowSeconds
+ return {
+ totalBytes,
+ windowSeconds,
+ bytesPerDay,
+ retainedBytes: bytesPerDay * retentionDays,
+ truncated,
+ }
+}
+
+export function retentionProjectionText(projection: RetentionStorageProjection, retentionDays: number): string {
+ if (projection.totalBytes === 0) {
+ return "No logs matched these filters in the last 24 hours, so this rule wouldn't store anything today."
+ }
+ const base =
+ `Based on the last 24 hours, this rule would store ~${formatBytes(projection.bytesPerDay)}/day ` +
+ `for ${retentionDays} days (~${formatBytes(projection.retainedBytes)} retained at steady state).`
+ return projection.truncated ? `${base} The preview hit its row limit, so actual volume may be higher.` : base
+}
diff --git a/products/logs/frontend/components/LogsSampling/LogsSamplingForm.tsx b/products/logs/frontend/components/LogsSampling/LogsSamplingForm.tsx
index 823e45f62507..b5aad88d1b48 100644
--- a/products/logs/frontend/components/LogsSampling/LogsSamplingForm.tsx
+++ b/products/logs/frontend/components/LogsSampling/LogsSamplingForm.tsx
@@ -1,15 +1,12 @@
import { useActions, useValues } from 'kea'
-import { useMemo } from 'react'
-import { LemonButton, LemonInput, LemonSegmentedButton, LemonSelect, LemonSwitch } from '@posthog/lemon-ui'
+import { LemonInput, LemonSegmentedButton, LemonSelect, LemonSwitch } from '@posthog/lemon-ui'
-import { dataColorVars } from 'lib/colors'
-import { Sparkline, SparklineReferenceLine, SparklineTimeSeries } from 'lib/components/Sparkline'
-import { dayjs } from 'lib/dayjs'
import { LemonField } from 'lib/lemon-ui/LemonField'
import { SceneSection } from '~/layout/scenes/components/SceneSection'
+import { LogsFilterVolumeSparkline } from 'products/logs/frontend/components/LogsFilterPreview/LogsFilterVolumeSparkline'
import { RuleTypeEnumApi } from 'products/logs/frontend/generated/api.schemas'
import { DropRuleFilterEditor } from './DropRuleFilterEditor'
@@ -26,87 +23,9 @@ const ACTION_OPTIONS: { value: RuleTypeEnumApi; label: string }[] = [
{ value: RuleTypeEnumApi.RateLimit, label: 'Rate limit' },
]
-const TOP_SERVICES_LIMIT = 10
-
-interface SparklineSeriesData {
- labels: string[]
- series: SparklineTimeSeries[]
- total: number
- truncatedServiceCount: number
- /** Width of one bar/bucket in seconds; needed to translate a per-second rate limit into per-bucket units. */
- bucketSeconds: number
- /** Tallest stacked total across buckets; used to position the rate-limit reference line. */
- chartMax: number
-}
-
-type FilterPreviewPoint = { time: string; service: string; count: number; bytes_uncompressed?: number }
-
-function buildSparklineSeries(points: FilterPreviewPoint[] | null, metric: 'count' | 'bytes'): SparklineSeriesData {
- if (!points || points.length === 0) {
- return { labels: [], series: [], total: 0, truncatedServiceCount: 0, bucketSeconds: 0, chartMax: 0 }
- }
- const timeOrder: string[] = []
- const seenTimes = new Set<string>()
- const byService: Record<string, Map<string, number>> = {}
- const serviceTotals = new Map<string, number>()
- const bucketTotals = new Map<string, number>()
- let total = 0
- for (const point of points) {
- if (!seenTimes.has(point.time)) {
- seenTimes.add(point.time)
- timeOrder.push(point.time)
- }
- const svc = point.service || 'unknown'
- const value = metric === 'bytes' ? (point.bytes_uncompressed ?? 0) : point.count
- const bucket = byService[svc] ?? (byService[svc] = new Map())
- bucket.set(point.time, (bucket.get(point.time) ?? 0) + value)
- serviceTotals.set(svc, (serviceTotals.get(svc) ?? 0) + value)
- bucketTotals.set(point.time, (bucketTotals.get(point.time) ?? 0) + value)
- total += value
- }
- const labels = timeOrder.map((t) => dayjs(t).format('D MMM HH:mm'))
- const rankedServices = Array.from(serviceTotals.entries()).sort(([, a], [, b]) => b - a)
- const topServices = rankedServices.slice(0, TOP_SERVICES_LIMIT)
- const otherServices = rankedServices.slice(TOP_SERVICES_LIMIT)
- const truncatedServiceCount = otherServices.length
- const series: SparklineTimeSeries[] = topServices.map(([service], index) => ({
- name: service,
- color: dataColorVars[index % dataColorVars.length],
- values: timeOrder.map((t) => byService[service]?.get(t) ?? 0),
- }))
- if (otherServices.length > 0) {
- // Roll up the long tail into a single "Others" series so the chart still adds up to total volume,
- // and the rate-limit reference line lines up against an honest stacked max.
- const othersValues = timeOrder.map((t) =>
- otherServices.reduce((sum, [service]) => sum + (byService[service]?.get(t) ?? 0), 0)
- )
- series.push({
- name: `Others (${otherServices.length} services)`,
- color: 'muted',
- values: othersValues,
- })
- }
- const bucketSeconds = timeOrder.length >= 2 ? dayjs(timeOrder[1]).diff(dayjs(timeOrder[0]), 'second') : 0
- const chartMax = Math.max(0, ...Array.from(bucketTotals.values()))
- return { labels, series, total, truncatedServiceCount, bucketSeconds, chartMax }
-}
-
-function formatBytes(bytes: number): string {
- if (bytes < 1000) {
- return `${bytes.toLocaleString()} B`
- }
- if (bytes < 1_000_000) {
- return `${(bytes / 1000).toFixed(1)} KB`
- }
- if (bytes < 1_000_000_000) {
- return `${(bytes / 1_000_000).toFixed(1)} MB`
- }
- return `${(bytes / 1_000_000_000).toFixed(2)} GB`
-}
-
export function LogsSamplingForm(): JSX.Element {
- const { samplingForm, samplingFormErrors, filterPreview, filterPreviewLoading } = useValues(logsSamplingFormLogic)
- const { setSamplingFormValue, refreshFilterPreview } = useActions(logsSamplingFormLogic)
+ const { samplingForm, samplingFormErrors } = useValues(logsSamplingFormLogic)
+ const { setSamplingFormValue } = useActions(logsSamplingFormLogic)
const isRateLimit = samplingForm.rule_type === RuleTypeEnumApi.RateLimit
const hasFilters = samplingForm.filter_group.values.length > 0
@@ -119,15 +38,8 @@ export function LogsSamplingForm(): JSX.Element {
}.`
: 'Drop logs matching these filters. Dropped lines are not stored — they will not appear in the UI, exports, or alerts. Already-dropped data cannot be recovered.'
- const previewMetric: 'count' | 'bytes' = isRateLimit ? 'bytes' : 'count'
- const { labels, series, total, bucketSeconds, chartMax } = useMemo(
- () => buildSparklineSeries(filterPreview, previewMetric),
- [filterPreview, previewMetric]
- )
- const formattedTotal = previewMetric === 'bytes' ? formatBytes(total) : `${total.toLocaleString()} logs`
-
- // Rate limit threshold projected onto the same y-axis units the chart uses (bytes/bucket).
- const rateLimitThresholdPerBucket = useMemo<number | null>(() => {
+ /** Rate limit projected onto the same y-axis units the chart uses (bytes/bucket). */
+ const rateLimitThresholdPerBucket = (bucketSeconds: number): number | null => {
if (!isRateLimit || bucketSeconds <= 0) {
return null
}
@@ -137,24 +49,7 @@ export function LogsSamplingForm(): JSX.Element {
}
// KB/s × 1000 = bytes/s, × bucket width in seconds = bytes/bucket.
return kbPerSecond * 1000 * bucketSeconds
- }, [isRateLimit, bucketSeconds, samplingForm.rate_limit_amount, samplingForm.rate_limit_unit])
-
- const rateLimitReferenceLines = useMemo<SparklineReferenceLine[] | undefined>(() => {
- if (rateLimitThresholdPerBucket == null) {
- return undefined
- }
- return [
- {
- value: rateLimitThresholdPerBucket,
- color: 'danger',
- label: `Rate limit (${samplingForm.rate_limit_amount.trim()} ${samplingForm.rate_limit_unit})`,
- labelPosition: 'end',
- },
- ]
- }, [rateLimitThresholdPerBucket, samplingForm.rate_limit_amount, samplingForm.rate_limit_unit])
-
- const rateLimitAboveChart =
- rateLimitThresholdPerBucket != null && chartMax > 0 && rateLimitThresholdPerBucket > chartMax
+ }
return (
<div className="flex flex-col gap-4 max-w-3xl">
@@ -211,55 +106,37 @@ export function LogsSamplingForm(): JSX.Element {
{/* filter_group is an object — kea-forms types only allow scalar field errors,
so this inline message mirrors what samplingFormSaveDisabledReason returns. */}
{!hasFilters && <p className="text-danger text-xs mt-1 mb-0">Add at least one filter to match logs.</p>}
- <div className="mt-3 flex flex-col gap-1">
- <div className="flex items-center justify-between text-xs text-muted">
- <span>
- Volume preview by service (last 24h, top {TOP_SERVICES_LIMIT}
- {previewMetric === 'bytes' ? ', bytes' : ''})
- </span>
- {hasFilters && !filterPreviewLoading ? <span>{formattedTotal}</span> : null}
- </div>
- <div className="relative h-24 border border-border rounded-md bg-bg-light px-2 py-1">
- {!hasFilters ? (
- <div className="h-full flex items-center justify-center text-muted text-xs">
- Add a filter above to preview matching log volume
- </div>
- ) : filterPreviewLoading ? (
- <Sparkline
- data={[]}
- labels={[]}
- loading
- className="w-full h-full"
- maximumIndicator={false}
- />
- ) : !filterPreview ? (
- <div className="h-full flex flex-col gap-1 items-center justify-center text-muted text-xs">
- <span>Couldn't load the volume preview.</span>
- <LemonButton size="xsmall" type="secondary" onClick={refreshFilterPreview}>
- Retry
- </LemonButton>
- </div>
- ) : series.length === 0 ? (
- <div className="h-full flex items-center justify-center text-muted text-xs">
- No logs match these filters in the last 24h
+ <LogsFilterVolumeSparkline
+ filterGroup={samplingForm.filter_group}
+ metric={isRateLimit ? 'bytes' : 'count'}
+ buildReferenceLines={({ bucketSeconds }) => {
+ const threshold = rateLimitThresholdPerBucket(bucketSeconds)
+ if (threshold == null) {
+ return undefined
+ }
+ return [
+ {
+ value: threshold,
+ color: 'danger',
+ label: `Rate limit (${samplingForm.rate_limit_amount.trim()} ${
+ samplingForm.rate_limit_unit
+ })`,
+ labelPosition: 'end',
+ },
+ ]
+ }}
+ renderCaption={({ bucketSeconds, chartMax }) => {
+ const threshold = rateLimitThresholdPerBucket(bucketSeconds)
+ if (threshold == null || chartMax <= 0 || threshold <= chartMax) {
+ return null
+ }
+ return (
+ <div className="text-xs text-muted">
+ Rate limit is above the current peak — no logs would be dropped in the previewed window.
</div>
- ) : (
- <Sparkline
- data={series}
- labels={labels}
- className="w-full h-full"
- maximumIndicator={false}
- referenceLines={rateLimitReferenceLines}
- renderTooltipValue={previewMetric === 'bytes' ? formatBytes : undefined}
- />
- )}
- </div>
- {isRateLimit && rateLimitAboveChart ? (
- <div className="text-xs text-muted">
- Rate limit is above the current peak — no logs would be dropped in the previewed window.
- </div>
- ) : null}
- </div>
+ )
+ }}
+ />
</SceneSection>
</div>
)
diff --git a/products/logs/frontend/components/LogsSampling/logsSamplingFormLogic.ts b/products/logs/frontend/components/LogsSampling/logsSamplingFormLogic.ts
index 45acb7bea27d..3cc10af81708 100644
--- a/products/logs/frontend/components/LogsSampling/logsSamplingFormLogic.ts
+++ b/products/logs/frontend/components/LogsSampling/logsSamplingFormLogic.ts
@@ -1,15 +1,13 @@
-import { MakeLogicType, actions, afterMount, connect, kea, key, listeners, path, props } from 'kea'
+import { MakeLogicType, connect, kea, key, path, props } from 'kea'
import { forms } from 'kea-forms'
import type { DeepPartial, DeepPartialMap, FieldName, ValidationErrorType } from 'kea-forms'
-import { loaders } from 'kea-loaders'
import { router } from 'kea-router'
import { lemonToast } from '@posthog/lemon-ui'
-import api from 'lib/api'
import { teamLogic } from 'scenes/teamLogic'
-import { FilterLogicalOperator, PropertyGroupFilter, UniversalFiltersGroup } from '~/types'
+import { FilterLogicalOperator, UniversalFiltersGroup } from '~/types'
import { logsSamplingRulesCreate, logsSamplingRulesPartialUpdate } from 'products/logs/frontend/generated/api'
import {
@@ -108,10 +106,6 @@ function wrapFilterGroup(inner: UniversalFiltersGroup): UniversalFiltersGroup {
return { type: FilterLogicalOperator.And, values: [inner] as never }
}
-function isFilterGroupNonEmpty(group: UniversalFiltersGroup): boolean {
- return Array.isArray(group.values) && group.values.length > 0
-}
-
export function buildSamplingFormDefaults(rule: LogsSamplingRuleApi | null): LogsSamplingFormType {
if (!rule) {
return { ...DEFAULT_FORM }
@@ -167,15 +161,6 @@ export interface LogsSamplingFormLogicProps {
// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface logsSamplingFormLogicValues {
currentTeamId: number | null // teamLogic
- filterPreview:
- | {
- bytes_uncompressed?: number
- count: number
- service: string
- time: string
- }[]
- | null
- filterPreviewLoading: boolean
isSamplingFormSubmitting: boolean
isSamplingFormValid: boolean
samplingForm: LogsSamplingFormType
@@ -192,38 +177,6 @@ export interface logsSamplingFormLogicValues {
// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface logsSamplingFormLogicActions {
- loadFilterPreview: (_: any) => any
- loadFilterPreviewFailure: (
- error: string,
- errorObject?: any
- ) => {
- error: string
- errorObject?: any
- }
- loadFilterPreviewSuccess: (
- filterPreview:
- | {
- bytes_uncompressed?: number | undefined
- count: number
- service: string
- time: string
- }[]
- | null,
- payload?: any
- ) => {
- filterPreview:
- | {
- bytes_uncompressed?: number | undefined
- count: number
- service: string
- time: string
- }[]
- | null
- payload?: any
- }
- refreshFilterPreview: () => {
- value: true
- }
resetSamplingForm: (values?: LogsSamplingFormType) => {
values?: LogsSamplingFormType
}
@@ -282,63 +235,6 @@ export const logsSamplingFormLogic = kea<logsSamplingFormLogicType>([
values: [teamLogic, ['currentTeamId']],
})),
- actions({
- refreshFilterPreview: true,
- }),
-
- loaders(({ values }) => ({
- filterPreview: [
- null as { time: string; service: string; count: number; bytes_uncompressed?: number }[] | null,
- {
- loadFilterPreview: async (_, breakpoint) => {
- await breakpoint(400)
- const form = values.samplingForm
- if (!isFilterGroupNonEmpty(form.filter_group)) {
- return null
- }
- const response = await api.logs.sparkline({
- query: {
- dateRange: { date_from: '-24h', date_to: null },
- filterGroup: wrapFilterGroup(form.filter_group) as PropertyGroupFilter,
- severityLevels: [],
- serviceNames: [],
- sparklineBreakdownBy: 'service',
- },
- })
- // The backend returns each row keyed by the breakdown value ('service' here),
- // not by the underlying column name (service_name).
- return response as {
- time: string
- service: string
- count: number
- bytes_uncompressed?: number
- }[]
- },
- },
- ],
- })),
-
- listeners(({ actions }) => ({
- refreshFilterPreview: () => {
- actions.loadFilterPreview(null)
- },
- setSamplingFormValue: ({ name }) => {
- if (name === 'filter_group') {
- actions.refreshFilterPreview()
- }
- },
- })),
-
- afterMount(({ actions, values }) => {
- // Kick off an initial preview load on mount whenever the form is opened with
- // a filter_group already set (edit mode, or pre-filled defaults). Without this
- // the loader only fires on subsequent edits, leaving the sparkline stuck on
- // "loading" because filterPreview is null and we never ran the request.
- if (isFilterGroupNonEmpty(values.samplingForm.filter_group)) {
- actions.refreshFilterPreview()
- }
- }),
-
forms(({ props, values }) => ({
samplingForm: {
defaults: buildSamplingFormDefaults(props.rule),