Files
supabase/apps/studio/data/compute/compute-instance-logs-query.ts
Matt Johnston 29878860a9 fix(compute): filter logs on the subservice attribute (#50562)
## Problem

Compute log rows are filtered on `log_attributes['source']`, the
deprecated twin of the top-level `subservice` the log writer now
publishes. FUNC-894 deletes the twin from the writer, which would leave
the per-instance log tabs and the Unified Logs `compute` type matching
nothing — silently, since a missing attribute key returns no rows rather
than an error.

## Fix

Read the stream from `log_attributes['subservice']` instead. Both keys
carry the same value on every row today, so this is a same-behaviour
switch that lets the twin be removed.

It stays a `log_attributes` lookup rather than a bare `subservice`
column: the unified logs mapping does not classify these rows, so
`source` is empty on a compute row and every key the backend publishes
lands in the attribute map. A bare `subservice` predicate fails the
whole query with `Field "subservice" does not exist`.

- `COMPUTE_LOG_SUBSERVICES` replaces `WORKER_LOG_SOURCES`; the values
keep their pre-rename `worker_*` spelling, which is still what the
backend publishes
- `STREAM_KEY` in `compute-instance-logs-query.ts` and the Unified Logs
condition used by the log-type, status, method, pathname, metadata and
level expressions both move to the new key
- row fixtures in the three utils test files carry `subservice` instead
of `source`, so they match the wire shape that survives FUNC-894

Supersedes #50219, which targets a `subservice` column and a `source =
'worker_logs'` mapping that do not exist yet; that shape becomes the
follow-up if the mapping ships.

Relates to [FE-4358](https://linear.app/supabase/issue/FE-4358).

## How to test

- Open a compute instance's Invocations, Logs, and Activity tabs — each
shows only its own stream, and message filtering still narrows within
it.
- In Unified Logs, include and then exclude the Compute log type; rows,
counts, and charts move together, and compute rows keep their metadata
while status, method, and pathname stay null.

<!-- This is an auto-generated comment: release notes by coderabbit.ai
-->
## Summary by CodeRabbit

- **Bug Fixes**
- Compute logs are now identified and filtered using subservice metadata
in unified logs and compute instance logs.
- Compute log classification and display now handle compute-specific
fields and severity consistently.
- Guest and ingress compute streams now use subservice metadata for more
consistent results across supported log views.
<!-- end of auto-generated comment: release notes by coderabbit.ai -->
2026-10-20 15:57:04 +02:00

113 lines
3.8 KiB
TypeScript

import { queryOptions } from '@tanstack/react-query'
import { z } from 'zod'
import { computeKeys } from './keys'
import type { LogData } from '@/components/interfaces/Settings/Logs/Logs.types'
import { otelTimestampToMicros } from '@/components/interfaces/Settings/Logs/Logs.utils.otel'
import { executeAnalyticsSql } from '@/data/logs/execute-analytics-sql'
import { logsAllEndpointUrl } from '@/data/logs/logs-endpoint'
import { analyticsLiteral, safeSql } from '@/data/logs/safe-analytics-sql'
import { IS_PLATFORM } from '@/lib/constants'
import { COMPUTE_LOG_SUBSERVICES } from '@/lib/constants/compute'
export type ComputeInstanceLogStream = keyof typeof COMPUTE_LOG_SUBSERVICES
export const COMPUTE_INSTANCE_LOG_STREAM_LABEL: Record<ComputeInstanceLogStream, string> = {
requests: 'Invocations',
output: 'Logs',
builds: 'Activity',
}
// Both are read from `log_attributes` rather than the endpoint's own columns: that
// mapping does not currently classify these rows, so `source` is empty on one and every
// key the backend publishes — the top-level `subservice` included — lands in the
// attribute map. The name key is still the pre-rename "worker" attribute.
const WORKER_NAME_KEY = 'worker'
const STREAM_KEY = 'subservice'
const LOG_LIMIT = 100
const computeInstanceLogRowSchema = z.object({
id: z.string(),
timestamp: z.union([z.string(), z.number()]),
severity: z.string().nullish(),
message: z.string().nullish(),
})
export type ComputeInstanceLogsVariables = {
projectRef?: string
name?: string
stream: ComputeInstanceLogStream
iso_timestamp_start: string
iso_timestamp_end: string
message?: string
}
export const computeInstanceLogsSql = (
name: string,
stream: ComputeInstanceLogStream,
{ message }: Pick<ComputeInstanceLogsVariables, 'message'> = {}
) => {
const messageFilter = message
? safeSql` and event_message ilike ${analyticsLiteral(`%${message}%`)}`
: safeSql``
return safeSql`select id, timestamp, severity_text as severity, event_message as message from logs where log_attributes[${analyticsLiteral(WORKER_NAME_KEY)}] = ${analyticsLiteral(name)} and log_attributes[${analyticsLiteral(STREAM_KEY)}] = ${analyticsLiteral(COMPUTE_LOG_SUBSERVICES[stream])}${messageFilter} order by timestamp desc limit ${analyticsLiteral(LOG_LIMIT)}`
}
export const parseComputeInstanceLogRows = (result: unknown): LogData[] =>
z
.array(computeInstanceLogRowSchema)
.parse(result ?? [])
.map((row) => ({
id: row.id,
timestamp: otelTimestampToMicros(row.timestamp),
event_message: row.message ?? '',
severity_text: row.severity ?? '',
}))
async function getComputeInstanceLogs(
{
projectRef,
name,
stream,
iso_timestamp_start,
iso_timestamp_end,
message,
}: ComputeInstanceLogsVariables,
signal?: AbortSignal
): Promise<LogData[]> {
if (!projectRef) throw new Error('projectRef is required')
if (!name) throw new Error('name is required')
const data = await executeAnalyticsSql({
projectRef,
endpoint: logsAllEndpointUrl(true),
sql: computeInstanceLogsSql(name, stream, { message }),
iso_timestamp_start,
iso_timestamp_end,
signal,
})
return parseComputeInstanceLogRows(data?.result)
}
export const computeInstanceLogsQueryOptions = (variables: ComputeInstanceLogsVariables) => {
const { projectRef, name, stream, iso_timestamp_start, iso_timestamp_end } = variables
const message = variables.message?.trim() || undefined
return queryOptions({
queryKey: computeKeys.logs(projectRef, name, stream, {
iso_timestamp_start,
iso_timestamp_end,
message,
}),
queryFn: ({ signal }) =>
getComputeInstanceLogs(
{ projectRef, name, stream, iso_timestamp_start, iso_timestamp_end, message },
signal
),
enabled: IS_PLATFORM && typeof projectRef !== 'undefined' && typeof name !== 'undefined',
})
}