:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
feat(logs): sync the anomalies service and week to the URL (#94931)
Jon McCallum0ab8cb9cf2b5
diff --git a/products/logs/frontend/logsAnomaliesLogic.tsx b/products/logs/frontend/logsAnomaliesLogic.tsxindex 93f878e00f05..70658246468a 100644--- a/products/logs/frontend/logsAnomaliesLogic.tsx+++ b/products/logs/frontend/logsAnomaliesLogic.tsx@@ -11,6 +11,8 @@ import { logsAnomaliesSeriesBandsCreate } from 'products/logs/frontend/generatedimport type { LogsSeriesBandSeriesApi, LogsSeriesBandsResponseApi } from 'products/logs/frontend/generated/api.schemas'export const DEFAULT_VISIBLE_SERIES = 12+// Shared with the URL sync in logsSceneLogic, which drops the param at this value.+export const DEFAULT_ANOMALIES_DATE_RANGE: DateRange = { date_from: '-7d' }// Generated by kea-typegen. Update if you're an agent, ignore if you're human.export interface logsAnomaliesLogicValues {@@ -87,6 +89,7 @@ export const logsAnomaliesLogic = kea<logsAnomaliesLogicType>([showMoreSeries: true,openLogsForBucket: (severity: string, dateRange: DateRange) => ({ severity, dateRange }),}),+loaders(({ values }) => ({seriesBands: [null as LogsSeriesBandsResponseApi | null,@@ -115,7 +118,7 @@ export const logsAnomaliesLogic = kea<logsAnomaliesLogicType>([},],dateRange: [- { date_from: '-7d' } as DateRange,+ DEFAULT_ANOMALIES_DATE_RANGE as DateRange,{setDateRange: (_, { dateRange }) => dateRange,},diff --git a/products/logs/frontend/logsSceneLogic.test.ts b/products/logs/frontend/logsSceneLogic.test.tsindex 981b7779f4b9..d41e966aa2bb 100644--- a/products/logs/frontend/logsSceneLogic.test.ts+++ b/products/logs/frontend/logsSceneLogic.test.ts@@ -27,6 +27,17 @@ describe('logsSceneLogic', () => {post: {'/api/environments/:team_id/logs/query/': () => [200, { results: [], maxExportableLogs: 5000 }],'/api/environments/:team_id/logs/sparkline/': () => [200, []],+ '/api/projects/:team_id/logs/anomalies/series_bands/': () => [+ 200,+ {+ service_name: 'checkout',+ window_start: '2026-08-10T10:00:00Z',+ window_end: '2026-08-17T10:00:00Z',+ interval_minutes: 60,+ series_truncated: false,+ series: [],+ },+ ],},})initKeaTests()@@ -276,4 +287,129 @@ describe('logsSceneLogic', () => {expect(router.values.searchParams).not.toHaveProperty('facetNameSearch')})})++ describe('anomalies tab URL sync', () => {+ // A write arms the sync guard, which clears on a macrotask that `toFinishAllListeners`+ // does not flush. A real back-navigation lands long after that tick.+ const flushUrlSyncGuard = async (): Promise<void> => {+ await new Promise((resolve) => setTimeout(resolve, 0))+ }++ const onAnomaliesTab = async (): Promise<void> => {+ await expectLogic(logic, () => {+ logic.actions.setActiveTab('anomalies')+ }).toFinishAllListeners()+ }++ it('reads the service and the window off the URL', async () => {+ await expectLogic(logic, () => {+ router.actions.push('/logs', {+ activeTab: 'anomalies',+ anomaliesService: 'checkout',+ anomaliesDateRange: { date_from: '-24h' },+ })+ }).toFinishAllListeners()++ expect(logic.values.anomaliesService).toEqual('checkout')+ expect(logic.values.anomaliesDateRange).toEqual({ date_from: '-24h' })+ })++ it('ignores the params while another tab is shown', async () => {+ // Reading a service fetches its band charts, so an ungated read would fire that+ // request from any URL change made on the viewer.+ await expectLogic(logic, () => {+ router.actions.push('/logs', { anomaliesService: 'checkout' })+ }).toFinishAllListeners()++ expect(logic.values.anomaliesService).toBeNull()+ })++ it('returns the picker to the default window when the param goes', async () => {+ // This is the Back case: stepping past the change that wrote the param has to+ // return the default week, not keep the older pick.+ await expectLogic(logic, () => {+ router.actions.push('/logs', {+ activeTab: 'anomalies',+ anomaliesDateRange: { date_from: '-24h' },+ })+ }).toFinishAllListeners()+ await flushUrlSyncGuard()++ await expectLogic(logic, () => {+ router.actions.push('/logs', { activeTab: 'anomalies' })+ }).toFinishAllListeners()++ expect(logic.values.anomaliesDateRange).toEqual({ date_from: '-7d' })+ })++ it('falls back to the default window when the param is not a date range', async () => {+ // A hand-edited or stale URL must not push a shape the picker and the band request+ // cannot read.+ await expectLogic(logic, () => {+ router.actions.push('/logs', {+ activeTab: 'anomalies',+ anomaliesDateRange: ['-24h'],+ })+ }).toFinishAllListeners()++ expect(logic.values.anomaliesDateRange).toEqual({ date_from: '-7d' })+ })++ it('writes both params, and drops each one at its default', async () => {+ await onAnomaliesTab()++ await expectLogic(logic, () => {+ logic.actions.setAnomaliesService('checkout')+ logic.actions.setAnomaliesDateRange({ date_from: '-24h' })+ }).toFinishAllListeners()++ expect(router.values.searchParams).toHaveProperty('anomaliesService', 'checkout')+ expect(router.values.searchParams.anomaliesDateRange).toEqual({ date_from: '-24h' })++ // Left in the URL, the default week would ride along in every link from this tab.+ await expectLogic(logic, () => {+ logic.actions.setAnomaliesService(null)+ logic.actions.setAnomaliesDateRange({ date_from: '-7d' })+ }).toFinishAllListeners()++ expect(router.values.searchParams).not.toHaveProperty('anomaliesService')+ expect(router.values.searchParams).not.toHaveProperty('anomaliesDateRange')+ })++ it('leaves the viewer own service and window params alone', async () => {+ // Both tabs live under one URL. Sharing `dateRange` would move the viewer window,+ // and `serviceNames` is deleted by the viewer writer, so the pick would not survive.+ await expectLogic(logic, () => {+ router.actions.push('/logs', {+ activeTab: 'anomalies',+ dateRange: { date_from: '-1h' },+ })+ }).toFinishAllListeners()++ await expectLogic(logic, () => {+ logic.actions.setAnomaliesService('checkout')+ logic.actions.setAnomaliesDateRange({ date_from: '-24h' })+ }).toFinishAllListeners()++ expect(logic.values.filters.dateRange).toEqual({ date_from: '-1h' })+ expect(router.values.searchParams.dateRange).toEqual({ date_from: '-1h' })+ })++ it('carries the params in and out of the URL with the tab', async () => {+ // A clicked bucket sends the user to the viewer on a URL that has neither param, so+ // the selection has to go back into the URL when the tab comes back.+ await onAnomaliesTab()+ await expectLogic(logic, () => {+ logic.actions.setAnomaliesService('checkout')+ }).toFinishAllListeners()++ await expectLogic(logic, () => {+ logic.actions.setActiveTab('viewer')+ }).toFinishAllListeners()+ expect(router.values.searchParams).not.toHaveProperty('anomaliesService')++ await onAnomaliesTab()+ expect(router.values.searchParams).toHaveProperty('anomaliesService', 'checkout')+ })+ })})diff --git a/products/logs/frontend/logsSceneLogic.tsx b/products/logs/frontend/logsSceneLogic.tsxindex bc83e9e110f3..58d1fdc553d5 100644--- a/products/logs/frontend/logsSceneLogic.tsx+++ b/products/logs/frontend/logsSceneLogic.tsx@@ -37,8 +37,9 @@ import {} from 'products/logs/frontend/components/LogsViewer/Filters/logsViewerFiltersLogic'import { logDetailsModalLogic } from 'products/logs/frontend/components/LogsViewer/LogDetailsModal/logDetailsModalLogic'import { logsViewerLogic } from 'products/logs/frontend/components/LogsViewer/logsViewerLogic'+import { DEFAULT_ANOMALIES_DATE_RANGE, logsAnomaliesLogic } from 'products/logs/frontend/logsAnomaliesLogic'-import type { LogMessage } from '../../../frontend/src/queries/schema/schema-general'+import type { DateRange, LogMessage } from '../../../frontend/src/queries/schema/schema-general'import type { LogsOrderBy } from './types'export const getLogsSqlEditorTabId = (id: string): string => `logs-sql-editor-${id}`@@ -68,6 +69,34 @@ const VALID_ACTIVE_TABS: LogsSceneActiveTab[] = []export const DEFAULT_ACTIVE_TAB: LogsSceneActiveTab = 'viewer'+// The Anomalies tab needs its own two params. `dateRange` below is written from the viewer's+// filters and `serviceNames` is deleted outright, so a shared name would let one tab reframe+// the other tab's logs.+const ANOMALIES_SERVICE_PARAM = 'anomaliesService'+const ANOMALIES_DATE_RANGE_PARAM = 'anomaliesDateRange'++const isDateRangeBound = (value: unknown): boolean => value === undefined || value === null || typeof value === 'string'++// kea-router hands the param back as an object, but a hand-written link can carry the JSON string.+// Anything that is not a pair of date bounds is dropped, so a stale or edited URL falls back to+// the default window instead of reaching the picker and the series-bands request.+const parseDateRangeParam = (raw: unknown): DateRange | null => {+ let candidate: unknown = raw+ if (typeof raw === 'string') {+ try {+ candidate = JSON.parse(raw)+ } catch {+ // Ignore malformed dateRange JSON in URL+ return null+ }+ }+ if (!candidate || typeof candidate !== 'object' || Array.isArray(candidate)) {+ return null+ }+ const { date_from, date_to } = candidate as Record<string, unknown>+ return isDateRangeBound(date_from) && isDateRangeBound(date_to) ? (candidate as DateRange) : null+}+const resolveActiveTabFromParams = (params: Params): LogsSceneActiveTab | null => {if (typeof params.alertId === 'string' && params.alertId.length > 0) {return 'alerts'@@ -81,6 +110,8 @@ const resolveActiveTabFromParams = (params: Params): LogsSceneActiveTab | null =// Generated by kea-typegen. Update if you're an agent, ignore if you're human.export interface logsSceneLogicValues {facetNameSearch: string // facetRailLogic+ anomaliesDateRange: DateRange // logsAnomaliesLogic+ anomaliesService: string | null // logsAnomaliesLogicorderBy: LogsOrderBy // logsViewerConfigLogicviewMode: LogsViewerViewMode // logsViewerConfigLogicinitialLogsLimit: number | null // logsViewerDataLogic@@ -103,6 +134,12 @@ export interface logsSceneLogicActions {closeLogDetails: () => {value: true} // logDetailsModalLogic+ setAnomaliesDateRange: (dateRange: DateRange) => {+ dateRange: DateRange+ } // logsAnomaliesLogic+ setAnomaliesService: (serviceName: string | null) => {+ serviceName: string | null+ } // logsAnomaliesLogicpushToFilterHistory: (filters: LogsViewerFilters) => {filters: LogsViewerFilters} // logsFilterHistoryLogic@@ -183,6 +220,8 @@ export const logsSceneLogic = kea<logsSceneLogicType>([['closeLogDetails'],facetRailLogic({ id: LOGS_SCENE_VIEWER_ID }),['setFacetNameSearch'],+ logsAnomaliesLogic,+ ['setServiceName as setAnomaliesService', 'setDateRange as setAnomaliesDateRange'],],values: [logsViewerFiltersLogic({ id: LOGS_SCENE_VIEWER_ID }),@@ -195,6 +234,8 @@ export const logsSceneLogic = kea<logsSceneLogicType>([['linkToLogId'],facetRailLogic({ id: LOGS_SCENE_VIEWER_ID }),['facetNameSearch'],+ logsAnomaliesLogic,+ ['serviceName as anomaliesService', 'dateRange as anomaliesDateRange'],],})),urlToAction(({ actions, values, cache }) => {@@ -320,6 +361,25 @@ export const logsSceneLogic = kea<logsSceneLogicType>([if (facetNameSearch !== values.facetNameSearch) {actions.setFacetNameSearch(facetNameSearch)}++ // The Anomalies params are read only while that tab is the one shown. Picking a+ // service fetches its band charts, so an ungated read would fire that request from+ // any URL change made on the viewer or the SQL tab. The tab resolved above is+ // already applied, so this reads the tab the URL asked for.+ if (values.activeTab === 'anomalies') {+ // An absent window param means the default, not "leave the picker alone", so+ // stepping back past the change that wrote it returns to the default week.+ const anomaliesDateRange =+ parseDateRangeParam(params[ANOMALIES_DATE_RANGE_PARAM]) ?? DEFAULT_ANOMALIES_DATE_RANGE+ if (!equal(anomaliesDateRange, values.anomaliesDateRange)) {+ actions.setAnomaliesDateRange(anomaliesDateRange)+ }+ const serviceParam = params[ANOMALIES_SERVICE_PARAM]+ const anomaliesService = typeof serviceParam === 'string' && serviceParam ? serviceParam : null+ if (anomaliesService !== values.anomaliesService) {+ actions.setAnomaliesService(anomaliesService)+ }+ }}return {'*': urlToAction,@@ -396,10 +456,34 @@ export const logsSceneLogic = kea<logsSceneLogicType>([)}+ // The two params belong to the Anomalies tab, so they leave the URL with it. Written on+ // the tab switch as well, because a bucket deep link drops them on the way to the viewer+ // and the selection they describe is still there when the user comes back.+ const writeAnomaliesParams = (params: Params): void => {+ const onAnomaliesTab = values.activeTab === 'anomalies'+ updateSearchParams(params, ANOMALIES_SERVICE_PARAM, onAnomaliesTab ? values.anomaliesService : null, null)+ updateSearchParams(+ params,+ ANOMALIES_DATE_RANGE_PARAM,+ onAnomaliesTab ? values.anomaliesDateRange : DEFAULT_ANOMALIES_DATE_RANGE,+ DEFAULT_ANOMALIES_DATE_RANGE+ )+ }++ const syncAnomalies = (): ReturnType<typeof syncSearchParams> => {+ return withUrlSyncGuard(() =>+ syncSearchParams(router, (params: Params) => {+ writeAnomaliesParams(params)+ return params+ })+ )+ }+const syncActiveTab = (): ReturnType<typeof syncSearchParams> => {return withUrlSyncGuard(() =>syncSearchParams(router, (params: Params) => {updateSearchParams(params, 'activeTab', values.activeTab, DEFAULT_ACTIVE_TAB)+ writeAnomaliesParams(params)return params}))@@ -424,6 +508,8 @@ export const logsSceneLogic = kea<logsSceneLogicType>([syncUrl: () => syncUrl(),setActiveTab: () => syncActiveTab(),setViewMode: () => syncViewMode(),+ setAnomaliesService: () => syncAnomalies(),+ setAnomaliesDateRange: () => syncAnomalies(),}}),