import { QueryClient } from '@tanstack/react-query' import { act, fireEvent, screen, waitFor, within } from '@testing-library/react' import userEvent from '@testing-library/user-event' import { platformComponents as components } from 'api-types' import { FeatureFlagContext, IS_PLATFORM, LOCAL_STORAGE_KEYS } from 'common' import { mockAnimationsApi } from 'jsdom-testing-mocks' import { http, HttpResponse } from 'msw' import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' import { z } from 'zod' import { UnifiedLogs } from './UnifiedLogs' import { SEARCH_PARAMS_PARSER } from './UnifiedLogs.constants' import { createUnifiedLogsSearch, serializeUnifiedLogsSearchParams } from './UnifiedLogs.utils' import { EDGE_FUNCTION_LOGS_VIEW, getEdgeFunctionLogsScope, } from '@/components/interfaces/Functions/EdgeFunctionOverview/EdgeFunctionOverview.utils' import { retrieveUnifiedLogs } from '@/data/logs/get-unified-logs' import { getUnifiedLogs } from '@/data/logs/unified-logs-infinite-query' import type { UnifiedLogsQueryRow } from '@/data/logs/unified-logs.utils' import { customRender, CustomWrapper } from '@/tests/lib/custom-render' import { addAPIMock, mswServer, type APIErrorBody } from '@/tests/lib/msw' type AnalyticsResponse = components['schemas']['AnalyticsResponse_Output'] type ProjectResponse = components['schemas']['ProjectDetailResponse_Output'] type SourcesResponse = components['schemas']['SourcesResponse_Output'] const FUNCTION_SCOPE = getEdgeFunctionLogsScope('fn-123') const PIPELINES_ENABLED_FLAGS = { etlEnableBigQueryPrivateAlpha: 'all' } const mockReplicationSources = (sources: SourcesResponse['sources']) => addAPIMock({ method: 'get', path: '/platform/replication/:ref/sources', response: () => HttpResponse.json({ sources }), }) mockAnimationsApi() describe('UnifiedLogs', () => { afterEach(() => { vi.useRealTimers() localStorage.removeItem(LOCAL_STORAGE_KEYS.UNIFIED_LOGS_DOCK) localStorage.removeItem(`${LOCAL_STORAGE_KEYS.UNIFIED_LOGS_DOCK}-edge-function`) }) beforeEach(() => { addAPIMock({ method: 'get', path: '/platform/projects/:ref', response: () => HttpResponse.json({ id: 1, ref: 'default', organization_id: 1, name: 'Test Project', status: 'INACTIVE', cloud_provider: 'AWS', region: 'us-east-1', db_host: 'db.default.supabase.co', restUrl: 'https://default.supabase.co/rest/v1/', inserted_at: '2024-01-01T00:00:00Z', updated_at: '2024-01-01T00:00:00Z', subscription_id: 'sub_123', is_branch_enabled: false, is_physical_backups_enabled: false, high_availability: false, integration_source: null, connectionString: null, }), }) }) it.each([ { hasLoaded: true, isConfigCatStale: false, isCreating: true }, { hasLoaded: true, isConfigCatStale: true, isCreating: false }, { hasLoaded: false, isConfigCatStale: false, isCreating: false }, ])( 'applies a typed pathname exclusion with flag state $hasLoaded/$isConfigCatStale', async ({ hasLoaded, isConfigCatStale, isCreating }) => { vi.useFakeTimers({ shouldAdvanceTime: true }) const user = userEvent.setup({ advanceTimers: vi.advanceTimersByTime }) const pendingSourceFilters = !hasLoaded || isConfigCatStale ? [ 'log_type:eq:multigres', 'log_type:eq:pipelines', ...(IS_PLATFORM ? ['log_type:eq:compute'] : []), ] : [] const queries: string[] = [] const onUrlUpdate = vi.fn() const date = [new Date('2026-11-26T10:00:00Z'), new Date('2026-11-26T11:00:00Z')] addAPIMock({ method: 'post', path: '/platform/projects/:ref/analytics/endpoints/logs.all.otel', response: async ({ request }) => { queries.push(z.object({ sql: z.string() }).parse(await request.json()).sql) return HttpResponse.json({ result: [] }) }, }) customRender( , { nuqs: { hasMemory: true, onUrlUpdate, searchParams: serializeUnifiedLogsSearchParams('', { date, filter: isCreating ? [] : [...pendingSourceFilters, 'pathname:ilike:health'], }), }, } ) await screen.findByText('No results found') if (isCreating) { await user.click(screen.getByTestId('filter-bar-freeform-input')) await user.click(screen.getByRole('option', { name: 'Pathname' })) await user.click(screen.getByRole('option', { name: /Not iLike/ })) } const pathnameValue = screen.getByLabelText('Value for Pathname') await user.click(pathnameValue) await user.clear(pathnameValue) await user.paste('jaeger') await user.click(screen.getByLabelText('Operator for Pathname')) if (!isCreating) await user.click(screen.getByRole('option', { name: /Not iLike/ })) await waitFor(() => { const update = onUrlUpdate.mock.lastCall?.[0] expect(SEARCH_PARAMS_PARSER.filter.parse(update?.searchParams.get('filter') ?? '')).toEqual( [...pendingSourceFilters, 'pathname:notilike:jaeger'] ) expect(update?.searchParams.get('date')).toBe(`${date[0].getTime()}-${date[1].getTime()}`) const listQuery = queries.filter((query) => query.includes('row list')).at(-1) expect(listQuery).toContain("NOT ILIKE '%jaeger%'") }) } ) it('refreshes pathname options for a sidebar filter change before the URL updates', async () => { let pathnameOption: string | null = null const onUrlUpdate = vi.fn() const queryClient = new QueryClient({ defaultOptions: { queries: { retry: false } } }) addAPIMock({ method: 'post', path: '/platform/projects/:ref/analytics/endpoints/logs.all', response: () => HttpResponse.json({ result: pathnameOption === null ? [] : [{ value: pathnameOption, count: 1 }], }), }) customRender( , { nuqs: { hasMemory: true, onUrlUpdate }, queryClient, } ) expect(await screen.findByText('No results found', {}, { timeout: 5_000 })).toBeInTheDocument() await waitFor(() => expect(queryClient.isFetching()).toBe(0), { timeout: 5_000 }) pathnameOption = '/before' fireEvent.click(screen.getByRole('button', { name: 'Pathname' })) expect(await screen.findByText('/before', {}, { timeout: 5_000 })).toBeInTheDocument() await waitFor(() => expect(queryClient.isFetching()).toBe(0), { timeout: 5_000 }) onUrlUpdate.mockClear() fireEvent.click(screen.getByRole('button', { name: 'Method' })) pathnameOption = '/after' fireEvent.click(screen.getByRole('checkbox', { name: /POST/ })) expect(onUrlUpdate).not.toHaveBeenCalled() expect(screen.queryByText('/before')).not.toBeInTheDocument() await waitFor(() => expect(screen.getByText('/after')).toBeInTheDocument(), { timeout: 5_000, }) }, 15_000) it.each([true, false])( 'displays application logs and pipeline details with the OTEL backend %s', async (useOtel) => { vi.useFakeTimers({ shouldAdvanceTime: true }) const queries: string[] = [] const pipelineId = '03dg2o5teb2eucxr9ggh3uie6' const metadata = { pipeline_id_v2: pipelineId, level: 'error', table_id: '123' } addAPIMock({ method: 'post', path: useOtel ? '/platform/projects/:ref/analytics/endpoints/logs.all.otel' : '/platform/projects/:ref/analytics/endpoints/logs.all', response: async ({ request }) => { const { sql } = z.object({ sql: z.string() }).parse(await request.json()) queries.push(sql) const isList = useOtel ? sql.includes('row list') : sql.includes('ORDER BY timestamp DESC') return HttpResponse.json({ result: isList ? [ { id: 'application-log', log_type: 'pipelines', pipeline_id: pipelineId, timestamp: Date.now() * 1000, event_message: 'Table copy failed', level: 'error', method: null, pathname: null, status: null, log_count: null, logs: null, ...(useOtel ? { metadata } : { pipeline_metadata: JSON.stringify(metadata) }), }, ] : [], }) }, }) mswServer.use( http.get('/api/enabled-features-overrides', () => HttpResponse.json<{ disabled_features: string[] }>({ disabled_features: [] }) ) ) mockReplicationSources([ { id: 1, name: 'default', tenant_id: 'tenant', config: { host: 'db.internal', port: 5432, name: 'postgres', username: 'postgres' }, }, ]) customRender( , { nuqs: { hasMemory: true, searchParams: `?filter=log_type:eq:pipelines,pipeline_id:eq:${pipelineId}&id=application-log`, }, } ) expect((await screen.findAllByText('Table copy failed'))[0]).toBeVisible() expect(screen.getAllByText(pipelineId).length).toBeGreaterThan(0) expect(screen.getByRole('img', { name: 'Pipelines' })).toBeInTheDocument() expect(await screen.findByRole('tab', { name: 'Overview' })).toBeVisible() expect(screen.queryByRole('tab', { name: /Timeline|User/ })).not.toBeInTheDocument() expect(screen.getAllByText('Pipeline ID').length).toBeGreaterThan(0) await waitFor(() => expect(queries.length).toBeGreaterThanOrEqual(3)) for (const sql of queries) { expect(sql).toContain('etl_replication_logs') expect(sql).toContain('pipeline_id_v2') expect(sql).toContain(pipelineId) } const rawTab = screen.getByRole('tab', { name: 'Raw JSON' }) fireEvent.keyDown(rawTab, { key: 'Enter' }) expect(rawTab).toHaveAttribute('aria-selected', 'true') expect((await screen.findAllByText(/table_id/)).length).toBeGreaterThan(0) } ) it('hides Pipelines logs for projects without a replication source', async () => { addAPIMock({ method: 'post', path: '/platform/projects/:ref/analytics/endpoints/logs.all.otel', response: () => HttpResponse.json({ result: [] }), }) mockReplicationSources([]) customRender( , { nuqs: { hasMemory: true, searchParams: '?filter=log_type:eq:pipelines' } } ) expect(await screen.findByText('No results found', {}, { timeout: 5_000 })).toBeInTheDocument() expect(screen.getAllByText('Postgres').length).toBeGreaterThan(0) expect(screen.queryByText('Pipelines')).not.toBeInTheDocument() expect(screen.queryByRole('button', { name: 'Pipeline ID' })).not.toBeInTheDocument() }, 15_000) it('limits function logs to the supported filters and scopes rows, counts, and chart requests', async () => { const user = userEvent.setup() const queries: string[] = [] addAPIMock({ method: 'post', path: '/platform/projects/:ref/analytics/endpoints/logs.all.otel', response: async ({ request }) => { queries.push(z.object({ sql: z.string() }).parse(await request.json()).sql) return HttpResponse.json({ result: [] }) }, }) customRender( , { nuqs: { hasMemory: true } } ) expect(await screen.findByText('No results found')).toBeInTheDocument() expect(screen.queryByRole('button', { name: /^(Show|Hide) filters$/ })).not.toBeInTheDocument() await user.click(screen.getByTestId('filter-bar-freeform-input')) expect(screen.getAllByRole('option').map((option) => option.textContent)).toEqual([ 'New filter group', 'Time range', 'Log Type', 'Level', 'Event message', ]) await waitFor(() => { expect(queries.some((sql) => sql.includes('row list'))).toBe(true) expect(queries.some((sql) => sql.includes('sidebar facet counts'))).toBe(true) expect(queries.some((sql) => sql.includes('severity chart'))).toBe(true) }) for (const sql of queries.filter((sql) => !sql.includes('arrayJoin(mapKeys'))) { expect(sql).toContain("log_attributes['function_id'] IN ('fn-123')") expect(sql).toContain("source = 'function_logs'") } }) it('removes unavailable builtins from function URLs while preserving attributes and resource scope', async () => { const queries: string[] = [] const onUrlUpdate = vi.fn() const filters = [ 'status:eq:500', 'level:eq:error', 'attribute.status:eq:runtime-status', 'request_id:eq:req-123', 'function_id:eq:fn-123', 'log_type:eq:edge function runtime', ] const date = [new Date('2026-05-08T09:00:00Z'), new Date('2026-05-08T10:00:00Z')] addAPIMock({ method: 'post', path: '/platform/projects/:ref/analytics/endpoints/logs.all.otel', response: async ({ request }) => { queries.push(z.object({ sql: z.string() }).parse(await request.json()).sql) return HttpResponse.json({ result: [] }) }, }) customRender( , { nuqs: { hasMemory: true, onUrlUpdate, searchParams: serializeUnifiedLogsSearchParams('', { filter: filters, date }), }, } ) await waitFor(() => { const update = onUrlUpdate.mock.lastCall?.[0] expect(update?.searchParams.get('filter')).toBe(filters.slice(1).join(',')) expect(update?.searchParams.get('date')).toBe(`${date[0].getTime()}-${date[1].getTime()}`) }) await waitFor(() => { const rowQuery = queries.filter((sql) => sql.includes('row list')).at(-1) expect(rowQuery).toContain("log_attributes['status'] IN ('runtime-status')") expect(rowQuery).toContain("log_attributes['request_id'] IN ('req-123')") expect(rowQuery).toContain("log_attributes['function_id'] IN ('fn-123')") expect(rowQuery).toContain("source = 'function_logs'") expect(rowQuery).not.toContain("IN ('500')") }) }) it('applies an OR filter group from the URL to every query and keeps it in the URL', async () => { const queries: string[] = [] const onUrlUpdate = vi.fn() const group = 'group:or:status:neq:200,pathname:neq:%2Fhealth' addAPIMock({ method: 'post', path: '/platform/projects/:ref/analytics/endpoints/logs.all.otel', response: async ({ request }) => { queries.push(z.object({ sql: z.string() }).parse(await request.json()).sql) return HttpResponse.json({ result: [] }) }, }) customRender( , { nuqs: { hasMemory: true, onUrlUpdate, searchParams: serializeUnifiedLogsSearchParams('', { filter: ['level:eq:error', group] }), }, } ) expect(await screen.findByText('No results found', {}, { timeout: 5_000 })).toBeInTheDocument() expect(screen.getByText('OR')).toBeInTheDocument() await waitFor(() => { for (const kind of ['row list', 'severity chart']) { const sql = queries.filter((query) => query.includes(kind)).at(-1) expect(sql).toMatch( /END\) NOT IN \('200'\) OR \(multiIf\([\s\S]*?\)\) NOT IN \('\/health'\)\)/ ) } }) await waitFor(() => { const update = onUrlUpdate.mock.lastCall?.[0] expect(SEARCH_PARAMS_PARSER.filter.parse(update?.searchParams.get('filter') ?? '')).toEqual([ 'level:eq:error', group, ]) }) }, 15_000) it('does not offer filter groups on the legacy backend', async () => { const user = userEvent.setup() const queryClient = new QueryClient({ defaultOptions: { queries: { retry: false } } }) addAPIMock({ method: 'post', path: '/platform/projects/:ref/analytics/endpoints/logs.all', response: () => HttpResponse.json({ result: [] }), }) customRender( , { nuqs: { hasMemory: true }, queryClient } ) expect(await screen.findByText('No results found', {}, { timeout: 5_000 })).toBeInTheDocument() await waitFor(() => expect(queryClient.isFetching()).toBe(0), { timeout: 5_000 }) await user.click(screen.getByTestId('filter-bar-freeform-input')) const options = await screen.findAllByRole('option', {}, { timeout: 5_000 }) expect(options.map((option) => option.textContent)).toContain('Log Type') expect(options.map((option) => option.textContent)).not.toContain('New filter group') }, 20_000) it('lets a filter group be toggled to AND and back to OR', async () => { const user = userEvent.setup() const onUrlUpdate = vi.fn() const group = 'group:or:status:neq:200,pathname:neq:%2Fhealth' addAPIMock({ method: 'post', path: '/platform/projects/:ref/analytics/endpoints/logs.all.otel', response: () => HttpResponse.json({ result: [] }), }) customRender( , { nuqs: { hasMemory: true, onUrlUpdate, searchParams: serializeUnifiedLogsSearchParams('', { filter: [group] }), }, } ) const lastFilterParam = () => SEARCH_PARAMS_PARSER.filter.parse( onUrlUpdate.mock.lastCall?.[0].searchParams.get('filter') ?? '' ) await user.click(await screen.findByText('OR', {}, { timeout: 5_000 })) // Applied as two ANDed filters, but the group stays on screen so it can be toggled back. expect(await screen.findByText('AND')).toBeInTheDocument() expect(screen.queryByText('OR')).not.toBeInTheDocument() await waitFor( () => expect(lastFilterParam()).toEqual(['status:neq:200', 'pathname:neq:/health']), { timeout: 5_000, } ) await user.click(screen.getByText('AND')) expect(await screen.findByText('OR')).toBeInTheDocument() await waitFor(() => expect(lastFilterParam()).toEqual([group]), { timeout: 5_000 }) }, 20_000) it('stops filtering when the last condition is removed from a group', async () => { const user = userEvent.setup() const onUrlUpdate = vi.fn() addAPIMock({ method: 'post', path: '/platform/projects/:ref/analytics/endpoints/logs.all.otel', response: () => HttpResponse.json({ result: [] }), }) customRender( , { nuqs: { hasMemory: true, onUrlUpdate, searchParams: serializeUnifiedLogsSearchParams('', { filter: ['group:or:status:neq:200', 'method:eq:GET'], }), }, } ) const removeStatus = await screen.findByTestId('filter-remove-status', {}, { timeout: 5_000 }) expect(screen.getByPlaceholderText('+ Add filter')).toBeInTheDocument() await user.click(removeStatus) // The emptied group leaves the bar too, instead of lingering as an empty "( )". expect(screen.queryByPlaceholderText('+ Add filter')).not.toBeInTheDocument() await waitFor( () => expect( SEARCH_PARAMS_PARSER.filter.parse( onUrlUpdate.mock.lastCall?.[0].searchParams.get('filter') ?? '' ) ).toEqual(['method:eq:GET']), { timeout: 5_000 } ) }, 20_000) it('drops filter groups that use unavailable builtins from function URLs', async () => { const onUrlUpdate = vi.fn() const unavailable = 'group:or:status:neq:200,level:eq:error' const available = 'group:or:level:eq:error,attribute.status:eq:runtime-status' addAPIMock({ method: 'post', path: '/platform/projects/:ref/analytics/endpoints/logs.all.otel', response: () => HttpResponse.json({ result: [] }), }) customRender( , { nuqs: { hasMemory: true, onUrlUpdate, searchParams: serializeUnifiedLogsSearchParams('', { filter: [unavailable, available], }), }, } ) await waitFor( () => { const filter = onUrlUpdate.mock.lastCall?.[0].searchParams.get('filter') ?? '' expect(SEARCH_PARAMS_PARSER.filter.parse(filter)).toEqual([available]) }, { timeout: 5_000 } ) }, 15_000) it('discovers attributes after opening the picker and applies manual keys across requests', async () => { const user = userEvent.setup() const queries: string[] = [] const onUrlUpdate = vi.fn() const queryClient = new QueryClient({ defaultOptions: { queries: { retry: false } } }) addAPIMock({ method: 'post', path: '/platform/projects/:ref/analytics/endpoints/logs.all.otel', response: async ({ request }) => { const { sql } = z.object({ sql: z.string() }).parse(await request.json()) queries.push(sql) return HttpResponse.json({ result: sql.includes('arrayJoin(mapKeys') ? [{ key: 'request_id', n: 1 }] : [], }) }, }) customRender( , { queryClient, nuqs: { hasMemory: true, onUrlUpdate }, } ) expect(await screen.findByText('No results found')).toBeInTheDocument() await waitFor(() => expect(queryClient.isFetching()).toBe(0)) expect(queries.some((sql) => sql.includes('arrayJoin(mapKeys'))).toBe(false) const input = screen.getByTestId('filter-bar-freeform-input') await user.click(input) expect(await screen.findByRole('option', { name: 'Attributes: request_id' })).toHaveTextContent( /^request_id$/ ) expect(screen.getByText('Attributes')).toBeVisible() fireEvent.change(input, { target: { value: 'manual:key' } }) await user.click(await screen.findByRole('option', { name: 'Attributes: manual:key' })) const valueInput = screen.getByTestId('filter-value-attribute.manual:key') expect( screen.getByRole('button', { name: 'Change property from manual:key' }) ).toHaveTextContent('manual:key') fireEvent.change(valueInput, { target: { value: "value'with:colon" } }) await user.keyboard('{Enter}') await waitFor(() => { const filtered = queries.filter((sql) => sql.includes("log_attributes['manual:key'] IN ('value''with:colon')") ) expect(filtered.some((sql) => sql.includes('row list'))).toBe(true) expect(filtered.some((sql) => sql.includes('sidebar facet counts'))).toBe(true) expect(filtered.some((sql) => sql.includes('severity chart'))).toBe(true) }) expect(onUrlUpdate).toHaveBeenCalled() expect( queries .filter((sql) => sql.includes('arrayJoin(mapKeys')) .some((sql) => sql.includes("source = 'postgres_logs'")) ).toBe(true) expect( queries .filter((sql) => sql.includes('arrayJoin(mapKeys')) .some((sql) => sql.includes("source = 'edge_logs'")) ).toBe(true) }) it.each([ { scenario: 'successful discovery', hasError: false, completion: 'Log attributes loaded.' }, { scenario: 'partially failed discovery', hasError: true, completion: 'Some log attributes could not be loaded.', }, ])('announces $scenario only after every source settles', async ({ hasError, completion }) => { const user = userEvent.setup() const postgresResponse = Promise.withResolvers() const edgeResponse = Promise.withResolvers() const queryClient = new QueryClient({ defaultOptions: { queries: { retry: false } } }) addAPIMock({ method: 'post', path: '/platform/projects/:ref/analytics/endpoints/logs.all.otel', response: async ({ request }) => { const { sql } = z.object({ sql: z.string() }).parse(await request.json()) if (!sql.includes('arrayJoin(mapKeys')) return HttpResponse.json({ result: [] }) if (sql.includes("source = 'postgres_logs'")) { await postgresResponse.promise return HttpResponse.json({ result: [{ key: 'postgres_key', n: 1 }] }) } await edgeResponse.promise if (hasError) return HttpResponse.json( { message: 'Discovery unavailable' }, { status: 500 } ) return HttpResponse.json({ result: [{ key: 'edge_key', n: 1 }] }) }, }) customRender(, { queryClient, nuqs: { hasMemory: true }, }) try { expect(await screen.findByText('No results found')).toBeInTheDocument() const status = screen.getByRole('status') expect(status).toBeEmptyDOMElement() expect(status).toHaveAttribute('aria-live', 'polite') expect(status).toHaveAttribute('aria-atomic', 'true') await user.click(screen.getByTestId('filter-bar-freeform-input')) expect(status).toHaveTextContent('Loading log attributes.') postgresResponse.resolve() expect(await screen.findByRole('option', { name: 'Attributes: postgres_key' })).toBeVisible() expect(status).toHaveTextContent('Loading log attributes.') edgeResponse.resolve() await waitFor(() => expect(status).toHaveTextContent(completion)) expect(screen.getByRole('status')).toBe(status) } finally { postgresResponse.resolve() edgeResponse.resolve() await waitFor(() => expect(queryClient.isFetching()).toBe(0)) } }) it('keeps restored attribute exclusions when changing builtin filters', async () => { const queries: string[] = [] const onUrlUpdate = vi.fn() addAPIMock({ method: 'post', path: '/platform/projects/:ref/analytics/endpoints/logs.all.otel', response: async ({ request }) => { const { sql } = z.object({ sql: z.string() }).parse(await request.json()) queries.push(sql) return HttpResponse.json({ result: [] }) }, }) const queryClient = new QueryClient({ defaultOptions: { queries: { retry: false } } }) const view = customRender( , { queryClient, nuqs: { hasMemory: true, onUrlUpdate, searchParams: '?filter=attribute.status:neq:failure,request_id:eq:req-1', }, } ) expect(await screen.findByText('No results found')).toBeInTheDocument() expect(screen.getByTestId('filter-value-attribute.status')).toHaveValue('failure') expect(screen.getByTestId('filter-value-request_id')).toHaveValue('req-1') fireEvent.click(screen.getByRole('button', { name: 'Method' })) fireEvent.click(screen.getByRole('checkbox', { name: /POST/ })) await waitFor(() => expect( queries.some( (sql) => sql.includes("log_attributes['status'] NOT IN ('failure')") && sql.includes("log_attributes['request_id'] IN ('req-1')") && sql.includes("IN ('POST')") ) ).toBe(true) ) const lastUpdate = onUrlUpdate.mock.lastCall?.[0] expect(lastUpdate.searchParams.get('filter')).toContain('attribute.status:neq:failure') expect(lastUpdate.searchParams.get('filter')).toContain('request_id:eq:req-1') view.unmount() }) it('keeps attribute filters in paginated and exported network requests', async () => { const queries: string[] = [] addAPIMock({ method: 'post', path: '/platform/projects/:ref/analytics/endpoints/logs.all.otel', response: async ({ request }) => { queries.push(z.object({ sql: z.string() }).parse(await request.json()).sql) return HttpResponse.json({ result: [] }) }, }) const search = createUnifiedLogsSearch({ filter: ['attribute.trace_id:neq:trace-1'] }) await getUnifiedLogs({ projectRef: 'default', search, useOtel: true, pageParam: { direction: 'next', cursor: 1, row: { id: 'cursor-row', timestamp: '2026-01-01T10:00:00Z' }, }, }) await retrieveUnifiedLogs({ projectRef: 'default', search, useOtel: true, limit: 100 }) expect(queries).toHaveLength(2) expect(queries[0]).toContain("'cursor-row'") expect(queries[1]).toContain('LIMIT 100') for (const sql of queries) expect(sql).toContain("log_attributes['trace_id'] NOT IN ('trace-1')") }) it.each([ ['an excluded log type', '?filter=log_type:neq:postgres', 'storage_logs', 'req.storage_key'], ['a user filter', '?user=user-1', 'auth_logs', 'auth_event.custom_key'], ])('discovers matching source attributes with %s', async (_, searchParams, source, key) => { const user = userEvent.setup() const discoveryQueries: string[] = [] const queryClient = new QueryClient({ defaultOptions: { queries: { retry: false } } }) addAPIMock({ method: 'post', path: '/platform/projects/:ref/analytics/endpoints/logs.all.otel', response: async ({ request }) => { const { sql } = z.object({ sql: z.string() }).parse(await request.json()) if (sql.includes('arrayJoin(mapKeys')) discoveryQueries.push(sql) const hasKey = sql.includes('arrayJoin(mapKeys') && sql.includes(`source = '${source}'`) return HttpResponse.json({ result: hasKey ? [{ key, n: 1 }] : [] }) }, }) customRender(, { queryClient, nuqs: { hasMemory: true, searchParams }, }) expect(await screen.findByText('No results found')).toBeInTheDocument() await waitFor(() => expect(queryClient.isFetching()).toBe(0)) expect(discoveryQueries).toHaveLength(0) await user.click(screen.getByTestId('filter-bar-freeform-input')) expect(await screen.findByRole('option', { name: `Attributes: ${key}` })).toBeVisible() expect(discoveryQueries.some((sql) => sql.includes("source = 'postgres_logs'"))).toBe(false) }) it('restores pending source filters when navigating before a local edit is synchronized', async () => { vi.useFakeTimers({ shouldAdvanceTime: true }) const user = userEvent.setup({ advanceTimers: vi.advanceTimersByTime }) const onUrlUpdate = vi.fn() let location = '?filter=log_type:eq:multigres,pathname:ilike:jaeger' addAPIMock({ method: 'post', path: '/platform/projects/:ref/analytics/endpoints/logs.all.otel', response: () => HttpResponse.json({ result: [] }), }) const view = customRender(, { wrapper: ({ children }) => ( {children} ), }) await screen.findByText('No results found') await user.click(screen.getByLabelText('Operator for Pathname')) await user.click(screen.getByRole('option', { name: /Not iLike/ })) onUrlUpdate.mockClear() location = '?filter=pathname:ilike:jaeger' view.rerender() await waitFor(() => expect(screen.getByLabelText('Operator for Pathname')).toHaveValue('~~*')) expect(screen.queryByLabelText('Value for Log Type')).not.toBeInTheDocument() await act(() => vi.advanceTimersByTimeAsync(300)) expect( onUrlUpdate.mock.calls.every( ([update]) => !update.searchParams.get('filter')?.includes('multigres') ) ).toBe(true) }) it('restores attribute and date filters when navigating between URLs without remounting', async () => { const requests: { sql: string; iso_timestamp_start: string; iso_timestamp_end: string }[] = [] const onUrlUpdate = vi.fn() addAPIMock({ method: 'post', path: '/platform/projects/:ref/analytics/endpoints/logs.all.otel', response: async ({ request }) => { requests.push( z .object({ sql: z.string(), iso_timestamp_start: z.string(), iso_timestamp_end: z.string(), }) .parse(await request.json()) ) return HttpResponse.json({ result: [] }) }, }) const firstUrl = '?filter=attribute.trace_id:eq:first&date=1778230800000-1778234400000' const secondUrl = '?filter=attribute.trace_id:neq:second&date=1778317200000-1778320800000' let location = firstUrl const queryClient = new QueryClient({ defaultOptions: { queries: { retry: false } } }) const view = customRender(, { wrapper: ({ children }) => ( {children} ), }) expect(await screen.findByText('No results found')).toBeInTheDocument() expect(screen.getByTestId('filter-value-attribute.trace_id')).toHaveValue('first') await waitFor(() => expect(queryClient.isFetching()).toBe(0)) onUrlUpdate.mockClear() location = secondUrl view.rerender() await waitFor(() => expect(screen.getByTestId('filter-value-attribute.trace_id')).toHaveValue('second') ) expect(screen.getByTestId('filter-value-date').value).toContain('09 May') await waitFor(() => expect( requests.some( ({ sql, iso_timestamp_start }) => sql.includes("log_attributes['trace_id'] NOT IN ('second')") && iso_timestamp_start === new Date(1778317200000).toISOString() ) ).toBe(true) ) location = firstUrl view.rerender() await waitFor(() => expect(screen.getByTestId('filter-value-attribute.trace_id')).toHaveValue('first') ) expect(screen.getByTestId('filter-value-date').value).toContain('08 May') expect( onUrlUpdate.mock.calls.every( ([event]) => !event.searchParams.get('filter')?.includes('second') || event.searchParams.get('date') === '1778317200000-1778320800000' ) ).toBe(true) }) it('keeps loaded logs readable without claiming zero matches when counts fail', async () => { let releaseCount: () => void = () => {} const pendingCount = new Promise((resolve) => { releaseCount = resolve }) const queryClient = new QueryClient({ defaultOptions: { queries: { retry: false } } }) addAPIMock({ method: 'post', path: '/platform/projects/:ref/analytics/endpoints/logs.all.otel', response: async ({ request }) => { const { sql } = z.object({ sql: z.string() }).parse(await request.json()) if (sql.includes('sidebar facet counts')) { await pendingCount return HttpResponse.json({ error: 'Count query failed' }) } return HttpResponse.json({ result: sql.includes('row list') ? [0, 1].map((index) => ({ id: `log-${index}`, log_type: 'edge function runtime', timestamp: Date.now() * 1000, event_message: `Runtime error ${index}`, level: 'error', method: null, pathname: null, status: null, log_count: null, logs: null, })) : [], }) }, }) customRender( , { queryClient } ) try { expect(await screen.findByText('Runtime error 0')).toBeInTheDocument() expect(screen.getByText(/No more data to load/)).toHaveTextContent( /^No more data to load \(2 rows\)$/ ) } finally { releaseCount() } await waitFor(() => expect(queryClient.isFetching()).toBe(0)) expect(screen.getByText('Runtime error 1')).toBeInTheDocument() expect(screen.getByText(/No more data to load/)).toHaveTextContent( /^No more data to load \(2 rows\)$/ ) }) it('remembers the function dock independently from the project dock when reopening logs', async () => { const user = userEvent.setup({ delay: null }) mswServer.use( http.get('/api/enabled-features-overrides', () => HttpResponse.json<{ disabled_features: string[] }>({ disabled_features: [] }) ) ) const log: UnifiedLogsQueryRow = { id: 'function-log', log_type: 'edge function runtime', timestamp: Date.now() * 1000, event_message: 'Function started', level: 'success', method: null, pathname: null, status: null, log_count: null, logs: null, } for (const path of [ '/platform/projects/:ref/analytics/endpoints/logs.all', '/platform/projects/:ref/analytics/endpoints/logs.all.otel', ] as const) { addAPIMock({ method: 'post', path, response: async ({ request }) => { const { sql } = z.object({ sql: z.string() }).parse(await request.json()) return HttpResponse.json({ result: sql.includes('row list') ? [log] : [], }) }, }) } const renderLogs = (isFunction: boolean) => customRender( , { nuqs: { hasMemory: true, searchParams: '?id=function-log' } } ) const waitForDock = async ({ container }: ReturnType) => { const view = within(container) await view.findByLabelText('Dock side') return view } const first = renderLogs(true) const firstView = await waitForDock(first) expect(firstView.getByRole('separator', { hidden: true })).toHaveAttribute( 'aria-orientation', 'horizontal' ) fireEvent.keyDown(firstView.getByLabelText('Dock side'), { key: 'Enter' }) await user.click(await screen.findByRole('menuitem', { name: 'Dock to right', hidden: true })) await waitFor(() => expect(firstView.getByRole('separator', { hidden: true })).toHaveAttribute( 'aria-orientation', 'vertical' ) ) first.unmount() const project = renderLogs(false) const projectView = await waitForDock(project) expect(projectView.getByRole('separator', { hidden: true })).toHaveAttribute( 'aria-orientation', 'horizontal' ) project.unmount() const reopenedView = await waitForDock(renderLogs(true)) await waitFor(() => expect(reopenedView.getByRole('separator', { hidden: true })).toHaveAttribute( 'aria-orientation', 'vertical' ) ) }) })