: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(metrics): write metrics insights in builder, promql or sql (#113477)
Frank Hamanded2f1de88955
diff --git a/frontend/src/lib/constants.tsx b/frontend/src/lib/constants.tsxindex d7ba623739eb..a1b584120948 100644--- a/frontend/src/lib/constants.tsx+++ b/frontend/src/lib/constants.tsx@@ -403,6 +403,7 @@ export const FEATURE_FLAGS = {LOGS_IMPACT_STRIP: 'logs-impact-strip', // owner: #team-logsLOGS_IN_ERROR_TRACKING: 'logs-in-error-tracking', // owner: @jonmcwest #team-logsLOGS_JSON_ATTRIBUTE_PARSING: 'logs-json-attribute-parsing', // owner: #team-logs+ LOGS_METRICS_SNUFFLE_API: 'logs-metrics-snuffle-api', // owner: #team-apm — the PromQL/LogQL APIs; the backend enforces it, the metrics insight editor reads it to offer PromQLLOGS_SERVICES_VIEW: 'logs-services-view', // owner: #team-logsLOGS_SERVICES_VIEW_V2: 'logs-services-view-v2', // owner: #team-logsLOGS_SESSION_ERROR_BADGES: 'logs-session-error-badges', // owner: #team-logs@@ -447,6 +448,7 @@ export const FEATURE_FLAGS = {METRICS_DASHBOARD_PANELS: 'metrics-dashboard-panels', // owner: #team-apm — gates the stat/gauge/bargauge/table panel picker entriesMETRICS_ERROR_OVERLAYS: 'metrics-error-overlays', // owner: #team-apm — gates the error-spike overlay PoC on metrics chartsMETRICS_INSIGHT_BUILDER: 'metrics-insight-builder', // owner: #team-apm — offers Metrics in the new insight menu and the metrics builder in insight edit mode+ METRICS_QUERY_LANGUAGES: 'metrics-query-languages', // owner: #team-apm — lets a metrics insight switch between the builder, PromQL and SQLML_INFERENCE_DECISIONS: 'ml-inference-decisions', // owner: #team-ai-research, gates the decisions playground; the API checks the same flag server sideNEW_COMMAND_K_SEARCH: 'new-command-k-search', // owner: @adamleithp #team-platform-ux, gates the Command K search with smart filtersNEW_TAB_PROJECT_EXPLORER: 'new-tab-project-explorer', // owner: #team-platform-uxdiff --git a/frontend/src/lib/monaco/CodeEditorImpl.tsx b/frontend/src/lib/monaco/CodeEditorImpl.tsxindex 9afe713a56e0..34dd7c83052a 100644--- a/frontend/src/lib/monaco/CodeEditorImpl.tsx+++ b/frontend/src/lib/monaco/CodeEditorImpl.tsx@@ -21,6 +21,7 @@ import { initHogJsonLanguage } from 'lib/monaco/languages/hogJson'import { initHogQLLanguage } from 'lib/monaco/languages/hogQL'import { initHogTemplateLanguage } from 'lib/monaco/languages/hogTemplate'import { initLiquidLanguage } from 'lib/monaco/languages/liquid'+import { initPromQLLanguage } from 'lib/monaco/languages/promql'import { clearLogicReference, initModel } from 'lib/monaco/modelLogicReference'import { registerMountedCodeEditor } from 'lib/monaco/mountedCodeEditors'import 'lib/monaco/monacoEnvironment'@@ -103,6 +104,9 @@ function initEditor(if (editorProps?.language === 'codeowners') {initCodeownersLanguage(monaco)}+ if (editorProps?.language === 'promql') {+ initPromQLLanguage(monaco)+ }editor.onKeyDown((evt) => {if (evt.keyCode === monaco.KeyCode.Space) {diff --git a/frontend/src/lib/monaco/languages/promql.ts b/frontend/src/lib/monaco/languages/promql.tsnew file mode 100644index 000000000000..674d008ebec5--- /dev/null+++ b/frontend/src/lib/monaco/languages/promql.ts@@ -0,0 +1,127 @@+import { Monaco } from '@monaco-editor/react'+import { IPosition, editor, languages } from 'monaco-editor'++import { type PromQLCompletionItem, getPromQLCompletionProvider } from './promqlCompletionRegistry'++const itemKind = (monaco: Monaco, kind: PromQLCompletionItem['kind']): languages.CompletionItemKind => {+ const kinds = monaco.languages.CompletionItemKind+ switch (kind) {+ case 'function':+ case 'aggregation':+ return kinds.Function+ case 'metric':+ return kinds.Constructor+ case 'label':+ return kinds.Enum+ case 'value':+ return kinds.EnumMember+ case 'duration':+ return kinds.Unit+ case 'keyword':+ return kinds.Keyword+ }+}++const completionItemProvider = (monaco: Monaco): languages.CompletionItemProvider => ({+ triggerCharacters: ['{', ',', '(', '[', '=', '~', '"', ' ', ':'],+ provideCompletionItems: async (model: editor.ITextModel, position: IPosition) => {+ const provider = getPromQLCompletionProvider()+ if (!provider) {+ return { suggestions: [] }+ }+ const result = await provider(model.getValue(), model.getOffsetAt(position))+ if (!result) {+ return { suggestions: [] }+ }+ const start = model.getPositionAt(result.from)+ const range = {+ startLineNumber: start.lineNumber,+ startColumn: start.column,+ endLineNumber: position.lineNumber,+ endColumn: position.column,+ }+ return {+ incomplete: result.incomplete,+ suggestions: result.items.map((item) => ({+ label: item.label,+ kind: itemKind(monaco, item.kind),+ insertText: item.insertText,+ range,+ filterText: item.label,+ ...(item.detail ? { detail: item.detail } : {}),+ ...(item.documentation ? { documentation: item.documentation } : {}),+ ...(item.sortText ? { sortText: item.sortText } : {}),+ ...(item.snippet+ ? { insertTextRules: monaco.languages.CompletionItemInsertTextRule.InsertAsSnippet }+ : {}),+ ...(item.retrigger ? { command: { id: 'editor.action.triggerSuggest', title: 'Suggest' } } : {}),+ })),+ }+ },+})++export const conf: () => languages.LanguageConfiguration = () => ({+ // OTel metric and label names contain dots, so a word runs across them.+ wordPattern: /(-?\d*\.\d\w*)|([A-Za-z_$][\w:.]*)/,+ comments: {+ lineComment: '#',+ },+ brackets: [+ ['{', '}'],+ ['[', ']'],+ ['(', ')'],+ ],+ autoClosingPairs: [+ { open: '{', close: '}' },+ { open: '[', close: ']' },+ { open: '(', close: ')' },+ { open: '"', close: '"' },+ ],+})++export const language: () => languages.IMonarchLanguage = () => ({+ defaultToken: '',+ keywords: ['by', 'without', 'on', 'ignoring', 'group_left', 'group_right', 'bool', 'offset', 'and', 'or', 'unless'],+ aggregations: [+ 'sum',+ 'avg',+ 'count',+ 'min',+ 'max',+ 'stddev',+ 'stdvar',+ 'topk',+ 'bottomk',+ 'quantile',+ 'count_values',+ 'group',+ 'limitk',+ 'limit_ratio',+ ],+ tokenizer: {+ root: [+ [/#.*$/, 'comment'],+ [/"([^"\\]|\\.)*"/, 'string'],+ [/'([^'\\]|\\.)*'/, 'string'],+ [/`[^`]*`/, 'string'],+ [/\[[^\]]*\]/, 'number'],+ [/\d+(\.\d+)?(ms|s|m|h|d|w|y)/, 'number'],+ [/\d*\.?\d+([eE][+-]?\d+)?/, 'number'],+ [+ /[a-zA-Z_][\w:.]*(?=\s*\()/,+ { cases: { '@aggregations': 'keyword', '@keywords': 'keyword', '@default': 'type' } },+ ],+ [/[a-zA-Z_][\w:.]*/, { cases: { '@keywords': 'keyword', '@default': 'identifier' } }],+ [/=~|!~|!=|==|>=|<=|[-+*/%^<>=]/, 'operator'],+ ],+ },+})++export function initPromQLLanguage(monaco: Monaco): void {+ if (!monaco.languages.getLanguages().some((lang: { id: string }) => lang.id === 'promql')) {+ monaco.languages.register({ id: 'promql' })+ monaco.languages.setLanguageConfiguration('promql', conf())+ monaco.languages.setMonarchTokensProvider('promql', language())+ monaco.languages.registerCompletionItemProvider('promql', completionItemProvider(monaco))+ }+}diff --git a/frontend/src/lib/monaco/languages/promqlCompletionRegistry.test.ts b/frontend/src/lib/monaco/languages/promqlCompletionRegistry.test.tsnew file mode 100644index 000000000000..0571275d7558--- /dev/null+++ b/frontend/src/lib/monaco/languages/promqlCompletionRegistry.test.ts@@ -0,0 +1,21 @@+import {+ type PromQLCompletionProvider,+ getPromQLCompletionProvider,+ setPromQLCompletionProvider,+} from './promqlCompletionRegistry'++describe('promqlCompletionRegistry', () => {+ it('gives the older editor its suggestions back when the newer one closes', () => {+ const older: PromQLCompletionProvider = async () => null+ const newer: PromQLCompletionProvider = async () => null+ const removeOlder = setPromQLCompletionProvider(older)+ const removeNewer = setPromQLCompletionProvider(newer)+ expect(getPromQLCompletionProvider()).toBe(newer)++ removeNewer()+ expect(getPromQLCompletionProvider()).toBe(older)++ removeOlder()+ expect(getPromQLCompletionProvider()).toBeNull()+ })+})diff --git a/frontend/src/lib/monaco/languages/promqlCompletionRegistry.ts b/frontend/src/lib/monaco/languages/promqlCompletionRegistry.tsnew file mode 100644index 000000000000..5a26c00e79d6--- /dev/null+++ b/frontend/src/lib/monaco/languages/promqlCompletionRegistry.ts@@ -0,0 +1,37 @@+export interface PromQLCompletionItem {+ label: string+ insertText: string+ kind: 'function' | 'aggregation' | 'metric' | 'label' | 'value' | 'duration' | 'keyword'+ detail?: string+ documentation?: string+ /** `insertText` is a snippet (it has a `$0` cursor stop). */+ snippet?: boolean+ /** Open the suggestions again after the insert, as for a label name that needs a value next. */+ retrigger?: boolean+ sortText?: string+}++/** Suggestions for the text at `offset`, and the offset where the replaced word starts. */+export type PromQLCompletionProvider = (+ text: string,+ offset: number+) => Promise<{ from: number; items: PromQLCompletionItem[]; incomplete: boolean } | null>++// Each mounted editor that owns the data (a product, with its own API) adds one; the language stays+// generic. The newest one answers, and removing it gives the next editor its suggestions back.+const completionProviders: PromQLCompletionProvider[] = []++/** Adds a source of PromQL suggestions. Returns a function that removes it again. */+export function setPromQLCompletionProvider(provider: PromQLCompletionProvider): () => void {+ completionProviders.push(provider)+ return () => {+ const index = completionProviders.lastIndexOf(provider)+ if (index !== -1) {+ completionProviders.splice(index, 1)+ }+ }+}++export function getPromQLCompletionProvider(): PromQLCompletionProvider | null {+ return completionProviders[completionProviders.length - 1] ?? null+}diff --git a/frontend/src/queries/schema.json b/frontend/src/queries/schema.jsonindex c6fe5a67f72e..facacc8b3afe 100644--- a/frontend/src/queries/schema.json+++ b/frontend/src/queries/schema.json@@ -39486,6 +39486,7 @@"additionalProperties": false,"properties": {"clauses": {+ "description": "Empty when `language` is `promql` or `sql`.","items": {"$ref": "#/definitions/MetricsQueryClause"},@@ -39511,13 +39512,25 @@"const": "MetricsQuery","type": "string"},+ "language": {+ "$ref": "#/definitions/MetricsQueryLanguage",+ "description": "How the query is written; the builder when unset."+ },"modifiers": {"$ref": "#/definitions/HogQLQueryModifiers","description": "Modifiers used when performing the query"},+ "promql": {+ "description": "PromQL expression, run as a range query. Used when `language` is `promql`.",+ "type": "string"+ },"response": {"$ref": "#/definitions/MetricsQueryResponse"},+ "sql": {+ "description": "HogQL SELECT over the posthog.metric* tables. Used when `language` is `sql`. It must return a `time` and a `value` column; every other column is a series label. `{date_from}`, `{date_to}`, `{interval}` and `{interval_seconds}` are filled in from the date range and interval.",+ "type": "string"+ },"tags": {"$ref": "#/definitions/QueryLogTags"},@@ -39603,6 +39616,11 @@"required": ["key"],"type": "object"},+ "MetricsQueryLanguage": {+ "description": "How a metrics query is written. All three run through the metrics query runner, with its caching and limits.",+ "enum": ["builder", "promql", "sql"],+ "type": "string"+ },"MetricsQueryPoint": {"additionalProperties": false,"properties": {diff --git a/frontend/src/queries/schema/schema-general.ts b/frontend/src/queries/schema/schema-general.tsindex d369795d559d..f871c16a0204 100644--- a/frontend/src/queries/schema/schema-general.ts+++ b/frontend/src/queries/schema/schema-general.ts@@ -5015,9 +5015,21 @@ export interface MetricsDisplaySettings {legendCalcs?: MetricsReducer[]}+/** How a metrics query is written. All three run through the metrics query runner, with its caching and limits. */+export type MetricsQueryLanguage = 'builder' | 'promql' | 'sql'+export interface MetricsQuery extends DataNode<MetricsQueryResponse> {kind: NodeKind.MetricsQuery+ /** Empty when `language` is `promql` or `sql`. */clauses: MetricsQueryClause[]+ /** How the query is written; the builder when unset. */+ language?: MetricsQueryLanguage+ /** PromQL expression, run as a range query. Used when `language` is `promql`. */+ promql?: string+ /** HogQL SELECT over the posthog.metric* tables. Used when `language` is `sql`. It must return a `time` and a+ * `value` column; every other column is a series label. `{date_from}`, `{date_to}`, `{interval}` and+ * `{interval_seconds}` are filled in from the date range and interval. */+ sql?: string/** Defaults to the last 24 hours when omitted; dashboard date filters override it */dateRange?: DateRange/** Bucket size, one of: second_15, second_30, minute, minute_5, minute_15, minute_30, hour, hour_6, day, week; auto-picked from the range when omitted. Coarsened when the range would need more than 10,000 buckets. */diff --git a/frontend/src/scenes/dashboard/dashboardControls.test.ts b/frontend/src/scenes/dashboard/dashboardControls.test.tsindex 6bdbca92517e..21997c21aa79 100644--- a/frontend/src/scenes/dashboard/dashboardControls.test.ts+++ b/frontend/src/scenes/dashboard/dashboardControls.test.ts@@ -19,6 +19,11 @@ describe('dashboardControls', () => {['a trends insight', trendsTile, ['dateRange', 'interval', 'properties', 'breakdown', 'testAccounts']],['a retention insight', retentionTile, ['dateRange', 'properties', 'breakdown', 'testAccounts']],['a metrics insight', metricsTile, ['dateRange', 'metricLabels']],+ [+ 'a PromQL metrics insight',+ insightTile({ kind: NodeKind.MetricsQuery, clauses: [], language: 'promql', promql: 'sum(x)' }),+ ['dateRange'],+ ],['a SQL insight',insightTile({ kind: NodeKind.DataVisualizationNode, source: { kind: NodeKind.HogQLQuery, query: '' } }),diff --git a/frontend/src/scenes/dashboard/dashboardControls.ts b/frontend/src/scenes/dashboard/dashboardControls.tsindex 42ec545253a0..fe8bfe75e3b7 100644--- a/frontend/src/scenes/dashboard/dashboardControls.ts+++ b/frontend/src/scenes/dashboard/dashboardControls.ts@@ -1,4 +1,4 @@-import { Node, NodeKind } from '~/queries/schema/schema-general'+import { MetricsQuery, Node, NodeKind } from '~/queries/schema/schema-general'import { isNodeWithSource } from '~/queries/utils'import { DashboardTile } from '~/types'@@ -38,6 +38,11 @@ const CONTROLS_BY_QUERY_KIND: Partial<Record<NodeKind, DashboardControl[]>> = {export function dashboardControlsForQuery(query: Node | null | undefined): DashboardControl[] {const source = isNodeWithSource(query) ? query.source : query+ // Label filters are added to builder clauses only; PromQL and SQL text is not rewritten.+ const metricsLanguage = source?.kind === NodeKind.MetricsQuery ? (source as MetricsQuery).language : undefined+ if (metricsLanguage && metricsLanguage !== 'builder') {+ return ['dateRange']+ }return (source?.kind && CONTROLS_BY_QUERY_KIND[source.kind as NodeKind]) || DEFAULT_CONTROLS}diff --git a/posthog/api/snuffle_proxy.py b/posthog/api/snuffle_proxy.pyindex 368c46a6d469..536fe000640c 100644--- a/posthog/api/snuffle_proxy.py+++ b/posthog/api/snuffle_proxy.py@@ -114,6 +114,44 @@ def schedule_snuffle_budget_debit(team_id: str, bytes_read: int) -> None:logger.exception("snuffle_proxy_budget_debit_submit_failed", team_id=team_id)+class SnuffleNotConfiguredError(Exception):+ """Raised when no Snuffle URL is configured for this deployment."""+++def snuffle_request(+ team_id: int,+ method: str,+ upstream_path: str,+ *,+ params: dict[str, list[str]] | dict[str, str] | None = None,+ data: dict[str, list[str]] | dict[str, str] | None = None,+ accept: str = "application/json",+) -> requests.Response:+ """Send one request to Snuffle as `team_id` and debit the bytes it read from the query budget.++ `upstream_path` is the Snuffle path, for example ``/api/v1/query_range``. Network errors from+ `requests` propagate, so each caller can map them to its own error format.+ """+ base_url = settings.SNUFFLE_APM_URL+ if not base_url:+ raise SnuffleNotConfiguredError("PromQL/LogQL query API is not configured")+ headers = {TEAM_ID_HEADER: str(team_id), "Accept": accept}+ auth = (settings.SNUFFLE_APM_USER, settings.SNUFFLE_APM_PASSWORD) if settings.SNUFFLE_APM_USER else None+ upstream = internal_requests.request(+ method,+ f"{base_url.rstrip('/')}{upstream_path}",+ params=params,+ data=data,+ headers=headers,+ auth=auth,+ timeout=settings.SNUFFLE_APM_TIMEOUT_SECONDS,+ )+ bytes_read = _read_bytes_from(upstream)+ if bytes_read is not None:+ schedule_snuffle_budget_debit(str(team_id), bytes_read)+ return upstream++class SnuffleProxyViewSet(TeamAndOrgViewSetMixin, viewsets.ViewSet):"""Base for the team-scoped Prometheus- and Loki-compatible query endpoints.@@ -154,8 +192,7 @@ class SnuffleProxyViewSet(TeamAndOrgViewSetMixin, viewsets.ViewSet):if not any(pattern.fullmatch(path) for pattern in self.allowed_paths):return _error_response(status.HTTP_404_NOT_FOUND, "not_found", f"unsupported endpoint: {path}")- base_url = settings.SNUFFLE_APM_URL- if not base_url:+ if not settings.SNUFFLE_APM_URL:return _error_response(status.HTTP_501_NOT_IMPLEMENTED, "unavailable", "PromQL/LogQL query API is not configured")@@ -173,21 +210,16 @@ class SnuffleProxyViewSet(TeamAndOrgViewSetMixin, viewsets.ViewSet):return responsemethod = request.method or "GET"- url = f"{base_url.rstrip('/')}{self.upstream_prefix}/{path}"- params = _forwardable(request.query_params)- headers = {TEAM_ID_HEADER: str(team_id), "Accept": request.headers.get("Accept", "application/json")}body = _forwardable(request.data) if method == "POST" and isinstance(request.data, QueryDict) else None- auth = (settings.SNUFFLE_APM_USER, settings.SNUFFLE_APM_PASSWORD) if settings.SNUFFLE_APM_USER else Nonetry:- upstream = internal_requests.request(+ upstream = snuffle_request(+ team_id,method,- url,- params=params,+ f"{self.upstream_prefix}/{path}",+ params=_forwardable(request.query_params),data=body,- headers=headers,- auth=auth,- timeout=settings.SNUFFLE_APM_TIMEOUT_SECONDS,+ accept=request.headers.get("Accept", "application/json"),)except requests.Timeout:logger.warning("snuffle_proxy_timeout", team_id=team_id, path=path)@@ -211,6 +243,5 @@ class SnuffleProxyViewSet(TeamAndOrgViewSetMixin, viewsets.ViewSet):)bytes_read = _read_bytes_from(upstream)if bytes_read is not None:- schedule_snuffle_budget_debit(str(team_id), bytes_read)response["X-PostHog-Query-Bytes-Read"] = str(bytes_read)return responsediff --git a/posthog/schema.py b/posthog/schema.pyindex 46b98e0ef474..63e7ca750f28 100644--- a/posthog/schema.py+++ b/posthog/schema.py@@ -215,6 +215,7 @@ from posthog.schema_enums import (MetricsFilterOp as MetricsFilterOp,MetricsNullMode as MetricsNullMode,MetricsOtelType as MetricsOtelType,+ MetricsQueryLanguage as MetricsQueryLanguage,MetricsRangeFunction as MetricsRangeFunction,MetricsReducer as MetricsReducer,MetricsStatSummary as MetricsStatSummary,@@ -29236,7 +29237,7 @@ class MetricsQuery(BaseModel):model_config = ConfigDict(extra="forbid",)- clauses: list[MetricsQueryClause]+ clauses: list[MetricsQueryClause] = Field(..., description="Empty when `language` is `promql` or `sql`.")dateRange: DateRange | None = Field(default=None,description=("Defaults to the last 24 hours when omitted; dashboard date filters override it"),@@ -29258,8 +29259,24 @@ class MetricsQuery(BaseModel):),)kind: Literal["MetricsQuery"] = "MetricsQuery"+ language: MetricsQueryLanguage | None = Field(+ default=None, description="How the query is written; the builder when unset."+ )modifiers: HogQLQueryModifiers | None = Field(default=None, description="Modifiers used when performing the query")+ promql: str | None = Field(+ default=None,+ description=("PromQL expression, run as a range query. Used when `language` is `promql`."),+ )response: MetricsQueryResponse | None = None+ sql: str | None = Field(+ default=None,+ description=(+ "HogQL SELECT over the posthog.metric* tables. Used when `language` is"+ " `sql`. It must return a `time` and a `value` column; every other column"+ " is a series label. `{date_from}`, `{date_to}`, `{interval}` and"+ " `{interval_seconds}` are filled in from the date range and interval."+ ),+ )tags: QueryLogTags | None = Noneversion: float | None = Field(default=None, description="version of the node, used for schema migrations")diff --git a/posthog/schema_enums.py b/posthog/schema_enums.pyindex e7daa2e7bfa5..eb01329797c9 100644--- a/posthog/schema_enums.py+++ b/posthog/schema_enums.py@@ -2216,6 +2216,12 @@ class MetricsOtelType(StrEnum):SUMMARY = "summary"+class MetricsQueryLanguage(StrEnum):+ BUILDER = "builder"+ PROMQL = "promql"+ SQL = "sql"++class MetricsRangeFunction(StrEnum):RATE = "rate"INCREASE = "increase"diff --git a/posthog/tasks/alerts/test/test_metrics_alerts.py b/posthog/tasks/alerts/test/test_metrics_alerts.pyindex 0a9582d33959..1a90f1259c50 100644--- a/posthog/tasks/alerts/test/test_metrics_alerts.py+++ b/posthog/tasks/alerts/test/test_metrics_alerts.py@@ -91,8 +91,11 @@ class TestMetricsAlerts(APIBaseTest, ClickhouseTestMixin):clauses: Optional[list[dict[str, Any]]] = None,formula: Optional[str] = None,date_range: Optional[dict[str, str]] = None,+ sql: Optional[str] = None,) -> dict:- if clauses is None:+ if sql is not None:+ clauses = []+ elif clauses is None:clause: dict[str, Any] = {"name": "a", "metricName": self.metric_name, "aggregation": "avg"}if group_by:clause["groupBy"] = [{"key": key} for key in group_by]@@ -102,6 +105,8 @@ class TestMetricsAlerts(APIBaseTest, ClickhouseTestMixin):query_dict["formula"] = formulaif date_range:query_dict["dateRange"] = date_range+ if sql is not None:+ query_dict.update(language="sql", sql=sql)return self.dashboard_api.create_insight(data={"name": "metrics insight", "query": query_dict})[1]def create_alert(@@ -207,6 +212,32 @@ class TestMetricsAlerts(APIBaseTest, ClickhouseTestMixin):assert alert_check.calculated_value == 0assert alert_check.error is None+ def test_sql_insight_alert_counts_an_empty_bucket_as_zero(+ self, mock_send_breaches: MagicMock, mock_send_errors: MagicMock, mock_feature_enabled: MagicMock+ ) -> None:+ # The builder fills empty buckets with 0; a SQL insight leaves them empty. Series b stops+ # reporting after 06:30, so the 07:30 anchor bucket is empty and must breach a lower bound.+ stopped_metric = f"{self.metric_name}.stopped"+ self.seed_gauge({6: 5.0, 7: 5.0, 8: 5.0})+ seed_metric(+ team_id=self.team.pk,+ metric_name=stopped_metric,+ metric_type="gauge",+ points=[(dt.datetime(2026, 9, 19, 6, 30, tzinfo=dt.UTC), 5.0)],+ )+ sql = (+ "SELECT toStartOfInterval(timestamp, {interval}) AS time, metric_name AS clause, avg(value) AS value "+ f"FROM posthog.metrics WHERE metric_name IN ('{self.metric_name}', '{stopped_metric}') "+ "AND timestamp >= {date_from} AND timestamp < {date_to} GROUP BY time, clause"+ )+ alert = self.create_alert(self.create_metrics_insight(sql=sql), lower=1.0)++ run_alert_check(alert["id"])++ assert AlertConfiguration.objects.get(pk=alert["id"]).state == AlertState.FIRING+ breach_messages = mock_send_breaches.call_args.args[1]+ assert any(stopped_metric in message for message in breach_messages), breach_messages+def test_group_by_fires_on_any_breaching_series(self, mock_send_breaches: MagicMock, mock_send_errors: MagicMock, mock_feature_enabled: MagicMock) -> None:diff --git a/products/alerts/backend/evaluation/metrics.py b/products/alerts/backend/evaluation/metrics.pyindex b3e8a249c53f..c34ec4c855ed 100644--- a/products/alerts/backend/evaluation/metrics.py+++ b/products/alerts/backend/evaluation/metrics.py@@ -1,6 +1,6 @@from typing import Any-from posthog.schema import InsightThreshold, MetricsAlertConfig, MetricsQuery+from posthog.schema import InsightThreshold, MetricsAlertConfig, MetricsQuery, MetricsQueryLanguagefrom posthog.api.services.query import ExecutionModefrom posthog.caching.calculate_results import calculate_for_query_based_insight@@ -40,7 +40,7 @@ class MetricsExtractor:def extract(self, alert: AlertConfiguration, insight: Insight, query: Any, execution_mode: ExecutionMode) -> ExtractionResult:- MetricsQuery.model_validate(query)+ metrics_query = MetricsQuery.model_validate(query)if not (alert.config and alert.config.get("type") == "MetricsAlertConfig"):raise ValueError(f"Unsupported alert config type: {alert.config}")config = MetricsAlertConfig.model_validate(alert.config)@@ -71,6 +71,9 @@ class MetricsExtractor:calculation_result.result,anchor_last_point=check_ongoing_interval,is_current_interval=check_ongoing_interval,+ # The builder engine fills an empty bucket with 0. PromQL and SQL results leave it empty+ # (a gap on the chart), so count it as 0 here, or a lower bound never fires when a metric stops.+ zero_fill=metrics_query.language in (MetricsQueryLanguage.PROMQL, MetricsQueryLanguage.SQL),)if not series:# No observed buckets at all: the metric is genuinely absent, evaluated as 0 so a@@ -93,13 +96,20 @@ class MetricsExtractor:*,anchor_last_point: bool,is_current_interval: bool,+ zero_fill: bool,) -> list[ComparableSeries]:series: list[ComparableSeries] = []for row in results:if not isinstance(row, dict):continueraw_points = row.get("points") or []- points = [SeriesPoint(date=point.get("time"), value=point.get("value")) for point in raw_points]+ points = [+ SeriesPoint(+ date=point.get("time"),+ value=0.0 if zero_fill and point.get("value") is None else point.get("value"),+ )+ for point in raw_points+ ]if not points:continue# Anchor on the last observed bucket (ongoing mode) or the one before it. A single-pointdiff --git a/products/metrics/backend/hogql_queries/metrics_query_runner.py b/products/metrics/backend/hogql_queries/metrics_query_runner.pyindex 75cc2290872c..a3b54140333d 100644--- a/products/metrics/backend/hogql_queries/metrics_query_runner.py+++ b/products/metrics/backend/hogql_queries/metrics_query_runner.py@@ -15,6 +15,7 @@ from posthog.schema import (DashboardFilter,DateRange,MetricsQuery,+ MetricsQueryLanguage,MetricsQueryPoint,MetricsQueryResponse,MetricsQuerySeries,@@ -23,6 +24,7 @@ from posthog.schema import (from posthog.hogql import astfrom posthog.hogql.errors import ExposedHogQLError+from posthog.api.snuffle_proxy import SNUFFLE_API_FEATURE_FLAGfrom posthog.hogql_queries.query_runner import AnalyticsQueryRunnerfrom posthog.hogql_queries.utils.query_date_range import QueryDateRangefrom posthog.permissions import posthog_feature_flag_enabled@@ -36,6 +38,7 @@ from products.metrics.backend.facade.contracts import (MetricGroupBy,MetricQueryClause,MetricQueryRequest,+ MetricSeries,)from products.metrics.backend.facade.enums import (AttributeScope,@@ -44,6 +47,8 @@ from products.metrics.backend.facade.enums import (MetricRangeFunction,MetricType,)+from products.metrics.backend.promql import run_promql_range+from products.metrics.backend.sql_mode import run_metrics_sqlif TYPE_CHECKING:from posthog.models import Team, User@@ -87,21 +92,38 @@ class MetricsQueryRunner(AnalyticsQueryRunner[MetricsQueryResponse]):team_id=self.team.pk,):raise UserAccessControlError("metrics", "viewer")+ # PromQL runs through Snuffle, which has its own private-alpha flag.+ if self.query.language == MetricsQueryLanguage.PROMQL and not posthog_feature_flag_enabled(+ SNUFFLE_API_FEATURE_FLAG,+ str(user.distinct_id),+ organization_id=self.team.organization_id,+ team_id=self.team.pk,+ ):+ raise UserAccessControlError("metrics", "viewer")return True- def _enforce_alpha_gate_for_anonymous_viewers(self) -> None:- # Shared-link renders execute with an anonymous SharedLinkUser, which skips- # validate_query_runner_access (the share link is its authorization) — so the- # alpha flag gate must also hold here. Userless runs (scheduled refreshes,- # cache warming) stay allowed: they only ever refresh flagged teams' insights.+ def _enforce_alpha_gates_without_a_request_user(self) -> None:+ # Shared-link renders execute with an anonymous SharedLinkUser, and userless runs (scheduled+ # refreshes, cache warming) have no user. Both skip validate_query_runner_access (the share+ # link is the authorization), so the alpha flag gates must also hold here.# user is typed Optional[User] but runtime also passes SharedLinkUser (shared# renders); broaden for is_anonymous.user = cast("Optional[User | SharedLinkUser]", self.user)- if user is None or not user.is_anonymous:+ if user is not None and not user.is_anonymous:return- if not posthog_feature_flag_enabled(+ distinct_id = str(getattr(user, "distinct_id", None) or f"shared-viewer-{self.team.pk}")+ # Userless runs pass the metrics gate: they only ever refresh insights of teams with the flag.+ if user is not None and not posthog_feature_flag_enabled(METRICS_FEATURE_FLAG,- str(getattr(user, "distinct_id", None) or f"shared-viewer-{self.team.pk}"),+ distinct_id,+ organization_id=self.team.organization_id,+ team_id=self.team.pk,+ ):+ raise UserAccessControlError("metrics", "viewer")+ # A team can have metrics without Snuffle, so a PromQL insight checks the Snuffle flag on every run.+ if self.query.language == MetricsQueryLanguage.PROMQL and not posthog_feature_flag_enabled(+ SNUFFLE_API_FEATURE_FLAG,+ distinct_id,organization_id=self.team.organization_id,team_id=self.team.pk,):@@ -157,10 +179,21 @@ class MetricsQueryRunner(AnalyticsQueryRunner[MetricsQueryResponse]):formula=self.query.formula,)+ def _run(self) -> list[MetricSeries]:+ language = self.query.language or MetricsQueryLanguage.BUILDER+ if language == MetricsQueryLanguage.BUILDER:+ return run_metric_query(team=self.team, request=self._to_request())+ date_range = metrics_query_date_range(self.team, self.query.dateRange)+ text = (self.query.promql if language == MetricsQueryLanguage.PROMQL else self.query.sql) or ""+ if not text.strip():+ raise ValueError(f"Write a {'PromQL' if language == MetricsQueryLanguage.PROMQL else 'SQL'} query first.")+ run = run_promql_range if language == MetricsQueryLanguage.PROMQL else run_metrics_sql+ return run(self.team, text, date_range.date_from(), date_range.date_to(), self.query.interval)+def _calculate(self) -> MetricsQueryResponse:- self._enforce_alpha_gate_for_anonymous_viewers()+ self._enforce_alpha_gates_without_a_request_user()try:- series = run_metric_query(team=self.team, request=self._to_request())+ series = self._run()except ValueError as exc:# The facade signals user errors (bad formula, unknown clause alias, bad# quantile) with ValueError; /query only exposes typed errors, so a bare@@ -181,7 +214,8 @@ class MetricsQueryRunner(AnalyticsQueryRunner[MetricsQueryResponse]):def apply_dashboard_filters(self, dashboard_filter: DashboardFilter) -> None:# Metric label predicates are not PostHog property filters, so the dashboard's- # property filters do not apply. Its date range and label filters do.+ # property filters do not apply. Its date range and label filters do. Label filters+ # reach builder clauses only: PromQL and SQL text is not rewritten.if dashboard_filter.date_from or dashboard_filter.date_to:self.query.dateRange = DateRange(date_from=dashboard_filter.date_from,diff --git a/products/metrics/backend/promql.py b/products/metrics/backend/promql.pynew file mode 100644index 000000000000..7be11f6eba80--- /dev/null+++ b/products/metrics/backend/promql.py@@ -0,0 +1,109 @@+"""Run a PromQL metrics insight as a Snuffle range query.++The range and step come from the same interval ladder as the builder engine, so a PromQL insight+and a builder insight over the same window chart the same buckets.+"""++import re+import math+import datetime as dt+from typing import Any++import requests++from posthog.api.snuffle_proxy import SnuffleNotConfiguredError, snuffle_request+from posthog.models import Team++from products.metrics.backend.facade.contracts import MetricPoint, MetricSeries+from products.metrics.backend.metric_query_runner import _align_to_interval, _interval_step, _resolve_interval+from products.metrics.backend.series import rank_and_fill_series++# The label that builderToPromql adds to keep the series of a multi-series query apart.+CLAUSE_LABEL = "clause"+# builderToPromql sets the label with `label_replace(<series>, "clause", "<alias>", "", "")`. Without+# that call, a `clause` label belongs to the user's data.+_SETS_CLAUSE_LABEL = re.compile(r'label_replace\s*\(.*,\s*"clause"\s*,\s*"', re.DOTALL)+++class PromQLQueryError(ValueError):+ """A PromQL query that Snuffle rejected or could not run. The message is safe to show."""+++def _sample_value(raw: Any) -> float | None:+ try:+ value = float(raw)+ except (TypeError, ValueError):+ return None+ return value if math.isfinite(value) else None+++def _error_message(response: requests.Response) -> str:+ try:+ payload = response.json()+ except ValueError:+ return f"The PromQL query failed with status {response.status_code}."+ return str(payload.get("error") or f"The PromQL query failed with status {response.status_code}.")+++def run_promql_range(+ team: Team, expr: str, date_from: dt.datetime, date_to: dt.datetime, interval: str | None+) -> list[MetricSeries]:+ resolved = _resolve_interval(date_from, date_to, interval)+ step = _interval_step(resolved)+ start = _align_to_interval(date_from, resolved, tzinfo=team.timezone_info)+ try:+ response = snuffle_request(+ team.pk,+ "POST",+ "/api/v1/query_range",+ data={+ "query": expr,+ "start": str(start.timestamp()),+ "end": str(date_to.timestamp()),+ "step": str(int(step.total_seconds())),+ },+ )+ except SnuffleNotConfiguredError as exc:+ raise PromQLQueryError("PromQL queries are not available on this PostHog instance.") from exc+ except requests.Timeout as exc:+ raise PromQLQueryError("The PromQL query timed out. Try a shorter date range.") from exc+ except requests.RequestException as exc:+ raise PromQLQueryError("The PromQL query backend cannot be reached. Try again later.") from exc++ if response.status_code in (401, 403) or response.status_code >= 500:+ raise PromQLQueryError("The PromQL query backend failed. Try again later.")+ if response.status_code >= 400:+ raise PromQLQueryError(_error_message(response))+ try:+ payload = response.json()+ except ValueError as exc:+ raise PromQLQueryError("The PromQL query backend sent a response that cannot be read.") from exc+ if payload.get("status") != "success":+ raise PromQLQueryError(_error_message(response))++ data = payload.get("data") or {}+ result_type = data.get("resultType")+ results = data.get("result") or []+ if result_type == "scalar":+ # A constant expression: one value for the whole range.+ results = [{"metric": {}, "values": [results]}] if results else []+ elif result_type != "matrix":+ raise PromQLQueryError(f"A PromQL range query cannot return a {result_type} result.")++ tzinfo = team.timezone_info+ marks_clauses = bool(_SETS_CLAUSE_LABEL.search(expr))+ rows: list[tuple[dict[str, str], str | None, str | None, list[MetricPoint]]] = []+ for result in results:+ labels = {str(key): str(value) for key, value in (result.get("metric") or {}).items()}+ metric_name = labels.pop("__name__", None)+ clause = labels.pop(CLAUSE_LABEL, None) if marks_clauses else None+ points = [+ MetricPoint(+ time=dt.datetime.fromtimestamp(float(timestamp), tz=tzinfo).isoformat(),+ value=_sample_value(value),+ )+ for timestamp, value in result.get("values") or []+ ]+ rows.append((labels, metric_name, clause, points))+ # PromQL has no sample for a time that a series does not report, so the chart shows a gap.+ return rank_and_fill_series(rows, fill=None)diff --git a/products/metrics/backend/series.py b/products/metrics/backend/series.pynew file mode 100644index 000000000000..be68d2323ef4--- /dev/null+++ b/products/metrics/backend/series.py@@ -0,0 +1,54 @@+from collections.abc import Sequence++from products.metrics.backend.facade.api import MAX_SERIES_PER_CLAUSE+from products.metrics.backend.facade.contracts import MAX_CLAUSES_PER_QUERY, MetricPoint, MetricSeries+from products.metrics.backend.metric_query_runner import _MAX_BUCKET_COUNT++# The most a builder query can return: every clause at its series cap, on the longest bucket grid.+# A PromQL or SQL query chooses its own clauses and times, so these limits bound its output too.+MAX_SERIES_TOTAL = MAX_CLAUSES_PER_QUERY * MAX_SERIES_PER_CLAUSE+# An unaligned range start adds a partial first bucket, and a PromQL range query includes its end.+MAX_POINTS_TOTAL = MAX_SERIES_TOTAL * (_MAX_BUCKET_COUNT + 2)++Row = tuple[dict[str, str], str | None, str | None, list[MetricPoint]]+++def rank_and_fill_series(rows: Sequence[Row], *, fill: float | None) -> list[MetricSeries]:+ """Keep the largest series of each clause and put every series on one shared time grid.++ Each row is `(labels, metric_name, clause, points)`. Series rank by summed absolute value and the+ cap applies per clause, as in the builder engine. The grid is every time of every row, also the+ rows the cap drops, as in the builder engine. A bucket with no point gets `fill`.+ """+ grid = sorted({point.time for row in rows for point in row[3]})+ rows_by_clause: dict[str | None, list[Row]] = {}+ for row in rows:+ rows_by_clause.setdefault(row[2], []).append(row)+ ranked = [+ row+ for clause_rows in rows_by_clause.values()+ for row in sorted(+ clause_rows,+ key=lambda row: (+ -sum(abs(point.value) for point in row[3] if point.value is not None),+ sorted(row[0].items()),+ ),+ )[:MAX_SERIES_PER_CLAUSE]+ ]+ if len(ranked) > MAX_SERIES_TOTAL or len(ranked) * len(grid) > MAX_POINTS_TOTAL:+ raise ValueError(+ f"The query returns too many series or time buckets to chart ({len(ranked)} series, "+ f"{len(grid)} buckets). Use fewer series, a coarser interval, or a shorter date range."+ )+ series: list[MetricSeries] = []+ for labels, metric_name, clause, points in ranked:+ values = {point.time: point.value for point in points}+ series.append(+ MetricSeries(+ labels=labels,+ points=tuple(MetricPoint(time=time, value=values.get(time, fill)) for time in grid),+ metric_name=metric_name,+ clause=clause,+ )+ )+ return seriesdiff --git a/products/metrics/backend/sql_mode.py b/products/metrics/backend/sql_mode.pynew file mode 100644index 000000000000..76643804dd4a--- /dev/null+++ b/products/metrics/backend/sql_mode.py@@ -0,0 +1,217 @@+"""Run a SQL metrics insight.++A SQL metrics insight is a HogQL SELECT over the metrics tables. It runs on the metrics query path,+not as a generic SQL insight: the metrics runner caches it, the logs workload runs it, and the+metrics byte cap limits it. To keep those limits honest, it may read only the metrics tables.++The result contract: a `time` column, a numeric `value` column, and any other columns as series+labels. A `clause` column names the series of a multi-series query. When every time is the start of+a chart interval, a series with no row for a time that another series has gets 0 there, as in the+builder. The SQL can use `{date_from}`, `{date_to}`,+`{interval}` and `{interval_seconds}`, filled in from the insight's (or dashboard's) date range and+the bucket interval.+"""++import math+import datetime as dt+from typing import Any++from posthog.hogql import ast+from posthog.hogql.constants import MAX_SELECT_RETURNED_ROWS+from posthog.hogql.context import HogQLContext+from posthog.hogql.database.database import Database+from posthog.hogql.database.models import Table+from posthog.hogql.database.schema.metrics import (+ MetricAttributesTable,+ MetricNamesTable,+ MetricSamplesTable,+ MetricSeriesTable,+ MetricsTable,+)+from posthog.hogql.errors import ExposedHogQLError+from posthog.hogql.parser import parse_select+from posthog.hogql.query import execute_hogql_query+from posthog.hogql.resolver import resolve_types+from posthog.hogql.visitor import TraversingVisitor++from posthog.clickhouse.client.connection import Workload+from posthog.models import Team++from products.metrics.backend.facade.contracts import MetricPoint, MetricSeries+from products.metrics.backend.metric_query_runner import (+ _QUERY_SETTINGS,+ _RAW_ROW_LIMIT,+ _align_to_interval,+ _interval_expr,+ _interval_step,+ _resolve_interval,+)+from products.metrics.backend.series import rank_and_fill_series++METRICS_SQL_TABLES: frozenset[str] = frozenset(+ {"metrics", "metric_samples", "metric_series", "metric_names", "metric_attributes"}+)++# One row for each series and bucket, as a builder clause without an aggregation returns. HogQL+# returns at most MAX_SELECT_RETURNED_ROWS rows, so a higher limit would drop rows without an error.+_SQL_ROW_LIMIT = min(_RAW_ROW_LIMIT, MAX_SELECT_RETURNED_ROWS)++# The same label as a PromQL `clause` label: it names the series of a multi-series query.+CLAUSE_COLUMN = "clause"+++# A FROM source that reads no table itself: its own FROM clauses are checked where they appear.+_SUBQUERY_TYPES = (+ ast.SelectQueryType,+ ast.SelectSetQueryType,+ ast.SelectQueryAliasType,+ ast.CTETableType,+ ast.CTETableAliasType,+)+_METRICS_TABLE_CLASSES: tuple[type[Table], ...] = (+ MetricsTable,+ MetricSamplesTable,+ MetricNamesTable,+ MetricSeriesTable,+ MetricAttributesTable,+)+++class _TableCollector(TraversingVisitor):+ """Collects every FROM and JOIN source of a resolved query that is not a metrics table.++ It reads the resolved types, not the raw AST: the resolver applies the CTE scope rules and+ expands HogQLX tags, so a CTE name or a tag cannot hide another table.+ """++ def __init__(self) -> None:+ self.other_tables: list[str] = []++ def visit_join_expr(self, node: ast.JoinExpr) -> None:+ table_type = node.type+ while isinstance(table_type, ast.TableAliasType):+ table_type = table_type.table_type+ if not isinstance(table_type, _SUBQUERY_TYPES) and not (+ isinstance(table_type, ast.TableType) and isinstance(table_type.table, _METRICS_TABLE_CLASSES)+ ):+ name = ".".join(str(part) for part in node.table.chain) if isinstance(node.table, ast.Field) else None+ self.other_tables.append(name or "a table that is not a metrics table")+ super().visit_join_expr(node)+++def _assert_reads_only_metrics_tables(team: Team, query: ast.SelectQuery | ast.SelectSetQuery) -> None:+ context = HogQLContext(+ team_id=team.pk, team=team, database=Database.create_for(team=team), enable_select_queries=True+ )+ collector = _TableCollector()+ collector.visit(resolve_types(query, context, dialect="clickhouse"))+ if collector.other_tables:+ raise ExposedHogQLError(+ f"A SQL metrics insight can only read the metrics tables "+ f"({', '.join(f'posthog.{table}' for table in sorted(METRICS_SQL_TABLES))}), "+ f"not {collector.other_tables[0]}."+ )+++def build_metrics_sql_query(+ team: Team, sql: str, date_from: dt.datetime, date_to: dt.datetime, interval: str | None+) -> ast.SelectQuery:+ """Parse the insight's SQL with the date placeholders filled in, wrapped in the row limit."""+ resolved = _resolve_interval(date_from, date_to, interval)+ step = _interval_step(resolved)+ placeholders: dict[str, ast.Expr] = {+ "date_from": ast.Constant(value=_align_to_interval(date_from, resolved, tzinfo=team.timezone_info)),+ "date_to": ast.Constant(value=date_to),+ "interval": _interval_expr(resolved),+ "interval_seconds": ast.Constant(value=int(step.total_seconds())),+ }+ inner = parse_select(sql, placeholders=placeholders)+ _assert_reads_only_metrics_tables(team, inner)+ wrapped = parse_select(+ "SELECT * FROM {inner} LIMIT {row_limit}",+ placeholders={"inner": inner, "row_limit": ast.Constant(value=_SQL_ROW_LIMIT)},+ )+ assert isinstance(wrapped, ast.SelectQuery)+ return wrapped+++def _time_text(value: Any) -> str:+ if isinstance(value, dt.datetime | dt.date):+ return value.isoformat()+ return str(value)+++def _numeric(value: Any) -> float | None:+ if value is None:+ return None+ try:+ number = float(value)+ except (TypeError, ValueError):+ raise ExposedHogQLError(f'The "value" column must be a number, not {value!r}.')+ return number if math.isfinite(number) else None+++def _on_interval_starts(times: list[Any], interval: str, team: Team) -> bool:+ """Whether every time is the start of a chart interval, as the times of `toStartOfInterval(…, {interval})` are."""+ step = _interval_step(interval)+ for time in times:+ if isinstance(time, dt.datetime):+ time = time if time.tzinfo else time.replace(tzinfo=dt.UTC)+ elif isinstance(time, dt.date):+ # ClickHouse returns week intervals as dates.+ time = dt.datetime.combine(time, dt.time(), tzinfo=team.timezone_info)+ else:+ return False+ # ClickHouse counts intervals shorter than an hour from the Unix epoch, not from local midnight.+ on_epoch_grid = step < dt.timedelta(hours=1) and time.timestamp() % step.total_seconds() == 0+ if not on_epoch_grid and _align_to_interval(time, interval, tzinfo=team.timezone_info) != time:+ return False+ return True+++def run_metrics_sql(+ team: Team, sql: str, date_from: dt.datetime, date_to: dt.datetime, interval: str | None+) -> list[MetricSeries]:+ query = build_metrics_sql_query(team, sql, date_from, date_to, interval)+ response = execute_hogql_query(+ query_type="MetricsSQLQuery",+ query=query,+ team=team,+ workload=Workload.LOGS,+ settings=_QUERY_SETTINGS,+ )+ columns = [str(column) for column in response.columns or []]+ lowered = [column.lower() for column in columns]+ if "time" not in lowered or "value" not in lowered:+ raise ExposedHogQLError(+ f'A SQL metrics insight must return a "time" and a "value" column. It returned: {", ".join(columns)}.'+ )+ results = response.results or []+ if len(results) >= _SQL_ROW_LIMIT:+ raise ExposedHogQLError(+ "The query returned too many rows. Use a coarser interval, a shorter date range, or fewer labels."+ )++ time_index = lowered.index("time")+ value_index = lowered.index("value")+ clause_index = lowered.index(CLAUSE_COLUMN) if CLAUSE_COLUMN in lowered else None+ label_indexes = [index for index in range(len(columns)) if index not in (time_index, value_index, clause_index)]++ # Raw sample times of different series do not line up, so a 0 between them would be invented.+ on_interval_starts = _on_interval_starts(+ [row[time_index] for row in results], _resolve_interval(date_from, date_to, interval), team+ )+ points_by_series: dict[tuple[str | None, tuple[tuple[str, str], ...]], list[MetricPoint]] = {}+ for row in results:+ labels = tuple((columns[index], "" if row[index] is None else str(row[index])) for index in label_indexes)+ clause = str(row[clause_index]) if clause_index is not None else None+ points_by_series.setdefault((clause, labels), []).append(+ MetricPoint(time=_time_text(row[time_index]), value=_numeric(row[value_index]))+ )+ return rank_and_fill_series(+ [+ (dict(labels), None, clause, sorted(points, key=lambda point: point.time))+ for (clause, labels), points in points_by_series.items()+ ],+ fill=0.0 if on_interval_starts else None,+ )diff --git a/products/metrics/backend/tests/test_metrics_query_languages.py b/products/metrics/backend/tests/test_metrics_query_languages.pynew file mode 100644index 000000000000..a3d26d02e3c8--- /dev/null+++ b/products/metrics/backend/tests/test_metrics_query_languages.py@@ -0,0 +1,468 @@+import json+import math+import datetime as dt+from pathlib import Path+from typing import Any, cast++import pytest+import time_machine+from posthog.test.base import APIBaseTest, ClickhouseTestMixin+from unittest.mock import MagicMock, patch++from django.test import override_settings++import requests+from parameterized import parameterized++from posthog.schema import DateRange, HogQLQuery, MetricsQuery, MetricsQueryClause++from posthog.hogql.errors import ExposedHogQLError++from posthog.hogql_queries.hogql_query_runner import HogQLQueryRunner+from posthog.models import User+from posthog.models.sharing_configuration import SharingConfiguration+from posthog.shared_link_user import SharedLinkUser++from products.access_control.backend.facade.user_access_control import UserAccessControlError+from products.metrics.backend.facade.contracts import MetricPoint+from products.metrics.backend.hogql_queries.metrics_query_runner import MetricsQueryRunner+from products.metrics.backend.series import rank_and_fill_series+from products.metrics.backend.tests._seeder import seed_metric++FIXTURES: dict[str, dict[str, Any]] = json.loads(+ (Path(__file__).parents[2] / "frontend/queryLanguages/__fixtures__/builder_sql.json").read_text()+)+NOW = dt.datetime(2026, 9, 19, 12, 0, tzinfo=dt.UTC)+DATE_RANGE = DateRange(date_from="2026-09-19T11:00:00Z", date_to="2026-09-19T12:00:00Z")+HISTOGRAM_BOUNDS = [10.0, 50.0, 100.0]+# Gauges the fixtures need in a special shape: one series stops halfway, one service is missing, or every value is 0.+SPARSE_METRIC = "sparse_queue_depth"+API_ONLY_METRIC = "api_queue_depth"+ZERO_METRIC = "idle_queue_depth"+SERIES_LABELS = [+ ("api", {"http.route": "/api/users", "http.request.method": "GET", "http.response.status_code": "200"}),+ ("api", {"http.route": "/health", "http.request.method": "OPTIONS", "http.response.status_code": "500"}),+ ("worker", {"http.route": "/api/jobs", "http.request.method": "GET", "http.response.status_code": "503"}),+]+++def _metric_kinds() -> dict[str, str]:+ kinds: dict[str, str] = {}+ for fixture in FIXTURES.values():+ for clause in fixture["builder"]["clauses"]:+ aggregation = clause["aggregation"]+ kinds[clause["metricName"]] = (+ "histogram"+ if aggregation == "histogram_quantile"+ else "counter"+ if aggregation in ("rate", "increase")+ else "gauge"+ )+ return kinds+++def _comparable(series: list[Any], *, use_clause: bool) -> dict[tuple, dict[str, float | None]]:+ # A SQL union fills the labels another series groups by with ''; the builder has no such label.+ out: dict[tuple, dict[str, float | None]] = {}+ for item in series:+ labels = tuple(sorted((key, value) for key, value in item.labels.items() if value != ""))+ key = (item.clause if use_clause else None, labels)+ out[key] = {point.time: point.value for point in item.points}+ return out+++@time_machine.travel(NOW, tick=False)+class TestMetricsSqlMode(ClickhouseTestMixin, APIBaseTest):+ def _seed(self) -> None:+ start = NOW - dt.timedelta(minutes=70)+ for metric_name, kind in _metric_kinds().items():+ for index, (service, labels) in enumerate(SERIES_LABELS):+ if metric_name == API_ONLY_METRIC and service != "api":+ continue+ minutes = range(0, 35 if metric_name == SPARSE_METRIC and service == "worker" else 70)+ if kind == "gauge":+ points = [+ (+ start + dt.timedelta(minutes=m),+ 0.0 if metric_name == ZERO_METRIC else float((index + 1) * 10 + m % 7),+ )+ for m in minutes+ ]+ seed_metric(+ team_id=self.team.pk,+ metric_name=metric_name,+ points=points,+ labels={**labels, "queue": 'it\'s a "quoted" \\ value'},+ service_name=service,+ )+ elif kind == "counter":+ points = [(start + dt.timedelta(minutes=m), float((index + 1) * m * 3)) for m in minutes]+ seed_metric(+ team_id=self.team.pk,+ metric_name=metric_name,+ points=points,+ labels=labels,+ service_name=service,+ metric_type="sum",+ is_monotonic=True,+ )+ else:+ for m in minutes:+ seed_metric(+ team_id=self.team.pk,+ metric_name=metric_name,+ points=[(start + dt.timedelta(minutes=m), 0.0)],+ labels=labels,+ service_name=service,+ metric_type="histogram",+ histogram_bounds=HISTOGRAM_BOUNDS,+ histogram_counts=[m * (index + 1), m * 3, m, 0],+ )++ def _run(self, **fields: Any) -> list[Any]:+ query = MetricsQuery(dateRange=DATE_RANGE, interval="minute_5", **fields)+ return MetricsQueryRunner(query=query, team=self.team).calculate().results++ def test_generated_sql_matches_the_builder_engine(self) -> None:+ self._seed()+ for name, fixture in FIXTURES.items():+ with self.subTest(fixture=name):+ builder = fixture["builder"]+ expected = self._run(+ clauses=[MetricsQueryClause(**clause) for clause in builder["clauses"]],+ formula=builder.get("formula"),+ )+ actual = self._run(clauses=[], language="sql", sql=fixture["sql"])++ use_clause = len(builder["clauses"]) > 1 and not builder.get("formula")+ expected_points = _comparable(expected, use_clause=use_clause)+ actual_points = _comparable(actual, use_clause=use_clause)+ # With no data the builder returns one series without points, and SQL returns none.+ expected_points = {key: values for key, values in expected_points.items() if values}+ assert set(actual_points) == set(expected_points), name+ for key, expected_values in expected_points.items():+ assert list(actual_points[key]) == list(expected_values), (name, key)+ for time, value in expected_values.items():+ actual_value = actual_points[key][time]+ assert (actual_value is None) == (value is None), (name, key, time)+ if value is not None and actual_value is not None:+ assert math.isclose(actual_value, value, rel_tol=1e-6, abs_tol=1e-9), (name, key, time)++ def test_mixed_histogram_bounds_fail_in_both_languages(self) -> None:+ start = NOW - dt.timedelta(minutes=30)+ for bounds, service in (([10.0], "api"), ([100.0], "worker")):+ for m in range(0, 30):+ seed_metric(+ team_id=self.team.pk,+ metric_name="http.server.duration",+ points=[(start + dt.timedelta(minutes=m), 0.0)],+ service_name=service,+ metric_type="histogram",+ histogram_bounds=bounds,+ histogram_counts=[m * 10, 0],+ )+ fixture = FIXTURES["histogram p99"]++ with pytest.raises(ExposedHogQLError, match="histogram bounds differ"):+ self._run(clauses=[MetricsQueryClause(**clause) for clause in fixture["builder"]["clauses"]])+ with pytest.raises(Exception, match="different histogram bounds"):+ self._run(clauses=[], language="sql", sql=fixture["sql"])++ @parameterized.expand(+ [+ # 40 series in 288 buckets: more rows than an aggregated builder clause may return,+ # but fewer than a clause without an aggregation may.+ ("per_series_day_of_5_minute_buckets", 11_520, None),+ ("over_the_row_limit", 100_000, "too many rows"),+ # Each row its own clause: under the row limit, but too many series to chart.+ ("a_clause_for_each_row", 9_000, "too many series"),+ ]+ )+ def test_sql_output_limits(self, _name: str, rows: int, error: str | None) -> None:+ clause = "toString(n) AS clause, " if error == "too many series" else ""+ sql = (+ f"SELECT toDateTime('2026-09-19 11:00:00') + toIntervalMinute(intDiv(n, 40) * 5) AS time, "+ f"1 AS value, {clause}toString(n % 40) AS series FROM (SELECT arrayJoin(range({rows})) AS n)"+ )+ if error:+ with pytest.raises(ExposedHogQLError, match=error):+ self._run(clauses=[], language="sql", sql=sql)+ else:+ results = self._run(clauses=[], language="sql", sql=sql)+ assert (len(results), {len(series.points) for series in results}) == (40, {288})++ @parameterized.expand(+ [+ ("no_value_column", "SELECT timestamp AS time FROM posthog.metrics", 'a "time" and a "value" column'),+ ("other_table", "SELECT timestamp AS time, 1 AS value FROM events", "can only read the metrics tables"),+ (+ "other_table_in_subquery",+ "SELECT now() AS time, count() AS value FROM posthog.metrics WHERE metric_name IN (SELECT event FROM events)",+ "can only read the metrics tables",+ ),+ (+ "other_table_in_hogqlx_tag",+ "SELECT 1 AS time, 1 AS value FROM <HogQLQuery query='SELECT event FROM events' />",+ "can only read the metrics tables",+ ),+ (+ "cte_name_from_another_scope",+ "SELECT now() AS time, 1 AS value FROM posthog.metrics "+ "WHERE 1 IN (WITH events AS (SELECT 1 AS x) SELECT x FROM events) "+ "UNION ALL SELECT timestamp AS time, 1 AS value FROM events",+ "can only read the metrics tables",+ ),+ (+ "cte_that_reads_another_table",+ "WITH events AS (SELECT * FROM events) SELECT timestamp AS time, 1 AS value FROM events",+ "can only read the metrics tables",+ ),+ ]+ )+ def test_rejects_sql_outside_the_contract(self, _name: str, sql: str, message: str) -> None:+ with pytest.raises(ExposedHogQLError, match=message):+ self._run(clauses=[], language="sql", sql=sql)++ @parameterized.expand(+ [+ (+ "cte",+ "WITH samples AS (SELECT * FROM posthog.metrics) SELECT now() AS time, count() AS value FROM samples AS s",+ ),+ (+ "subquery_join",+ "SELECT now() AS time, count() AS value FROM (SELECT metric_name FROM posthog.metrics) AS m "+ "JOIN posthog.metric_names AS n ON m.metric_name = n.metric_name",+ ),+ ]+ )+ def test_accepts_ctes_and_subqueries_over_metrics_tables(self, _name: str, sql: str) -> None:+ self._run(clauses=[], language="sql", sql=sql)++ def test_date_placeholders_follow_the_date_range(self) -> None:+ seed_metric(+ team_id=self.team.pk,+ metric_name="queue_depth",+ points=[(NOW - dt.timedelta(minutes=30), 4.0), (NOW - dt.timedelta(hours=3), 9.0)],+ )+ sql = (+ "SELECT toStartOfInterval(timestamp, {interval}) AS time, max(value) AS value FROM posthog.metrics "+ "WHERE metric_name = 'queue_depth' AND timestamp >= {date_from} AND timestamp < {date_to} GROUP BY time"+ )++ [series] = self._run(clauses=[], language="sql", sql=sql)++ assert [point.value for point in series.points] == [4.0]++ def test_raw_sample_times_are_not_zero_filled(self) -> None:+ for service, offset in (("api", 0), ("worker", 7)):+ seed_metric(+ team_id=self.team.pk,+ metric_name="cpu",+ points=[(NOW - dt.timedelta(minutes=30, seconds=offset + 15 * i), 50.0) for i in range(4)],+ service_name=service,+ )+ sql = (+ "SELECT timestamp AS time, service_name, value FROM posthog.metrics "+ "WHERE metric_name = 'cpu' AND timestamp >= {date_from} AND timestamp < {date_to}"+ )++ results = self._run(clauses=[], language="sql", sql=sql)++ assert {point.value for series in results for point in series.points} == {50.0, None}++ @parameterized.expand([("UTC", "week", "-30d"), ("Asia/Kathmandu", "minute_30", "-3h")])+ def test_interval_starts_are_zero_filled_in_any_timezone(+ self, timezone: str, interval: str, date_from: str+ ) -> None:+ self.team.timezone = timezone+ self.team.save()+ sql = (+ "SELECT toStartOfInterval({date_from} + toIntervalSecond(n * {interval_seconds}), {interval}) AS time, "+ "if(n = 0, 'api', 'worker') AS service, 1 AS value FROM (SELECT arrayJoin([0, 1, 2]) AS n)"+ )+ query = MetricsQuery(+ clauses=[], language="sql", sql=sql, interval=interval, dateRange=DateRange(date_from=date_from)+ )++ results = MetricsQueryRunner(query=query, team=self.team).calculate().results++ by_service = {series.labels["service"]: [point.value for point in series.points] for series in results}+ assert by_service == {"api": [1.0, 0.0, 0.0], "worker": [0.0, 1.0, 1.0]}++ def test_caches_like_a_metrics_insight_not_a_sql_insight(self) -> None:+ sql = "SELECT now() AS time, 1 AS value FROM posthog.metrics"+ sql_runner = MetricsQueryRunner(query=MetricsQuery(clauses=[], language="sql", sql=sql), team=self.team)+ builder_runner = MetricsQueryRunner(+ query=MetricsQuery(clauses=[MetricsQueryClause(name="a", metricName="queue_depth", aggregation="sum")]),+ team=self.team,+ )+ other_sql_runner = MetricsQueryRunner(+ query=MetricsQuery(clauses=[], language="sql", sql=sql + " LIMIT 5"), team=self.team+ )++ sql_insight_runner = HogQLQueryRunner(query=HogQLQuery(query=sql), team=self.team)++ sql_age = sql_runner.cache_target_age(NOW)+ sql_insight_age = sql_insight_runner.cache_target_age(NOW)+ assert sql_age is not None and sql_insight_age is not None+ assert sql_age == builder_runner.cache_target_age(NOW)+ assert sql_age < sql_insight_age+ assert sql_runner.get_cache_key() != other_sql_runner.get_cache_key()+ assert sql_runner.get_cache_payload()["query_runner"] == "MetricsQueryRunner"+++def _snuffle_response(status_code: int, payload: dict[str, Any]) -> MagicMock:+ response = MagicMock(spec=requests.Response)+ response.status_code = status_code+ response.json.return_value = payload+ response.headers = {}+ return response+++@override_settings(SNUFFLE_APM_URL="http://snuffle.test:9091", SNUFFLE_APM_USER="reader", SNUFFLE_APM_PASSWORD="secret")+@time_machine.travel(NOW, tick=False)+class TestMetricsPromQLMode(APIBaseTest):+ def _runner(self, promql: str = "sum by (job) (rate(http_requests_total))") -> MetricsQueryRunner:+ query = MetricsQuery(clauses=[], language="promql", promql=promql, dateRange=DATE_RANGE)+ return MetricsQueryRunner(query=query, team=self.team)++ def test_runs_a_range_query_and_maps_the_matrix(self) -> None:+ start = int(dt.datetime(2026, 9, 19, 11, 0, tzinfo=dt.UTC).timestamp())+ payload = {+ "status": "success",+ "data": {+ "resultType": "matrix",+ "result": [+ {"metric": {"job": "api", "clause": "a"}, "values": [[start, "1.5"], [start + 60, "NaN"]]},+ {"metric": {"__name__": "up", "job": "worker"}, "values": [[start + 60, "4"]]},+ ],+ },+ }+ with patch(+ "posthog.api.snuffle_proxy.internal_requests.request", return_value=_snuffle_response(200, payload)+ ) as request:+ results = self._runner().calculate().results++ method, url = request.call_args.args+ sent = request.call_args.kwargs+ assert (method, url) == ("POST", "http://snuffle.test:9091/api/v1/query_range")+ assert sent["data"]["query"] == "sum by (job) (rate(http_requests_total))"+ assert sent["data"]["step"] == "60"+ assert sent["headers"]["X-Team-ID"] == str(self.team.pk)+ by_job = {series.labels["job"]: series for series in results}+ assert [point.value for point in by_job["worker"].points] == [None, 4.0]+ assert [point.value for point in by_job["api"].points] == [1.5, None]+ assert by_job["worker"].metricName == "up"++ @parameterized.expand(+ [+ # (name, promql, the series' clause, its labels)+ (+ "builder_series_marker",+ 'label_replace(sum by (job) (rate(x)), "clause", "a", "", "")',+ "a",+ {"job": "api"},+ ),+ ("label_from_the_data", "sum by (job, clause) (rate(x))", None, {"job": "api", "clause": "a"}),+ ]+ )+ def test_clause_label_marks_a_series_only_when_the_query_sets_it(+ self, _name: str, promql: str, clause: str | None, labels: dict[str, str]+ ) -> None:+ start = int(dt.datetime(2026, 9, 19, 11, 0, tzinfo=dt.UTC).timestamp())+ payload = {+ "status": "success",+ "data": {+ "resultType": "matrix",+ "result": [{"metric": {"job": "api", "clause": "a"}, "values": [[start, "1"]]}],+ },+ }+ with patch("posthog.api.snuffle_proxy.internal_requests.request", return_value=_snuffle_response(200, payload)):+ [series] = self._runner(promql).calculate().results++ assert (series.clause, series.labels) == (clause, labels)++ def test_empty_scalar_result_has_no_series(self) -> None:+ payload = {"status": "success", "data": {"resultType": "scalar", "result": []}}+ with patch("posthog.api.snuffle_proxy.internal_requests.request", return_value=_snuffle_response(200, payload)):+ assert self._runner("1").calculate().results == []++ @parameterized.expand(+ [+ (+ "bad_query",+ _snuffle_response(400, {"status": "error", "errorType": "bad_data", "error": "parse error at char 5"}),+ "parse error at char 5",+ ),+ ("upstream_failure", _snuffle_response(503, {}), "backend failed"),+ ]+ )+ def test_upstream_errors_are_shown_to_the_user(self, _name: str, response: MagicMock, message: str) -> None:+ with patch("posthog.api.snuffle_proxy.internal_requests.request", return_value=response):+ with pytest.raises(ExposedHogQLError, match=message):+ self._runner().calculate()++ def test_explains_when_snuffle_is_not_configured(self) -> None:+ with override_settings(SNUFFLE_APM_URL=""):+ with pytest.raises(ExposedHogQLError, match="not available"):+ self._runner().calculate()++ def test_timeout_is_shown_to_the_user(self) -> None:+ with patch("posthog.api.snuffle_proxy.internal_requests.request", side_effect=requests.Timeout()):+ with pytest.raises(ExposedHogQLError, match="timed out"):+ self._runner().calculate()++ @parameterized.expand([("request_user",), ("shared_link_viewer",), ("userless_refresh",)])+ def test_needs_the_snuffle_flag(self, viewer: str) -> None:+ def flag_enabled(flag: str, *args: Any, **kwargs: Any) -> bool:+ return flag != "logs-metrics-snuffle-api"++ with patch("posthoganalytics.feature_enabled", side_effect=flag_enabled):+ with pytest.raises(UserAccessControlError):+ if viewer == "request_user":+ self._runner().validate_query_runner_access(self.user)+ else:+ # Shared links and scheduled refreshes skip validate_query_runner_access.+ user = (+ cast(User, SharedLinkUser(SharingConfiguration.objects.create(team=self.team, enabled=True)))+ if viewer == "shared_link_viewer"+ else None+ )+ MetricsQueryRunner(query=self._runner().query, team=self.team, user=user).calculate()+++def test_series_cap_applies_per_clause() -> None:+ def row(clause: str, job: str, value: float) -> tuple[dict[str, str], None, str, list[MetricPoint]]:+ return ({"job": job}, None, clause, [MetricPoint(time="2026-09-19T11:00:00+00:00", value=value)])++ rows = [row("a", "big", 100.0), row("a", "huge", 900.0), row("b", "small", 1.0)]+ with patch("products.metrics.backend.series.MAX_SERIES_PER_CLAUSE", 1):+ series = rank_and_fill_series(rows, fill=None)++ assert [(item.clause, item.labels["job"]) for item in series] == [("a", "huge"), ("b", "small")]+++def test_grid_keeps_the_times_of_series_the_cap_drops() -> None:+ rows = [+ ({"job": "big"}, None, "a", [MetricPoint(time="11:00", value=100.0)]),+ ({"job": "small"}, None, "a", [MetricPoint(time="11:00", value=1.0), MetricPoint(time="11:05", value=1.0)]),+ ]+ with patch("products.metrics.backend.series.MAX_SERIES_PER_CLAUSE", 1):+ [series] = rank_and_fill_series(rows, fill=0.0)++ assert [(point.time, point.value) for point in series.points] == [("11:00", 100.0), ("11:05", 0.0)]++[email protected]([("too_many_series", 3, 1), ("too_many_points", 2, 3)])+def test_output_is_bounded(_name: str, series_count: int, time_count: int) -> None:+ rows = [+ ({"job": str(index)}, None, str(index), [MetricPoint(time=str(time), value=1.0) for time in range(time_count)])+ for index in range(series_count)+ ]+ with (+ patch("products.metrics.backend.series.MAX_SERIES_TOTAL", 2),+ patch("products.metrics.backend.series.MAX_POINTS_TOTAL", 4),+ pytest.raises(ValueError, match="too many series"),+ ):+ rank_and_fill_series(rows, fill=None)diff --git a/products/metrics/frontend/components/MetricsQueryControls.tsx b/products/metrics/frontend/components/MetricsQueryControls.tsxnew file mode 100644index 000000000000..4a61efe560ca--- /dev/null+++ b/products/metrics/frontend/components/MetricsQueryControls.tsx@@ -0,0 +1,354 @@+import { useActions, useMountedLogic, useValues } from 'kea'+import { ReactNode, useEffect, useMemo, useState } from 'react'++import { IconPlusSmall } from '@posthog/icons'+import { LemonButton, LemonInput, LemonSelect, Tooltip } from '@posthog/lemon-ui'++import { DateFilter } from 'lib/components/DateFilter/DateFilter'+import { CUSTOM_OPTION_KEY } from 'lib/components/DateFilter/types'+import { dayjs } from 'lib/dayjs'+import { useFeatureFlag } from 'lib/hooks/useFeatureFlag'+import { CodeEditorResizeable } from 'lib/monaco/CodeEditorResizable'+import { setPromQLCompletionProvider } from 'lib/monaco/languages/promqlCompletionRegistry'+import { getAccessControlDisabledReason } from 'lib/utils/accessControlUtils'+import { DATE_TIME_FORMAT, formatDateRange } from 'lib/utils/datetime'+import { teamLogic } from 'scenes/teamLogic'++import {+ type MetricsDisplayType,+ type MetricsQuery,+ type MetricsQueryLanguage,+ NodeKind,+} from '~/queries/schema/schema-general'+import { AccessControlLevel, AccessControlResourceType, DateMappingOption } from '~/types'++import { METRICS_PANELS } from '../panels/registry'+import { getPromQLCompletions } from '../queryLanguages/promqlCompletion'+import { createMetricsPromQLCompletionSource } from '../queryLanguages/promqlCompletionSource'+import { MetricsChartSettings } from './MetricsChartSettings'+import { MetricsClauseRow } from './MetricsClauseRow'+import { MetricsIntervalPicker } from './MetricsIntervalPicker'+import { MetricsQueryLanguagePicker } from './MetricsQueryLanguagePicker'+import { MAX_CLAUSES, metricsViewerLogic, sanitizeFormulaInput } from './metricsViewerLogic'++// Mirrors the curated set used by `LogsViewer/Filters/DateRangeFilter`.+const METRICS_DATE_OPTIONS: DateMappingOption[] = [+ { key: CUSTOM_OPTION_KEY, values: [] },+ {+ key: 'Last 5 minutes',+ values: ['-5M'],+ getFormattedDate: (date: dayjs.Dayjs): string => date.subtract(5, 'minute').format(DATE_TIME_FORMAT),+ defaultInterval: 'minute',+ },+ {+ key: 'Last 30 minutes',+ values: ['-30M'],+ getFormattedDate: (date: dayjs.Dayjs): string => date.subtract(30, 'minute').format(DATE_TIME_FORMAT),+ defaultInterval: 'minute',+ },+ {+ key: 'Last 1 hour',+ values: ['-1h'],+ getFormattedDate: (date: dayjs.Dayjs): string => formatDateRange(date.subtract(1, 'h'), date.endOf('d')),+ defaultInterval: 'hour',+ },+ {+ key: 'Last 24 hours',+ values: ['-24h'],+ getFormattedDate: (date: dayjs.Dayjs): string => formatDateRange(date.subtract(24, 'h'), date.endOf('d')),+ defaultInterval: 'hour',+ },+ {+ key: 'Last 7 days',+ values: ['-7d'],+ getFormattedDate: (date: dayjs.Dayjs): string => formatDateRange(date.subtract(7, 'd'), date.endOf('d')),+ defaultInterval: 'day',+ },+]++const BASE_DISPLAY_TYPES: MetricsDisplayType[] = ['line', 'area', 'bar']+const PANEL_DISPLAY_TYPES: MetricsDisplayType[] = ['stat', 'gauge', 'bargauge', 'table']++// Shown in an empty editor, so the expected shape is visible without help text.+const PLACEHOLDERS: Record<Exclude<MetricsQueryLanguage, 'builder'>, string> = {+ promql: 'sum by (service_name) (rate(http_requests_total))',+ sql: 'SELECT … AS time, … AS value FROM posthog.metrics WHERE timestamp >= {date_from}',+}++function MetricsQueryTextEditor({+ language,+ disabledReason,+ onRun,+}: {+ language: Exclude<MetricsQueryLanguage, 'builder'>+ disabledReason: string | null+ onRun: () => void+}): JSX.Element {+ const { queryDraft } = useValues(metricsViewerLogic)+ const { setQueryDraft } = useActions(metricsViewerLogic)+ const { currentTeamId } = useValues(teamLogic)++ useEffect(() => {+ if (language !== 'promql' || !currentTeamId) {+ return+ }+ const source = createMetricsPromQLCompletionSource(String(currentTeamId))+ // Load the metric names now, so the first suggestions do not wait for them.+ void source.metricNames('').catch(() => undefined)+ return setPromQLCompletionProvider((text, offset) => getPromQLCompletions(text, offset, source))+ }, [language, currentTeamId])++ return (+ <div className="w-full" data-attr={`metrics-query-editor-${language}`}>+ <CodeEditorResizeable+ // HogQL validation would flag the date placeholders, so SQL gets plain SQL highlighting.+ language={language === 'promql' ? 'promql' : 'sql'}+ value={queryDraft}+ onChange={(value) => setQueryDraft(value ?? '')}+ onPressCmdEnter={onRun}+ minHeight={language === 'sql' ? '8rem' : '2.5rem'}+ maxHeight="24rem"+ options={{+ readOnly: !!disabledReason,+ placeholder: PLACEHOLDERS[language],+ minimap: { enabled: false },+ wordWrap: 'on',+ scrollBeyondLastLine: false,+ lineNumbers: language === 'sql' ? 'on' : 'off',+ folding: false,+ glyphMargin: false,+ lineDecorationsWidth: 10,+ overviewRulerLanes: 0,+ hideCursorInOverviewRuler: true,+ renderLineHighlight: 'none',+ padding: { top: 6, bottom: 6 },+ scrollbar: { useShadows: false, verticalScrollbarSize: 8, alwaysConsumeMouseWheel: false },+ // Label values and quoted OTel names are typed inside strings.+ quickSuggestions: { other: true, comments: false, strings: true },+ }}+ />+ </div>+ )+}++export interface MetricsQueryControlsProps {+ /** Prefix of the `data-attr` of each control, so each surface keeps its own analytics names. */+ dataAttrPrefix: 'metrics-viewer' | 'metrics-query-editor'+ /** The query a language switch converts while the builder has no metric yet. */+ fallbackQuery?: MetricsQuery+ /** Shows the builder / PromQL / SQL switch. Gets the query as it is now, including an unrun draft. */+ onSwitchLanguage?: (current: MetricsQuery, to: MetricsQueryLanguage) => void+ /** Runs the current PromQL or SQL query again when Run is pressed without a change, as after a failure. */+ onRerun?: () => void+ /** Whether the result has labels. Without it, the builder's group-bys decide. */+ resultIsGrouped?: boolean+ /** Offers the heatmap display, which saves a histogram query instead of a time series. */+ heatmap?: { eligible: boolean }+ /** Controls after the date range and interval. */+ toolbarExtras?: ReactNode+ /** Controls after the display settings. */+ displayExtras?: ReactNode+ /** Buttons on the right of the display row. */+ actions?: ReactNode+}++/** The metrics query controls of the `/metrics` viewer and the metrics insight editor. */+export function MetricsQueryControls({+ dataAttrPrefix,+ fallbackQuery,+ onSwitchLanguage,+ onRerun,+ resultIsGrouped: resultIsGroupedProp,+ heatmap,+ toolbarExtras,+ displayExtras,+ actions,+}: MetricsQueryControlsProps): JSX.Element {+ const { viewerClauses, activeClauseIndex, formula, namedClauses, dateFrom, dateTo, interval } =+ useValues(metricsViewerLogic)+ const { displayType, language, queryDraft } = useValues(metricsViewerLogic)+ const { addClause, setDateFrom, setDateTo, setInterval, setDisplayType, runQueryText } =+ useActions(metricsViewerLogic)+ const logic = useMountedLogic(metricsViewerLogic)+ const dashboardPanelsEnabled = useFeatureFlag('METRICS_DASHBOARD_PANELS')+ const disabledReason = getAccessControlDisabledReason(AccessControlResourceType.Metrics, AccessControlLevel.Viewer)++ // A changed query runs through the query node. An unchanged one (after a failure) runs again in place.+ const runQuery = (): void => (logic.values.queryTextChanged ? runQueryText() : onRerun?.())++ const switchLanguage = (to: MetricsQueryLanguage): void => {+ // Read the logic at click time, so a draft the user has not run yet still converts.+ const { metricsQueryNode: node, queryDraft } = logic.values+ const current = node ?? fallbackQuery ?? { kind: NodeKind.MetricsQuery, clauses: [] }+ onSwitchLanguage?.(language === 'builder' ? current : { ...current, [language]: queryDraft.trim() }, to)+ }++ // A formula result is ungrouped even when its input clauses group. PromQL and SQL results can have any labels.+ const resultIsGrouped =+ resultIsGroupedProp ??+ (language !== 'builder' || (!formula && namedClauses.some((clause) => clause.groupByKeys.length > 0)))+ const displayTypeOptions = useMemo(() => {+ const types: MetricsDisplayType[] = dashboardPanelsEnabled+ ? [...BASE_DISPLAY_TYPES, ...PANEL_DISPLAY_TYPES, ...(heatmap ? (['heatmap'] as const) : [])]+ : BASE_DISPLAY_TYPES+ return types.map((value) => {+ const def = METRICS_PANELS[value]+ const reason = def.needsGroupBy+ ? !resultIsGrouped+ ? 'Add a group-by to use this panel'+ : undefined+ : def.needsHistogram && !heatmap?.eligible+ ? 'Pick a single histogram metric (no formula) to use this panel'+ : undefined+ return { value, label: def.label, disabledReason: reason }+ })+ }, [dashboardPanelsEnabled, resultIsGrouped, heatmap])++ const showFormulaInput = viewerClauses.length > 1 || formula !== ''++ const dateControls = (+ <div className="flex flex-wrap items-center gap-2">+ <DateFilter+ size="small"+ dateFrom={dateFrom}+ dateTo={dateTo}+ dateOptions={METRICS_DATE_OPTIONS}+ onChange={(changedDateFrom, changedDateTo) => {+ setDateFrom(changedDateFrom)+ setDateTo(changedDateTo)+ }}+ allowTimePrecision+ allowFixedRangeWithTime+ allowedRollingDateOptions={['minutes', 'hours', 'days', 'weeks']}+ use24HourFormat+ disabledReason={disabledReason}+ />+ <MetricsIntervalPicker value={interval} onChange={setInterval} disabledReason={disabledReason} />+ {toolbarExtras}+ </div>+ )++ const builderControls = (+ <div className="flex flex-col gap-2 flex-1 min-w-[16rem]">+ {viewerClauses.map((clause, index) => (+ <MetricsClauseRow+ key={clause.name}+ clause={clause}+ index={index}+ isActive={index === activeClauseIndex}+ showAlias={viewerClauses.length > 1}+ disabledReason={disabledReason}+ />+ ))}+ <div className="flex flex-wrap items-center gap-2">+ <LemonButton+ size="small"+ type="secondary"+ icon={<IconPlusSmall />}+ onClick={() => addClause()}+ disabledReason={+ disabledReason ??+ (viewerClauses.length >= MAX_CLAUSES+ ? `A query can have at most ${MAX_CLAUSES} series`+ : undefined)+ }+ data-attr={`${dataAttrPrefix}-add-series`}+ >+ Add series+ </LemonButton>+ {showFormulaInput && <MetricsFormulaInput disabledReason={disabledReason} />}+ </div>+ </div>+ )++ return (+ <div className="flex flex-col gap-2" data-attr={dataAttrPrefix}>+ {onSwitchLanguage ? (+ <>+ <div className="flex flex-wrap items-center justify-between gap-2">+ <MetricsQueryLanguagePicker+ value={language}+ onChange={switchLanguage}+ disabledReason={disabledReason}+ />+ {dateControls}+ </div>+ {language === 'builder' ? (+ builderControls+ ) : (+ <MetricsQueryTextEditor language={language} disabledReason={disabledReason} onRun={runQuery} />+ )}+ </>+ ) : (+ <div className="flex flex-wrap items-start gap-2 justify-between">+ {builderControls}+ {dateControls}+ </div>+ )}+ <div className="flex flex-wrap items-center justify-between gap-2">+ <div className="flex flex-wrap items-center gap-2">+ <LemonSelect+ size="small"+ value={displayType}+ options={displayTypeOptions}+ onChange={setDisplayType}+ data-attr={`${dataAttrPrefix}-display-type`}+ disabledReason={disabledReason}+ />+ <MetricsChartSettings />+ {displayExtras}+ </div>+ <div className="flex flex-wrap items-center gap-2">+ {actions}+ {language !== 'builder' && (+ <LemonButton+ type="primary"+ size="small"+ onClick={runQuery}+ disabledReason={disabledReason ?? (queryDraft.trim() ? undefined : 'Write a query first')}+ data-attr={`metrics-query-editor-run-${language}`}+ >+ Run+ </LemonButton>+ )}+ </div>+ </div>+ </div>+ )+}++// Committed on blur/Enter (mirroring TrendsFormula) so a half-typed formula doesn't fire+// a query per keystroke. Input is lowercased — clause aliases are lowercase and the+// backend parser is case-sensitive.+const MetricsFormulaInput = ({ disabledReason }: { disabledReason: string | null }): JSX.Element => {+ const { formula } = useValues(metricsViewerLogic)+ const { setFormula } = useActions(metricsViewerLogic)+ const [draft, setDraft] = useState(formula)++ // An external change (URL restore, clause reset) replaces the local draft.+ useEffect(() => {+ setDraft(formula)+ }, [formula])++ const commit = (): void => {+ if (draft !== formula) {+ setFormula(draft)+ }+ }++ return (+ <Tooltip title="Arithmetic over the series letters, with + - * / and parentheses. Only the formula result is charted.">+ <LemonInput+ size="small"+ className="min-w-48"+ value={draft}+ onChange={(value) => setDraft(sanitizeFormulaInput(value))}+ onBlur={commit}+ onPressEnter={commit}+ placeholder="Formula, e.g. (a - b) / a"+ data-attr="metrics-viewer-formula"+ disabledReason={disabledReason}+ />+ </Tooltip>+ )+}diff --git a/products/metrics/frontend/components/MetricsQueryEditor.tsx b/products/metrics/frontend/components/MetricsQueryEditor.tsxindex fe3e506ddac4..f0f9fcb374dc 100644--- a/products/metrics/frontend/components/MetricsQueryEditor.tsx+++ b/products/metrics/frontend/components/MetricsQueryEditor.tsx@@ -1,62 +1,48 @@-import { BindLogic, useActions, useValues } from 'kea'+import { BindLogic, useValues } from 'kea'import { useEffect, useMemo, useRef } from 'react'-import { IconPlusSmall } from '@posthog/icons'-import { LemonButton, LemonSelect } from '@posthog/lemon-ui'--import { DateFilter } from 'lib/components/DateFilter/DateFilter'-import { useFeatureFlag } from 'lib/hooks/useFeatureFlag'-import { getAccessControlDisabledReason } from 'lib/utils/accessControlUtils'import { objectsEqual } from 'lib/utils/objects'-import type { MetricsDisplayType, MetricsQuery } from '~/queries/schema/schema-general'-import { AccessControlLevel, AccessControlResourceType } from '~/types'--import { METRICS_PANELS } from '../panels/registry'-import { MetricsChartSettings } from './MetricsChartSettings'-import { MetricsClauseRow } from './MetricsClauseRow'-import { MetricsIntervalPicker } from './MetricsIntervalPicker'-import { METRICS_DATE_OPTIONS, MetricsFormulaInput } from './MetricsViewer'-import { MAX_CLAUSES, metricsViewerLogic } from './metricsViewerLogic'+import type { MetricsQuery, MetricsQueryLanguage } from '~/queries/schema/schema-general'-// The heatmap saves a different query kind, so the insight editor leaves it out.-const BASE_DISPLAY_TYPES: MetricsDisplayType[] = ['line', 'area', 'bar']-const PANEL_DISPLAY_TYPES: MetricsDisplayType[] = ['stat', 'gauge', 'bargauge', 'table']+import { MetricsQueryControls } from './MetricsQueryControls'+import { metricsViewerLogic } from './metricsViewerLogic'/** The `/metrics` viewer's builder, editing a `MetricsQuery` in the insight editor. */export function MetricsQueryEditor({editorKey,query,setQuery,+ onSwitchLanguage,+ onRerun,}: {editorKey: stringquery: MetricsQuerysetQuery: (query: MetricsQuery) => void+ /** Shows the builder / PromQL / SQL switch. Gets the query as it is now, including an unrun draft. */+ onSwitchLanguage?: (current: MetricsQuery, to: MetricsQueryLanguage) => void+ /** Runs the current PromQL or SQL query again when Run is pressed without a change, as after a failure. */+ onRerun?: () => void}): JSX.Element {// The query seeds the logic once. After that the builder only writes the query, so the two cannot loop.const logicProps = useMemo(() => ({ key: editorKey, initialQuery: query }), [editorKey]) // eslint-disable-line react-hooks/exhaustive-depsreturn (<BindLogic logic={metricsViewerLogic} props={logicProps}>- <MetricsQueryEditorControls query={query} setQuery={setQuery} />+ <MetricsQuerySync query={query} setQuery={setQuery} />+ <MetricsQueryControls+ dataAttrPrefix="metrics-query-editor"+ fallbackQuery={query}+ onSwitchLanguage={onSwitchLanguage}+ onRerun={onRerun}+ /></BindLogic>)}-function MetricsQueryEditorControls({- query,- setQuery,-}: {- query: MetricsQuery- setQuery: (query: MetricsQuery) => void-}): JSX.Element {- const { viewerClauses, activeClauseIndex, formula, namedClauses, dateFrom, dateTo, interval } =- useValues(metricsViewerLogic)- const { displayType, metricsQueryNode } = useValues(metricsViewerLogic)- const { addClause, setDateFrom, setDateTo, setInterval, setDisplayType } = useActions(metricsViewerLogic)- const dashboardPanelsEnabled = useFeatureFlag('METRICS_DASHBOARD_PANELS')- const disabledReason = getAccessControlDisabledReason(AccessControlResourceType.Metrics, AccessControlLevel.Viewer)-+/** Writes the builder's query back to the insight as it changes. */+function MetricsQuerySync({ query, setQuery }: { query: MetricsQuery; setQuery: (query: MetricsQuery) => void }): null {+ const { metricsQueryNode } = useValues(metricsViewerLogic)// The node the saved query maps to. Until the first edit, a node equal to it is not written back,// so opening the editor does not mark the insight as changed.const seedNode = useRef(metricsQueryNode)@@ -67,89 +53,16 @@ function MetricsQueryEditorControls({}edited.current = true// Keep node fields the builder does not own; drop the optional ones it does, so clearing them sticks.- const { formula: _formula, interval: _interval, display: _display, ...rest } = query+ const {+ formula: _formula,+ interval: _interval,+ display: _display,+ language: _language,+ promql: _promql,+ sql: _sql,+ ...rest+ } = querysetQuery({ ...rest, ...metricsQueryNode })}, [metricsQueryNode]) // eslint-disable-line react-hooks/exhaustive-deps-- // A formula result is ungrouped even when its input clauses group.- const resultIsGrouped = !formula && namedClauses.some((clause) => clause.groupByKeys.length > 0)- const displayTypeOptions = useMemo(() => {- const types = dashboardPanelsEnabled ? [...BASE_DISPLAY_TYPES, ...PANEL_DISPLAY_TYPES] : BASE_DISPLAY_TYPES- return types.map((value) => {- const def = METRICS_PANELS[value]- return {- value,- label: def.label,- disabledReason: def.needsGroupBy && !resultIsGrouped ? 'Add a group-by to use this panel' : undefined,- }- })- }, [dashboardPanelsEnabled, resultIsGrouped])-- const showFormulaInput = viewerClauses.length > 1 || formula !== ''-- return (- <div className="flex flex-col gap-2" data-attr="metrics-query-editor">- <div className="flex flex-wrap items-start gap-2 justify-between">- <div className="flex flex-col gap-2 flex-1 min-w-[16rem]">- {viewerClauses.map((clause, index) => (- <MetricsClauseRow- key={clause.name}- clause={clause}- index={index}- isActive={index === activeClauseIndex}- showAlias={viewerClauses.length > 1}- disabledReason={disabledReason}- />- ))}- <div className="flex flex-wrap items-center gap-2">- <LemonButton- size="small"- type="secondary"- icon={<IconPlusSmall />}- onClick={() => addClause()}- disabledReason={- disabledReason ??- (viewerClauses.length >= MAX_CLAUSES- ? `A query can have at most ${MAX_CLAUSES} series`- : undefined)- }- data-attr="metrics-query-editor-add-series"- >- Add series- </LemonButton>- {showFormulaInput && <MetricsFormulaInput disabledReason={disabledReason} />}- </div>- </div>- <div className="flex flex-wrap items-center gap-2">- <DateFilter- size="small"- dateFrom={dateFrom}- dateTo={dateTo}- dateOptions={METRICS_DATE_OPTIONS}- onChange={(changedDateFrom, changedDateTo) => {- setDateFrom(changedDateFrom)- setDateTo(changedDateTo)- }}- allowTimePrecision- allowFixedRangeWithTime- allowedRollingDateOptions={['minutes', 'hours', 'days', 'weeks']}- use24HourFormat- disabledReason={disabledReason}- />- <MetricsIntervalPicker value={interval} onChange={setInterval} disabledReason={disabledReason} />- </div>- </div>- <div className="flex flex-wrap items-center gap-2">- <LemonSelect- size="small"- value={displayType}- options={displayTypeOptions}- onChange={setDisplayType}- data-attr="metrics-query-editor-display-type"- disabledReason={disabledReason}- />- <MetricsChartSettings />- </div>- </div>- )+ return null}diff --git a/products/metrics/frontend/components/MetricsQueryLanguagePicker.tsx b/products/metrics/frontend/components/MetricsQueryLanguagePicker.tsxnew file mode 100644index 000000000000..62dbadcae325--- /dev/null+++ b/products/metrics/frontend/components/MetricsQueryLanguagePicker.tsx@@ -0,0 +1,37 @@+import { LemonSegmentedButton } from '@posthog/lemon-ui'++import { useFeatureFlag } from 'lib/hooks/useFeatureFlag'++import type { MetricsQueryLanguage } from '~/queries/schema/schema-general'++import { METRICS_QUERY_LANGUAGE_LABELS } from './metricsQueryLanguageSwitch'++export function MetricsQueryLanguagePicker({+ value,+ onChange,+ disabledReason,+}: {+ value: MetricsQueryLanguage+ onChange: (language: MetricsQueryLanguage) => void+ disabledReason?: string | null+}): JSX.Element {+ // PromQL runs through Snuffle, which has its own flag.+ const promqlEnabled = useFeatureFlag('LOGS_METRICS_SNUFFLE_API')+ return (+ <LemonSegmentedButton+ size="small"+ value={value}+ onChange={onChange}+ data-attr="metrics-query-language"+ options={(['builder', 'promql', 'sql'] as const).map((language) => ({+ value: language,+ label: METRICS_QUERY_LANGUAGE_LABELS[language],+ disabledReason:+ disabledReason ??+ (language === 'promql' && !promqlEnabled && value !== 'promql'+ ? 'PromQL is not turned on for this project'+ : undefined),+ }))}+ />+ )+}diff --git a/products/metrics/frontend/components/MetricsViewer.tsx b/products/metrics/frontend/components/MetricsViewer.tsxindex 508c4cf3a844..a03bcc623567 100644--- a/products/metrics/frontend/components/MetricsViewer.tsx+++ b/products/metrics/frontend/components/MetricsViewer.tsx@@ -1,95 +1,36 @@import { useActions, useMountedLogic, useValues } from 'kea'import { router } from 'kea-router'-import { useEffect, useMemo, useState } from 'react'+import { useEffect, useMemo } from 'react'-import { IconPlusSmall } from '@posthog/icons'-import {- LemonBanner,- LemonButton,- LemonInput,- LemonSelect,- LemonSwitch,- SpinnerOverlay,- Tooltip,-} from '@posthog/lemon-ui'+import { LemonBanner, LemonButton, LemonSwitch, SpinnerOverlay } from '@posthog/lemon-ui'import { AddToDashboardModal } from 'lib/components/AddToDashboard/AddToDashboardModal'-import { DateFilter } from 'lib/components/DateFilter/DateFilter'-import { CUSTOM_OPTION_KEY } from 'lib/components/DateFilter/types'import { dayjs } from 'lib/dayjs'import { useFeatureFlag } from 'lib/hooks/useFeatureFlag'import { getAccessControlDisabledReason } from 'lib/utils/accessControlUtils'-import { DATE_TIME_FORMAT, formatDateRange } from 'lib/utils/datetime'import { NewDashboardModal } from 'scenes/dashboard/NewDashboardModal'import { teamLogic } from 'scenes/teamLogic'import { urls } from 'scenes/urls'-import type { MetricsDisplayType } from '~/queries/schema/schema-general'-import { AccessControlLevel, AccessControlResourceType, DateMappingOption } from '~/types'+import { AccessControlLevel, AccessControlResourceType } from '~/types'import { traceUrl } from 'products/tracing/frontend/traceLinks'import { getMetricsInsightEditorDisabledReason } from '../metricsAccess'import { MetricsHistogramQueryNode } from '../nodes/MetricsHistogramQueryNode'import { MetricsPanel } from '../panels/MetricsPanel'-import { METRICS_PANELS } from '../panels/registry'import { MetricsAnomalyPanel } from './MetricsAnomalyPanel'-import { MetricsChartSettings } from './MetricsChartSettings'-import { MetricsClauseRow } from './MetricsClauseRow'import { type MetricsExemplar } from './MetricsExemplarMarkers'-import { MetricsIntervalPicker } from './MetricsIntervalPicker'import { MetricsLogsSourceTag } from './MetricsLogsSourceTag'+import { MetricsQueryControls } from './MetricsQueryControls'+import { switchMetricsQueryLanguage } from './metricsQueryLanguageSwitch'import { MetricsRelatedMenu } from './MetricsRelatedMenu'import { metricsSamplesLogic } from './metricsSamplesLogic'import { MetricsSamplesPanel } from './MetricsSamplesPanel'import { metricsStarterDashboardLogic } from './metricsStarterDashboardLogic'import { MetricsStarterDashboardModal } from './MetricsStarterDashboardModal'import { metricsUsageTrackingLogic } from './metricsUsageTrackingLogic'-import {- LIVE_REFRESH_MS,- MAX_CLAUSES,- MAX_UNAGGREGATED_SERIES,- metricsViewerLogic,- sanitizeFormulaInput,-} from './metricsViewerLogic'--const BASE_DISPLAY_TYPES: MetricsDisplayType[] = ['line', 'area', 'bar']-const PANEL_DISPLAY_TYPES: MetricsDisplayType[] = ['stat', 'gauge', 'bargauge', 'table', 'heatmap']--// Mirrors the curated set used by `LogsViewer/Filters/DateRangeFilter`.-export const METRICS_DATE_OPTIONS: DateMappingOption[] = [- { key: CUSTOM_OPTION_KEY, values: [] },- {- key: 'Last 5 minutes',- values: ['-5M'],- getFormattedDate: (date: dayjs.Dayjs): string => date.subtract(5, 'minute').format(DATE_TIME_FORMAT),- defaultInterval: 'minute',- },- {- key: 'Last 30 minutes',- values: ['-30M'],- getFormattedDate: (date: dayjs.Dayjs): string => date.subtract(30, 'minute').format(DATE_TIME_FORMAT),- defaultInterval: 'minute',- },- {- key: 'Last 1 hour',- values: ['-1h'],- getFormattedDate: (date: dayjs.Dayjs): string => formatDateRange(date.subtract(1, 'h'), date.endOf('d')),- defaultInterval: 'hour',- },- {- key: 'Last 24 hours',- values: ['-24h'],- getFormattedDate: (date: dayjs.Dayjs): string => formatDateRange(date.subtract(24, 'h'), date.endOf('d')),- defaultInterval: 'hour',- },- {- key: 'Last 7 days',- values: ['-7d'],- getFormattedDate: (date: dayjs.Dayjs): string => formatDateRange(date.subtract(7, 'd'), date.endOf('d')),- defaultInterval: 'day',- },-]+import { LIVE_REFRESH_MS, MAX_UNAGGREGATED_SERIES, metricsViewerLogic } from './metricsViewerLogic'export const MetricsViewer = (): JSX.Element => {const logic = metricsViewerLogic()@@ -98,15 +39,12 @@ export const MetricsViewer = (): JSX.Element => {useMountedLogic(metricsSamplesLogic())const { openModal: openStarterDashboardModal } = useActions(metricsStarterDashboardLogic)const {- viewerClauses,- activeClauseIndex,formula,queryFingerprint,anomalyFingerprint,metricName,dateFrom,dateTo,- interval,chartSeries,anomalyBadge,liveRefresh,@@ -116,6 +54,9 @@ export const MetricsViewer = (): JSX.Element => {savedInsight,isAddToDashboardModalOpen,hasMetricName,+ hasQuery,+ language,+ queryText,hasResults,seriesCapReached,displayType,@@ -124,11 +65,7 @@ export const MetricsViewer = (): JSX.Element => {histogramQueryNode,} = useValues(logic)const {- setDateFrom,- setDateTo,- setInterval,setLiveRefresh,- addClause,fetchQueryResults,fetchAnomaly,clearAnomaly,@@ -136,15 +73,13 @@ export const MetricsViewer = (): JSX.Element => {addToDashboard,createAlert,closeAddToDashboardModal,- setDisplayType,+ applyQuery,} = useActions(logic)const { traceExemplars, errorSpikes, showErrorSpikes } = useValues(metricsSamplesLogic)const { timezone } = useValues(teamLogic)const { toggleShowErrorSpikes } = useActions(metricsSamplesLogic)// Staff-only PoC gate, layered on top of the wider metrics alpha flag.const errorOverlaysEnabled = useFeatureFlag('METRICS_ERROR_OVERLAYS')- // Grafana-style scalar/categorical panels. Flag-gated; the registry describes each panel.- const dashboardPanelsEnabled = useFeatureFlag('METRICS_DASHBOARD_PANELS')// Gate on the result shape, not the clause edits: a formula result is ungrouped even// when its input clauses group, and a clause without a metric name never runs.@@ -152,28 +87,13 @@ export const MetricsViewer = (): JSX.Element => {// The heatmap saves a MetricsHistogramQuery, but insight alerts only support MetricsQuery,// so alert creation would save a query the alerts page cannot validate.const isHeatmap = displayType === 'heatmap' && histogramQueryNode !== null- const displayTypeOptions = useMemo(() => {- const types = dashboardPanelsEnabled ? [...BASE_DISPLAY_TYPES, ...PANEL_DISPLAY_TYPES] : BASE_DISPLAY_TYPES- return types.map((value) => {- const def = METRICS_PANELS[value]- const disabledReason = def.needsGroupBy- ? !resultIsGrouped- ? 'Add a group-by to use this panel'- : undefined- : def.needsHistogram- ? !heatmapEligible- ? 'Pick a single histogram metric (no formula) to use this panel'- : undefined- : undefined- return { value, label: def.label, disabledReason }- })- }, [dashboardPanelsEnabled, resultIsGrouped, heatmapEligible])const { exemplarDotClicked } = useActions(metricsUsageTrackingLogic)const metricsViewerDisabledReason = getAccessControlDisabledReason(AccessControlResourceType.Metrics,AccessControlLevel.Viewer)const insightEditorDisabledReason = getMetricsInsightEditorDisabledReason()+ const noQueryReason = hasQuery ? undefined : language === 'builder' ? 'Pick a metric first' : 'Write a query first'const tracingDisabledReason = getAccessControlDisabledReason(AccessControlResourceType.Tracing,AccessControlLevel.Viewer@@ -246,63 +166,20 @@ export const MetricsViewer = (): JSX.Element => {}}, [anomalyFingerprint, dateFrom, dateTo, hasMetricName, timezone]) // eslint-disable-line react-hooks/exhaustive-deps- const showFormulaInput = viewerClauses.length > 1 || formula !== ''+ const languagesEnabled = useFeatureFlag('METRICS_QUERY_LANGUAGES')return (<div className="flex flex-col gap-3">- <div className="flex flex-col gap-2">- <div className="flex flex-wrap items-start gap-2 justify-between">- <div className="flex flex-col gap-2 flex-1 min-w-[16rem]">- {viewerClauses.map((clause, index) => (- <MetricsClauseRow- key={clause.name}- clause={clause}- index={index}- isActive={index === activeClauseIndex}- showAlias={viewerClauses.length > 1}- disabledReason={metricsViewerDisabledReason}- />- ))}- <div className="flex flex-wrap items-center gap-2">- <LemonButton- size="small"- type="secondary"- icon={<IconPlusSmall />}- onClick={() => addClause()}- disabledReason={- metricsViewerDisabledReason ??- (viewerClauses.length >= MAX_CLAUSES- ? `A query can have at most ${MAX_CLAUSES} series`- : undefined)- }- data-attr="metrics-viewer-add-series"- >- Add series- </LemonButton>- {showFormulaInput && <MetricsFormulaInput disabledReason={metricsViewerDisabledReason} />}- </div>- </div>- <div className="flex flex-wrap items-center gap-2">- <DateFilter- size="small"- dateFrom={dateFrom}- dateTo={dateTo}- dateOptions={METRICS_DATE_OPTIONS}- onChange={(changedDateFrom, changedDateTo) => {- setDateFrom(changedDateFrom)- setDateTo(changedDateTo)- }}- allowTimePrecision- allowFixedRangeWithTime- allowedRollingDateOptions={['minutes', 'hours', 'days', 'weeks']}- use24HourFormat- disabledReason={metricsViewerDisabledReason}- />- <MetricsIntervalPicker- value={interval}- onChange={setInterval}- disabledReason={metricsViewerDisabledReason}- />+ <MetricsQueryControls+ dataAttrPrefix="metrics-viewer"+ onSwitchLanguage={+ languagesEnabled ? (current, to) => switchMetricsQueryLanguage(current, to, applyQuery) : undefined+ }+ onRerun={() => fetchQueryResults({})}+ resultIsGrouped={resultIsGrouped}+ heatmap={{ eligible: heatmapEligible }}+ toolbarExtras={+ <><LemonSwitchlabel="Auto-refresh"checked={liveRefresh}@@ -325,32 +202,23 @@ export const MetricsViewer = (): JSX.Element => {disabledReason={metricsViewerDisabledReason}/>)}- </div>- </div>- <div className="flex flex-wrap items-center gap-2 justify-between">- <div className="flex flex-wrap items-center gap-2">- <LemonSelect- size="small"- value={displayType}- options={displayTypeOptions}- onChange={setDisplayType}- data-attr="metrics-viewer-display-type"- disabledReason={metricsViewerDisabledReason}- />- <MetricsChartSettings />+ </>+ }+ displayExtras={+ <><MetricsRelatedMenu />{anomalyBadge && <MetricsAnomalyPanel anomaly={anomalyBadge} />}<MetricsLogsSourceTag metricName={metricName} />- </div>- <div className="flex flex-wrap items-center gap-2">+ </>+ }+ actions={+ <><LemonButtonsize="small"type="secondary"onClick={() => saveAsInsight()}loading={savedInsightLoading}- disabledReason={- insightEditorDisabledReason ?? (!hasMetricName ? 'Pick a metric first' : undefined)- }+ disabledReason={insightEditorDisabledReason ?? noQueryReason}>Save as insight</LemonButton>@@ -362,11 +230,8 @@ export const MetricsViewer = (): JSX.Element => {tooltip="Get notified when this metric crosses a threshold (uses insight alerts)"disabledReason={insightEditorDisabledReason ??- (!hasMetricName- ? 'Pick a metric first'- : isHeatmap- ? 'Alerts are not supported for the heatmap display'- : undefined)+ noQueryReason ??+ (isHeatmap ? 'Alerts are not supported for the heatmap display' : undefined)}data-attr="metrics-viewer-create-alert">@@ -377,9 +242,7 @@ export const MetricsViewer = (): JSX.Element => {type="primary"onClick={() => addToDashboard()}loading={savedInsightLoading}- disabledReason={- insightEditorDisabledReason ?? (!hasMetricName ? 'Pick a metric first' : undefined)- }+ disabledReason={insightEditorDisabledReason ?? noQueryReason}data-attr="metrics-viewer-add-to-dashboard">Add to dashboard@@ -394,9 +257,9 @@ export const MetricsViewer = (): JSX.Element => {>New service dashboard</LemonButton>- </div>- </div>- </div>+ </>+ }+ /><MetricsStarterDashboardModal />{savedInsight && (<>@@ -421,9 +284,11 @@ export const MetricsViewer = (): JSX.Element => {</LemonBanner>)}<div className="relative h-[360px] border rounded p-3">- {!hasMetricName ? (+ {!hasQuery ? (<div className="h-full flex items-center justify-center text-secondary text-sm">- Pick a metric to see its time series.+ {language === 'builder'+ ? 'Pick a metric to see its time series.'+ : 'Run a query to see results.'}</div>) : isHeatmap && histogramQueryNode ? (// The heatmap runs its own histogram query, so it mounts the histogram@@ -434,14 +299,14 @@ export const MetricsViewer = (): JSX.Element => {<MetricsHistogramQueryNode query={histogramQueryNode} context={{}} />) : queryError ? (<div className="h-full flex items-center justify-center">- <LemonBanner type="error" className="max-w-md">+ <LemonBanner type="error" className="w-full max-w-md">{queryError}</LemonBanner></div>) : hasResults ? (<MetricsPanelseries={chartSeries}- fallbackName={formula || metricName || 'metric'}+ fallbackName={formula || metricName || (language === 'promql' ? queryText : 'metric')}display={metricsDisplay}exemplars={chartMarkers}/>@@ -462,42 +327,3 @@ export const MetricsViewer = (): JSX.Element => {</div>)}--// How the recent slice of the window compares against the rest of it, sitting next to the-// controls that define the window rather than over the chart, where it would fight the legend.--// Committed on blur/Enter (mirroring TrendsFormula) so a half-typed formula doesn't fire-// a query per keystroke. Input is lowercased — clause aliases are lowercase and the-// backend parser is case-sensitive.-export const MetricsFormulaInput = ({ disabledReason }: { disabledReason: string | null }): JSX.Element => {- const { formula } = useValues(metricsViewerLogic)- const { setFormula } = useActions(metricsViewerLogic)- const [draft, setDraft] = useState(formula)-- // An external change (URL restore, clause reset) replaces the local draft.- useEffect(() => {- setDraft(formula)- }, [formula])-- const commit = (): void => {- if (draft !== formula) {- setFormula(draft)- }- }-- return (- <Tooltip title="Arithmetic over the series letters, with + - * / and parentheses. Only the formula result is charted.">- <LemonInput- size="small"- className="min-w-48"- value={draft}- onChange={(value) => setDraft(sanitizeFormulaInput(value))}- onBlur={commit}- onPressEnter={commit}- placeholder="Formula, e.g. (a - b) / a"- data-attr="metrics-viewer-formula"- disabledReason={disabledReason}- />- </Tooltip>- )-}diff --git a/products/metrics/frontend/components/metricsQueryLanguageSwitch.test.ts b/products/metrics/frontend/components/metricsQueryLanguageSwitch.test.tsnew file mode 100644index 000000000000..7a9cbbbd6700--- /dev/null+++ b/products/metrics/frontend/components/metricsQueryLanguageSwitch.test.ts@@ -0,0 +1,67 @@+import posthog from 'posthog-js'++import { LemonDialog } from '@posthog/lemon-ui'++import { MetricsQuery, NodeKind } from '~/queries/schema/schema-general'++import { switchMetricsQueryLanguage } from './metricsQueryLanguageSwitch'++jest.mock('@posthog/lemon-ui', () => ({+ ...jest.requireActual('@posthog/lemon-ui'),+ LemonDialog: { open: jest.fn() },+}))++const builderQuery = (fields: Partial<MetricsQuery['clauses'][number]> = {}): MetricsQuery => ({+ kind: NodeKind.MetricsQuery,+ clauses: [{ name: 'a', metricName: 'queue_depth', aggregation: 'sum', ...fields }],+ dateRange: { date_from: '-1h' },+})++describe('switchMetricsQueryLanguage', () => {+ beforeEach(() => {+ jest.mocked(LemonDialog.open).mockClear()+ jest.spyOn(posthog, 'capture').mockImplementation(() => undefined)+ })++ it('switches a lossless conversion without asking', () => {+ const apply = jest.fn()+ switchMetricsQueryLanguage(builderQuery(), 'promql', apply)++ expect(LemonDialog.open).not.toHaveBeenCalled()+ expect(apply).toHaveBeenCalledWith({+ kind: NodeKind.MetricsQuery,+ clauses: [],+ language: 'promql',+ promql: 'sum(queue_depth)',+ dateRange: { date_from: '-1h' },+ })+ expect(posthog.capture).toHaveBeenCalledWith('metrics query language switched', {+ from: 'builder',+ to: 'promql',+ lossy: false,+ issue_count: 0,+ confirmed: true,+ })+ })++ it('asks before a lossy conversion and keeps the query on cancel', () => {+ const apply = jest.fn()+ switchMetricsQueryLanguage(+ builderQuery({ filters: [{ key: 'host.name', op: 'eq', value: 'a', scope: 'resource' }] }),+ 'promql',+ apply+ )++ expect(apply).not.toHaveBeenCalled()+ const dialog = jest.mocked(LemonDialog.open).mock.calls[0][0]+ ;(dialog.secondaryButton?.onClick as () => void)()+ expect(apply).not.toHaveBeenCalled()+ expect(posthog.capture).toHaveBeenCalledWith(+ 'metrics query language switched',+ expect.objectContaining({ lossy: true, confirmed: false })+ )++ ;(dialog.primaryButton?.onClick as () => void)()+ expect(apply).toHaveBeenCalledWith(expect.objectContaining({ language: 'promql' }))+ })+})diff --git a/products/metrics/frontend/components/metricsQueryLanguageSwitch.tsx b/products/metrics/frontend/components/metricsQueryLanguageSwitch.tsxnew file mode 100644index 000000000000..1d28d0015b96--- /dev/null+++ b/products/metrics/frontend/components/metricsQueryLanguageSwitch.tsx@@ -0,0 +1,59 @@+import posthog from 'posthog-js'++import { LemonDialog } from '@posthog/lemon-ui'++import type { MetricsQuery, MetricsQueryLanguage } from '~/queries/schema/schema-general'++import { convertMetricsQuery, queryLanguage } from '../queryLanguages/convert'++export const METRICS_QUERY_LANGUAGE_LABELS: Record<MetricsQueryLanguage, string> = {+ builder: 'Builder',+ promql: 'PromQL',+ sql: 'SQL',+}++/** Converts a metrics query to another language. When the conversion loses something, it asks first. */+export function switchMetricsQueryLanguage(+ query: MetricsQuery,+ to: MetricsQueryLanguage,+ apply: (query: MetricsQuery) => void+): void {+ const from = queryLanguage(query)+ if (from === to) {+ return+ }+ const { query: converted, issues } = convertMetricsQuery(query, to)+ const track = (confirmed: boolean): void => {+ posthog.capture('metrics query language switched', {+ from,+ to,+ lossy: issues.length > 0,+ issue_count: issues.length,+ confirmed,+ })+ }+ if (!issues.length) {+ track(true)+ apply(converted)+ return+ }+ const label = METRICS_QUERY_LANGUAGE_LABELS[to]+ LemonDialog.open({+ title: `Switch to ${label}?`,+ description: (+ <ul className="list-disc pl-5 mt-2 flex flex-col gap-1">+ {issues.map((issue) => (+ <li key={issue}>{issue}</li>+ ))}+ </ul>+ ),+ primaryButton: {+ children: 'Switch',+ onClick: () => {+ track(true)+ apply(converted)+ },+ },+ secondaryButton: { children: 'Cancel', onClick: () => track(false) },+ })+}diff --git a/products/metrics/frontend/components/metricsViewerLogic.test.ts b/products/metrics/frontend/components/metricsViewerLogic.test.tsindex 4c32b0c3dbc7..ce6f78902784 100644--- a/products/metrics/frontend/components/metricsViewerLogic.test.ts+++ b/products/metrics/frontend/components/metricsViewerLogic.test.ts@@ -6,6 +6,7 @@ import { lemonToast } from '@posthog/lemon-ui'import { NEW_QUERY_STARTED_ERROR_MESSAGE } from 'lib/utils/kea-logic-builders'import { insightsApi } from 'scenes/insights/utils/api'+import { performQuery } from '~/queries/query'import { MetricsQuery, NodeKind } from '~/queries/schema/schema-general'import { initKeaTests } from '~/test/init'import {@@ -37,6 +38,11 @@ jest.mock('products/metrics/frontend/generated/api', () => ({metricsCharacterizeCreate: jest.fn(),}))+jest.mock('~/queries/query', () => ({+ ...jest.requireActual('~/queries/query'),+ performQuery: jest.fn(),+}))+jest.mock('scenes/insights/utils/api', () => ({...jest.requireActual('scenes/insights/utils/api'),insightsApi: { create: jest.fn() },@@ -273,6 +279,14 @@ describe('metricsViewerLogic', () => {expectHeatmapFallback(() =>logic.actions.setClauses([createViewerClause('a'), createViewerClause('b')], 'a / 2'))+ expectHeatmapFallback(() =>+ logic.actions.applyQuery({+ kind: NodeKind.MetricsQuery,+ clauses: [],+ language: 'promql',+ promql: 'sum(rate(request_duration_bucket))',+ })+ )})// Guards the multi-series save path: each clause carries its own metric/aggregation,@@ -368,6 +382,28 @@ describe('metricsViewerLogic', () => {expect(requestBody.query).not.toHaveProperty('formula')})+ it('runs a PromQL query through the query runner and charts its series', async () => {+ jest.mocked(performQuery).mockResolvedValue({+ results: [{ labels: { job: 'api' }, points: [{ time: '2026-01-01T00:00:00Z', value: 1 }], clause: 'a' }],+ })+ logic.actions.applyQuery({ kind: NodeKind.MetricsQuery, clauses: [], language: 'promql', promql: 'sum(up)' })++ await expectLogic(logic, () => {+ logic.actions.fetchQueryResults({})+ }).toDispatchActions(['fetchQueryResultsSuccess'])++ expect(jest.mocked(performQuery).mock.calls[0][0]).toMatchObject({ language: 'promql', promql: 'sum(up)' })+ expect(metricsQueryCreate).not.toHaveBeenCalled()+ expect(logic.values.chartSeries).toEqual([+ {+ labels: { job: 'api' },+ points: [{ time: '2026-01-01T00:00:00Z', value: 1 }],+ metricName: null,+ clause: 'a',+ },+ ])+ })+// A "vs baseline" badge computed from one input clause would be attributed to the// whole (multi-series or formula) chart — suppressing it is the honest behavior.it('suppresses the anomaly characterization for multi-series queries', async () => {@@ -415,21 +451,49 @@ describe('metricsViewerLogic', () => {toastSpy.mockRestore()})- it('names a formula insight after the formula and its inputs', async () => {+ it.each<[string, () => void, string]>([+ [+ 'a formula, after the formula and its inputs',+ () => {+ logic.actions.setMetricName('requests_total')+ logic.actions.addClause()+ logic.actions.setMetricName('queue_depth')+ logic.actions.setFormula('a / b')+ },+ 'a / b (requests_total, queue_depth)',+ ],+ [+ 'a PromQL query, after its text',+ () =>+ logic.actions.applyQuery({+ kind: NodeKind.MetricsQuery,+ clauses: [],+ language: 'promql',+ promql: 'sum(rate(requests_total))',+ }),+ 'PromQL: sum(rate(requests_total))',+ ],+ [+ 'a SQL query, after its text',+ () =>+ logic.actions.applyQuery({+ kind: NodeKind.MetricsQuery,+ clauses: [],+ language: 'sql',+ sql: 'SELECT now() AS time,\n 1 AS value',+ }),+ 'SQL: SELECT now() AS time, 1 AS value',+ ],+ ])('names %s', async (_name, setUp, expectedName) => {jest.mocked(insightsApi.create).mockImplementation(async (insight: any) => ({ id: 1, short_id: 'abc123', ...insight }) as any)- logic.actions.setMetricName('requests_total')- logic.actions.addClause()- logic.actions.setMetricName('queue_depth')- logic.actions.setFormula('a / b')+ setUp()logic.actions.saveAsInsight()await expectLogic(logic).toDispatchActions(['saveAsInsightSuccess'])- expect(insightsApi.create).toHaveBeenCalledWith(- expect.objectContaining({ name: 'a / b (requests_total, queue_depth)' })- )+ expect(insightsApi.create).toHaveBeenCalledWith(expect.objectContaining({ name: expectedName }))})// A type outside the API enum (or a metric missing from the picker list) must be@@ -911,10 +975,49 @@ describe('metricsViewerLogic', () => {// The editor writes this node back to the insight; if it differs from the saved// query, merely opening edit mode would mark the insight as changed.- it('maps a saved query back to the same node', () => {- const editor = metricsViewerLogic({ key: 'editor-test', initialQuery: SAVED_QUERY })+ it.each<[string, MetricsQuery]>([+ ['builder', SAVED_QUERY],+ [+ 'PromQL',+ {+ kind: NodeKind.MetricsQuery,+ clauses: [],+ language: 'promql',+ promql: 'sum by (job) (rate(requests_total))',+ dateRange: { date_from: '-6h' },+ display: { type: 'area' },+ },+ ],+ [+ 'SQL',+ {+ kind: NodeKind.MetricsQuery,+ clauses: [],+ language: 'sql',+ sql: 'SELECT now() AS time, 1 AS value',+ dateRange: { date_from: '-6h' },+ interval: 'minute_5',+ },+ ],+ ])('maps a saved %s query back to the same node', (_name, query) => {+ const editor = metricsViewerLogic({ key: 'editor-test', initialQuery: query })+ editor.mount()+ expect(editor.values.metricsQueryNode).toEqual(query)+ editor.unmount()+ })++ it('changes the PromQL in the query only when the draft runs', () => {+ const editor = metricsViewerLogic({+ key: 'editor-test',+ initialQuery: { kind: NodeKind.MetricsQuery, clauses: [], language: 'promql', promql: 'sum(x)' },+ })editor.mount()- expect(editor.values.metricsQueryNode).toEqual(SAVED_QUERY)+ editor.actions.setQueryDraft('sum(y) ')+ expect(editor.values.metricsQueryNode?.promql).toBe('sum(x)')+ expect(editor.values.queryTextChanged).toBe(true)+ editor.actions.runQueryText()+ expect(editor.values.metricsQueryNode?.promql).toBe('sum(y)')+ expect(editor.values.queryTextChanged).toBe(false)editor.unmount()})diff --git a/products/metrics/frontend/components/metricsViewerLogic.tsx b/products/metrics/frontend/components/metricsViewerLogic.tsxindex 1852f4c5cfb4..722cedebe5ba 100644--- a/products/metrics/frontend/components/metricsViewerLogic.tsx+++ b/products/metrics/frontend/components/metricsViewerLogic.tsx@@ -20,6 +20,7 @@ import { insightsApi } from 'scenes/insights/utils/api'import { teamLogic } from 'scenes/teamLogic'import { urls } from 'scenes/urls'+import { performQuery } from '~/queries/query'import {GoalLine,MetricsAttributeScope,@@ -30,6 +31,7 @@ import {MetricsQueryClause,MetricsQueryFilter,MetricsReducer,+ MetricsQueryLanguage,MetricsYAxisSettings,NodeKind,} from '~/queries/schema/schema-general'@@ -60,6 +62,7 @@ import { type MetricTopMoverRow, topMoverRows } from '../metricsAnomaly'import { EMPTY_SERVICE_PATTERN, SERVICE_NAME_KEY } from '../metricsAttributes'import { correlationServiceNames, metricsFilterGroup } from '../metricsLinks'import { METRICS_PANELS, resolveReducer } from '../panels/registry'+import { metricsQueryText, queryLanguage } from '../queryLanguages/convert'import { metricNamePickerLogic } from './metricNamePickerLogic'import type { MetricNameItem } from './metricNamePickerLogic'import type { MetricsChartSeries } from './metricsSeries'@@ -336,10 +339,18 @@ export const singleAggregationForClause = (return !clause.aggregation || clause.aggregation === 'sum' ? clause.rangeFunction : null}-const insightNameForViewerQuery = (clauses: MetricsViewerClause[], formula: string): string => {+const insightNameForViewerQuery = (+ language: MetricsQueryLanguage,+ queryText: string,+ clauses: MetricsViewerClause[],+ formula: string+): string => {const names = clauses.map((clause) => clause.metricName.trim())let name: string- if (formula) {+ if (language !== 'builder') {+ // A PromQL or SQL query has no named clauses, so its text names it.+ name = `${language === 'promql' ? 'PromQL' : 'SQL'}: ${queryText.replace(/\s+/g, ' ').trim()}`+ } else if (formula) {name = `${formula} (${names.join(', ')})`} else if (clauses.length > 1) {name = `${names.join(', ')} (${clauses.length} series)`@@ -474,11 +485,13 @@ export interface metricsViewerLogicValues {groupByKeys: string[]groupBySearch: stringhasMetricName: boolean+ hasQuery: booleanhasResults: booleanheatmapEligible: booleanhistogramQueryNode: MetricsHistogramQuery | nullinterval: string | nullisAddToDashboardModalOpen: boolean+ language: MetricsQueryLanguagelastSavedQueryNode: MetricsHistogramQuery | MetricsQuery | nullliveRefresh: booleanmetricName: string@@ -488,6 +501,7 @@ export interface metricsViewerLogicValues {pendingAddToDashboard: booleanpendingAlert: booleanqueryAbortController: AbortController | null+ queryDraft: stringqueryError: string | nullqueryFilters: _MetricFilterApi[]queryFingerprint: string@@ -496,6 +510,8 @@ export interface metricsViewerLogicValues {queryResults: MetricsViewerSeries[]queryResultsLoading: booleanqueryState: MetricsViewerQueryState+ queryText: string+ queryTextChanged: booleanrangeFunction: MetricRangeFunction | nullreduce: MetricsReducersavedInsight: InsightModel | null@@ -542,6 +558,9 @@ export interface metricsViewerLogicActions {addToDashboard: () => {value: true}+ applyQuery: (query: MetricsQuery) => {+ query: MetricsQuery+ }backfillClauses: (updates: MetricsViewerClauseBackfill[]) => {updates: MetricsViewerClauseBackfill[]}@@ -640,6 +659,9 @@ export interface metricsViewerLogicActions {resetPendingAlert: () => {value: true}+ runQueryText: () => {+ value: true+ }saveAsInsight: () => anysaveAsInsightFailure: (error: string,@@ -707,6 +729,12 @@ export interface metricsViewerLogicActions {setQueryAbortController: (controller: AbortController | null) => {controller: AbortController | null}+ setQueryDraft: (queryDraft: string) => {+ queryDraft: string+ }+ setQueryText: (queryText: string) => {+ queryText: string+ }setRangeFunction: (rangeFunction: MetricRangeFunction | null) => {rangeFunction: MetricRangeFunction | null}@@ -750,12 +778,18 @@ export interface metricsViewerLogicMeta {filterGroup: (activeClause: MetricsViewerClause) => UniversalFiltersGroupnamedClauses: (viewerClauses: MetricsViewerClause[]) => MetricsViewerClause[]hasMetricName: (namedClauses: MetricsViewerClause[]) => boolean+ hasQuery: (language: MetricsQueryLanguage, hasMetricName: boolean, queryText: string) => booleanqueryPayload: (namedClauses: MetricsViewerClause[],formula: string,interval: string | null) => MetricsQueryRequestBody | null- queryFingerprint: (queryPayload: MetricsQueryRequestBody | null) => string+ queryFingerprint: (+ queryPayload: MetricsQueryRequestBody | null,+ language: MetricsQueryLanguage,+ queryText: string,+ interval: string | null+ ) => stringanomalyQuery: (namedClauses: MetricsViewerClause[], formula: string) => MetricsAnomalyRequestBody | nullanomalyFingerprint: (anomalyQuery: MetricsAnomalyRequestBody | null) => stringmetricsDisplay: (@@ -770,9 +804,16 @@ export interface metricsViewerLogicMeta {dateFrom: string | null,dateTo: string | null,metricsDisplay: MetricsDisplaySettings | undefined,- interval: string | null+ interval: string | null,+ language: MetricsQueryLanguage,+ queryText: string) => MetricsQuery | null- heatmapEligible: (namedClauses: MetricsViewerClause[], formula: string) => boolean+ queryTextChanged: (queryDraft: string, queryText: string) => boolean+ heatmapEligible: (+ language: MetricsQueryLanguage,+ namedClauses: MetricsViewerClause[],+ formula: string+ ) => booleanhistogramQueryNode: (namedClauses: MetricsViewerClause[],heatmapEligible: boolean,@@ -886,6 +927,13 @@ export const metricsViewerLogic = kea<metricsViewerLogicType>([value,}),setReduce: (reduce: MetricsReducer) => ({ reduce }),+ // PromQL and SQL modes: the draft follows each keystroke, and only a run moves it into the+ // query, so typing does not run a half-written query.+ setQueryDraft: (queryDraft: string) => ({ queryDraft }),+ setQueryText: (queryText: string) => ({ queryText }),+ runQueryText: true,+ // Replaces the whole query, as a language switch does.+ applyQuery: (query: MetricsQuery) => ({ query }),}),reducers(({ props }) => ({// The clause list, active index, and formula live in one reducer so the@@ -896,6 +944,7 @@ export const metricsViewerLogic = kea<metricsViewerLogicType>([? queryStateFromNode(props.initialQuery): DEFAULT_QUERY_STATE) as MetricsViewerQueryState,{+ applyQuery: (_, { query }) => queryStateFromNode(query),setMetricName: (state, { metricName }) =>withActiveClause(state, (clause) => ({ ...clause, metricName })),// The picked metric's type, latched at pick time (and backfilled if the@@ -986,6 +1035,25 @@ export const metricsViewerLogic = kea<metricsViewerLogicType>([: state,},],+ language: [+ (props.initialQuery?.language ?? 'builder') as MetricsQueryLanguage,+ { applyQuery: (_, { query }) => queryLanguage(query) },+ ],+ queryText: [+ props.initialQuery ? metricsQueryText(props.initialQuery) : '',+ {+ setQueryText: (_, { queryText }) => queryText,+ applyQuery: (_, { query }) => metricsQueryText(query),+ },+ ],+ queryDraft: [+ props.initialQuery ? metricsQueryText(props.initialQuery) : '',+ {+ setQueryDraft: (_, { queryDraft }) => queryDraft,+ setQueryText: (_, { queryText }) => queryText,+ applyQuery: (_, { query }) => metricsQueryText(query),+ },+ ],dateFrom: [(props.initialQuery?.dateRange?.date_from ?? DEFAULT_DATE_FROM) as string | null,{ setDateFrom: (_, { dateFrom }) => dateFrom },@@ -1127,8 +1195,8 @@ export const metricsViewerLogic = kea<metricsViewerLogicType>([}}// The heatmap display is valid only while the query stays eligible. Every change- // that can end eligibility (a formula, a second clause, a group-by, a URL restore)- // must fall back, or "heatmap" stays selected while the viewer renders a time+ // that can end eligibility (a formula, a second clause, a group-by, a URL restore,+ // a switch to PromQL or SQL) must fall back, or "heatmap" stays selected while the viewer renders a time// series and saving silently does nothing (savedQueryNode is null).const resetHeatmapIfIneligible = (): void => {if (values.displayType === 'heatmap' && !values.heatmapEligible) {@@ -1150,6 +1218,7 @@ export const metricsViewerLogic = kea<metricsViewerLogicType>([resetHeatmapIfIneligible()},setFormula: resetHeatmapIfIneligible,+ applyQuery: resetHeatmapIfIneligible,// `setFilterGroup` changes the active clause's chips; the clause-navigation// actions change which clause's chips are the scope.setFilterGroup: syncPickerServices,@@ -1224,6 +1293,9 @@ export const metricsViewerLogic = kea<metricsViewerLogicType>([saveAsInsightFailure: ({ error }) => {lemonToast.error(`Failed to save insight: ${error}`)},+ runQueryText: () => {+ actions.setQueryText(values.queryDraft.trim())+ },addToDashboard: () => {if (!canCreateMetricsInsight() || !values.savedQueryNode) {return@@ -1323,6 +1395,25 @@ export const metricsViewerLogic = kea<metricsViewerLogicType>([if (!canViewMetrics()) {return []}+ if (values.language !== 'builder') {+ // PromQL and SQL run through the same query runner as a saved metrics insight.+ const node = values.metricsQueryNode+ if (!node || !values.queryText.trim()) {+ return []+ }+ await breakpoint(300)+ const controller = new AbortController()+ actions.cancelInProgressQuery(controller)+ const response = await performQuery(node, { signal: controller.signal })+ breakpoint()+ actions.setQueryAbortController(null)+ return response.results.map((series) => ({+ labels: series.labels,+ points: series.points,+ metric_name: series.metricName ?? null,+ clause: series.clause ?? null,+ }))+ }const queryPayload = values.queryPayloadif (!queryPayload) {return []@@ -1364,7 +1455,12 @@ export const metricsViewerLogic = kea<metricsViewerLogicType>([return null}const insight = await insightsApi.create({- name: insightNameForViewerQuery(values.namedClauses, values.formula),+ name: insightNameForViewerQuery(+ values.language,+ values.queryText,+ values.namedClauses,+ values.formula+ ),query,saved: true,})@@ -1470,6 +1566,12 @@ export const metricsViewerLogic = kea<metricsViewerLogicType>([clauses.filter((clause) => clause.metricName.trim().length > 0),],hasMetricName: [(s) => [s.namedClauses], (namedClauses: MetricsViewerClause[]) => namedClauses.length > 0],+ // Whether there is anything to run: a picked metric, or PromQL or SQL text.+ hasQuery: [+ (s) => [s.language, s.hasMetricName, s.queryText],+ (language: MetricsQueryLanguage, hasMetricName: boolean, queryText: string): boolean =>+ language === 'builder' ? hasMetricName : queryText.trim() !== '',+ ],// The chart request minus the date range (resolved at fetch time). The fetch// loader sends this object verbatim, so the fingerprint below can't drift from// the real payload. Null when nothing queries anything yet.@@ -1492,8 +1594,13 @@ export const metricsViewerLogic = kea<metricsViewerLogicType>([// and a blank-row add/remove (which changes `viewerClauses` but not the request)// doesn't refetch the chart and cascade into samples/exemplar reloads.queryFingerprint: [- (s) => [s.queryPayload],- (queryPayload: MetricsQueryRequestBody | null): string => JSON.stringify(queryPayload),+ (s) => [s.queryPayload, s.language, s.queryText, s.interval],+ (+ queryPayload: MetricsQueryRequestBody | null,+ language: MetricsQueryLanguage,+ queryText: string,+ interval: string | null+ ): string => JSON.stringify(language === 'builder' ? queryPayload : { language, queryText, interval }),],// The characterize request minus the anomaly window, null when the badge is// suppressed: with several clauses (or a formula result) there is no single@@ -1545,15 +1652,43 @@ export const metricsViewerLogic = kea<metricsViewerLogicType>([// The viewer state as a `MetricsQuery` schema node — what "Save as insight"// persists, so the saved tile re-runs exactly what the viewer shows.metricsQueryNode: [- (s) => [s.namedClauses, s.formula, s.dateFrom, s.dateTo, s.metricsDisplay, s.interval],+ (s) => [+ s.namedClauses,+ s.formula,+ s.dateFrom,+ s.dateTo,+ s.metricsDisplay,+ s.interval,+ s.language,+ s.queryText,+ ],(namedClauses: MetricsViewerClause[],formula: string,dateFrom: string | null,dateTo: string | null,metricsDisplay: MetricsDisplaySettings | undefined,- interval: string | null+ interval: string | null,+ language: MetricsQueryLanguage,+ queryText: string): MetricsQuery | null => {+ const shared = {+ dateRange: {+ date_from: dateFrom ?? DEFAULT_DATE_FROM,+ ...(dateTo ? { date_to: dateTo } : {}),+ },+ ...(interval ? { interval } : {}),+ ...(metricsDisplay ? { display: metricsDisplay } : {}),+ }+ if (language !== 'builder') {+ return {+ kind: NodeKind.MetricsQuery,+ clauses: [],+ language,+ ...(language === 'promql' ? { promql: queryText } : { sql: queryText }),+ ...shared,+ }+ }if (!namedClauses.length) {return null}@@ -1561,21 +1696,21 @@ export const metricsViewerLogic = kea<metricsViewerLogicType>([kind: NodeKind.MetricsQuery,clauses: namedClauses.map(clauseToNodeClause),...(formula ? { formula } : {}),- dateRange: {- date_from: dateFrom ?? DEFAULT_DATE_FROM,- ...(dateTo ? { date_to: dateTo } : {}),- },- ...(interval ? { interval } : {}),- ...(metricsDisplay ? { display: metricsDisplay } : {}),+ ...shared,}},],- // The heatmap renders one distribution, so it needs exactly one non-formula clause on a- // distribution metric. The OTel type is latched at pick time (backfilled from the picker+ queryTextChanged: [+ (s) => [s.queryDraft, s.queryText],+ (queryDraft: string, queryText: string): boolean => queryDraft.trim() !== queryText,+ ],+ // The heatmap renders one distribution, so it needs exactly one non-formula builder clause+ // on a distribution metric. The OTel type is latched at pick time (backfilled from the picker// list), so this doesn't flicker as the live picker search results change.heatmapEligible: [- (s) => [s.namedClauses, s.formula],- (namedClauses: MetricsViewerClause[], formula: string): boolean =>+ (s) => [s.language, s.namedClauses, s.formula],+ (language: MetricsQueryLanguage, namedClauses: MetricsViewerClause[], formula: string): boolean =>+ language === 'builder' &&namedClauses.length === 1 &&!formula &&namedClauses[0].groupByKeys.length === 0 &&diff --git a/products/metrics/frontend/metricsSceneLogic.test.ts b/products/metrics/frontend/metricsSceneLogic.test.tsindex 338b6d3480a5..44ac0695c239 100644--- a/products/metrics/frontend/metricsSceneLogic.test.ts+++ b/products/metrics/frontend/metricsSceneLogic.test.ts@@ -4,6 +4,7 @@ import { expectLogic } from 'kea-test-utils'import { FEATURE_FLAGS } from 'lib/constants'import { featureFlagLogic } from 'lib/logic/featureFlagLogic'+import { NodeKind } from '~/queries/schema/schema-general'import { initKeaTests } from '~/test/init'import {AccessControlLevel,@@ -301,6 +302,30 @@ describe('metricsSceneLogic', () => {expect(router.values.searchParams).toMatchObject({ metricName: 'requests_total' })})+ it('round-trips a PromQL query through the URL, and a builder link leaves it', async () => {+ await expectLogic(logic, () => {+ metricsViewerLogic.actions.applyQuery({+ kind: NodeKind.MetricsQuery,+ clauses: [],+ language: 'promql',+ promql: 'sum(up)',+ })+ }).toFinishAllListeners()+ expect(router.values.searchParams).toMatchObject({ language: 'promql', query: 'sum(up)' })++ await expectLogic(logic, () => {+ router.actions.push('/metrics', { metricName: 'queue_depth' })+ }).toFinishAllListeners()+ expect(metricsViewerLogic.values.language).toEqual('builder')+ expect(metricsViewerLogic.values.metricName).toEqual('queue_depth')++ await expectLogic(logic, () => {+ router.actions.push('/metrics', { language: 'sql', query: 'SELECT 1' })+ }).toFinishAllListeners()+ expect(metricsViewerLogic.values.language).toEqual('sql')+ expect(metricsViewerLogic.values.queryText).toEqual('SELECT 1')+ })+// The two URL encodings must never disagree: multi-series/formula state writes// `clauses` and removes the legacy params, and collapsing back restores them.it('switches between the legacy and clauses encodings as series come and go', async () => {diff --git a/products/metrics/frontend/metricsSceneLogic.tsx b/products/metrics/frontend/metricsSceneLogic.tsxindex 1c42a0f3f879..7c221cdcf5e2 100644--- a/products/metrics/frontend/metricsSceneLogic.tsx+++ b/products/metrics/frontend/metricsSceneLogic.tsx@@ -15,6 +15,7 @@ import { SQLEditorMode } from 'scenes/data-warehouse/editor/sqlEditorModes'import { Params } from 'scenes/sceneTypes'import { urls } from 'scenes/urls'+import { MetricsQueryLanguage, NodeKind } from '~/queries/schema/schema-general'import { UniversalFiltersGroup } from '~/types'import { OtelMetricTypeEnumApi } from 'products/metrics/frontend/generated/api.schemas'@@ -63,6 +64,8 @@ const LEGACY_VIEWER_PARAMS = ['groupBy','filterGroup',] as const+// PromQL and SQL queries are written as `language` plus the query text in `query`.+const TEXT_LANGUAGES: MetricsQueryLanguage[] = ['promql', 'sql']// A clause's alias must satisfy the backend's identifier rules (formulas reference it).const CLAUSE_NAME_PATTERN = /^[a-z][a-z0-9_]{0,63}$/@@ -149,8 +152,10 @@ export interface metricsSceneLogicValues {filterGroup: UniversalFiltersGroup // metricsViewerLogicformula: string // metricsViewerLogicgroupByKeys: string[] // metricsViewerLogic+ language: MetricsQueryLanguage // metricsViewerLogicmetricName: string // metricsViewerLogicnamedClauses: MetricsViewerClause[] // metricsViewerLogic+ queryText: string // metricsViewerLogicrangeFunction: MetricRangeFunction | null // metricsViewerLogicselectedMetricType: OtelMetricTypeEnumApi | null // metricsViewerLogicviewerClauses: MetricsViewerClause[] // metricsViewerLogic@@ -160,6 +165,9 @@ export interface metricsSceneLogicValues {// Generated by kea-typegen. Update if you're an agent, ignore if you're human.export interface metricsSceneLogicActions {+ applyQuery: (query: import('~/queries/schema').MetricsQuery) => {+ query: import('~/queries/schema').MetricsQuery+ } // metricsViewerLogicbackfillClauses: (updates: import('./components/metricsViewerLogic').MetricsViewerClauseBackfill[]) => {updates: import('./components/metricsViewerLogic').MetricsViewerClauseBackfill[]} // metricsViewerLogic@@ -197,6 +205,9 @@ export interface metricsSceneLogicActions {setMetricName: (metricName: string) => {metricName: string} // metricsViewerLogic+ setQueryText: (queryText: string) => {+ queryText: string+ } // metricsViewerLogicsetRangeFunction: (rangeFunction: MetricRangeFunction | null) => {rangeFunction: MetricRangeFunction | null} // metricsViewerLogic@@ -236,6 +247,8 @@ export const metricsSceneLogic = kea<metricsSceneLogicType>(['viewerClauses','namedClauses','formula',+ 'language',+ 'queryText',],],actions: [@@ -254,6 +267,8 @@ export const metricsSceneLogic = kea<metricsSceneLogicType>(['removeClause','duplicateClause','backfillClauses',+ 'applyQuery',+ 'setQueryText',],],})),@@ -298,7 +313,23 @@ export const metricsSceneLogic = kea<metricsSceneLogicType>([) {actions.setActiveTab(requested as MetricsSceneActiveTab)}- if (params.clauses) {+ const textLanguage = TEXT_LANGUAGES.find((language) => language === params.language)+ if (!textLanguage && values.language !== 'builder') {+ // A builder link leaves PromQL or SQL; the clause params below then fill the builder.+ actions.applyQuery({ kind: NodeKind.MetricsQuery, clauses: [] })+ }+ if (textLanguage) {+ // The text query is the whole query, so the builder params do not apply.+ const queryText = typeof params.query === 'string' ? params.query : ''+ if (textLanguage !== values.language || queryText !== values.queryText) {+ actions.applyQuery({+ kind: NodeKind.MetricsQuery,+ clauses: [],+ language: textLanguage,+ [textLanguage]: queryText,+ })+ }+ } else if (params.clauses) {// A present-but-invalid clauses param is ignored outright, like a malformed// filterGroup — falling through to the legacy branch would collapse the// multi-series state on screen.@@ -393,7 +424,17 @@ export const metricsSceneLogic = kea<metricsSceneLogicType>([// A blank just-added row is unsaved work in progress, not link state.const namedClauses = values.namedClausesconst useClausesEncoding = namedClauses.length > 1 || (!!values.formula && namedClauses.length > 0)- if (useClausesEncoding) {+ if (values.language !== 'builder') {+ params.language = values.language+ params.query = values.queryText+ delete params.clauses+ delete params.formula+ for (const legacyParam of LEGACY_VIEWER_PARAMS) {+ delete params[legacyParam]+ }+ } else if (useClausesEncoding) {+ delete params.language+ delete params.query// The two encodings must never disagree, so whichever one is written// deletes the other's params.params.clauses = namedClauses.map(serializeViewerClause)@@ -402,6 +443,8 @@ export const metricsSceneLogic = kea<metricsSceneLogicType>([delete params[legacyParam]}} else {+ delete params.language+ delete params.querydelete params.clausesdelete params.formula// Serialize the named clause, not the focused one — with a blank just-added@@ -447,6 +490,8 @@ export const metricsSceneLogic = kea<metricsSceneLogicType>([removeClause: () => syncUrl(),duplicateClause: () => syncUrl(),backfillClauses: () => syncUrl(),+ applyQuery: () => syncUrl(),+ setQueryText: () => syncUrl(),}}),])diff --git a/products/metrics/frontend/nodes/MetricsQueryNode.tsx b/products/metrics/frontend/nodes/MetricsQueryNode.tsxindex b8be6b9f5804..60ebf5755282 100644--- a/products/metrics/frontend/nodes/MetricsQueryNode.tsx+++ b/products/metrics/frontend/nodes/MetricsQueryNode.tsx@@ -5,14 +5,18 @@ import { LemonBanner, SpinnerOverlay } from '@posthog/lemon-ui'import { useFeatureFlag } from 'lib/hooks/useFeatureFlag'import { useAttachedLogic } from 'lib/logic/scenes/useAttachedLogic'+import { truncate } from 'lib/utils/strings'import { dataNodeLogic } from '~/queries/nodes/DataNode/dataNodeLogic'-import { AnyResponseType, MetricsQuery } from '~/queries/schema/schema-general'+import { AnyResponseType, MetricsQuery, MetricsQueryLanguage } from '~/queries/schema/schema-general'import { QueryContext } from '~/queries/types'import { MetricsQueryEditor } from '../components/MetricsQueryEditor'+import { MetricsQueryLanguagePicker } from '../components/MetricsQueryLanguagePicker'+import { switchMetricsQueryLanguage } from '../components/metricsQueryLanguageSwitch'import { isBuilderCompatibleQuery } from '../components/metricsViewerLogic'import { MetricsPanel } from '../panels/MetricsPanel'+import { metricsQueryText, queryLanguage } from '../queryLanguages/convert'import { seriesFromMetricsResponse } from './metricsResponseSeries'let uniqueNode = 0@@ -30,16 +34,28 @@ interface MetricsQueryNodeProps {/** Renders a `MetricsQuery` wherever the generic `Query` component is used —* saved insights, dashboard tiles, notebooks. */+const EMPTY_QUERY_MESSAGE: Record<MetricsQueryLanguage, string> = {+ builder: 'Pick a metric to see its time series.',+ promql: 'Run a query to see results.',+ sql: 'Run a query to see results.',+}+export function MetricsQueryNode(props: MetricsQueryNodeProps): JSX.Element | null {const builderEnabled = useFeatureFlag('METRICS_INSIGHT_BUILDER')- const [editorKey] = useState(() => `MetricsQueryEditor.${uniqueEditor++}`)+ const languagesEnabled = useFeatureFlag('METRICS_QUERY_LANGUAGES')+ // A language switch replaces the query, so the editor remounts to seed its logic from the new one.+ const [editorKey, setEditorKey] = useState(() => `MetricsQueryEditor.${uniqueEditor++}`)+ const [dataKey] = useState(() => `MetricsQueryNode.${uniqueNode++}`)+ const language = queryLanguage(props.query)// A new insight starts with no clauses, which the backend rejects, so there is nothing to run yet.- const results = props.query.clauses.length ? (- <MetricsQueryResults {...props} />+ const hasQuery =+ language === 'builder' ? props.query.clauses.length > 0 : metricsQueryText(props.query).trim() !== ''+ const results = hasQuery ? (+ <MetricsQueryResults {...props} dataKey={dataKey} />) : (<div className="flex-1 flex items-center justify-center min-h-[200px] text-secondary text-sm">- Pick a metric to see its time series.+ {EMPTY_QUERY_MESSAGE[language]}</div>)@@ -47,23 +63,48 @@ export function MetricsQueryNode(props: MetricsQueryNodeProps): JSX.Element | nureturn results}+ const setQuery = props.setQuery+ const onSwitchLanguage = languagesEnabled+ ? (current: MetricsQuery, to: MetricsQueryLanguage): void =>+ switchMetricsQueryLanguage(current, to, (converted) => {+ setQuery(converted)+ setEditorKey(`MetricsQueryEditor.${uniqueEditor++}`)+ })+ : undefined+return (<div className="flex flex-col gap-3 w-full">- {isBuilderCompatibleQuery(props.query) ? (- <MetricsQueryEditor editorKey={editorKey} query={props.query} setQuery={props.setQuery} />+ {language !== 'builder' || isBuilderCompatibleQuery(props.query) ? (+ <MetricsQueryEditor+ key={editorKey}+ editorKey={editorKey}+ query={props.query}+ setQuery={setQuery}+ onSwitchLanguage={onSwitchLanguage}+ onRerun={() => dataNodeLogic.findMounted({ key: dataKey })?.actions.loadData('force_blocking')}+ />) : (- <LemonBanner type="info">- This insight uses settings that the builder cannot show, so the builder is off for this insight.- </LemonBanner>+ <div className="flex flex-col items-start gap-2">+ {onSwitchLanguage && (+ <MetricsQueryLanguagePicker+ value="builder"+ onChange={(to) => onSwitchLanguage(props.query, to)}+ />+ )}+ <LemonBanner type="info" className="w-full">+ {onSwitchLanguage+ ? 'The builder cannot show this query. Switch to PromQL or SQL to edit it.'+ : 'This insight uses settings that the builder cannot show, so the builder is off for this insight.'}+ </LemonBanner>+ </div>)}<div className="relative flex h-[360px] border rounded p-3">{results}</div></div>)}-function MetricsQueryResults(props: MetricsQueryNodeProps): JSX.Element {+function MetricsQueryResults({ dataKey: key, ...props }: MetricsQueryNodeProps & { dataKey: string }): JSX.Element {const { onData, loadPriority, dataNodeCollectionId } = props.context.insightProps ?? {}- const [key] = useState(() => `MetricsQueryNode.${uniqueNode++}`)// `dataNodeLogic` deep-compares its query to decide whether to refetch. Its// `ignoreVisualizationOnlyChanges` option doesn't help here — that only reaches// `cleanInsightQuery`, which bails unless both sides are insight query nodes, and a@@ -84,16 +125,25 @@ function MetricsQueryResults(props: MetricsQueryNodeProps): JSX.Element {useAttachedLogic(logic, props.attachTo)- const { response, responseLoading } = useValues(logic)+ const { response, responseLoading, responseError } = useValues(logic)const series = seriesFromMetricsResponse(response)const hasPoints = series.some((s) => s.points.length > 0)// A formula query returns only the formula result (metricName is null on it),// so the formula text itself is the honest name for an unlabelled series.- const fallbackName = props.query.formula ?? props.query.clauses[0]?.metricName ?? 'metric'+ const fallbackName =+ props.query.formula ??+ props.query.clauses[0]?.metricName ??+ (props.query.language === 'promql' && props.query.promql ? truncate(props.query.promql, 80) : 'metric')return (<div className="relative flex flex-col w-full h-full min-h-[200px]">- {hasPoints ? (+ {responseError && !responseLoading ? (+ <div className="flex-1 flex items-center p-4 min-w-0">+ <LemonBanner type="error" className="w-full">+ {responseError}+ </LemonBanner>+ </div>+ ) : hasPoints ? (<MetricsPanel series={series} fallbackName={fallbackName} display={props.query.display} />) : !responseLoading ? (<div className="flex-1 flex items-center justify-center text-secondary text-sm">diff --git a/products/metrics/frontend/queryLanguages/__fixtures__/builder_sql.json b/products/metrics/frontend/queryLanguages/__fixtures__/builder_sql.jsonnew file mode 100644index 000000000000..0a76d2302060--- /dev/null+++ b/products/metrics/frontend/queryLanguages/__fixtures__/builder_sql.json@@ -0,0 +1,703 @@+{+ "gauge sum": {+ "builder": {+ "clauses": [+ {+ "name": "a",+ "aggregation": "sum",+ "metricName": "queue_depth"+ }+ ]+ },+ "sql": "SELECT\n s.time AS time,\n sum(s.series_value) AS value\nFROM (\n SELECT\n toStartOfInterval(timestamp, {interval}) AS time,\n series_fingerprint,\n argMax(value, timestamp) AS series_value\n FROM posthog.metrics\n WHERE metric_name = 'queue_depth'\n AND timestamp >= {date_from}\n AND timestamp < {date_to}\n GROUP BY time, series_fingerprint\n) AS s\nGROUP BY time\nORDER BY time"+ },+ "gauge avg": {+ "builder": {+ "clauses": [+ {+ "name": "a",+ "aggregation": "avg",+ "metricName": "process.cpu.utilization"+ }+ ]+ },+ "sql": "SELECT\n s.time AS time,\n avg(s.series_value) AS value\nFROM (\n SELECT\n toStartOfInterval(timestamp, {interval}) AS time,\n series_fingerprint,\n argMax(value, timestamp) AS series_value\n FROM posthog.metrics\n WHERE metric_name = 'process.cpu.utilization'\n AND timestamp >= {date_from}\n AND timestamp < {date_to}\n GROUP BY time, series_fingerprint\n) AS s\nGROUP BY time\nORDER BY time"+ },+ "gauge min": {+ "builder": {+ "clauses": [+ {+ "name": "a",+ "aggregation": "min",+ "metricName": "free_disk_bytes"+ }+ ]+ },+ "sql": "SELECT\n s.time AS time,\n min(s.series_value) AS value\nFROM (\n SELECT\n toStartOfInterval(timestamp, {interval}) AS time,\n series_fingerprint,\n argMax(value, timestamp) AS series_value\n FROM posthog.metrics\n WHERE metric_name = 'free_disk_bytes'\n AND timestamp >= {date_from}\n AND timestamp < {date_to}\n GROUP BY time, series_fingerprint\n) AS s\nGROUP BY time\nORDER BY time"+ },+ "gauge max": {+ "builder": {+ "clauses": [+ {+ "name": "a",+ "aggregation": "max",+ "metricName": "jvm.memory.used"+ }+ ]+ },+ "sql": "SELECT\n s.time AS time,\n max(s.series_value) AS value\nFROM (\n SELECT\n toStartOfInterval(timestamp, {interval}) AS time,\n series_fingerprint,\n argMax(value, timestamp) AS series_value\n FROM posthog.metrics\n WHERE metric_name = 'jvm.memory.used'\n AND timestamp >= {date_from}\n AND timestamp < {date_to}\n GROUP BY time, series_fingerprint\n) AS s\nGROUP BY time\nORDER BY time"+ },+ "series count": {+ "builder": {+ "clauses": [+ {+ "name": "a",+ "aggregation": "count",+ "metricName": "up"+ }+ ]+ },+ "sql": "SELECT\n s.time AS time,\n toFloat(count()) AS value\nFROM (\n SELECT\n toStartOfInterval(timestamp, {interval}) AS time,\n series_fingerprint,\n argMax(value, timestamp) AS series_value\n FROM posthog.metrics\n WHERE metric_name = 'up'\n AND timestamp >= {date_from}\n AND timestamp < {date_to}\n GROUP BY time, series_fingerprint\n) AS s\nGROUP BY time\nORDER BY time"+ },+ "p95": {+ "builder": {+ "clauses": [+ {+ "name": "a",+ "aggregation": "quantile",+ "metricName": "request_latency_ms",+ "quantile": 0.95+ }+ ]+ },+ "sql": "SELECT\n s.time AS time,\n quantile(0.95)(s.series_value) AS value\nFROM (\n SELECT\n toStartOfInterval(timestamp, {interval}) AS time,\n series_fingerprint,\n argMax(value, timestamp) AS series_value\n FROM posthog.metrics\n WHERE metric_name = 'request_latency_ms'\n AND timestamp >= {date_from}\n AND timestamp < {date_to}\n GROUP BY time, series_fingerprint\n) AS s\nGROUP BY time\nORDER BY time"+ },+ "counter rate": {+ "builder": {+ "clauses": [+ {+ "name": "a",+ "aggregation": "sum",+ "metricName": "http.server.request.count",+ "rangeFunction": "rate"+ }+ ]+ },+ "sql": "SELECT\n s.time AS time,\n sum(s.series_value) AS value\nFROM (\n SELECT\n toStartOfInterval(c.sample_timestamp, {interval}) AS time,\n c.series_fingerprint AS series_fingerprint,\n sum(c.contribution) / {interval_seconds} AS series_value\n FROM (\n SELECT\n timestamp AS sample_timestamp,\n series_fingerprint,\n multiIf(\n aggregation_temporality = 'delta', value,\n isNull(prev_value), NULL,\n value >= assumeNotNull(prev_value), value - assumeNotNull(prev_value),\n value\n ) AS contribution\n FROM (\n SELECT\n timestamp,\n series_fingerprint,\n value,\n aggregation_temporality,\n lagInFrame(toNullable(value)) OVER (\n PARTITION BY series_fingerprint\n ORDER BY timestamp ASC\n ROWS BETWEEN 1 PRECEDING AND 1 PRECEDING\n ) AS prev_value\n FROM posthog.metrics\n WHERE metric_name = 'http.server.request.count'\n AND timestamp >= {date_from} - toIntervalSecond(greatest({interval_seconds}, 300))\n AND timestamp < {date_to}\n )\n ) AS c\n WHERE c.sample_timestamp >= {date_from}\n GROUP BY time, series_fingerprint\n HAVING isNotNull(series_value)\n) AS s\nGROUP BY time\nORDER BY time"+ },+ "legacy increase aggregation": {+ "builder": {+ "clauses": [+ {+ "name": "a",+ "aggregation": "increase",+ "metricName": "jobs_processed_total"+ }+ ]+ },+ "sql": "SELECT\n s.time AS time,\n sum(s.series_value) AS value\nFROM (\n SELECT\n toStartOfInterval(c.sample_timestamp, {interval}) AS time,\n c.series_fingerprint AS series_fingerprint,\n sum(c.contribution) AS series_value\n FROM (\n SELECT\n timestamp AS sample_timestamp,\n series_fingerprint,\n multiIf(\n aggregation_temporality = 'delta', value,\n isNull(prev_value), NULL,\n value >= assumeNotNull(prev_value), value - assumeNotNull(prev_value),\n value\n ) AS contribution\n FROM (\n SELECT\n timestamp,\n series_fingerprint,\n value,\n aggregation_temporality,\n lagInFrame(toNullable(value)) OVER (\n PARTITION BY series_fingerprint\n ORDER BY timestamp ASC\n ROWS BETWEEN 1 PRECEDING AND 1 PRECEDING\n ) AS prev_value\n FROM posthog.metrics\n WHERE metric_name = 'jobs_processed_total'\n AND timestamp >= {date_from} - toIntervalSecond(greatest({interval_seconds}, 300))\n AND timestamp < {date_to}\n )\n ) AS c\n WHERE c.sample_timestamp >= {date_from}\n GROUP BY time, series_fingerprint\n HAVING isNotNull(series_value)\n) AS s\nGROUP BY time\nORDER BY time"+ },+ "max of per-series increase by service": {+ "builder": {+ "clauses": [+ {+ "name": "a",+ "aggregation": "max",+ "metricName": "jobs_processed_total",+ "rangeFunction": "increase",+ "groupBy": [+ {+ "key": "service_name"+ }+ ]+ }+ ]+ },+ "sql": "SELECT\n s.time AS time,\n ser.group_0 AS service_name,\n max(s.series_value) AS value\nFROM (\n SELECT\n toStartOfInterval(c.sample_timestamp, {interval}) AS time,\n c.series_fingerprint AS series_fingerprint,\n sum(c.contribution) AS series_value\n FROM (\n SELECT\n timestamp AS sample_timestamp,\n series_fingerprint,\n multiIf(\n aggregation_temporality = 'delta', value,\n isNull(prev_value), NULL,\n value >= assumeNotNull(prev_value), value - assumeNotNull(prev_value),\n value\n ) AS contribution\n FROM (\n SELECT\n timestamp,\n series_fingerprint,\n value,\n aggregation_temporality,\n lagInFrame(toNullable(value)) OVER (\n PARTITION BY series_fingerprint\n ORDER BY timestamp ASC\n ROWS BETWEEN 1 PRECEDING AND 1 PRECEDING\n ) AS prev_value\n FROM posthog.metrics\n WHERE metric_name = 'jobs_processed_total'\n AND timestamp >= {date_from} - toIntervalSecond(greatest({interval_seconds}, 300))\n AND timestamp < {date_to}\n )\n ) AS c\n WHERE c.sample_timestamp >= {date_from}\n GROUP BY time, series_fingerprint\n HAVING isNotNull(series_value)\n) AS s\nLEFT JOIN (\n SELECT\n series_fingerprint,\n any(toString(service_name)) AS group_0\n FROM posthog.metric_series\n WHERE metric_name = 'jobs_processed_total'\n AND last_seen >= {date_from} - toIntervalHour(1)\n GROUP BY series_fingerprint\n) AS ser ON s.series_fingerprint = ser.series_fingerprint\nGROUP BY time, service_name\nORDER BY time"+ },+ "count of per-series rate": {+ "builder": {+ "clauses": [+ {+ "name": "a",+ "aggregation": "count",+ "metricName": "http.server.request.count",+ "rangeFunction": "rate"+ }+ ]+ },+ "sql": "SELECT\n s.time AS time,\n toFloat(count()) AS value\nFROM (\n SELECT\n toStartOfInterval(c.sample_timestamp, {interval}) AS time,\n c.series_fingerprint AS series_fingerprint,\n sum(c.contribution) / {interval_seconds} AS series_value\n FROM (\n SELECT\n timestamp AS sample_timestamp,\n series_fingerprint,\n multiIf(\n aggregation_temporality = 'delta', value,\n isNull(prev_value), NULL,\n value >= assumeNotNull(prev_value), value - assumeNotNull(prev_value),\n value\n ) AS contribution\n FROM (\n SELECT\n timestamp,\n series_fingerprint,\n value,\n aggregation_temporality,\n lagInFrame(toNullable(value)) OVER (\n PARTITION BY series_fingerprint\n ORDER BY timestamp ASC\n ROWS BETWEEN 1 PRECEDING AND 1 PRECEDING\n ) AS prev_value\n FROM posthog.metrics\n WHERE metric_name = 'http.server.request.count'\n AND timestamp >= {date_from} - toIntervalSecond(greatest({interval_seconds}, 300))\n AND timestamp < {date_to}\n )\n ) AS c\n WHERE c.sample_timestamp >= {date_from}\n GROUP BY time, series_fingerprint\n HAVING isNotNull(series_value)\n) AS s\nGROUP BY time\nORDER BY time"+ },+ "histogram p99": {+ "builder": {+ "clauses": [+ {+ "name": "a",+ "aggregation": "histogram_quantile",+ "metricName": "http.server.duration",+ "quantile": 0.99+ }+ ]+ },+ "sql": "SELECT\n time,\n if(\n idx > length(bounds),\n bounds[length(bounds)],\n if(idx > 1, bounds[idx - 1], least(0.0, bounds[1]))\n + (bounds[idx] - if(idx > 1, bounds[idx - 1], least(0.0, bounds[1])))\n * (rank - (cumulative[idx] - counts[idx])) / counts[idx]\n ) AS value\nFROM (\n SELECT\n time,\n bounds,\n counts,\n arrayCumSum(counts) AS cumulative,\n 0.99 * arraySum(counts) AS rank,\n arrayFirstIndex(c -> c >= rank, cumulative) AS idx\n FROM (\n SELECT\n toStartOfInterval(s.sample_timestamp, {interval}) AS time,\n any(s.histogram_bounds) AS bounds,\n uniqExactIf(s.histogram_bounds, notEmpty(s.histogram_bounds)) AS layouts,\n arrayMap(x -> ifNull(x, 0.0), sumForEach(s.contribution_counts)) AS counts\n FROM (\n SELECT\n timestamp AS sample_timestamp,\n series_fingerprint,\n histogram_bounds,\n multiIf(\n aggregation_temporality = 'delta', counts_f,\n empty(prev_counts), arrayMap(x -> 0.0, counts_f),\n length(prev_counts) != length(counts_f), counts_f,\n arrayAll((c, p) -> c >= p, counts_f, prev_counts), arrayMap((c, p) -> c - p, counts_f, prev_counts),\n counts_f\n ) AS contribution_counts\n FROM (\n SELECT\n timestamp,\n series_fingerprint,\n aggregation_temporality,\n histogram_bounds,\n arrayMap(x -> toFloat(x), histogram_counts) AS counts_f,\n lagInFrame(arrayMap(x -> toFloat(x), histogram_counts)) OVER (\n PARTITION BY series_fingerprint\n ORDER BY timestamp ASC\n ROWS BETWEEN 1 PRECEDING AND 1 PRECEDING\n ) AS prev_counts\n FROM posthog.metrics\n WHERE metric_name = 'http.server.duration'\n AND timestamp >= {date_from} - toIntervalSecond(greatest({interval_seconds}, 300))\n AND timestamp < {date_to}\n AND notEmpty(histogram_counts)\n )\n ) AS s\n WHERE s.sample_timestamp >= {date_from}\n GROUP BY time\n )\n WHERE arraySum(counts) > 0\n AND throwIf(layouts > 1, 'The series have different histogram bounds. Add filters so that all series use the same buckets.') = 0\n)\nORDER BY time"+ },+ "histogram p50 by service": {+ "builder": {+ "clauses": [+ {+ "name": "a",+ "aggregation": "histogram_quantile",+ "metricName": "http.server.duration",+ "quantile": 0.5,+ "groupBy": [+ {+ "key": "service_name"+ }+ ]+ }+ ]+ },+ "sql": "SELECT\n time,\n service_name,\n if(\n idx > length(bounds),\n bounds[length(bounds)],\n if(idx > 1, bounds[idx - 1], least(0.0, bounds[1]))\n + (bounds[idx] - if(idx > 1, bounds[idx - 1], least(0.0, bounds[1])))\n * (rank - (cumulative[idx] - counts[idx])) / counts[idx]\n ) AS value\nFROM (\n SELECT\n time,\n service_name,\n bounds,\n counts,\n arrayCumSum(counts) AS cumulative,\n 0.5 * arraySum(counts) AS rank,\n arrayFirstIndex(c -> c >= rank, cumulative) AS idx\n FROM (\n SELECT\n toStartOfInterval(s.sample_timestamp, {interval}) AS time,\n ser.group_0 AS service_name,\n any(s.histogram_bounds) AS bounds,\n uniqExactIf(s.histogram_bounds, notEmpty(s.histogram_bounds)) AS layouts,\n arrayMap(x -> ifNull(x, 0.0), sumForEach(s.contribution_counts)) AS counts\n FROM (\n SELECT\n timestamp AS sample_timestamp,\n series_fingerprint,\n histogram_bounds,\n multiIf(\n aggregation_temporality = 'delta', counts_f,\n empty(prev_counts), arrayMap(x -> 0.0, counts_f),\n length(prev_counts) != length(counts_f), counts_f,\n arrayAll((c, p) -> c >= p, counts_f, prev_counts), arrayMap((c, p) -> c - p, counts_f, prev_counts),\n counts_f\n ) AS contribution_counts\n FROM (\n SELECT\n timestamp,\n series_fingerprint,\n aggregation_temporality,\n histogram_bounds,\n arrayMap(x -> toFloat(x), histogram_counts) AS counts_f,\n lagInFrame(arrayMap(x -> toFloat(x), histogram_counts)) OVER (\n PARTITION BY series_fingerprint\n ORDER BY timestamp ASC\n ROWS BETWEEN 1 PRECEDING AND 1 PRECEDING\n ) AS prev_counts\n FROM posthog.metrics\n WHERE metric_name = 'http.server.duration'\n AND timestamp >= {date_from} - toIntervalSecond(greatest({interval_seconds}, 300))\n AND timestamp < {date_to}\n AND notEmpty(histogram_counts)\n )\n ) AS s\n LEFT JOIN (\n SELECT\n series_fingerprint,\n any(toString(service_name)) AS group_0\n FROM posthog.metric_series\n WHERE metric_name = 'http.server.duration'\n AND last_seen >= {date_from} - toIntervalHour(1)\n GROUP BY series_fingerprint\n ) AS ser ON s.series_fingerprint = ser.series_fingerprint\n WHERE s.sample_timestamp >= {date_from}\n GROUP BY time, service_name\n )\n WHERE arraySum(counts) > 0\n AND throwIf(layouts > 1, 'The series have different histogram bounds. Add filters so that all series use the same buckets.') = 0\n)\nORDER BY time"+ },+ "eq filter": {+ "builder": {+ "clauses": [+ {+ "name": "a",+ "aggregation": "sum",+ "metricName": "queue_depth",+ "filters": [+ {+ "key": "service_name",+ "op": "eq",+ "value": "api"+ }+ ]+ }+ ]+ },+ "sql": "SELECT\n s.time AS time,\n sum(s.series_value) AS value\nFROM (\n SELECT\n toStartOfInterval(timestamp, {interval}) AS time,\n series_fingerprint,\n argMax(value, timestamp) AS series_value\n FROM posthog.metrics\n WHERE metric_name = 'queue_depth'\n AND timestamp >= {date_from}\n AND timestamp < {date_to}\n AND series_fingerprint IN (\n SELECT series_fingerprint\n FROM posthog.metric_series\n WHERE metric_name = 'queue_depth'\n AND last_seen >= {date_from} - toIntervalHour(1)\n AND service_name = 'api'\n )\n GROUP BY time, series_fingerprint\n) AS s\nGROUP BY time\nORDER BY time"+ },+ "neq filter on dotted key": {+ "builder": {+ "clauses": [+ {+ "name": "a",+ "aggregation": "rate",+ "metricName": "http.server.request.count",+ "filters": [+ {+ "key": "http.request.method",+ "op": "neq",+ "value": "OPTIONS"+ }+ ]+ }+ ]+ },+ "sql": "SELECT\n s.time AS time,\n sum(s.series_value) AS value\nFROM (\n SELECT\n toStartOfInterval(c.sample_timestamp, {interval}) AS time,\n c.series_fingerprint AS series_fingerprint,\n sum(c.contribution) / {interval_seconds} AS series_value\n FROM (\n SELECT\n timestamp AS sample_timestamp,\n series_fingerprint,\n multiIf(\n aggregation_temporality = 'delta', value,\n isNull(prev_value), NULL,\n value >= assumeNotNull(prev_value), value - assumeNotNull(prev_value),\n value\n ) AS contribution\n FROM (\n SELECT\n timestamp,\n series_fingerprint,\n value,\n aggregation_temporality,\n lagInFrame(toNullable(value)) OVER (\n PARTITION BY series_fingerprint\n ORDER BY timestamp ASC\n ROWS BETWEEN 1 PRECEDING AND 1 PRECEDING\n ) AS prev_value\n FROM posthog.metrics\n WHERE metric_name = 'http.server.request.count'\n AND timestamp >= {date_from} - toIntervalSecond(greatest({interval_seconds}, 300))\n AND timestamp < {date_to}\n AND series_fingerprint IN (\n SELECT series_fingerprint\n FROM posthog.metric_series\n WHERE metric_name = 'http.server.request.count'\n AND last_seen >= {date_from} - toIntervalHour(1)\n AND if(arrayElement(resource_attributes, 'http.request.method') != '', arrayElement(resource_attributes, 'http.request.method'), arrayElement(attributes, 'http.request.method')) != 'OPTIONS'\n )\n )\n ) AS c\n WHERE c.sample_timestamp >= {date_from}\n GROUP BY time, series_fingerprint\n HAVING isNotNull(series_value)\n) AS s\nGROUP BY time\nORDER BY time"+ },+ "multi-value chip regex": {+ "builder": {+ "clauses": [+ {+ "name": "a",+ "aggregation": "sum",+ "metricName": "queue_depth",+ "filters": [+ {+ "key": "service_name",+ "op": "regex",+ "value": "^(?:api|worker)$"+ }+ ]+ }+ ]+ },+ "sql": "SELECT\n s.time AS time,\n sum(s.series_value) AS value\nFROM (\n SELECT\n toStartOfInterval(timestamp, {interval}) AS time,\n series_fingerprint,\n argMax(value, timestamp) AS series_value\n FROM posthog.metrics\n WHERE metric_name = 'queue_depth'\n AND timestamp >= {date_from}\n AND timestamp < {date_to}\n AND series_fingerprint IN (\n SELECT series_fingerprint\n FROM posthog.metric_series\n WHERE metric_name = 'queue_depth'\n AND last_seen >= {date_from} - toIntervalHour(1)\n AND match(service_name, '^(?:api|worker)$')\n )\n GROUP BY time, series_fingerprint\n) AS s\nGROUP BY time\nORDER BY time"+ },+ "unanchored regex": {+ "builder": {+ "clauses": [+ {+ "name": "a",+ "aggregation": "sum",+ "metricName": "queue_depth",+ "filters": [+ {+ "key": "http.route",+ "op": "regex",+ "value": "users"+ }+ ]+ }+ ]+ },+ "sql": "SELECT\n s.time AS time,\n sum(s.series_value) AS value\nFROM (\n SELECT\n toStartOfInterval(timestamp, {interval}) AS time,\n series_fingerprint,\n argMax(value, timestamp) AS series_value\n FROM posthog.metrics\n WHERE metric_name = 'queue_depth'\n AND timestamp >= {date_from}\n AND timestamp < {date_to}\n AND series_fingerprint IN (\n SELECT series_fingerprint\n FROM posthog.metric_series\n WHERE metric_name = 'queue_depth'\n AND last_seen >= {date_from} - toIntervalHour(1)\n AND match(if(arrayElement(resource_attributes, 'http.route') != '', arrayElement(resource_attributes, 'http.route'), arrayElement(attributes, 'http.route')), 'users')\n )\n GROUP BY time, series_fingerprint\n) AS s\nGROUP BY time\nORDER BY time"+ },+ "prefix regex": {+ "builder": {+ "clauses": [+ {+ "name": "a",+ "aggregation": "sum",+ "metricName": "queue_depth",+ "filters": [+ {+ "key": "http.route",+ "op": "regex",+ "value": "^/api"+ }+ ]+ }+ ]+ },+ "sql": "SELECT\n s.time AS time,\n sum(s.series_value) AS value\nFROM (\n SELECT\n toStartOfInterval(timestamp, {interval}) AS time,\n series_fingerprint,\n argMax(value, timestamp) AS series_value\n FROM posthog.metrics\n WHERE metric_name = 'queue_depth'\n AND timestamp >= {date_from}\n AND timestamp < {date_to}\n AND series_fingerprint IN (\n SELECT series_fingerprint\n FROM posthog.metric_series\n WHERE metric_name = 'queue_depth'\n AND last_seen >= {date_from} - toIntervalHour(1)\n AND match(if(arrayElement(resource_attributes, 'http.route') != '', arrayElement(resource_attributes, 'http.route'), arrayElement(attributes, 'http.route')), '^/api')\n )\n GROUP BY time, series_fingerprint\n) AS s\nGROUP BY time\nORDER BY time"+ },+ "suffix not regex": {+ "builder": {+ "clauses": [+ {+ "name": "a",+ "aggregation": "sum",+ "metricName": "queue_depth",+ "filters": [+ {+ "key": "http.route",+ "op": "not_regex",+ "value": "health$"+ }+ ]+ }+ ]+ },+ "sql": "SELECT\n s.time AS time,\n sum(s.series_value) AS value\nFROM (\n SELECT\n toStartOfInterval(timestamp, {interval}) AS time,\n series_fingerprint,\n argMax(value, timestamp) AS series_value\n FROM posthog.metrics\n WHERE metric_name = 'queue_depth'\n AND timestamp >= {date_from}\n AND timestamp < {date_to}\n AND series_fingerprint IN (\n SELECT series_fingerprint\n FROM posthog.metric_series\n WHERE metric_name = 'queue_depth'\n AND last_seen >= {date_from} - toIntervalHour(1)\n AND NOT match(if(arrayElement(resource_attributes, 'http.route') != '', arrayElement(resource_attributes, 'http.route'), arrayElement(attributes, 'http.route')), 'health$')\n )\n GROUP BY time, series_fingerprint\n) AS s\nGROUP BY time\nORDER BY time"+ },+ "empty service pattern": {+ "builder": {+ "clauses": [+ {+ "name": "a",+ "aggregation": "sum",+ "metricName": "queue_depth",+ "filters": [+ {+ "key": "service_name",+ "op": "regex",+ "value": "^$"+ }+ ]+ }+ ]+ },+ "sql": "SELECT\n s.time AS time,\n sum(s.series_value) AS value\nFROM (\n SELECT\n toStartOfInterval(timestamp, {interval}) AS time,\n series_fingerprint,\n argMax(value, timestamp) AS series_value\n FROM posthog.metrics\n WHERE metric_name = 'queue_depth'\n AND timestamp >= {date_from}\n AND timestamp < {date_to}\n AND series_fingerprint IN (\n SELECT series_fingerprint\n FROM posthog.metric_series\n WHERE metric_name = 'queue_depth'\n AND last_seen >= {date_from} - toIntervalHour(1)\n AND match(service_name, '^$')\n )\n GROUP BY time, series_fingerprint\n) AS s\nGROUP BY time\nORDER BY time"+ },+ "value with quotes and backslashes": {+ "builder": {+ "clauses": [+ {+ "name": "a",+ "aggregation": "sum",+ "metricName": "queue_depth",+ "filters": [+ {+ "key": "queue",+ "op": "eq",+ "value": "it's a \"quoted\" \\ value"+ }+ ]+ }+ ]+ },+ "sql": "SELECT\n s.time AS time,\n sum(s.series_value) AS value\nFROM (\n SELECT\n toStartOfInterval(timestamp, {interval}) AS time,\n series_fingerprint,\n argMax(value, timestamp) AS series_value\n FROM posthog.metrics\n WHERE metric_name = 'queue_depth'\n AND timestamp >= {date_from}\n AND timestamp < {date_to}\n AND series_fingerprint IN (\n SELECT series_fingerprint\n FROM posthog.metric_series\n WHERE metric_name = 'queue_depth'\n AND last_seen >= {date_from} - toIntervalHour(1)\n AND if(arrayElement(resource_attributes, 'queue') != '', arrayElement(resource_attributes, 'queue'), arrayElement(attributes, 'queue')) = 'it\\'s a \"quoted\" \\\\ value'\n )\n GROUP BY time, series_fingerprint\n) AS s\nGROUP BY time\nORDER BY time"+ },+ "several filters": {+ "builder": {+ "clauses": [+ {+ "name": "a",+ "aggregation": "increase",+ "metricName": "http.server.request.count",+ "filters": [+ {+ "key": "service_name",+ "op": "eq",+ "value": "api"+ },+ {+ "key": "http.response.status_code",+ "op": "regex",+ "value": "^5"+ },+ {+ "key": "http.route",+ "op": "neq",+ "value": "/health"+ }+ ]+ }+ ]+ },+ "sql": "SELECT\n s.time AS time,\n sum(s.series_value) AS value\nFROM (\n SELECT\n toStartOfInterval(c.sample_timestamp, {interval}) AS time,\n c.series_fingerprint AS series_fingerprint,\n sum(c.contribution) AS series_value\n FROM (\n SELECT\n timestamp AS sample_timestamp,\n series_fingerprint,\n multiIf(\n aggregation_temporality = 'delta', value,\n isNull(prev_value), NULL,\n value >= assumeNotNull(prev_value), value - assumeNotNull(prev_value),\n value\n ) AS contribution\n FROM (\n SELECT\n timestamp,\n series_fingerprint,\n value,\n aggregation_temporality,\n lagInFrame(toNullable(value)) OVER (\n PARTITION BY series_fingerprint\n ORDER BY timestamp ASC\n ROWS BETWEEN 1 PRECEDING AND 1 PRECEDING\n ) AS prev_value\n FROM posthog.metrics\n WHERE metric_name = 'http.server.request.count'\n AND timestamp >= {date_from} - toIntervalSecond(greatest({interval_seconds}, 300))\n AND timestamp < {date_to}\n AND series_fingerprint IN (\n SELECT series_fingerprint\n FROM posthog.metric_series\n WHERE metric_name = 'http.server.request.count'\n AND last_seen >= {date_from} - toIntervalHour(1)\n AND service_name = 'api'\n AND match(if(arrayElement(resource_attributes, 'http.response.status_code') != '', arrayElement(resource_attributes, 'http.response.status_code'), arrayElement(attributes, 'http.response.status_code')), '^5')\n AND if(arrayElement(resource_attributes, 'http.route') != '', arrayElement(resource_attributes, 'http.route'), arrayElement(attributes, 'http.route')) != '/health'\n )\n )\n ) AS c\n WHERE c.sample_timestamp >= {date_from}\n GROUP BY time, series_fingerprint\n HAVING isNotNull(series_value)\n) AS s\nGROUP BY time\nORDER BY time"+ },+ "regex with an escaped dot": {+ "builder": {+ "clauses": [+ {+ "name": "a",+ "aggregation": "count",+ "metricName": "build_info",+ "filters": [+ {+ "key": "version",+ "op": "regex",+ "value": "^v1\\.2"+ }+ ]+ }+ ]+ },+ "sql": "SELECT\n s.time AS time,\n toFloat(count()) AS value\nFROM (\n SELECT\n toStartOfInterval(timestamp, {interval}) AS time,\n series_fingerprint,\n argMax(value, timestamp) AS series_value\n FROM posthog.metrics\n WHERE metric_name = 'build_info'\n AND timestamp >= {date_from}\n AND timestamp < {date_to}\n AND series_fingerprint IN (\n SELECT series_fingerprint\n FROM posthog.metric_series\n WHERE metric_name = 'build_info'\n AND last_seen >= {date_from} - toIntervalHour(1)\n AND match(if(arrayElement(resource_attributes, 'version') != '', arrayElement(resource_attributes, 'version'), arrayElement(attributes, 'version')), '^v1\\\\.2')\n )\n GROUP BY time, series_fingerprint\n) AS s\nGROUP BY time\nORDER BY time"+ },+ "non-ASCII and spaced names": {+ "builder": {+ "clauses": [+ {+ "name": "a",+ "aggregation": "sum",+ "metricName": "größe_bytes",+ "filters": [+ {+ "key": "queue name",+ "op": "eq",+ "value": "é"+ }+ ],+ "groupBy": [+ {+ "key": "région"+ }+ ]+ }+ ]+ },+ "sql": "SELECT\n s.time AS time,\n ser.group_0 AS `région`,\n sum(s.series_value) AS value\nFROM (\n SELECT\n toStartOfInterval(timestamp, {interval}) AS time,\n series_fingerprint,\n argMax(value, timestamp) AS series_value\n FROM posthog.metrics\n WHERE metric_name = 'größe_bytes'\n AND timestamp >= {date_from}\n AND timestamp < {date_to}\n AND series_fingerprint IN (\n SELECT series_fingerprint\n FROM posthog.metric_series\n WHERE metric_name = 'größe_bytes'\n AND last_seen >= {date_from} - toIntervalHour(1)\n AND if(arrayElement(resource_attributes, 'queue name') != '', arrayElement(resource_attributes, 'queue name'), arrayElement(attributes, 'queue name')) = 'é'\n )\n GROUP BY time, series_fingerprint\n) AS s\nLEFT JOIN (\n SELECT\n series_fingerprint,\n any(toString(if(arrayElement(resource_attributes, 'région') != '', arrayElement(resource_attributes, 'région'), arrayElement(attributes, 'région')))) AS group_0\n FROM posthog.metric_series\n WHERE metric_name = 'größe_bytes'\n AND last_seen >= {date_from} - toIntervalHour(1)\n GROUP BY series_fingerprint\n) AS ser ON s.series_fingerprint = ser.series_fingerprint\nGROUP BY time, `région`\nORDER BY time"+ },+ "group by one": {+ "builder": {+ "clauses": [+ {+ "name": "a",+ "aggregation": "sum",+ "metricName": "queue_depth",+ "groupBy": [+ {+ "key": "service_name"+ }+ ]+ }+ ]+ },+ "sql": "SELECT\n s.time AS time,\n ser.group_0 AS service_name,\n sum(s.series_value) AS value\nFROM (\n SELECT\n toStartOfInterval(timestamp, {interval}) AS time,\n series_fingerprint,\n argMax(value, timestamp) AS series_value\n FROM posthog.metrics\n WHERE metric_name = 'queue_depth'\n AND timestamp >= {date_from}\n AND timestamp < {date_to}\n GROUP BY time, series_fingerprint\n) AS s\nLEFT JOIN (\n SELECT\n series_fingerprint,\n any(toString(service_name)) AS group_0\n FROM posthog.metric_series\n WHERE metric_name = 'queue_depth'\n AND last_seen >= {date_from} - toIntervalHour(1)\n GROUP BY series_fingerprint\n) AS ser ON s.series_fingerprint = ser.series_fingerprint\nGROUP BY time, service_name\nORDER BY time"+ },+ "group by two dotted": {+ "builder": {+ "clauses": [+ {+ "name": "a",+ "aggregation": "rate",+ "metricName": "http.server.request.count",+ "groupBy": [+ {+ "key": "http.route"+ },+ {+ "key": "http.request.method"+ }+ ]+ }+ ]+ },+ "sql": "SELECT\n s.time AS time,\n ser.group_0 AS `http.route`,\n ser.group_1 AS `http.request.method`,\n sum(s.series_value) AS value\nFROM (\n SELECT\n toStartOfInterval(c.sample_timestamp, {interval}) AS time,\n c.series_fingerprint AS series_fingerprint,\n sum(c.contribution) / {interval_seconds} AS series_value\n FROM (\n SELECT\n timestamp AS sample_timestamp,\n series_fingerprint,\n multiIf(\n aggregation_temporality = 'delta', value,\n isNull(prev_value), NULL,\n value >= assumeNotNull(prev_value), value - assumeNotNull(prev_value),\n value\n ) AS contribution\n FROM (\n SELECT\n timestamp,\n series_fingerprint,\n value,\n aggregation_temporality,\n lagInFrame(toNullable(value)) OVER (\n PARTITION BY series_fingerprint\n ORDER BY timestamp ASC\n ROWS BETWEEN 1 PRECEDING AND 1 PRECEDING\n ) AS prev_value\n FROM posthog.metrics\n WHERE metric_name = 'http.server.request.count'\n AND timestamp >= {date_from} - toIntervalSecond(greatest({interval_seconds}, 300))\n AND timestamp < {date_to}\n )\n ) AS c\n WHERE c.sample_timestamp >= {date_from}\n GROUP BY time, series_fingerprint\n HAVING isNotNull(series_value)\n) AS s\nLEFT JOIN (\n SELECT\n series_fingerprint,\n any(toString(if(arrayElement(resource_attributes, 'http.route') != '', arrayElement(resource_attributes, 'http.route'), arrayElement(attributes, 'http.route')))) AS group_0,\n any(toString(if(arrayElement(resource_attributes, 'http.request.method') != '', arrayElement(resource_attributes, 'http.request.method'), arrayElement(attributes, 'http.request.method')))) AS group_1\n FROM posthog.metric_series\n WHERE metric_name = 'http.server.request.count'\n AND last_seen >= {date_from} - toIntervalHour(1)\n GROUP BY series_fingerprint\n) AS ser ON s.series_fingerprint = ser.series_fingerprint\nGROUP BY time, `http.route`, `http.request.method`\nORDER BY time"+ },+ "error ratio formula": {+ "builder": {+ "clauses": [+ {+ "name": "a",+ "aggregation": "rate",+ "metricName": "http.server.request.count",+ "filters": [+ {+ "key": "http.response.status_code",+ "op": "regex",+ "value": "^5"+ }+ ]+ },+ {+ "name": "b",+ "aggregation": "rate",+ "metricName": "http.server.request.count"+ }+ ],+ "formula": "a / b * 100"+ },+ "sql": "SELECT\n time,\n if(b = 0, 0, a / b) * 100 AS value\nFROM (\n SELECT\n time,\n sum(a) AS a,\n sum(b) AS b,\n max(max(a_seen)) OVER () AS a_in_label_set,\n max(max(b_seen)) OVER () AS b_in_label_set\n FROM (\n SELECT\n time, value AS a, 0 AS b, 1 AS a_seen, 0 AS b_seen\n FROM (\n SELECT\n s.time AS time,\n sum(s.series_value) AS value\n FROM (\n SELECT\n toStartOfInterval(c.sample_timestamp, {interval}) AS time,\n c.series_fingerprint AS series_fingerprint,\n sum(c.contribution) / {interval_seconds} AS series_value\n FROM (\n SELECT\n timestamp AS sample_timestamp,\n series_fingerprint,\n multiIf(\n aggregation_temporality = 'delta', value,\n isNull(prev_value), NULL,\n value >= assumeNotNull(prev_value), value - assumeNotNull(prev_value),\n value\n ) AS contribution\n FROM (\n SELECT\n timestamp,\n series_fingerprint,\n value,\n aggregation_temporality,\n lagInFrame(toNullable(value)) OVER (\n PARTITION BY series_fingerprint\n ORDER BY timestamp ASC\n ROWS BETWEEN 1 PRECEDING AND 1 PRECEDING\n ) AS prev_value\n FROM posthog.metrics\n WHERE metric_name = 'http.server.request.count'\n AND timestamp >= {date_from} - toIntervalSecond(greatest({interval_seconds}, 300))\n AND timestamp < {date_to}\n AND series_fingerprint IN (\n SELECT series_fingerprint\n FROM posthog.metric_series\n WHERE metric_name = 'http.server.request.count'\n AND last_seen >= {date_from} - toIntervalHour(1)\n AND match(if(arrayElement(resource_attributes, 'http.response.status_code') != '', arrayElement(resource_attributes, 'http.response.status_code'), arrayElement(attributes, 'http.response.status_code')), '^5')\n )\n )\n ) AS c\n WHERE c.sample_timestamp >= {date_from}\n GROUP BY time, series_fingerprint\n HAVING isNotNull(series_value)\n ) AS s\n GROUP BY time\n )\n UNION ALL\n SELECT\n time, 0 AS a, value AS b, 0 AS a_seen, 1 AS b_seen\n FROM (\n SELECT\n s.time AS time,\n sum(s.series_value) AS value\n FROM (\n SELECT\n toStartOfInterval(c.sample_timestamp, {interval}) AS time,\n c.series_fingerprint AS series_fingerprint,\n sum(c.contribution) / {interval_seconds} AS series_value\n FROM (\n SELECT\n timestamp AS sample_timestamp,\n series_fingerprint,\n multiIf(\n aggregation_temporality = 'delta', value,\n isNull(prev_value), NULL,\n value >= assumeNotNull(prev_value), value - assumeNotNull(prev_value),\n value\n ) AS contribution\n FROM (\n SELECT\n timestamp,\n series_fingerprint,\n value,\n aggregation_temporality,\n lagInFrame(toNullable(value)) OVER (\n PARTITION BY series_fingerprint\n ORDER BY timestamp ASC\n ROWS BETWEEN 1 PRECEDING AND 1 PRECEDING\n ) AS prev_value\n FROM posthog.metrics\n WHERE metric_name = 'http.server.request.count'\n AND timestamp >= {date_from} - toIntervalSecond(greatest({interval_seconds}, 300))\n AND timestamp < {date_to}\n )\n ) AS c\n WHERE c.sample_timestamp >= {date_from}\n GROUP BY time, series_fingerprint\n HAVING isNotNull(series_value)\n ) AS s\n GROUP BY time\n )\n )\n GROUP BY time\n)\nWHERE a_in_label_set = 1 AND b_in_label_set = 1\nORDER BY time"+ },+ "parenthesized formula": {+ "builder": {+ "clauses": [+ {+ "name": "a",+ "aggregation": "sum",+ "metricName": "queue_depth"+ },+ {+ "name": "b",+ "aggregation": "sum",+ "metricName": "retry_queue_depth"+ }+ ],+ "formula": "(a + b) / 2"+ },+ "sql": "SELECT\n time,\n if(2 = 0, 0, (a + b) / 2) AS value\nFROM (\n SELECT\n time,\n sum(a) AS a,\n sum(b) AS b,\n max(max(a_seen)) OVER () AS a_in_label_set,\n max(max(b_seen)) OVER () AS b_in_label_set\n FROM (\n SELECT\n time, value AS a, 0 AS b, 1 AS a_seen, 0 AS b_seen\n FROM (\n SELECT\n s.time AS time,\n sum(s.series_value) AS value\n FROM (\n SELECT\n toStartOfInterval(timestamp, {interval}) AS time,\n series_fingerprint,\n argMax(value, timestamp) AS series_value\n FROM posthog.metrics\n WHERE metric_name = 'queue_depth'\n AND timestamp >= {date_from}\n AND timestamp < {date_to}\n GROUP BY time, series_fingerprint\n ) AS s\n GROUP BY time\n )\n UNION ALL\n SELECT\n time, 0 AS a, value AS b, 0 AS a_seen, 1 AS b_seen\n FROM (\n SELECT\n s.time AS time,\n sum(s.series_value) AS value\n FROM (\n SELECT\n toStartOfInterval(timestamp, {interval}) AS time,\n series_fingerprint,\n argMax(value, timestamp) AS series_value\n FROM posthog.metrics\n WHERE metric_name = 'retry_queue_depth'\n AND timestamp >= {date_from}\n AND timestamp < {date_to}\n GROUP BY time, series_fingerprint\n ) AS s\n GROUP BY time\n )\n )\n GROUP BY time\n)\nWHERE a_in_label_set = 1 AND b_in_label_set = 1\nORDER BY time"+ },+ "grouped formula with the same labels": {+ "builder": {+ "clauses": [+ {+ "name": "a",+ "aggregation": "increase",+ "metricName": "errors_total",+ "groupBy": [+ {+ "key": "service_name"+ }+ ]+ },+ {+ "name": "b",+ "aggregation": "increase",+ "metricName": "requests_total",+ "groupBy": [+ {+ "key": "service_name"+ }+ ]+ }+ ],+ "formula": "a / b"+ },+ "sql": "SELECT\n time,\n service_name,\n if(b = 0, 0, a / b) AS value\nFROM (\n SELECT\n time,\n service_name,\n sum(a) AS a,\n sum(b) AS b,\n max(max(a_seen)) OVER (PARTITION BY service_name) AS a_in_label_set,\n max(max(b_seen)) OVER (PARTITION BY service_name) AS b_in_label_set\n FROM (\n SELECT\n time, service_name, value AS a, 0 AS b, 1 AS a_seen, 0 AS b_seen\n FROM (\n SELECT\n s.time AS time,\n ser.group_0 AS service_name,\n sum(s.series_value) AS value\n FROM (\n SELECT\n toStartOfInterval(c.sample_timestamp, {interval}) AS time,\n c.series_fingerprint AS series_fingerprint,\n sum(c.contribution) AS series_value\n FROM (\n SELECT\n timestamp AS sample_timestamp,\n series_fingerprint,\n multiIf(\n aggregation_temporality = 'delta', value,\n isNull(prev_value), NULL,\n value >= assumeNotNull(prev_value), value - assumeNotNull(prev_value),\n value\n ) AS contribution\n FROM (\n SELECT\n timestamp,\n series_fingerprint,\n value,\n aggregation_temporality,\n lagInFrame(toNullable(value)) OVER (\n PARTITION BY series_fingerprint\n ORDER BY timestamp ASC\n ROWS BETWEEN 1 PRECEDING AND 1 PRECEDING\n ) AS prev_value\n FROM posthog.metrics\n WHERE metric_name = 'errors_total'\n AND timestamp >= {date_from} - toIntervalSecond(greatest({interval_seconds}, 300))\n AND timestamp < {date_to}\n )\n ) AS c\n WHERE c.sample_timestamp >= {date_from}\n GROUP BY time, series_fingerprint\n HAVING isNotNull(series_value)\n ) AS s\n LEFT JOIN (\n SELECT\n series_fingerprint,\n any(toString(service_name)) AS group_0\n FROM posthog.metric_series\n WHERE metric_name = 'errors_total'\n AND last_seen >= {date_from} - toIntervalHour(1)\n GROUP BY series_fingerprint\n ) AS ser ON s.series_fingerprint = ser.series_fingerprint\n GROUP BY time, service_name\n )\n UNION ALL\n SELECT\n time, service_name, 0 AS a, value AS b, 0 AS a_seen, 1 AS b_seen\n FROM (\n SELECT\n s.time AS time,\n ser.group_0 AS service_name,\n sum(s.series_value) AS value\n FROM (\n SELECT\n toStartOfInterval(c.sample_timestamp, {interval}) AS time,\n c.series_fingerprint AS series_fingerprint,\n sum(c.contribution) AS series_value\n FROM (\n SELECT\n timestamp AS sample_timestamp,\n series_fingerprint,\n multiIf(\n aggregation_temporality = 'delta', value,\n isNull(prev_value), NULL,\n value >= assumeNotNull(prev_value), value - assumeNotNull(prev_value),\n value\n ) AS contribution\n FROM (\n SELECT\n timestamp,\n series_fingerprint,\n value,\n aggregation_temporality,\n lagInFrame(toNullable(value)) OVER (\n PARTITION BY series_fingerprint\n ORDER BY timestamp ASC\n ROWS BETWEEN 1 PRECEDING AND 1 PRECEDING\n ) AS prev_value\n FROM posthog.metrics\n WHERE metric_name = 'requests_total'\n AND timestamp >= {date_from} - toIntervalSecond(greatest({interval_seconds}, 300))\n AND timestamp < {date_to}\n )\n ) AS c\n WHERE c.sample_timestamp >= {date_from}\n GROUP BY time, series_fingerprint\n HAVING isNotNull(series_value)\n ) AS s\n LEFT JOIN (\n SELECT\n series_fingerprint,\n any(toString(service_name)) AS group_0\n FROM posthog.metric_series\n WHERE metric_name = 'requests_total'\n AND last_seen >= {date_from} - toIntervalHour(1)\n GROUP BY series_fingerprint\n ) AS ser ON s.series_fingerprint = ser.series_fingerprint\n GROUP BY time, service_name\n )\n )\n GROUP BY time, service_name\n)\nWHERE a_in_label_set = 1 AND b_in_label_set = 1\nORDER BY time"+ },+ "right-nested formula": {+ "builder": {+ "clauses": [+ {+ "name": "a",+ "aggregation": "sum",+ "metricName": "queue_depth"+ },+ {+ "name": "b",+ "aggregation": "sum",+ "metricName": "retry_queue_depth"+ },+ {+ "name": "c",+ "aggregation": "sum",+ "metricName": "dead_queue_depth"+ }+ ],+ "formula": "a - (b - c)"+ },+ "sql": "SELECT\n time,\n a - (b - c) AS value\nFROM (\n SELECT\n time,\n sum(a) AS a,\n sum(b) AS b,\n sum(c) AS c,\n max(max(a_seen)) OVER () AS a_in_label_set,\n max(max(b_seen)) OVER () AS b_in_label_set,\n max(max(c_seen)) OVER () AS c_in_label_set\n FROM (\n SELECT\n time, value AS a, 0 AS b, 0 AS c, 1 AS a_seen, 0 AS b_seen, 0 AS c_seen\n FROM (\n SELECT\n s.time AS time,\n sum(s.series_value) AS value\n FROM (\n SELECT\n toStartOfInterval(timestamp, {interval}) AS time,\n series_fingerprint,\n argMax(value, timestamp) AS series_value\n FROM posthog.metrics\n WHERE metric_name = 'queue_depth'\n AND timestamp >= {date_from}\n AND timestamp < {date_to}\n GROUP BY time, series_fingerprint\n ) AS s\n GROUP BY time\n )\n UNION ALL\n SELECT\n time, 0 AS a, value AS b, 0 AS c, 0 AS a_seen, 1 AS b_seen, 0 AS c_seen\n FROM (\n SELECT\n s.time AS time,\n sum(s.series_value) AS value\n FROM (\n SELECT\n toStartOfInterval(timestamp, {interval}) AS time,\n series_fingerprint,\n argMax(value, timestamp) AS series_value\n FROM posthog.metrics\n WHERE metric_name = 'retry_queue_depth'\n AND timestamp >= {date_from}\n AND timestamp < {date_to}\n GROUP BY time, series_fingerprint\n ) AS s\n GROUP BY time\n )\n UNION ALL\n SELECT\n time, 0 AS a, 0 AS b, value AS c, 0 AS a_seen, 0 AS b_seen, 1 AS c_seen\n FROM (\n SELECT\n s.time AS time,\n sum(s.series_value) AS value\n FROM (\n SELECT\n toStartOfInterval(timestamp, {interval}) AS time,\n series_fingerprint,\n argMax(value, timestamp) AS series_value\n FROM posthog.metrics\n WHERE metric_name = 'dead_queue_depth'\n AND timestamp >= {date_from}\n AND timestamp < {date_to}\n GROUP BY time, series_fingerprint\n ) AS s\n GROUP BY time\n )\n )\n GROUP BY time\n)\nWHERE a_in_label_set = 1 AND b_in_label_set = 1 AND c_in_label_set = 1\nORDER BY time"+ },+ "unary minus formula": {+ "builder": {+ "clauses": [+ {+ "name": "a",+ "aggregation": "sum",+ "metricName": "queue_depth"+ }+ ],+ "formula": "-a"+ },+ "sql": "SELECT\n time,\n -a AS value\nFROM (\n SELECT\n time,\n sum(a) AS a,\n max(max(a_seen)) OVER () AS a_in_label_set\n FROM (\n SELECT\n time, value AS a, 1 AS a_seen\n FROM (\n SELECT\n s.time AS time,\n sum(s.series_value) AS value\n FROM (\n SELECT\n toStartOfInterval(timestamp, {interval}) AS time,\n series_fingerprint,\n argMax(value, timestamp) AS series_value\n FROM posthog.metrics\n WHERE metric_name = 'queue_depth'\n AND timestamp >= {date_from}\n AND timestamp < {date_to}\n GROUP BY time, series_fingerprint\n ) AS s\n GROUP BY time\n )\n )\n GROUP BY time\n)\nWHERE a_in_label_set = 1\nORDER BY time"+ },+ "two series without formula": {+ "builder": {+ "clauses": [+ {+ "name": "a",+ "aggregation": "sum",+ "metricName": "queue_depth"+ },+ {+ "name": "b",+ "aggregation": "avg",+ "metricName": "process.cpu.utilization"+ }+ ]+ },+ "sql": "SELECT\n s.time AS time,\n 'a' AS clause,\n sum(s.series_value) AS value\nFROM (\n SELECT\n toStartOfInterval(timestamp, {interval}) AS time,\n series_fingerprint,\n argMax(value, timestamp) AS series_value\n FROM posthog.metrics\n WHERE metric_name = 'queue_depth'\n AND timestamp >= {date_from}\n AND timestamp < {date_to}\n GROUP BY time, series_fingerprint\n) AS s\nGROUP BY time\nUNION ALL\nSELECT\n s.time AS time,\n 'b' AS clause,\n avg(s.series_value) AS value\nFROM (\n SELECT\n toStartOfInterval(timestamp, {interval}) AS time,\n series_fingerprint,\n argMax(value, timestamp) AS series_value\n FROM posthog.metrics\n WHERE metric_name = 'process.cpu.utilization'\n AND timestamp >= {date_from}\n AND timestamp < {date_to}\n GROUP BY time, series_fingerprint\n) AS s\nGROUP BY time"+ },+ "three series with groups": {+ "builder": {+ "clauses": [+ {+ "name": "a",+ "aggregation": "sum",+ "metricName": "queue_depth",+ "groupBy": [+ {+ "key": "service_name"+ }+ ]+ },+ {+ "name": "b",+ "aggregation": "rate",+ "metricName": "http.server.request.count"+ },+ {+ "name": "c",+ "aggregation": "count",+ "metricName": "up",+ "groupBy": [+ {+ "key": "service_name"+ }+ ]+ }+ ]+ },+ "sql": "SELECT\n s.time AS time,\n 'a' AS clause,\n ser.group_0 AS service_name,\n sum(s.series_value) AS value\nFROM (\n SELECT\n toStartOfInterval(timestamp, {interval}) AS time,\n series_fingerprint,\n argMax(value, timestamp) AS series_value\n FROM posthog.metrics\n WHERE metric_name = 'queue_depth'\n AND timestamp >= {date_from}\n AND timestamp < {date_to}\n GROUP BY time, series_fingerprint\n) AS s\nLEFT JOIN (\n SELECT\n series_fingerprint,\n any(toString(service_name)) AS group_0\n FROM posthog.metric_series\n WHERE metric_name = 'queue_depth'\n AND last_seen >= {date_from} - toIntervalHour(1)\n GROUP BY series_fingerprint\n) AS ser ON s.series_fingerprint = ser.series_fingerprint\nGROUP BY time, service_name\nUNION ALL\nSELECT\n s.time AS time,\n 'b' AS clause,\n '' AS service_name,\n sum(s.series_value) AS value\nFROM (\n SELECT\n toStartOfInterval(c.sample_timestamp, {interval}) AS time,\n c.series_fingerprint AS series_fingerprint,\n sum(c.contribution) / {interval_seconds} AS series_value\n FROM (\n SELECT\n timestamp AS sample_timestamp,\n series_fingerprint,\n multiIf(\n aggregation_temporality = 'delta', value,\n isNull(prev_value), NULL,\n value >= assumeNotNull(prev_value), value - assumeNotNull(prev_value),\n value\n ) AS contribution\n FROM (\n SELECT\n timestamp,\n series_fingerprint,\n value,\n aggregation_temporality,\n lagInFrame(toNullable(value)) OVER (\n PARTITION BY series_fingerprint\n ORDER BY timestamp ASC\n ROWS BETWEEN 1 PRECEDING AND 1 PRECEDING\n ) AS prev_value\n FROM posthog.metrics\n WHERE metric_name = 'http.server.request.count'\n AND timestamp >= {date_from} - toIntervalSecond(greatest({interval_seconds}, 300))\n AND timestamp < {date_to}\n )\n ) AS c\n WHERE c.sample_timestamp >= {date_from}\n GROUP BY time, series_fingerprint\n HAVING isNotNull(series_value)\n) AS s\nGROUP BY time\nUNION ALL\nSELECT\n s.time AS time,\n 'c' AS clause,\n ser.group_0 AS service_name,\n toFloat(count()) AS value\nFROM (\n SELECT\n toStartOfInterval(timestamp, {interval}) AS time,\n series_fingerprint,\n argMax(value, timestamp) AS series_value\n FROM posthog.metrics\n WHERE metric_name = 'up'\n AND timestamp >= {date_from}\n AND timestamp < {date_to}\n GROUP BY time, series_fingerprint\n) AS s\nLEFT JOIN (\n SELECT\n series_fingerprint,\n any(toString(service_name)) AS group_0\n FROM posthog.metric_series\n WHERE metric_name = 'up'\n AND last_seen >= {date_from} - toIntervalHour(1)\n GROUP BY series_fingerprint\n) AS ser ON s.series_fingerprint = ser.series_fingerprint\nGROUP BY time, service_name"+ },+ "series that stops reporting": {+ "builder": {+ "clauses": [+ {+ "name": "a",+ "aggregation": "sum",+ "metricName": "sparse_queue_depth",+ "groupBy": [+ {+ "key": "service_name"+ }+ ]+ }+ ]+ },+ "sql": "SELECT\n s.time AS time,\n ser.group_0 AS service_name,\n sum(s.series_value) AS value\nFROM (\n SELECT\n toStartOfInterval(timestamp, {interval}) AS time,\n series_fingerprint,\n argMax(value, timestamp) AS series_value\n FROM posthog.metrics\n WHERE metric_name = 'sparse_queue_depth'\n AND timestamp >= {date_from}\n AND timestamp < {date_to}\n GROUP BY time, series_fingerprint\n) AS s\nLEFT JOIN (\n SELECT\n series_fingerprint,\n any(toString(service_name)) AS group_0\n FROM posthog.metric_series\n WHERE metric_name = 'sparse_queue_depth'\n AND last_seen >= {date_from} - toIntervalHour(1)\n GROUP BY series_fingerprint\n) AS ser ON s.series_fingerprint = ser.series_fingerprint\nGROUP BY time, service_name\nORDER BY time"+ },+ "formula over different label sets": {+ "builder": {+ "clauses": [+ {+ "name": "a",+ "aggregation": "sum",+ "metricName": "queue_depth",+ "groupBy": [+ {+ "key": "service_name"+ }+ ]+ },+ {+ "name": "b",+ "aggregation": "sum",+ "metricName": "api_queue_depth",+ "groupBy": [+ {+ "key": "service_name"+ }+ ]+ }+ ],+ "formula": "a - b"+ },+ "sql": "SELECT\n time,\n service_name,\n a - b AS value\nFROM (\n SELECT\n time,\n service_name,\n sum(a) AS a,\n sum(b) AS b,\n max(max(a_seen)) OVER (PARTITION BY service_name) AS a_in_label_set,\n max(max(b_seen)) OVER (PARTITION BY service_name) AS b_in_label_set\n FROM (\n SELECT\n time, service_name, value AS a, 0 AS b, 1 AS a_seen, 0 AS b_seen\n FROM (\n SELECT\n s.time AS time,\n ser.group_0 AS service_name,\n sum(s.series_value) AS value\n FROM (\n SELECT\n toStartOfInterval(timestamp, {interval}) AS time,\n series_fingerprint,\n argMax(value, timestamp) AS series_value\n FROM posthog.metrics\n WHERE metric_name = 'queue_depth'\n AND timestamp >= {date_from}\n AND timestamp < {date_to}\n GROUP BY time, series_fingerprint\n ) AS s\n LEFT JOIN (\n SELECT\n series_fingerprint,\n any(toString(service_name)) AS group_0\n FROM posthog.metric_series\n WHERE metric_name = 'queue_depth'\n AND last_seen >= {date_from} - toIntervalHour(1)\n GROUP BY series_fingerprint\n ) AS ser ON s.series_fingerprint = ser.series_fingerprint\n GROUP BY time, service_name\n )\n UNION ALL\n SELECT\n time, service_name, 0 AS a, value AS b, 0 AS a_seen, 1 AS b_seen\n FROM (\n SELECT\n s.time AS time,\n ser.group_0 AS service_name,\n sum(s.series_value) AS value\n FROM (\n SELECT\n toStartOfInterval(timestamp, {interval}) AS time,\n series_fingerprint,\n argMax(value, timestamp) AS series_value\n FROM posthog.metrics\n WHERE metric_name = 'api_queue_depth'\n AND timestamp >= {date_from}\n AND timestamp < {date_to}\n GROUP BY time, series_fingerprint\n ) AS s\n LEFT JOIN (\n SELECT\n series_fingerprint,\n any(toString(service_name)) AS group_0\n FROM posthog.metric_series\n WHERE metric_name = 'api_queue_depth'\n AND last_seen >= {date_from} - toIntervalHour(1)\n GROUP BY series_fingerprint\n ) AS ser ON s.series_fingerprint = ser.series_fingerprint\n GROUP BY time, service_name\n )\n )\n GROUP BY time, service_name\n)\nWHERE a_in_label_set = 1 AND b_in_label_set = 1\nORDER BY time"+ },+ "share of total, spreading a series without labels": {+ "builder": {+ "clauses": [+ {+ "name": "a",+ "aggregation": "sum",+ "metricName": "queue_depth",+ "groupBy": [+ {+ "key": "service_name"+ }+ ]+ },+ {+ "name": "b",+ "aggregation": "sum",+ "metricName": "queue_depth"+ }+ ],+ "formula": "a / b"+ },+ "sql": "SELECT\n time,\n service_name,\n if(b = 0, 0, a / b) AS value\nFROM (\n SELECT\n time,\n service_name,\n sum(a) AS a,\n sum(sum(b)) OVER (PARTITION BY time) AS b,\n max(max(a_seen)) OVER (PARTITION BY service_name) AS a_in_label_set,\n max(max(b_seen)) OVER () AS b_in_label_set\n FROM (\n SELECT\n time, service_name, value AS a, 0 AS b, 1 AS a_seen, 0 AS b_seen\n FROM (\n SELECT\n s.time AS time,\n ser.group_0 AS service_name,\n sum(s.series_value) AS value\n FROM (\n SELECT\n toStartOfInterval(timestamp, {interval}) AS time,\n series_fingerprint,\n argMax(value, timestamp) AS series_value\n FROM posthog.metrics\n WHERE metric_name = 'queue_depth'\n AND timestamp >= {date_from}\n AND timestamp < {date_to}\n GROUP BY time, series_fingerprint\n ) AS s\n LEFT JOIN (\n SELECT\n series_fingerprint,\n any(toString(service_name)) AS group_0\n FROM posthog.metric_series\n WHERE metric_name = 'queue_depth'\n AND last_seen >= {date_from} - toIntervalHour(1)\n GROUP BY series_fingerprint\n ) AS ser ON s.series_fingerprint = ser.series_fingerprint\n GROUP BY time, service_name\n )\n UNION ALL\n SELECT\n time, service_name, 0 AS a, value AS b, 0 AS a_seen, 1 AS b_seen\n FROM (\n SELECT\n s.time AS time,\n '' AS service_name,\n sum(s.series_value) AS value\n FROM (\n SELECT\n toStartOfInterval(timestamp, {interval}) AS time,\n series_fingerprint,\n argMax(value, timestamp) AS series_value\n FROM posthog.metrics\n WHERE metric_name = 'queue_depth'\n AND timestamp >= {date_from}\n AND timestamp < {date_to}\n GROUP BY time, series_fingerprint\n ) AS s\n GROUP BY time\n )\n )\n GROUP BY time, service_name\n)\nWHERE a_in_label_set = 1 AND b_in_label_set = 1\nORDER BY time"+ },+ "histogram share, spreading a series without labels": {+ "builder": {+ "clauses": [+ {+ "name": "a",+ "aggregation": "histogram_quantile",+ "metricName": "http.server.duration",+ "quantile": 0.5,+ "groupBy": [+ {+ "key": "service_name"+ }+ ]+ },+ {+ "name": "b",+ "aggregation": "histogram_quantile",+ "metricName": "http.server.duration",+ "quantile": 0.5+ }+ ],+ "formula": "a / b"+ },+ "sql": "SELECT\n time,\n service_name,\n if(b = 0, 0, a / b) AS value\nFROM (\n SELECT\n time,\n service_name,\n sum(a) AS a,\n sum(sum(b)) OVER (PARTITION BY time) AS b,\n max(max(a_seen)) OVER (PARTITION BY service_name) AS a_in_label_set,\n max(max(b_seen)) OVER () AS b_in_label_set\n FROM (\n SELECT\n time, service_name, value AS a, 0 AS b, 1 AS a_seen, 0 AS b_seen\n FROM (\n SELECT\n time,\n service_name,\n if(\n idx > length(bounds),\n bounds[length(bounds)],\n if(idx > 1, bounds[idx - 1], least(0.0, bounds[1]))\n + (bounds[idx] - if(idx > 1, bounds[idx - 1], least(0.0, bounds[1])))\n * (rank - (cumulative[idx] - counts[idx])) / counts[idx]\n ) AS value\n FROM (\n SELECT\n time,\n service_name,\n bounds,\n counts,\n arrayCumSum(counts) AS cumulative,\n 0.5 * arraySum(counts) AS rank,\n arrayFirstIndex(c -> c >= rank, cumulative) AS idx\n FROM (\n SELECT\n toStartOfInterval(s.sample_timestamp, {interval}) AS time,\n ser.group_0 AS service_name,\n any(s.histogram_bounds) AS bounds,\n uniqExactIf(s.histogram_bounds, notEmpty(s.histogram_bounds)) AS layouts,\n arrayMap(x -> ifNull(x, 0.0), sumForEach(s.contribution_counts)) AS counts\n FROM (\n SELECT\n timestamp AS sample_timestamp,\n series_fingerprint,\n histogram_bounds,\n multiIf(\n aggregation_temporality = 'delta', counts_f,\n empty(prev_counts), arrayMap(x -> 0.0, counts_f),\n length(prev_counts) != length(counts_f), counts_f,\n arrayAll((c, p) -> c >= p, counts_f, prev_counts), arrayMap((c, p) -> c - p, counts_f, prev_counts),\n counts_f\n ) AS contribution_counts\n FROM (\n SELECT\n timestamp,\n series_fingerprint,\n aggregation_temporality,\n histogram_bounds,\n arrayMap(x -> toFloat(x), histogram_counts) AS counts_f,\n lagInFrame(arrayMap(x -> toFloat(x), histogram_counts)) OVER (\n PARTITION BY series_fingerprint\n ORDER BY timestamp ASC\n ROWS BETWEEN 1 PRECEDING AND 1 PRECEDING\n ) AS prev_counts\n FROM posthog.metrics\n WHERE metric_name = 'http.server.duration'\n AND timestamp >= {date_from} - toIntervalSecond(greatest({interval_seconds}, 300))\n AND timestamp < {date_to}\n AND notEmpty(histogram_counts)\n )\n ) AS s\n LEFT JOIN (\n SELECT\n series_fingerprint,\n any(toString(service_name)) AS group_0\n FROM posthog.metric_series\n WHERE metric_name = 'http.server.duration'\n AND last_seen >= {date_from} - toIntervalHour(1)\n GROUP BY series_fingerprint\n ) AS ser ON s.series_fingerprint = ser.series_fingerprint\n WHERE s.sample_timestamp >= {date_from}\n GROUP BY time, service_name\n )\n WHERE arraySum(counts) > 0\n AND throwIf(layouts > 1, 'The series have different histogram bounds. Add filters so that all series use the same buckets.') = 0\n )\n )\n UNION ALL\n SELECT\n time, service_name, 0 AS a, value AS b, 0 AS a_seen, 1 AS b_seen\n FROM (\n SELECT\n time,\n service_name,\n if(\n idx > length(bounds),\n bounds[length(bounds)],\n if(idx > 1, bounds[idx - 1], least(0.0, bounds[1]))\n + (bounds[idx] - if(idx > 1, bounds[idx - 1], least(0.0, bounds[1])))\n * (rank - (cumulative[idx] - counts[idx])) / counts[idx]\n ) AS value\n FROM (\n SELECT\n time,\n service_name,\n bounds,\n counts,\n arrayCumSum(counts) AS cumulative,\n 0.5 * arraySum(counts) AS rank,\n arrayFirstIndex(c -> c >= rank, cumulative) AS idx\n FROM (\n SELECT\n toStartOfInterval(s.sample_timestamp, {interval}) AS time,\n '' AS service_name,\n any(s.histogram_bounds) AS bounds,\n uniqExactIf(s.histogram_bounds, notEmpty(s.histogram_bounds)) AS layouts,\n arrayMap(x -> ifNull(x, 0.0), sumForEach(s.contribution_counts)) AS counts\n FROM (\n SELECT\n timestamp AS sample_timestamp,\n series_fingerprint,\n histogram_bounds,\n multiIf(\n aggregation_temporality = 'delta', counts_f,\n empty(prev_counts), arrayMap(x -> 0.0, counts_f),\n length(prev_counts) != length(counts_f), counts_f,\n arrayAll((c, p) -> c >= p, counts_f, prev_counts), arrayMap((c, p) -> c - p, counts_f, prev_counts),\n counts_f\n ) AS contribution_counts\n FROM (\n SELECT\n timestamp,\n series_fingerprint,\n aggregation_temporality,\n histogram_bounds,\n arrayMap(x -> toFloat(x), histogram_counts) AS counts_f,\n lagInFrame(arrayMap(x -> toFloat(x), histogram_counts)) OVER (\n PARTITION BY series_fingerprint\n ORDER BY timestamp ASC\n ROWS BETWEEN 1 PRECEDING AND 1 PRECEDING\n ) AS prev_counts\n FROM posthog.metrics\n WHERE metric_name = 'http.server.duration'\n AND timestamp >= {date_from} - toIntervalSecond(greatest({interval_seconds}, 300))\n AND timestamp < {date_to}\n AND notEmpty(histogram_counts)\n )\n ) AS s\n WHERE s.sample_timestamp >= {date_from}\n GROUP BY time\n )\n WHERE arraySum(counts) > 0\n AND throwIf(layouts > 1, 'The series have different histogram bounds. Add filters so that all series use the same buckets.') = 0\n )\n )\n )\n GROUP BY time, service_name\n)\nWHERE a_in_label_set = 1 AND b_in_label_set = 1\nORDER BY time"+ },+ "formula with a small constant": {+ "builder": {+ "clauses": [+ {+ "name": "a",+ "aggregation": "sum",+ "metricName": "queue_depth"+ }+ ],+ "formula": "a * 0.0000001"+ },+ "sql": "SELECT\n time,\n a * 0.0000001 AS value\nFROM (\n SELECT\n time,\n sum(a) AS a,\n max(max(a_seen)) OVER () AS a_in_label_set\n FROM (\n SELECT\n time, value AS a, 1 AS a_seen\n FROM (\n SELECT\n s.time AS time,\n sum(s.series_value) AS value\n FROM (\n SELECT\n toStartOfInterval(timestamp, {interval}) AS time,\n series_fingerprint,\n argMax(value, timestamp) AS series_value\n FROM posthog.metrics\n WHERE metric_name = 'queue_depth'\n AND timestamp >= {date_from}\n AND timestamp < {date_to}\n GROUP BY time, series_fingerprint\n ) AS s\n GROUP BY time\n )\n )\n GROUP BY time\n)\nWHERE a_in_label_set = 1\nORDER BY time"+ },+ "formula with a zero denominator": {+ "builder": {+ "clauses": [+ {+ "name": "a",+ "aggregation": "sum",+ "metricName": "queue_depth"+ },+ {+ "name": "b",+ "aggregation": "sum",+ "metricName": "idle_queue_depth"+ }+ ],+ "formula": "a / b"+ },+ "sql": "SELECT\n time,\n if(b = 0, 0, a / b) AS value\nFROM (\n SELECT\n time,\n sum(a) AS a,\n sum(b) AS b,\n max(max(a_seen)) OVER () AS a_in_label_set,\n max(max(b_seen)) OVER () AS b_in_label_set\n FROM (\n SELECT\n time, value AS a, 0 AS b, 1 AS a_seen, 0 AS b_seen\n FROM (\n SELECT\n s.time AS time,\n sum(s.series_value) AS value\n FROM (\n SELECT\n toStartOfInterval(timestamp, {interval}) AS time,\n series_fingerprint,\n argMax(value, timestamp) AS series_value\n FROM posthog.metrics\n WHERE metric_name = 'queue_depth'\n AND timestamp >= {date_from}\n AND timestamp < {date_to}\n GROUP BY time, series_fingerprint\n ) AS s\n GROUP BY time\n )\n UNION ALL\n SELECT\n time, 0 AS a, value AS b, 0 AS a_seen, 1 AS b_seen\n FROM (\n SELECT\n s.time AS time,\n sum(s.series_value) AS value\n FROM (\n SELECT\n toStartOfInterval(timestamp, {interval}) AS time,\n series_fingerprint,\n argMax(value, timestamp) AS series_value\n FROM posthog.metrics\n WHERE metric_name = 'idle_queue_depth'\n AND timestamp >= {date_from}\n AND timestamp < {date_to}\n GROUP BY time, series_fingerprint\n ) AS s\n GROUP BY time\n )\n )\n GROUP BY time\n)\nWHERE a_in_label_set = 1 AND b_in_label_set = 1\nORDER BY time"+ }+}diff --git a/products/metrics/frontend/queryLanguages/builderToPromql.ts b/products/metrics/frontend/queryLanguages/builderToPromql.tsnew file mode 100644index 000000000000..a353822187c9--- /dev/null+++ b/products/metrics/frontend/queryLanguages/builderToPromql.ts@@ -0,0 +1,219 @@+import { type Matcher, type PromExpr, PromQLParseError, parsePromQL, unwrapParens } from './promqlParser'+import { printPromQL } from './promqlPrinter'+import { builderRegexToPromRegex } from './regex'+import {+ type BuilderClause,+ type BuilderQuery,+ CLAUSE_LABEL,+ type ConversionResult,+ normalizeClause,+ normalizeLabelKey,+} from './types'++const FILTER_OP_TO_MATCH_OP: Record<string, Matcher['op']> = {+ eq: '=',+ neq: '!=',+ regex: '=~',+ not_regex: '!~',+}++const SIMPLE_AGGREGATIONS = new Set(['sum', 'avg', 'min', 'max', 'count'])++interface ClauseExpr {+ expr: PromExpr+ /** Labels the clause groups by, sorted; used to pick vector matching in a formula. */+ labels: string[]+}++function clauseToPromExpr(builderClause: BuilderClause, issues: string[]): ClauseExpr {+ const clause = normalizeClause(builderClause)+ const matchers: Matcher[] = []+ for (const filter of clause.filters ?? []) {+ if (filter.scope && filter.scope !== 'auto') {+ issues.push(+ `PromQL cannot limit "${filter.key}" to ${filter.scope} attributes in series ${clause.name}; the filter matches both.`+ )+ }+ const op = FILTER_OP_TO_MATCH_OP[filter.op]+ matchers.push({+ label: normalizeLabelKey(filter.key),+ op,+ value: op === '=~' || op === '!~' ? builderRegexToPromRegex(filter.value) : filter.value,+ })+ }+ for (const groupBy of clause.groupBy ?? []) {+ if (groupBy.scope && groupBy.scope !== 'auto') {+ issues.push(+ `PromQL cannot limit the "${groupBy.key}" group-by to ${groupBy.scope} attributes in series ${clause.name}.`+ )+ }+ }+ // The pinned OTel type has no PromQL form. It is not reported: the picker sets it on every+ // clause, and it only matters for the rare name that exists as more than one type.+ const labels = [...new Set((clause.groupBy ?? []).map((groupBy) => normalizeLabelKey(groupBy.key)))]+ const grouping = labels.length ? { without: false, labels } : undefined+ const selector: PromExpr = { type: 'selector', name: clause.metricName, matchers }++ // An omitted range uses the query step, which is how the builder computes per-bucket rates.+ const series: PromExpr = clause.rangeFunction+ ? { type: 'call', func: clause.rangeFunction, args: [selector] }+ : selector++ let expr: PromExpr+ switch (clause.aggregation) {+ case undefined:+ // Without an aggregation, each series is its own line.+ expr = series+ break+ case 'quantile':+ expr = {+ type: 'aggregate',+ op: 'quantile',+ param: { type: 'number', value: clause.quantile ?? 0.95 },+ expr: series,+ ...(grouping ? { grouping } : {}),+ }+ break+ case 'histogram_quantile':+ expr = {+ type: 'call',+ func: 'histogram_quantile',+ args: [+ { type: 'number', value: clause.quantile ?? 0.95 },+ {+ type: 'aggregate',+ op: 'sum',+ grouping: { without: false, labels: ['le', ...labels.filter((label) => label !== 'le')] },+ expr: {+ type: 'call',+ func: 'rate',+ args: [{ ...selector, name: `${clause.metricName}_bucket` }],+ },+ },+ ],+ }+ break+ default:+ if (!SIMPLE_AGGREGATIONS.has(clause.aggregation)) {+ issues.push(`PromQL has no "${clause.aggregation}" aggregation; series ${clause.name} uses sum.`)+ }+ expr = {+ type: 'aggregate',+ op: SIMPLE_AGGREGATIONS.has(clause.aggregation) ? clause.aggregation : 'sum',+ expr: series,+ ...(grouping ? { grouping } : {}),+ }+ }+ return { expr, labels: [...labels].sort() }+}++const sameLabels = (a: string[], b: string[]): boolean => a.length === b.length && a.every((label, i) => label === b[i])++/** Replaces the aliases in a parsed builder formula with clause expressions, adding vector matching. */+function substituteFormula(+ node: PromExpr,+ clauses: Map<string, ClauseExpr>,+ used: Set<string>,+ issues: string[]+): { expr: PromExpr; labels: string[] | null } {+ switch (node.type) {+ case 'number':+ return { expr: node, labels: null }+ case 'paren': {+ const inner = substituteFormula(node.expr, clauses, used, issues)+ return { expr: { type: 'paren', expr: inner.expr }, labels: inner.labels }+ }+ case 'unary': {+ const inner = substituteFormula(node.expr, clauses, used, issues)+ return { expr: { ...node, expr: inner.expr }, labels: inner.labels }+ }+ case 'selector': {+ const clause = node.name !== null ? clauses.get(node.name) : undefined+ if (!clause || node.matchers.length) {+ throw new Error(`The formula refers to an unknown series "${node.name ?? ''}"`)+ }+ used.add(node.name as string)+ return clause+ }+ case 'binary': {+ const lhs = substituteFormula(node.lhs, clauses, used, issues)+ const rhs = substituteFormula(node.rhs, clauses, used, issues)+ const binary: PromExpr = { type: 'binary', op: node.op, lhs: lhs.expr, rhs: rhs.expr }+ if (lhs.labels === null || rhs.labels === null) {+ return { expr: binary, labels: lhs.labels ?? rhs.labels }+ }+ if (sameLabels(lhs.labels, rhs.labels)) {+ return { expr: binary, labels: lhs.labels }+ }+ // The builder spreads an ungrouped series over every label set of the other side.+ if (rhs.labels.length === 0) {+ return {+ expr: { ...binary, matching: { card: 'many-to-one', on: true, labels: [], include: [] } },+ labels: lhs.labels,+ }+ }+ if (lhs.labels.length === 0) {+ return {+ expr: { ...binary, matching: { card: 'one-to-many', on: true, labels: [], include: [] } },+ labels: rhs.labels,+ }+ }+ issues.push('The formula mixes series with different group-by labels.')+ return { expr: binary, labels: lhs.labels }+ }+ default:+ throw new Error('The formula has an unsupported term')+ }+}++export function builderToPromql(query: BuilderQuery): ConversionResult<string> {+ const issues: string[] = []+ const clauses = query.clauses.filter((clause) => clause.metricName.trim())+ if (clauses.length === 0) {+ return { value: '', issues }+ }+ const exprs = new Map(clauses.map((clause) => [clause.name, clauseToPromExpr(clause, issues)]))++ const formula = query.formula?.trim()+ if (formula) {+ let parsed: PromExpr+ try {+ parsed = parsePromQL(formula)+ } catch (error) {+ const message = error instanceof PromQLParseError ? error.message : String(error)+ return { value: null, issues: [`The formula "${formula}" cannot be read: ${message}`] }+ }+ const used = new Set<string>()+ try {+ const result = substituteFormula(parsed, exprs, used, issues)+ const unused = clauses.filter((clause) => !used.has(clause.name)).map((clause) => clause.name)+ if (unused.length) {+ issues.push(+ `Series ${unused.join(', ')} ${unused.length > 1 ? 'are' : 'is'} not in the formula and will be removed.`+ )+ }+ return { value: printPromQL(unwrapParens(result.expr)), issues }+ } catch (error) {+ return { value: null, issues: [error instanceof Error ? error.message : String(error)] }+ }+ }++ if (clauses.length === 1) {+ return { value: printPromQL(exprs.get(clauses[0].name)!.expr), issues }+ }++ // Several series without a formula: label each one with its alias, so the union keeps them apart.+ const labelled: PromExpr[] = clauses.map((clause) => ({+ type: 'call',+ func: 'label_replace',+ args: [+ exprs.get(clause.name)!.expr,+ { type: 'string', value: CLAUSE_LABEL },+ { type: 'string', value: clause.name },+ { type: 'string', value: '' },+ { type: 'string', value: '' },+ ],+ }))+ const union = labelled.reduce((lhs, rhs) => ({ type: 'binary', op: 'or', lhs, rhs }))+ return { value: printPromQL(union), issues }+}diff --git a/products/metrics/frontend/queryLanguages/builderToSql.ts b/products/metrics/frontend/queryLanguages/builderToSql.tsnew file mode 100644index 000000000000..8448823b22f2--- /dev/null+++ b/products/metrics/frontend/queryLanguages/builderToSql.ts@@ -0,0 +1,513 @@+import type { MetricsAttributeScope } from '~/queries/schema/schema-general'++import { type PromExpr, PromQLParseError, parsePromQL } from './promqlParser'+import {+ type BuilderClause,+ type BuilderQuery,+ type ConversionResult,+ SQL_EMPTY_INTERVAL_ISSUE,+ normalizeClause,+ normalizeLabelKey,+ plainNumber,+} from './types'++/**+ * Builder → SQL for a SQL metrics insight.+ *+ * The SQL follows the SQL-mode contract: a `time` column, a numeric `value` column, and one column+ * per label. `{date_from}`, `{date_to}`, `{interval}` and `{interval_seconds}` are filled in by the+ * backend, so dashboard date filters still apply. Each clause mirrors the query the builder engine+ * runs (products/metrics/backend/metric_query_runner.py): one value per series and bucket (the last+ * value, or the rate or increase from per-sample deltas with counter-reset handling), then the+ * aggregation across series, and the same bucket interpolation for histogram quantiles. A clause+ * without an aggregation keeps each series. A formula matches series by label set, as the builder+ * does, and divides by zero to 0. `sqlToBuilder` reads this exact shape back.+ */++/** The label column of a clause without an aggregation: SQL cannot list the attributes of each series. */+export const PER_SERIES_COLUMN = 'series_fingerprint'++export const SQL_RESERVED_COLUMNS = new Set(['time', 'value', 'clause', PER_SERIES_COLUMN])++/** The error a histogram query raises when the series of one interval have different bucket bounds. */+export const MIXED_HISTOGRAM_BOUNDS_ERROR =+ 'The series have different histogram bounds. Add filters so that all series use the same buckets.'++export const quoteSqlString = (value: string): string => `'${value.replace(/\\/g, '\\\\').replace(/'/g, "\\'")}'`++const SAFE_IDENTIFIER = /^[a-zA-Z_][a-zA-Z0-9_]*$/+export const quoteSqlIdentifier = (name: string): string =>+ SAFE_IDENTIFIER.test(name) ? name : `\`${name.replace(/\\/g, '\\\\').replace(/`/g, '\\`')}\``++export function attributeSqlField(key: string, scope: MetricsAttributeScope | undefined): string {+ const normalized = normalizeLabelKey(key)+ if (normalized === 'service_name') {+ return 'service_name'+ }+ const quoted = quoteSqlString(key)+ if (scope === 'resource') {+ return `arrayElement(resource_attributes, ${quoted})`+ }+ if (scope === 'attribute') {+ return `arrayElement(attributes, ${quoted})`+ }+ return `if(arrayElement(resource_attributes, ${quoted}) != '', arrayElement(resource_attributes, ${quoted}), arrayElement(attributes, ${quoted}))`+}++function filterCondition(filter: NonNullable<BuilderClause['filters']>[number]): string {+ const field = attributeSqlField(filter.key, filter.scope)+ const value = quoteSqlString(filter.value)+ switch (filter.op) {+ case 'eq':+ return `${field} = ${value}`+ case 'neq':+ return `${field} != ${value}`+ case 'regex':+ return `match(${field}, ${value})`+ case 'not_regex':+ return `NOT match(${field}, ${value})`+ }+}++const indent = (text: string, spaces: number): string =>+ text+ .split('\n')+ .map((line) => (line ? ' '.repeat(spaces) + line : line))+ .join('\n')++export const labelColumn = (key: string): string => quoteSqlIdentifier(normalizeLabelKey(key))++interface ClauseSqlOptions {+ /** Label columns every clause of the query must expose, in order; clauses fill missing ones with ''. */+ labelKeys: string[]+ /** Adds a `clause` label column with this alias, to keep the series of a multi-series query apart. */+ clauseLabel?: string+ orderByTime: boolean+}++function pointsWhere(clause: BuilderClause, from: string): string[] {+ const metricName = quoteSqlString(clause.metricName)+ const conditions = [`metric_name = ${metricName}`]+ if (clause.metricType) {+ conditions.push(`metric_type = ${quoteSqlString(clause.metricType)}`)+ }+ conditions.push(`timestamp >= ${from}`, 'timestamp < {date_to}')+ if (clause.filters?.length) {+ const seriesFilters = [+ `metric_name = ${metricName}`,+ 'last_seen >= {date_from} - toIntervalHour(1)',+ ...clause.filters.map(filterCondition),+ ]+ conditions.push(+ [+ 'series_fingerprint IN (',+ ' SELECT series_fingerprint',+ ' FROM posthog.metric_series',+ ` WHERE ${seriesFilters.join('\n AND ')}`,+ ')',+ ].join('\n')+ )+ }+ return conditions+}++function whereBlock(conditions: string[]): string {+ const lines = conditions.map((condition, i) => (i === 0 ? condition : `AND ${condition}`).replace(/\n/g, '\n '))+ return `WHERE ${lines.join('\n ')}`+}++function groupJoin(clause: BuilderClause): string | null {+ const groupBy = clause.groupBy ?? []+ if (!groupBy.length) {+ return null+ }+ const columns = groupBy.map(+ (group, index) => `any(toString(${attributeSqlField(group.key, group.scope)})) AS group_${index}`+ )+ return [+ 'LEFT JOIN (',+ ' SELECT',+ ` ${['series_fingerprint', ...columns].join(',\n ')}`,+ ' FROM posthog.metric_series',+ ` WHERE metric_name = ${quoteSqlString(clause.metricName)}`,+ ' AND last_seen >= {date_from} - toIntervalHour(1)',+ ' GROUP BY series_fingerprint',+ ') AS ser ON s.series_fingerprint = ser.series_fingerprint',+ ].join('\n')+}++function labelSelect(clause: BuilderClause, options: ClauseSqlOptions): { columns: string[]; groupBy: string[] } {+ const own = (clause.groupBy ?? []).map((group) => normalizeLabelKey(group.key))+ const columns: string[] = []+ const groupBy: string[] = []+ if (options.clauseLabel) {+ columns.push(`${quoteSqlString(options.clauseLabel)} AS clause`)+ }+ for (const key of options.labelKeys) {+ if (key === PER_SERIES_COLUMN) {+ columns.push(`${clause.aggregation ? "''" : 'toString(s.series_fingerprint)'} AS ${key}`)+ continue+ }+ const index = own.indexOf(key)+ columns.push(`${index >= 0 ? `ser.group_${index}` : "''"} AS ${quoteSqlIdentifier(key)}`)+ if (index >= 0) {+ groupBy.push(quoteSqlIdentifier(key))+ }+ }+ return { columns, groupBy }+}++const SIMPLE_VALUE: Record<string, (q: number | undefined) => string> = {+ sum: () => 'sum(s.series_value)',+ avg: () => 'avg(s.series_value)',+ min: () => 'min(s.series_value)',+ max: () => 'max(s.series_value)',+ // A float, so a UNION with the other series' values has one column type.+ count: () => 'toFloat(count())',+ quantile: (q) => `quantile(${q ?? 0.95})(s.series_value)`,+}++/** The last value of each series in each bucket. */+function lastValueSql(clause: BuilderClause): string[] {+ return [+ 'SELECT',+ ' toStartOfInterval(timestamp, {interval}) AS time,',+ ' series_fingerprint,',+ ' argMax(value, timestamp) AS series_value',+ 'FROM posthog.metrics',+ whereBlock(pointsWhere(clause, '{date_from}')),+ 'GROUP BY time, series_fingerprint',+ ]+}++const COUNTER_LOOKBACK_FROM = '{date_from} - toIntervalSecond(greatest({interval_seconds}, 300))'++/** The rate or increase of each series in each bucket, from per-sample deltas. */+function rangeFunctionSql(clause: BuilderClause): string[] {+ const value = clause.rangeFunction === 'rate' ? 'sum(c.contribution) / {interval_seconds}' : 'sum(c.contribution)'+ return [+ 'SELECT',+ ' toStartOfInterval(c.sample_timestamp, {interval}) AS time,',+ ' c.series_fingerprint AS series_fingerprint,',+ ` ${value} AS series_value`,+ 'FROM (',+ ' SELECT',+ ' timestamp AS sample_timestamp,',+ ' series_fingerprint,',+ ' multiIf(',+ " aggregation_temporality = 'delta', value,",+ ' isNull(prev_value), NULL,',+ ' value >= assumeNotNull(prev_value), value - assumeNotNull(prev_value),',+ ' value',+ ' ) AS contribution',+ ' FROM (',+ ' SELECT',+ ' timestamp,',+ ' series_fingerprint,',+ ' value,',+ ' aggregation_temporality,',+ ' lagInFrame(toNullable(value)) OVER (',+ ' PARTITION BY series_fingerprint',+ ' ORDER BY timestamp ASC',+ ' ROWS BETWEEN 1 PRECEDING AND 1 PRECEDING',+ ' ) AS prev_value',+ ' FROM posthog.metrics',+ indent(whereBlock(pointsWhere(clause, COUNTER_LOOKBACK_FROM)), 8),+ ' )',+ ') AS c',+ 'WHERE c.sample_timestamp >= {date_from}',+ 'GROUP BY time, series_fingerprint',+ 'HAVING isNotNull(series_value)',+ ]+}++/** Combines the per-series values of a clause, or keeps each series when it has no aggregation. */+function seriesClauseSql(clause: BuilderClause, options: ClauseSqlOptions): string {+ const labels = labelSelect(clause, options)+ const join = groupJoin(clause)+ const value = clause.aggregation ? SIMPLE_VALUE[clause.aggregation](clause.quantile) : 's.series_value'+ const inner = clause.rangeFunction ? rangeFunctionSql(clause) : lastValueSql(clause)+ const lines = [+ 'SELECT',+ ` ${['s.time AS time', ...labels.columns, `${value} AS value`].join(',\n ')}`,+ 'FROM (',+ indent(inner.join('\n'), 4),+ ') AS s',+ ...(join ? [join] : []),+ ...(clause.aggregation ? [`GROUP BY ${['time', ...labels.groupBy].join(', ')}`] : []),+ ...(options.orderByTime ? ['ORDER BY time'] : []),+ ]+ return lines.join('\n')+}++function histogramClauseSql(clause: BuilderClause, options: ClauseSqlOptions): string {+ const labels = labelSelect(clause, options)+ const join = groupJoin(clause)+ const labelNames = [...(options.clauseLabel ? ['clause'] : []), ...options.labelKeys.map(quoteSqlIdentifier)]+ const q = clause.quantile ?? 0.95+ // Interpolates inside the bucket that holds the rank, as _histogram_quantile does in the engine.+ const quantile = [+ 'if(',+ ' idx > length(bounds),',+ ' bounds[length(bounds)],',+ ' if(idx > 1, bounds[idx - 1], least(0.0, bounds[1]))',+ ' + (bounds[idx] - if(idx > 1, bounds[idx - 1], least(0.0, bounds[1])))',+ ' * (rank - (cumulative[idx] - counts[idx])) / counts[idx]',+ ')',+ ].join('\n')+ const lines = [+ 'SELECT',+ ` ${['time', ...labelNames, `${indent(quantile, 4).trimStart()} AS value`].join(',\n ')}`,+ 'FROM (',+ ' SELECT',+ ` ${[+ 'time',+ ...labelNames,+ 'bounds',+ 'counts',+ 'arrayCumSum(counts) AS cumulative',+ `${q} * arraySum(counts) AS rank`,+ 'arrayFirstIndex(c -> c >= rank, cumulative) AS idx',+ ].join(',\n ')}`,+ ' FROM (',+ ' SELECT',+ ` ${[+ 'toStartOfInterval(s.sample_timestamp, {interval}) AS time',+ ...labels.columns,+ 'any(s.histogram_bounds) AS bounds',+ // Adding counts by position is only right when every series has the same bounds.+ 'uniqExactIf(s.histogram_bounds, notEmpty(s.histogram_bounds)) AS layouts',+ 'arrayMap(x -> ifNull(x, 0.0), sumForEach(s.contribution_counts)) AS counts',+ ].join(',\n ')}`,+ ' FROM (',+ ' SELECT',+ ' timestamp AS sample_timestamp,',+ ' series_fingerprint,',+ ' histogram_bounds,',+ ' multiIf(',+ " aggregation_temporality = 'delta', counts_f,",+ ' empty(prev_counts), arrayMap(x -> 0.0, counts_f),',+ ' length(prev_counts) != length(counts_f), counts_f,',+ ' arrayAll((c, p) -> c >= p, counts_f, prev_counts), arrayMap((c, p) -> c - p, counts_f, prev_counts),',+ ' counts_f',+ ' ) AS contribution_counts',+ ' FROM (',+ ' SELECT',+ ' timestamp,',+ ' series_fingerprint,',+ ' aggregation_temporality,',+ ' histogram_bounds,',+ ' arrayMap(x -> toFloat(x), histogram_counts) AS counts_f,',+ ' lagInFrame(arrayMap(x -> toFloat(x), histogram_counts)) OVER (',+ ' PARTITION BY series_fingerprint',+ ' ORDER BY timestamp ASC',+ ' ROWS BETWEEN 1 PRECEDING AND 1 PRECEDING',+ ' ) AS prev_counts',+ ' FROM posthog.metrics',+ indent(whereBlock([...pointsWhere(clause, COUNTER_LOOKBACK_FROM), 'notEmpty(histogram_counts)']), 16),+ ' )',+ ' ) AS s',+ ...(join ? [indent(join, 8)] : []),+ ' WHERE s.sample_timestamp >= {date_from}',+ ` GROUP BY ${['time', ...labels.groupBy].join(', ')}`,+ ' )',+ ' WHERE arraySum(counts) > 0',+ ` AND throwIf(layouts > 1, ${quoteSqlString(MIXED_HISTOGRAM_BOUNDS_ERROR)}) = 0`,+ ')',+ ...(options.orderByTime ? ['ORDER BY time'] : []),+ ]+ return lines.join('\n')+}++function clauseSql(clause: BuilderClause, options: ClauseSqlOptions): string {+ return clause.aggregation === 'histogram_quantile'+ ? histogramClauseSql(clause, options)+ : seriesClauseSql(clause, options)+}++/** Builder formula → SQL expression over the per-clause value columns. A division by zero gives 0, as in the builder. */+function formulaToSql(expr: PromExpr): string {+ switch (expr.type) {+ case 'number':+ return plainNumber(expr.value)+ case 'selector':+ return expr.name ?? ''+ case 'paren':+ return `(${formulaToSql(expr.expr)})`+ case 'unary': {+ const inner = formulaToSql(expr.expr)+ return `${expr.op}${expr.expr.type === 'binary' ? `(${inner})` : inner}`+ }+ case 'binary': {+ const lhs = formulaToSql(expr.lhs)+ const rhs = formulaToSql(expr.rhs)+ return expr.op === '/' ? `if(${rhs} = 0, 0, ${lhs} / ${rhs})` : `${lhs} ${expr.op} ${rhs}`+ }+ default:+ throw new Error('The formula has an unsupported term')+ }+}++/** The formula's value for the given series values (0 when not given), with the builder's division policy. */+function formulaValue(expr: PromExpr, values: Record<string, number>): number {+ switch (expr.type) {+ case 'number':+ return expr.value+ case 'selector':+ return values[expr.name ?? ''] ?? 0+ case 'paren':+ return formulaValue(expr.expr, values)+ case 'unary':+ return expr.op === '-' ? -formulaValue(expr.expr, values) : formulaValue(expr.expr, values)+ case 'binary': {+ const lhs = formulaValue(expr.lhs, values)+ const rhs = formulaValue(expr.rhs, values)+ switch (expr.op) {+ case '+':+ return lhs + rhs+ case '-':+ return lhs - rhs+ case '*':+ return lhs * rhs+ default:+ return rhs === 0 ? 0 : lhs / rhs+ }+ }+ default:+ return 0+ }+}++/** Whether a clause returns labelled series. The builder spreads a clause without labels over every label set. */+const hasLabels = (clause: BuilderClause): boolean => !clause.aggregation || !!clause.groupBy?.length++export function builderToSql(query: BuilderQuery): ConversionResult<string> {+ const issues: string[] = []+ const clauses = query.clauses.filter((clause) => clause.metricName.trim()).map(normalizeClause)+ if (clauses.length === 0) {+ return { value: '', issues }+ }+ const labelKeys: string[] = []+ for (const clause of clauses) {+ if (!clause.aggregation) {+ issues.push(`SQL names each series of ${clause.name} by its fingerprint, not by its attributes.`)+ if (!labelKeys.includes(PER_SERIES_COLUMN)) {+ labelKeys.push(PER_SERIES_COLUMN)+ }+ }+ for (const group of clause.groupBy ?? []) {+ const key = normalizeLabelKey(group.key)+ if (SQL_RESERVED_COLUMNS.has(key)) {+ issues.push(`The "${key}" group-by has the same name as a result column and is dropped.`)+ continue+ }+ if (!labelKeys.includes(key)) {+ labelKeys.push(key)+ }+ }+ }+ const usable = clauses.map((clause) => ({+ ...clause,+ groupBy: clause.groupBy?.filter((group) => !SQL_RESERVED_COLUMNS.has(normalizeLabelKey(group.key))),+ }))++ if (usable.length === 1 && !query.formula?.trim()) {+ return { value: clauseSql(usable[0], { labelKeys, orderByTime: true }), issues }+ }++ const formula = query.formula?.trim()+ if (!formula) {+ const branches = usable.map((clause) =>+ clauseSql(clause, { labelKeys, clauseLabel: clause.name, orderByTime: false })+ )+ return { value: `${branches.join('\nUNION ALL\n')}`, issues }+ }++ const used = usable.filter((clause) => new RegExp(`\\b${clause.name}\\b`).test(formula))+ const unused = usable.filter((clause) => !used.includes(clause))+ if (unused.length) {+ issues.push(+ `Series ${unused.map((clause) => clause.name).join(', ')} ${unused.length > 1 ? 'are' : 'is'} not in the formula and will be removed.`+ )+ }+ const labelled = used.filter(hasLabels)+ // With no labelled clause, every clause is one series and nothing is spread.+ const spread = labelled.length ? used.filter((clause) => !hasLabels(clause)) : []+ const groupSets = new Set(+ labelled.map((clause) =>+ [+ clause.aggregation ? '' : PER_SERIES_COLUMN,+ ...(clause.groupBy ?? []).map((g) => normalizeLabelKey(g.key)),+ ].join(',')+ )+ )+ if (groupSets.size > 1) {+ issues.push('The formula mixes series with different group-by labels.')+ }+ let parsed: PromExpr+ try {+ parsed = parsePromQL(formula)+ } catch (error) {+ const message = error instanceof PromQLParseError ? error.message : String(error)+ return { value: null, issues: [`The formula "${formula}" cannot be read: ${message}`] }+ }+ let formulaSql: string+ try {+ formulaSql = formulaToSql(parsed)+ } catch (error) {+ return { value: null, issues: [error instanceof Error ? error.message : String(error)] }+ }+ // SQL has no row for a label set in an interval where none of its series has data, so the+ // chart shows 0 there. The builder shows the formula with those series at 0.+ if (+ labelled.length &&+ [0, 1, 2].some(+ (spreadValue) =>+ formulaValue(parsed, Object.fromEntries(spread.map((clause) => [clause.name, spreadValue]))) !== 0+ )+ ) {+ issues.push(SQL_EMPTY_INTERVAL_ISSUE)+ }+ const labelColumns = labelKeys.map(quoteSqlIdentifier)+ const branches = used.map((clause) => {+ const values = used.map((other) => `${other === clause ? 'value' : '0'} AS ${other.name}`)+ const seen = used.map((other) => `${other === clause ? 1 : 0} AS ${other.name}_seen`)+ return [+ 'SELECT',+ ` ${['time', ...labelColumns, ...values, ...seen].join(', ')}`,+ 'FROM (',+ indent(clauseSql(clause, { labelKeys, orderByTime: false }), 4),+ ')',+ ].join('\n')+ })+ // The builder keeps a label set only when every labelled series has it, and adds the value of+ // each series without labels to every label set in the same interval.+ const byLabels = labelColumns.length ? `OVER (PARTITION BY ${labelColumns.join(', ')})` : 'OVER ()'+ const lines = [+ 'SELECT',+ ` ${['time', ...labelColumns, `${formulaSql} AS value`].join(',\n ')}`,+ 'FROM (',+ ' SELECT',+ ` ${[+ 'time',+ ...labelColumns,+ ...used.map((clause) =>+ spread.includes(clause)+ ? `sum(sum(${clause.name})) OVER (PARTITION BY time) AS ${clause.name}`+ : `sum(${clause.name}) AS ${clause.name}`+ ),+ ...used.map(+ (clause) =>+ `max(max(${clause.name}_seen)) ${spread.includes(clause) ? 'OVER ()' : byLabels} AS ${clause.name}_in_label_set`+ ),+ ].join(',\n ')}`,+ ' FROM (',+ indent(branches.join('\nUNION ALL\n'), 8),+ ' )',+ ` GROUP BY ${['time', ...labelColumns].join(', ')}`,+ ')',+ `WHERE ${used.map((clause) => `${clause.name}_in_label_set = 1`).join(' AND ')}`,+ 'ORDER BY time',+ ]+ return { value: lines.join('\n'), issues }+}diff --git a/products/metrics/frontend/queryLanguages/convert.ts b/products/metrics/frontend/queryLanguages/convert.tsnew file mode 100644index 000000000000..88522e364617--- /dev/null+++ b/products/metrics/frontend/queryLanguages/convert.ts@@ -0,0 +1,236 @@+import type { MetricsQuery, MetricsQueryLanguage } from '~/queries/schema/schema-general'++import { builderToPromql } from './builderToPromql'+import { builderToSql } from './builderToSql'+import { type PromExpr, parsePromQL } from './promqlParser'+import { printPromQL } from './promqlPrinter'+import { promqlToBuilder } from './promqlToBuilder'+import { sqlToBuilder } from './sqlToBuilder'+import {+ type BuilderQuery,+ type ConversionResult,+ VALUE_ONLY_ISSUES,+ clauseAlias,+ normalizeClause,+ normalizeLabelKey,+} from './types'++export const METRICS_QUERY_LANGUAGES: MetricsQueryLanguage[] = ['builder', 'promql', 'sql']++export const queryLanguage = (query: Pick<MetricsQuery, 'language'>): MetricsQueryLanguage =>+ query.language ?? 'builder'++/** Shown when a round trip finds a change that no converter reported. */+export const GENERIC_LOSS_ISSUE = 'Parts of the query will change.'++// The aggregations the builder's clause rows can show (see isBuilderCompatibleQuery in metricsViewerLogic).+const BUILDER_EDITOR_AGGREGATIONS = new Set(['sum', 'avg', 'count', 'min', 'max'])++/** Parts of a builder query that the builder can chart but not show in its clause rows. */+function builderEditorLimits(query: BuilderQuery): string[] {+ const limits: string[] = []+ for (const clause of query.clauses.map(normalizeClause)) {+ if (clause.aggregation === 'histogram_quantile') {+ limits.push(`series ${clause.name} uses a histogram quantile`)+ } else if (+ clause.aggregation &&+ !BUILDER_EDITOR_AGGREGATIONS.has(clause.aggregation) &&+ !(clause.aggregation === 'quantile' && clause.quantile === 0.95)+ ) {+ limits.push(`series ${clause.name} uses ${clause.aggregation}`)+ }+ const scoped = [...(clause.filters ?? []), ...(clause.groupBy ?? [])].find(+ (item) => item.scope && item.scope !== 'auto'+ )+ if (scoped) {+ limits.push(`series ${clause.name} limits "${scoped.key}" to ${scoped.scope} attributes`)+ }+ }+ return limits+}++/** The builder form of a query in any language. */+export function toBuilderQuery(query: MetricsQuery): ConversionResult<BuilderQuery> {+ switch (queryLanguage(query)) {+ case 'promql':+ return promqlToBuilder(query.promql ?? '')+ case 'sql':+ return sqlToBuilder(query.sql ?? '')+ default:+ return {+ value: { clauses: query.clauses, ...(query.formula ? { formula: query.formula } : {}) },+ issues: [],+ }+ }+}++function fromBuilderQuery(builder: BuilderQuery, to: 'promql' | 'sql'): ConversionResult<string> {+ return to === 'promql' ? builderToPromql(builder) : builderToSql(builder)+}++/**+ * A canonical form of a builder query for comparison: aliases renamed in order, the pinned type+ * dropped (PromQL has no form for it, and the picker sets it again), default scopes and+ * `service.name` normalized, and group-by keys sorted.+ */+export function canonicalBuilder(query: BuilderQuery): string {+ const clauses = query.clauses.filter((clause) => clause.metricName.trim()).map(normalizeClause)+ const renames = new Map(clauses.map((clause, index) => [clause.name, clauseAlias(index)]))+ const formula = (query.formula ?? '')+ .replace(/[a-z_][a-z0-9_]*/g, (word) => renames.get(word) ?? word)+ .replace(/\s+/g, '')+ return JSON.stringify({+ clauses: clauses.map((clause) => ({+ metricName: clause.metricName.trim(),+ aggregation: clause.aggregation ?? null,+ rangeFunction: clause.rangeFunction ?? null,+ quantile:+ clause.aggregation === 'quantile' || clause.aggregation === 'histogram_quantile'+ ? (clause.quantile ?? 0.95)+ : null,+ filters: (clause.filters ?? []).map((filter) => ({+ key: normalizeLabelKey(filter.key),+ op: filter.op,+ value: filter.value,+ scope: filter.scope === 'auto' ? undefined : filter.scope,+ })),+ groupBy: (clause.groupBy ?? [])+ .map((group) => `${normalizeLabelKey(group.key)}:${group.scope === 'auto' ? '' : (group.scope ?? '')}`)+ .sort(),+ })),+ formula: formula === 'a' && clauses.length === 1 ? '' : formula,+ })+}++const stripParens = (expr: PromExpr): PromExpr => {+ switch (expr.type) {+ case 'paren':+ return stripParens(expr.expr)+ case 'unary':+ case 'offset':+ case 'subquery':+ return { ...expr, expr: stripParens(expr.expr) }+ case 'call':+ return { ...expr, args: expr.args.map(stripParens) }+ case 'aggregate':+ return { ...expr, expr: stripParens(expr.expr), ...(expr.param ? { param: stripParens(expr.param) } : {}) }+ case 'binary':+ return { ...expr, lhs: stripParens(expr.lhs), rhs: stripParens(expr.rhs) }+ case 'selector': {+ // A Grafana step variable means the same as an omitted range.+ const { range, ...rest } = expr+ return range?.startsWith('$__') && range !== '$__range' ? rest : expr+ }+ default:+ return expr+ }+}++/** PromQL in canonical form: one spelling of each construct, and only the parentheses it needs. */+export function canonicalPromQL(text: string): string | null {+ try {+ return printPromQL(stripParens(parsePromQL(text)))+ } catch {+ return null+ }+}++/** SQL without formatting differences: comments, spacing and keyword case. */+export function canonicalSql(text: string): string {+ return text+ .replace(/--[^\n]*/g, '')+ .replace(/\/\*[\s\S]*?\*\//g, '')+ .replace(/\s+/g, ' ')+ .replace(/\s*([(),=<>+\-*/])\s*/g, '$1')+ .replace(/;$/, '')+ .trim()+ .toLowerCase()+}++/** The PromQL or SQL text of a query, or '' for a builder query. */+export const metricsQueryText = (query: MetricsQuery): string => {+ const language = queryLanguage(query)+ return language === 'promql' ? (query.promql ?? '') : language === 'sql' ? (query.sql ?? '') : ''+}++/** Whether the text in `language` comes back unchanged from the builder form. */+function textSurvives(text: string, builder: BuilderQuery, language: 'promql' | 'sql'): boolean {+ const again = fromBuilderQuery(builder, language).value+ if (again === null) {+ return false+ }+ if (language === 'promql') {+ return canonicalPromQL(again) === canonicalPromQL(text)+ }+ return canonicalSql(again) === canonicalSql(text)+}++function builderSurvives(builder: BuilderQuery, text: string, language: 'promql' | 'sql'): boolean {+ const back = (language === 'promql' ? promqlToBuilder(text) : sqlToBuilder(text)).value+ return back !== null && canonicalBuilder(back) === canonicalBuilder(builder)+}++export interface MetricsQueryConversion {+ query: MetricsQuery+ /** What the switch loses or changes. Empty when the switch is lossless. */+ issues: string[]+}++/** Converts a metrics query to another language, best effort. Shared fields (date range, interval, display) are kept. */+export function convertMetricsQuery(query: MetricsQuery, to: MetricsQueryLanguage): MetricsQueryConversion {+ const from = queryLanguage(query)+ if (from === to) {+ return { query, issues: [] }+ }+ const { promql: _promql, sql: _sql, language: _language, formula: _formula, ...shared } = query+ const issues: string[] = []+ const source = toBuilderQuery(query)+ issues.push(...source.issues)+ const builder = source.value+ if (from === 'sql' && builder) {+ // The source SQL computes these values differently from every other language.+ issues.push(...builderToSql(builder).issues.filter((issue) => VALUE_ONLY_ISSUES.has(issue)))+ }++ if (to === 'builder') {+ const clauses = builder?.clauses ?? []+ const limits = builder ? builderEditorLimits(builder) : []+ if (limits.length) {+ issues.push(`The builder cannot edit this query: ${limits.join('; ')}.`)+ }+ if (+ from !== 'builder' &&+ builder &&+ !reportsQueryChange(issues) &&+ !textSurvives(metricsQueryText(query), builder, from)+ ) {+ issues.push(GENERIC_LOSS_ISSUE)+ }+ return {+ query: { ...shared, clauses, ...(builder?.formula ? { formula: builder.formula } : {}) },+ issues: dedupe(issues),+ }+ }++ const target = builder ? fromBuilderQuery(builder, to) : { value: null, issues: [] }+ issues.push(...target.issues)+ const text = target.value ?? ''+ if (builder && target.value !== null && !reportsQueryChange(issues)) {+ const survives =+ from === 'builder'+ ? builderSurvives(builder, text, to)+ : textSurvives(metricsQueryText(query), builder, from) && builderSurvives(builder, text, to)+ if (!survives) {+ issues.push(GENERIC_LOSS_ISSUE)+ }+ }+ return {+ query: { ...shared, clauses: [], language: to, ...(to === 'promql' ? { promql: text } : { sql: text }) },+ issues: dedupe(issues),+ }+}++const dedupe = (issues: string[]): string[] => [...new Set(issues)]++/** Whether an issue already reports a change to the query. Then the round-trip check has nothing to add. */+const reportsQueryChange = (issues: string[]): boolean => issues.some((issue) => !VALUE_ONLY_ISSUES.has(issue))diff --git a/products/metrics/frontend/queryLanguages/promqlCompletion.test.ts b/products/metrics/frontend/queryLanguages/promqlCompletion.test.tsnew file mode 100644index 000000000000..6d7dbe845dc5--- /dev/null+++ b/products/metrics/frontend/queryLanguages/promqlCompletion.test.ts@@ -0,0 +1,166 @@+import {+ type PromQLCompletionSource,+ type PromQLSituation,+ getPromQLCompletions,+ getSituation,+} from './promqlCompletion'++// `|` marks the cursor.+const at = (query: string): [string, number] => [query.replace('|', ''), query.indexOf('|')]++const source = (): PromQLCompletionSource & { calls: string[] } => {+ const calls: string[] = []+ return {+ calls,+ metricNames: async (search) => {+ calls.push(`names:${search}`)+ return [+ { name: 'http_requests_total', type: 'sum' },+ { name: 'http.server.duration', type: 'histogram' },+ ]+ },+ labelNames: async (metricName, search) => {+ calls.push(`labels:${metricName ?? ''}:${search}`)+ return ['service_name', 'http.route', 'job']+ },+ labelValues: async (labelName, metricName, search) => {+ calls.push(`values:${labelName}:${metricName ?? ''}:${search}`)+ return ['api', 'a.b "c"']+ },+ metricNamesSearchedOnServer: () => false,+ }+}++describe('PromQL autocomplete', () => {+ it.each<[string, PromQLSituation | null]>([+ ['|', { type: 'EMPTY' }],+ ['http_re|', { type: 'AT_ROOT' }],+ ['sum(|', { type: 'IN_FUNCTION' }],+ ['sum(rate(htt|', { type: 'IN_FUNCTION' }],+ ['topk(5, |', { type: 'IN_FUNCTION' }],+ ['sum(x) / |', { type: 'AT_ROOT' }],+ ['x or |', { type: 'AT_ROOT' }],+ ['rate(x[|', { type: 'IN_DURATION' }],+ ['rate(x[5m:|', { type: 'IN_DURATION' }],+ ['rate(x[5m] |', null],+ ['sum(x) |', null],+ ['x{|', { type: 'IN_LABEL_SELECTOR_NO_LABEL_NAME', metricName: 'x', otherLabels: [] }],+ ['x{jo|', { type: 'IN_LABEL_SELECTOR_NO_LABEL_NAME', metricName: 'x', otherLabels: [] }],+ [+ 'x{job="api", |',+ {+ type: 'IN_LABEL_SELECTOR_NO_LABEL_NAME',+ metricName: 'x',+ otherLabels: [{ label: 'job', op: '=', value: 'api' }],+ },+ ],+ [+ '{"http.server.duration", |',+ { type: 'IN_LABEL_SELECTOR_NO_LABEL_NAME', metricName: 'http.server.duration', otherLabels: [] },+ ],+ ['{__name__="x", |', { type: 'IN_LABEL_SELECTOR_NO_LABEL_NAME', metricName: 'x', otherLabels: [] }],+ [+ 'x{job=|',+ {+ type: 'IN_LABEL_SELECTOR_WITH_LABEL_NAME',+ metricName: 'x',+ labelName: 'job',+ op: '=',+ betweenQuotes: false,+ otherLabels: [],+ },+ ],+ [+ 'x{a="1", job=~"ap|',+ {+ type: 'IN_LABEL_SELECTOR_WITH_LABEL_NAME',+ metricName: 'x',+ labelName: 'job',+ op: '=~',+ betweenQuotes: true,+ otherLabels: [{ label: 'a', op: '=', value: '1' }],+ },+ ],+ [+ '{"http.server.duration", "http.route"!="|',+ {+ type: 'IN_LABEL_SELECTOR_WITH_LABEL_NAME',+ metricName: 'http.server.duration',+ labelName: 'http.route',+ op: '!=',+ betweenQuotes: true,+ otherLabels: [],+ },+ ],+ ['x{job="api"|', null],+ ['{"http.ser|', { type: 'IN_QUOTED_METRIC_NAME' }],+ ['{__name__="htt|', { type: 'IN_QUOTED_METRIC_NAME' }],+ ['sum by (|', { type: 'IN_GROUPING', metricName: undefined, usedLabels: [] }],+ ['sum by (|) (rate(errors_total))', { type: 'IN_GROUPING', metricName: 'errors_total', usedLabels: [] }],+ [+ 'sum(rate(errors_total{job="a"})) by (job, |',+ { type: 'IN_GROUPING', metricName: 'errors_total', usedLabels: ['job'] },+ ],+ [+ 'sum by (le) (rate({"http.server.duration_bucket"})) / on(|',+ { type: 'IN_GROUPING', metricName: 'http.server.duration_bucket', usedLabels: [] },+ ],+ ])('reads %j', (query, expected) => {+ const [text, offset] = at(query)+ expect(getSituation(text, offset)?.situation ?? null).toEqual(expected)+ })++ it('suggests metrics, aggregations and functions at the start, quoting dotted names', async () => {+ const [text, offset] = at('sum(htt|')+ const result = await getPromQLCompletions(text, offset, source())+ expect(result?.from).toBe(4)+ const byLabel = Object.fromEntries(result!.items.map((item) => [item.label, item]))+ expect(byLabel['http_requests_total']).toMatchObject({ insertText: 'http_requests_total', kind: 'metric' })+ expect(byLabel['http.server.duration']).toMatchObject({ insertText: '{"http.server.duration"}' })+ expect(byLabel['http.server.duration_bucket']).toMatchObject({ insertText: '{"http.server.duration_bucket"}' })+ expect(byLabel['rate']).toMatchObject({ insertText: 'rate($0)', snippet: true, kind: 'function' })+ expect(byLabel['quantile']).toMatchObject({ kind: 'aggregation' })+ // Names loaded once are filtered locally, so Monaco need not ask again on each keystroke.+ expect(result?.incomplete).toBe(false)+ })++ it('suggests unused label names for the selector metric, ready for a value', async () => {+ const fake = source()+ const [text, offset] = at('x{job="a", ht|}')+ const result = await getPromQLCompletions(text, offset, fake)+ expect(fake.calls).toEqual(['labels:x:ht'])+ expect(result?.items.map((item) => item.insertText)).toEqual(['service_name=', '"http.route"='])+ expect(result?.items.every((item) => item.retrigger)).toBe(true)+ expect(result?.incomplete).toBe(true)+ })++ it.each([+ ['x{job=|}', ['"api"', '"a.b \\"c\\""']],+ ['x{job="|"}', ['api', 'a.b \\"c\\"']],+ ['x{job=~"|"}', ['api', 'a\\\\.b \\"c\\"']],+ ])('quotes and escapes label values in %j', async (query, expected) => {+ const [text, offset] = at(query)+ const result = await getPromQLCompletions(text, offset, source())+ expect(result?.items.map((item) => item.insertText)).toEqual(expected)+ })++ it('suggests durations in a range and grouping labels without "="', async () => {+ const [rangeText, rangeOffset] = at('rate(x[|')+ const range = await getPromQLCompletions(rangeText, rangeOffset, source())+ expect(range?.items.map((item) => item.label)).toContain('5m')++ const [groupText, groupOffset] = at('sum by (job, |) (x)')+ const grouping = await getPromQLCompletions(groupText, groupOffset, source())+ expect(grouping?.items.map((item) => item.insertText)).toEqual(['service_name', '"http.route"'])+ })++ it('gives no suggestions when the source fails', async () => {+ const failing: PromQLCompletionSource = {+ metricNames: () => Promise.reject(new Error('down')),+ labelNames: () => Promise.reject(new Error('down')),+ labelValues: () => Promise.reject(new Error('down')),+ }+ const [text, offset] = at('x{|')+ expect((await getPromQLCompletions(text, offset, failing))?.items).toEqual([])+ })+})diff --git a/products/metrics/frontend/queryLanguages/promqlCompletion.ts b/products/metrics/frontend/queryLanguages/promqlCompletion.tsnew file mode 100644index 000000000000..527ab0df0429--- /dev/null+++ b/products/metrics/frontend/queryLanguages/promqlCompletion.ts@@ -0,0 +1,692 @@+/**+ * PromQL autocomplete, modeled on Grafana's Prometheus query field.+ *+ * The text before the cursor gives a "situation" (at the start of an expression, inside a+ * function, in a label selector before or after a label name, in a `by (…)` grouping, or in a+ * range). Each situation has its own suggestions: functions and metric names, label names,+ * label values, or durations. The text does not need to parse: the user is still typing it.+ */++import type { PromQLCompletionItem } from 'lib/monaco/languages/promqlCompletionRegistry'++import { printLabelName } from './promqlPrinter'++export interface PromQLLabelMatcher {+ label: string+ op: string+ value: string+}++export type PromQLSituation =+ | { type: 'EMPTY' }+ | { type: 'AT_ROOT' }+ | { type: 'IN_FUNCTION' }+ | { type: 'IN_DURATION' }+ | { type: 'IN_GROUPING'; metricName?: string; usedLabels: string[] }+ | { type: 'IN_QUOTED_METRIC_NAME' }+ | { type: 'IN_LABEL_SELECTOR_NO_LABEL_NAME'; metricName?: string; otherLabels: PromQLLabelMatcher[] }+ | {+ type: 'IN_LABEL_SELECTOR_WITH_LABEL_NAME'+ metricName?: string+ labelName: string+ op: string+ betweenQuotes: boolean+ otherLabels: PromQLLabelMatcher[]+ }++export type PromQLCompletion = PromQLCompletionItem++export interface PromQLMetricName {+ name: string+ /** OTel type, e.g. gauge, sum, histogram. */+ type?: string+}++/** Where suggestions come from. Each call can fail or be slow; a failure gives no suggestions. */+export interface PromQLCompletionSource {+ metricNames: (search: string) => Promise<PromQLMetricName[]>+ labelNames: (metricName: string | undefined, search: string) => Promise<string[]>+ labelValues: (labelName: string, metricName: string | undefined, search: string) => Promise<string[]>+ /** Whether the last metric names came from a search on the server, so typing more must ask again. */+ metricNamesSearchedOnServer?: () => boolean+}++export interface PromQLCompletionResult {+ /** Offset where the text the suggestions replace starts; the end is the cursor. */+ from: number+ items: PromQLCompletion[]+ /** The list was searched on the server for the typed word, so typing more must ask again. */+ incomplete: boolean+}++// --- Function and aggregation catalog -------------------------------------------------------++interface CatalogEntry {+ signature: string+ documentation: string+}++export const PROMQL_AGGREGATIONS: Record<string, CatalogEntry> = {+ sum: { signature: 'sum by (labels) (v)', documentation: 'Adds the values of the series in each group.' },+ avg: { signature: 'avg by (labels) (v)', documentation: 'Calculates the average of the series in each group.' },+ min: { signature: 'min by (labels) (v)', documentation: 'Selects the lowest value in each group.' },+ max: { signature: 'max by (labels) (v)', documentation: 'Selects the highest value in each group.' },+ count: { signature: 'count by (labels) (v)', documentation: 'Counts the series in each group.' },+ group: { signature: 'group by (labels) (v)', documentation: 'Gives 1 for each group.' },+ stddev: { signature: 'stddev by (labels) (v)', documentation: 'Calculates the population standard deviation.' },+ stdvar: { signature: 'stdvar by (labels) (v)', documentation: 'Calculates the population variance.' },+ quantile: {+ signature: 'quantile by (labels) (φ, v)',+ documentation: 'Calculates the φ-quantile (0 ≤ φ ≤ 1) of the series values in each group.',+ },+ median: { signature: 'median by (labels) (v)', documentation: 'Calculates the median of the series values.' },+ topk: { signature: 'topk(k, v)', documentation: 'Keeps the k series with the highest values.' },+ bottomk: { signature: 'bottomk(k, v)', documentation: 'Keeps the k series with the lowest values.' },+ count_values: {+ signature: 'count_values("label", v)',+ documentation: 'Counts the series that have each value, and puts the value in a label.',+ },+ limitk: { signature: 'limitk(k, v)', documentation: 'Keeps k series from each group.' },+ limit_ratio: { signature: 'limit_ratio(r, v)', documentation: 'Keeps about the ratio r of the series.' },+}++export const PROMQL_FUNCTIONS: Record<string, CatalogEntry> = {+ rate: {+ signature: 'rate(v range-vector)',+ documentation:+ 'Per-second rate of increase of a counter. Leave out the range, as in rate(x), to use the chart interval.',+ },+ increase: {+ signature: 'increase(v range-vector)',+ documentation: 'Increase of a counter in the range. Counter resets are handled.',+ },+ irate: {+ signature: 'irate(v range-vector)',+ documentation: 'Per-second rate from the last two samples in the range.',+ },+ delta: {+ signature: 'delta(v range-vector)',+ documentation: 'Difference between the first and last value of a gauge.',+ },+ idelta: {+ signature: 'idelta(v range-vector)',+ documentation: 'Difference between the last two samples of a gauge.',+ },+ deriv: {+ signature: 'deriv(v range-vector)',+ documentation: 'Per-second derivative of a gauge (linear regression).',+ },+ changes: { signature: 'changes(v range-vector)', documentation: 'Number of times the value changed in the range.' },+ resets: { signature: 'resets(v range-vector)', documentation: 'Number of counter resets in the range.' },+ predict_linear: {+ signature: 'predict_linear(v range-vector, t scalar)',+ documentation: 'Predicts the value t seconds from now (linear regression).',+ },+ histogram_quantile: {+ signature: 'histogram_quantile(φ scalar, b instant-vector)',+ documentation:+ 'Calculates the φ-quantile from histogram buckets, for example histogram_quantile(0.95, sum by (le) (rate(x_bucket))).',+ },+ histogram_quantiles: {+ signature: 'histogram_quantiles("label", φ1, φ2, …, b)',+ documentation: 'Calculates several quantiles at once and puts each quantile in a label.',+ },+ histogram_count: { signature: 'histogram_count(v)', documentation: 'Observation count of a native histogram.' },+ histogram_sum: { signature: 'histogram_sum(v)', documentation: 'Sum of observations of a native histogram.' },+ histogram_avg: { signature: 'histogram_avg(v)', documentation: 'Average observation of a native histogram.' },+ histogram_fraction: {+ signature: 'histogram_fraction(lower, upper, b)',+ documentation: 'Fraction of observations between lower and upper.',+ },+ avg_over_time: { signature: 'avg_over_time(v range-vector)', documentation: 'Average value in the range.' },+ min_over_time: { signature: 'min_over_time(v range-vector)', documentation: 'Lowest value in the range.' },+ max_over_time: { signature: 'max_over_time(v range-vector)', documentation: 'Highest value in the range.' },+ sum_over_time: { signature: 'sum_over_time(v range-vector)', documentation: 'Sum of the values in the range.' },+ count_over_time: { signature: 'count_over_time(v range-vector)', documentation: 'Number of samples in the range.' },+ last_over_time: { signature: 'last_over_time(v range-vector)', documentation: 'Last value in the range.' },+ present_over_time: {+ signature: 'present_over_time(v range-vector)',+ documentation: 'Gives 1 for a series with samples.',+ },+ quantile_over_time: {+ signature: 'quantile_over_time(φ scalar, v range-vector)',+ documentation: 'φ-quantile of the values in the range.',+ },+ stddev_over_time: {+ signature: 'stddev_over_time(v range-vector)',+ documentation: 'Standard deviation in the range.',+ },+ stdvar_over_time: { signature: 'stdvar_over_time(v range-vector)', documentation: 'Variance in the range.' },+ absent: { signature: 'absent(v instant-vector)', documentation: 'Gives 1 when the vector has no series.' },+ absent_over_time: {+ signature: 'absent_over_time(v range-vector)',+ documentation: 'Gives 1 when the range has no samples.',+ },+ abs: { signature: 'abs(v)', documentation: 'Absolute value.' },+ ceil: { signature: 'ceil(v)', documentation: 'Rounds up to the nearest integer.' },+ floor: { signature: 'floor(v)', documentation: 'Rounds down to the nearest integer.' },+ round: { signature: 'round(v, to_nearest=1)', documentation: 'Rounds to the nearest multiple of to_nearest.' },+ clamp: { signature: 'clamp(v, min, max)', documentation: 'Limits the values to the range min to max.' },+ clamp_min: { signature: 'clamp_min(v, min)', documentation: 'Limits the values to a lower bound.' },+ clamp_max: { signature: 'clamp_max(v, max)', documentation: 'Limits the values to an upper bound.' },+ sqrt: { signature: 'sqrt(v)', documentation: 'Square root.' },+ exp: { signature: 'exp(v)', documentation: 'Exponential function.' },+ ln: { signature: 'ln(v)', documentation: 'Natural logarithm.' },+ log2: { signature: 'log2(v)', documentation: 'Binary logarithm.' },+ log10: { signature: 'log10(v)', documentation: 'Decimal logarithm.' },+ sgn: { signature: 'sgn(v)', documentation: 'Sign of the value: 1, 0 or -1.' },+ scalar: { signature: 'scalar(v)', documentation: 'Changes a one-series vector to a scalar.' },+ vector: { signature: 'vector(s scalar)', documentation: 'Changes a scalar to a vector with no labels.' },+ sort: { signature: 'sort(v)', documentation: 'Sorts by value, lowest first (instant queries only).' },+ sort_desc: { signature: 'sort_desc(v)', documentation: 'Sorts by value, highest first (instant queries only).' },+ label_replace: {+ signature: 'label_replace(v, "dst", "replacement", "src", "regex")',+ documentation: 'Sets a label from a regex match on another label.',+ },+ label_join: {+ signature: 'label_join(v, "dst", "separator", "src1", …)',+ documentation: 'Sets a label to the joined values of other labels.',+ },+ timestamp: { signature: 'timestamp(v)', documentation: 'Timestamp of each sample, in seconds.' },+ time: { signature: 'time()', documentation: 'Evaluation time, in seconds since the epoch.' },+ running_sum: {+ signature: 'running_sum(v)',+ documentation: 'Adds the values of each series from the start of the range.',+ },+}++const GROUPING_KEYWORDS = new Set(['by', 'without', 'on', 'ignoring', 'group_left', 'group_right'])++export const PROMQL_DURATIONS: [string, string][] = [+ ['$__rate_interval', 'The chart interval, as an omitted range'],+ ['$__interval', 'The chart interval'],+ ['1m', '1 minute'],+ ['5m', '5 minutes'],+ ['10m', '10 minutes'],+ ['30m', '30 minutes'],+ ['1h', '1 hour'],+ ['6h', '6 hours'],+ ['1d', '1 day'],+ ['1w', '1 week'],+]++// --- Situation detection --------------------------------------------------------------------++type TokenType = 'ident' | 'string' | 'number' | 'op' | 'open' | 'close'++interface Token {+ type: TokenType+ value: string+ /** True for a string that the text ends inside. */+ unterminated?: boolean+}++const IDENT_CHAR = /[A-Za-z0-9_:.]/+const IDENT_START = /[A-Za-z_]/++function tokenize(text: string): Token[] {+ const tokens: Token[] = []+ let i = 0+ while (i < text.length) {+ const ch = text[i]+ if (/\s/.test(ch)) {+ i+++ } else if (ch === '#') {+ while (i < text.length && text[i] !== '\n') {+ i+++ }+ } else if (ch === '"' || ch === "'" || ch === '`') {+ let value = ''+ let j = i + 1+ while (j < text.length && text[j] !== ch) {+ if (text[j] === '\\' && ch !== '`' && j + 1 < text.length) {+ value += text[j + 1]+ j += 2+ continue+ }+ value += text[j]+ j+++ }+ tokens.push({ type: 'string', value, ...(j >= text.length ? { unterminated: true } : {}) })+ i = j + 1+ } else if (IDENT_START.test(ch) || ch === '$') {+ let j = i + 1+ while (j < text.length && IDENT_CHAR.test(text[j])) {+ j+++ }+ tokens.push({ type: 'ident', value: text.slice(i, j) })+ i = j+ } else if (/[0-9.]/.test(ch)) {+ let j = i + 1+ while (j < text.length && /[0-9a-zA-Z.]/.test(text[j])) {+ j+++ }+ tokens.push({ type: 'number', value: text.slice(i, j) })+ i = j+ } else if ('({['.includes(ch)) {+ tokens.push({ type: 'open', value: ch })+ i+++ } else if (')}]'.includes(ch)) {+ tokens.push({ type: 'close', value: ch })+ i+++ } else {+ const op = ['=~', '!~', '!=', '==', '>=', '<='].find((candidate) => text.startsWith(candidate, i)) ?? ch+ tokens.push({ type: 'op', value: op })+ i += op.length+ }+ }+ return tokens+}++interface Frame {+ open: '(' | '{' | '['+ /** Index of the open token. */+ start: number+ grouping: boolean+}++/** Frames still open at the end of the tokens, innermost last. */+function openFrames(tokens: Token[]): Frame[] {+ const frames: Frame[] = []+ tokens.forEach((token, index) => {+ if (token.type === 'open') {+ const previous = tokens[index - 1]+ frames.push({+ open: token.value as Frame['open'],+ start: index,+ grouping:+ token.value === '(' &&+ previous?.type === 'ident' &&+ GROUPING_KEYWORDS.has(previous.value.toLowerCase()),+ })+ } else if (token.type === 'close') {+ frames.pop()+ }+ })+ return frames+}++/** The metric a selector reads: the name before `{`, a leading quoted name, or `__name__="x"`. */+function selectorMetricName(tokens: Token[], braceIndex: number, inside: Token[]): string | undefined {+ const before = tokens[braceIndex - 1]+ if (before?.type === 'ident' && !GROUPING_KEYWORDS.has(before.value) && !before.value.startsWith('$')) {+ return before.value+ }+ if (inside[0]?.type === 'string' && !inside[0].unterminated && (inside[1] === undefined || isComma(inside[1]))) {+ return inside[0].value+ }+ for (let i = 0; i + 2 < inside.length; i++) {+ if (inside[i].type === 'ident' && inside[i].value === '__name__' && inside[i + 1].value === '=') {+ return inside[i + 2].value+ }+ }+ return undefined+}++const isComma = (token: Token): boolean => token.type === 'op' && token.value === ','+const MATCH_OPS = new Set(['=', '!=', '=~', '!~'])++function splitSegments(tokens: Token[]): Token[][] {+ const segments: Token[][] = [[]]+ for (const token of tokens) {+ if (isComma(token)) {+ segments.push([])+ } else {+ segments[segments.length - 1].push(token)+ }+ }+ return segments+}++function completeMatchers(segments: Token[][]): PromQLLabelMatcher[] {+ return segments+ .filter(+ (segment) =>+ segment.length === 3 &&+ (segment[0].type === 'ident' || segment[0].type === 'string') &&+ MATCH_OPS.has(segment[1].value) &&+ segment[2].type === 'string' &&+ !segment[2].unterminated &&+ segment[0].value !== '__name__'+ )+ .map((segment) => ({ label: segment[0].value, op: segment[1].value, value: segment[2].value }))+}++/** The metric name nearest to token `index`. Used to scope label suggestions in a grouping. */+function nearestMetricName(tokens: Token[], index: number): string | undefined {+ const candidates: { name: string; distance: number }[] = []+ const stack: { grouping: boolean; brace: boolean }[] = []+ tokens.forEach((token, i) => {+ const next = tokens[i + 1]+ if (token.type === 'open') {+ const previous = tokens[i - 1]+ stack.push({+ grouping: token.value === '(' && previous?.type === 'ident' && GROUPING_KEYWORDS.has(previous.value),+ brace: token.value === '{',+ })+ if (token.value === '{') {+ const end = tokens.findIndex((t, j) => j > i && t.type === 'close' && t.value === '}')+ const name = selectorMetricName(tokens, i, tokens.slice(i + 1, end === -1 ? undefined : end))+ if (name) {+ candidates.push({ name, distance: Math.abs(i - index) })+ }+ }+ return+ }+ if (token.type === 'close') {+ stack.pop()+ return+ }+ const frame = stack[stack.length - 1]+ const isCall = next?.type === 'open' && next.value === '('+ // `sum by (…)` puts the grouping between the name and its parenthesis.+ const isKeyword =+ GROUPING_KEYWORDS.has(token.value) ||+ ['and', 'or', 'unless', 'offset', 'bool'].includes(token.value) ||+ token.value in PROMQL_AGGREGATIONS ||+ token.value in PROMQL_FUNCTIONS+ const beforeBrace = next?.type === 'open' && next.value === '{'+ if (+ token.type === 'ident' &&+ !frame?.grouping &&+ !frame?.brace &&+ !isCall &&+ !isKeyword &&+ !beforeBrace &&+ !token.value.startsWith('$')+ ) {+ candidates.push({ name: token.value, distance: Math.abs(i - index) })+ }+ })+ return candidates.sort((a, b) => a.distance - b.distance)[0]?.name+}++/** The partial word the cursor is in: identifier characters before the cursor. */+function wordStart(text: string, offset: number): number {+ let start = offset+ while (start > 0 && IDENT_CHAR.test(text[start - 1])) {+ start--+ }+ if (start > 0 && text[start - 1] === '$') {+ start--+ }+ return start+}++/**+ * The situation at `offset` in `text`, and where the word being typed starts.+ * `text` can be the whole query; text after the cursor only helps to find the metric of a grouping.+ */+export function getSituation(text: string, offset: number): { situation: PromQLSituation; from: number } | null {+ const before = text.slice(0, offset)+ const tokens = tokenize(before)+ const last = tokens[tokens.length - 1]++ // Inside a quoted string: a label value, or a quoted metric name.+ if (last?.type === 'string' && last.unterminated) {+ const quoteAt = Math.max(before.lastIndexOf('"'), before.lastIndexOf("'"), before.lastIndexOf('`'))+ const from = quoteAt + 1+ const frames = openFrames(tokens)+ const frame = frames[frames.length - 1]+ if (frame?.open !== '{') {+ return null+ }+ const inside = tokens.slice(frame.start + 1)+ const segments = splitSegments(inside)+ const segment = segments[segments.length - 1]+ const metricName = selectorMetricName(tokens, frame.start, inside)+ if (segment.length === 3 && MATCH_OPS.has(segment[1].value)) {+ if (segment[0].value === '__name__') {+ return { situation: { type: 'IN_QUOTED_METRIC_NAME' }, from }+ }+ return {+ situation: {+ type: 'IN_LABEL_SELECTOR_WITH_LABEL_NAME',+ metricName,+ labelName: segment[0].value,+ op: segment[1].value,+ betweenQuotes: true,+ otherLabels: completeMatchers(segments.slice(0, -1)),+ },+ from,+ }+ }+ if (segment.length === 1 && segments.length === 1 && tokens[frame.start - 1]?.type !== 'ident') {+ return { situation: { type: 'IN_QUOTED_METRIC_NAME' }, from }+ }+ return null+ }++ const from = wordStart(before, offset)+ const context = tokenize(before.slice(0, from))+ const previous = context[context.length - 1]+ if (!context.length) {+ return { situation: before.trim() ? { type: 'AT_ROOT' } : { type: 'EMPTY' }, from }+ }++ const frames = openFrames(context)+ const frame = frames[frames.length - 1]++ if (frame?.open === '[') {+ const afterOpen = context.slice(frame.start + 1)+ const ok = afterOpen.length === 0 || (afterOpen.length === 2 && afterOpen[1].value === ':')+ return ok ? { situation: { type: 'IN_DURATION' }, from } : null+ }++ if (frame?.open === '{') {+ const inside = context.slice(frame.start + 1)+ const segments = splitSegments(inside)+ const segment = segments[segments.length - 1]+ const metricName = selectorMetricName(context, frame.start, inside)+ const otherLabels = completeMatchers(segments.slice(0, -1))+ if (segment.length === 0) {+ return { situation: { type: 'IN_LABEL_SELECTOR_NO_LABEL_NAME', metricName, otherLabels }, from }+ }+ if (segment.length === 2 && MATCH_OPS.has(segment[1].value)) {+ if (segment[0].value === '__name__') {+ return null+ }+ return {+ situation: {+ type: 'IN_LABEL_SELECTOR_WITH_LABEL_NAME',+ metricName,+ labelName: segment[0].value,+ op: segment[1].value,+ betweenQuotes: false,+ otherLabels,+ },+ from,+ }+ }+ return null+ }++ if (frame?.grouping) {+ const labels = context+ .slice(frame.start + 1)+ .filter((token) => token.type === 'ident' || token.type === 'string')+ const allTokens = tokenize(text)+ return {+ situation: {+ type: 'IN_GROUPING',+ metricName: nearestMetricName(allTokens, frame.start),+ usedLabels: labels.map((token) => token.value),+ },+ from,+ }+ }++ // Start of an expression: after an open paren, a comma, or an operator.+ const startsExpression =+ (previous.type === 'open' && previous.value === '(') ||+ isComma(previous) ||+ (previous.type === 'op' && !MATCH_OPS.has(previous.value)) ||+ (previous.type === 'ident' && ['and', 'or', 'unless'].includes(previous.value.toLowerCase()))+ if (startsExpression) {+ return { situation: frame?.open === '(' ? { type: 'IN_FUNCTION' } : { type: 'AT_ROOT' }, from }+ }+ return null+}++// --- Completions ----------------------------------------------------------------------------++const LEGACY_METRIC_NAME = /^[a-zA-Z_:][a-zA-Z0-9_:]*$/+const REGEX_SPECIAL = /[.*+?^${}()|[\]\\]/g++const escapeString = (value: string): string => value.replace(/\\/g, '\\\\').replace(/"/g, '\\"')++const METRIC_TYPE_LABELS: Record<string, string> = {+ sum: 'counter',+ gauge: 'gauge',+ histogram: 'histogram',+ exponential_histogram: 'exponential histogram',+ summary: 'summary',+}++function catalogItems(): PromQLCompletion[] {+ const aggregations = Object.entries(PROMQL_AGGREGATIONS).map(+ ([name, entry]): PromQLCompletion => ({+ label: name,+ insertText: `${name}($0)`,+ kind: 'aggregation',+ detail: entry.signature,+ documentation: entry.documentation,+ snippet: true,+ retrigger: true,+ sortText: `2${name}`,+ })+ )+ const functions = Object.entries(PROMQL_FUNCTIONS).map(+ ([name, entry]): PromQLCompletion => ({+ label: name,+ insertText: `${name}($0)`,+ kind: 'function',+ detail: entry.signature,+ documentation: entry.documentation,+ snippet: true,+ retrigger: true,+ sortText: `3${name}`,+ })+ )+ return [...aggregations, ...functions]+}++/** Metric names as PromQL needs them: OTel names with dots go in the quoted selector form. */+function metricItems(metrics: PromQLMetricName[]): PromQLCompletion[] {+ const items: PromQLCompletion[] = []+ for (const metric of metrics) {+ const names = metric.type === 'histogram' ? [metric.name, `${metric.name}_bucket`] : [metric.name]+ for (const name of names) {+ const type = name.endsWith('_bucket') && name !== metric.name ? 'histogram buckets (le)' : metric.type+ items.push({+ label: name,+ insertText: LEGACY_METRIC_NAME.test(name) ? name : `{"${escapeString(name)}"}`,+ kind: 'metric',+ detail: type ? (METRIC_TYPE_LABELS[type] ?? type) : undefined,+ sortText: `1${name}`,+ })+ }+ }+ return items+}++const settle = async <T>(promise: Promise<T>, fallback: T): Promise<T> => {+ try {+ return await promise+ } catch {+ return fallback+ }+}++export async function getPromQLCompletions(+ text: string,+ offset: number,+ source: PromQLCompletionSource+): Promise<PromQLCompletionResult | null> {+ const found = getSituation(text, offset)+ if (!found) {+ return null+ }+ const { situation, from } = found+ const typed = text.slice(from, offset)++ switch (situation.type) {+ case 'EMPTY':+ case 'AT_ROOT':+ case 'IN_FUNCTION': {+ const metrics = await settle(source.metricNames(typed), [])+ return {+ from,+ items: [...metricItems(metrics), ...catalogItems()],+ incomplete: source.metricNamesSearchedOnServer?.() ?? true,+ }+ }+ case 'IN_QUOTED_METRIC_NAME': {+ const metrics = await settle(source.metricNames(typed), [])+ return {+ from,+ items: metrics.map((metric) => ({+ label: metric.name,+ insertText: escapeString(metric.name),+ kind: 'metric',+ detail: metric.type ? (METRIC_TYPE_LABELS[metric.type] ?? metric.type) : undefined,+ })),+ incomplete: source.metricNamesSearchedOnServer?.() ?? true,+ }+ }+ case 'IN_DURATION':+ return {+ from,+ items: PROMQL_DURATIONS.map(([value, detail], index) => ({+ label: value,+ insertText: value,+ kind: 'duration',+ detail,+ sortText: String(index).padStart(2, '0'),+ })),+ incomplete: false,+ }+ case 'IN_GROUPING': {+ const labels = await settle(source.labelNames(situation.metricName, typed), [])+ return {+ from,+ items: labels+ .filter((label) => !situation.usedLabels.includes(label))+ .map((label) => ({ label, insertText: printLabelName(label), kind: 'label' })),+ incomplete: true,+ }+ }+ case 'IN_LABEL_SELECTOR_NO_LABEL_NAME': {+ const used = new Set(situation.otherLabels.map((matcher) => matcher.label))+ const labels = await settle(source.labelNames(situation.metricName, typed), [])+ return {+ from,+ items: labels+ .filter((label) => !used.has(label))+ .map((label) => ({+ label,+ insertText: `${printLabelName(label)}=`,+ kind: 'label',+ retrigger: true,+ })),+ incomplete: true,+ }+ }+ case 'IN_LABEL_SELECTOR_WITH_LABEL_NAME': {+ const values = await settle(source.labelValues(situation.labelName, situation.metricName, typed), [])+ const isRegex = situation.op === '=~' || situation.op === '!~'+ return {+ from,+ items: values.map((value) => {+ const literal = escapeString(isRegex ? value.replace(REGEX_SPECIAL, '\\$&') : value)+ return {+ label: value,+ insertText: situation.betweenQuotes ? literal : `"${literal}"`,+ kind: 'value',+ }+ }),+ incomplete: true,+ }+ }+ }+}diff --git a/products/metrics/frontend/queryLanguages/promqlCompletionSource.test.ts b/products/metrics/frontend/queryLanguages/promqlCompletionSource.test.tsnew file mode 100644index 000000000000..52e33600a03e--- /dev/null+++ b/products/metrics/frontend/queryLanguages/promqlCompletionSource.test.ts@@ -0,0 +1,60 @@+import {+ metricsAttributeValuesRetrieve,+ metricsAttributesRetrieve,+ metricsNamesRetrieve,+} from 'products/metrics/frontend/generated/api'++import { createMetricsPromQLCompletionSource } from './promqlCompletionSource'++jest.mock('products/metrics/frontend/generated/api', () => ({+ metricsNamesRetrieve: jest.fn(),+ metricsAttributesRetrieve: jest.fn(),+ metricsAttributeValuesRetrieve: jest.fn(),+}))++describe('createMetricsPromQLCompletionSource', () => {+ beforeEach(() => {+ jest.mocked(metricsNamesRetrieve).mockReset()+ jest.mocked(metricsAttributesRetrieve).mockReset()+ jest.mocked(metricsAttributeValuesRetrieve).mockReset()+ })++ it('loads metric names once and filters them while the user types', async () => {+ jest.mocked(metricsNamesRetrieve).mockResolvedValue({+ results: [+ { name: 'http.server.duration', metric_type: 'histogram' },+ { name: 'queue_depth', metric_type: 'gauge' },+ ],+ })+ const source = createMetricsPromQLCompletionSource('1')++ expect(await source.metricNames('HTTP')).toEqual([{ name: 'http.server.duration', type: 'histogram' }])+ expect(await source.metricNames('queue')).toEqual([{ name: 'queue_depth', type: 'gauge' }])+ expect(metricsNamesRetrieve).toHaveBeenCalledTimes(1)+ expect(source.metricNamesSearchedOnServer?.()).toBe(false)+ })++ it('asks for the labels of the histogram behind a bucket series, and adds le', async () => {+ jest.mocked(metricsAttributesRetrieve).mockResolvedValue({+ results: [+ { name: 'service.name', value_count: 2 },+ { name: 'http.route', value_count: 5 },+ ],+ count: 2,+ })+ const source = createMetricsPromQLCompletionSource('1')++ expect(await source.labelNames('http.server.duration_bucket', '')).toEqual(['service_name', 'le', 'http.route'])+ expect(metricsAttributesRetrieve).toHaveBeenCalledWith('1', { limit: 100, metricName: 'http.server.duration' })+ })++ it('does not cache a failed request', async () => {+ jest.mocked(metricsAttributeValuesRetrieve)+ .mockRejectedValueOnce(new Error('down'))+ .mockResolvedValueOnce({ results: [{ id: 'api', name: 'api', count: 3 }] })+ const source = createMetricsPromQLCompletionSource('1')++ await expect(source.labelValues('service_name', undefined, '')).rejects.toThrow('down')+ expect(await source.labelValues('service_name', undefined, '')).toEqual(['api'])+ })+})diff --git a/products/metrics/frontend/queryLanguages/promqlCompletionSource.ts b/products/metrics/frontend/queryLanguages/promqlCompletionSource.tsnew file mode 100644index 000000000000..5478ff64a28d--- /dev/null+++ b/products/metrics/frontend/queryLanguages/promqlCompletionSource.ts@@ -0,0 +1,86 @@+import {+ metricsAttributeValuesRetrieve,+ metricsAttributesRetrieve,+ metricsNamesRetrieve,+} from 'products/metrics/frontend/generated/api'++import type { PromQLCompletionSource, PromQLMetricName } from './promqlCompletion'++const CACHE_TTL_MS = 60_000+const LIMIT = 100+// The most names the API returns in one request.+const NAMES_PAGE = 1000+// Every series carries the service name, and Snuffle exposes it under this label.+const SERVICE_LABEL = 'service_name'+// Snuffle's virtual series of histogram buckets: `<name>_bucket` with an `le` label.+const BUCKET_SUFFIX = '_bucket'++/** Suggestions from the metrics API, cached briefly so each keystroke does not refetch the same list. */+export function createMetricsPromQLCompletionSource(projectId: string): PromQLCompletionSource {+ const cache = new Map<string, { at: number; value: Promise<unknown> }>()+ const cached = <T>(key: string, load: () => Promise<T>): Promise<T> => {+ const hit = cache.get(key)+ if (hit && Date.now() - hit.at < CACHE_TTL_MS) {+ return hit.value as Promise<T>+ }+ const value = load()+ cache.set(key, { at: Date.now(), value })+ // A failed request must not stay cached.+ value.catch(() => cache.delete(key))+ return value+ }+ const fetchNames = async (search: string): Promise<PromQLMetricName[]> => {+ const response = await metricsNamesRetrieve(projectId, {+ limit: NAMES_PAGE,+ ...(search ? { value: search } : {}),+ })+ return response.results.map((result) => ({ name: result.name, type: result.metric_type }))+ }+ const baseMetricName = (metricName: string | undefined): string | undefined =>+ metricName?.endsWith(BUCKET_SUFFIX) ? metricName.slice(0, -BUCKET_SUFFIX.length) : metricName++ let namesSearchedOnServer = false++ return {+ metricNamesSearchedOnServer: () => namesSearchedOnServer,+ metricNames: async (search) => {+ // Like Grafana, load the names once and filter here, so typing does not wait on the network.+ // A team with more names than one page gets a server-side search instead.+ const all = await cached('names', () => fetchNames(''))+ namesSearchedOnServer = all.length >= NAMES_PAGE+ if (!namesSearchedOnServer) {+ const needle = search.toLowerCase()+ return all.filter((metric) => metric.name.toLowerCase().includes(needle))+ }+ return search ? cached(`names:${search}`, () => fetchNames(search)) : all+ },+ labelNames: (metricName, search) =>+ cached(`labels:${metricName ?? ''}:${search}`, async () => {+ const metric = baseMetricName(metricName)+ const response = await metricsAttributesRetrieve(projectId, {+ limit: LIMIT,+ ...(metric ? { metricName: metric } : {}),+ ...(search ? { search } : {}),+ })+ const names = response.results+ .map((result) => result.name)+ .filter((name) => name !== 'service.name' && name !== SERVICE_LABEL)+ const extra = [+ ...(SERVICE_LABEL.includes(search) ? [SERVICE_LABEL] : []),+ ...(metricName?.endsWith(BUCKET_SUFFIX) && 'le'.includes(search) ? ['le'] : []),+ ]+ return [...extra, ...names]+ }),+ labelValues: (labelName, _metricName, search) =>+ labelName === 'le' || labelName === '__name__'+ ? Promise.resolve([])+ : cached(`values:${labelName}:${search}`, async () => {+ const response = await metricsAttributeValuesRetrieve(projectId, {+ key: labelName,+ limit: LIMIT,+ ...(search ? { value: search } : {}),+ })+ return response.results.map((result) => result.name)+ }),+ }+}diff --git a/products/metrics/frontend/queryLanguages/promqlParser.ts b/products/metrics/frontend/queryLanguages/promqlParser.tsnew file mode 100644index 000000000000..d8423fa0e019--- /dev/null+++ b/products/metrics/frontend/queryLanguages/promqlParser.ts@@ -0,0 +1,635 @@+/**+ * A PromQL parser for converting between the metrics builder and PromQL.+ *+ * It accepts the Prometheus 3 grammar that Snuffle accepts for the queries the builder can describe,+ * plus the constructs a user is likely to paste (offset, `@`, subqueries, vector matching), so a+ * conversion can say which part it drops instead of failing to parse. Quoted UTF-8 metric and label+ * names (`{"http.server.duration", "http.route"="/"}`) are supported because OTel names contain dots.+ */++export type MatchOp = '=' | '!=' | '=~' | '!~'++export interface Matcher {+ label: string+ op: MatchOp+ value: string+}++export interface VectorMatching {+ card: 'one-to-one' | 'many-to-one' | 'one-to-many'+ /** `on (...)` when true, `ignoring (...)` when false. */+ on: boolean+ labels: string[]+ /** Labels listed in `group_left (...)` / `group_right (...)`. */+ include: string[]+}++export type PromExpr =+ | { type: 'number'; value: number }+ | { type: 'string'; value: string }+ | {+ type: 'selector'+ name: string | null+ matchers: Matcher[]+ /** Range in the source form, e.g. `5m`. */+ range?: string+ offset?: string+ at?: string+ }+ | { type: 'subquery'; expr: PromExpr; range: string; step?: string; offset?: string; at?: string }+ | { type: 'call'; func: string; args: PromExpr[] }+ | {+ type: 'aggregate'+ op: string+ param?: PromExpr+ expr: PromExpr+ grouping?: { without: boolean; labels: string[] }+ }+ | { type: 'binary'; op: string; lhs: PromExpr; rhs: PromExpr; bool?: boolean; matching?: VectorMatching }+ | { type: 'unary'; op: '-' | '+'; expr: PromExpr }+ | { type: 'paren'; expr: PromExpr }+ | { type: 'offset'; expr: PromExpr; offset: string }++export class PromQLParseError extends Error {+ constructor(+ message: string,+ public position: number+ ) {+ super(`${message} at position ${position}`)+ this.name = 'PromQLParseError'+ }+}++type TokenKind = 'number' | 'duration' | 'string' | 'ident' | 'op' | 'eof'++interface Token {+ kind: TokenKind+ value: string+ pos: number+}++export const AGGREGATION_OPS = new Set([+ 'sum',+ 'avg',+ 'count',+ 'min',+ 'max',+ 'stddev',+ 'stdvar',+ 'topk',+ 'bottomk',+ 'quantile',+ 'count_values',+ 'group',+ 'limitk',+ 'limit_ratio',+ 'median',+])+const PARAM_AGGREGATION_OPS = new Set(['topk', 'bottomk', 'quantile', 'count_values', 'limitk', 'limit_ratio'])++const DURATION_RE = /^(\d+(\.\d+)?(ms|s|m|h|d|w|y|i))+/+const NUMBER_RE = /^(0x[0-9a-fA-F]+|(\d+\.?\d*|\.\d+)([eE][+-]?\d+)?)/+// Names may contain colons (recording rules) but do not start with one, so `[5m:30s]` stays a subquery.+const IDENT_RE = /^[a-zA-Z_][a-zA-Z0-9_:]*/+// Longest operators first, so `=~` is not read as `=` then `~`.+const OPERATORS = [+ '==',+ '!=',+ '>=',+ '<=',+ '=~',+ '!~',+ '+',+ '-',+ '*',+ '/',+ '%',+ '^',+ '>',+ '<',+ '=',+ '(',+ ')',+ '{',+ '}',+ '[',+ ']',+ ',',+ ':',+ '@',+]++const STRING_ESCAPES: Record<string, string> = {+ a: '\x07',+ b: '\b',+ f: '\f',+ n: '\n',+ r: '\r',+ t: '\t',+ v: '\v',+ '\\': '\\',+ '"': '"',+ "'": "'",+ '`': '`',+}++/** Reads the body of a quoted string that starts at `start`, with the Go escapes the Prometheus lexer accepts.+ * \x and octal escapes are bytes, so a run of them decodes as UTF-8. An unknown escape keeps its backslash. */+function readQuotedString(input: string, start: number): { value: string; end: number } {+ const quote = input[start]+ let value = ''+ let bytes: number[] = []+ const flushBytes = (): void => {+ if (bytes.length) {+ value += new TextDecoder().decode(new Uint8Array(bytes))+ bytes = []+ }+ }+ let j = start + 1+ while (j < input.length && input[j] !== quote) {+ if (input[j] !== '\\' || quote === '`') {+ flushBytes()+ value += input[j]+ j+++ continue+ }+ const next = input[j + 1]+ const hex = input.slice(j + 2, j + 4)+ const octal = input.slice(j + 1, j + 4)+ if (next === 'x' && /^[0-9a-fA-F]{2}$/.test(hex)) {+ bytes.push(parseInt(hex, 16))+ j += 4+ continue+ }+ if (/^[0-3][0-7]{2}$/.test(octal)) {+ bytes.push(parseInt(octal, 8))+ j += 4+ continue+ }+ flushBytes()+ const digits = next === 'u' ? 4 : next === 'U' ? 8 : 0+ const codePoint = digits ? input.slice(j + 2, j + 2 + digits) : ''+ if (digits && new RegExp(`^[0-9a-fA-F]{${digits}}$`).test(codePoint) && parseInt(codePoint, 16) <= 0x10ffff) {+ value += String.fromCodePoint(parseInt(codePoint, 16))+ j += 2 + digits+ continue+ }+ value += next in STRING_ESCAPES ? STRING_ESCAPES[next] : '\\' + next+ j += 2+ }+ flushBytes()+ return { value, end: j }+}++function tokenize(input: string): Token[] {+ const tokens: Token[] = []+ let i = 0+ while (i < input.length) {+ const ch = input[i]+ if (/\s/.test(ch)) {+ i+++ continue+ }+ if (ch === '#') {+ while (i < input.length && input[i] !== '\n') {+ i+++ }+ continue+ }+ const rest = input.slice(i)+ if (ch === '"' || ch === "'" || ch === '`') {+ const { value, end } = readQuotedString(input, i)+ if (end >= input.length) {+ throw new PromQLParseError('Unterminated string', i)+ }+ tokens.push({ kind: 'string', value, pos: i })+ i = end + 1+ continue+ }+ const variable = /^\$\{?(__rate_interval|__interval|__range)\}?/.exec(rest)+ if (variable) {+ // Grafana fills these in; they read as "the step", which is what an omitted range means.+ tokens.push({ kind: 'duration', value: `$${variable[1]}`, pos: i })+ i += variable[0].length+ continue+ }+ const duration = DURATION_RE.exec(rest)+ if (duration && !/^[a-zA-Z0-9_]/.test(rest.slice(duration[0].length))) {+ // A bare number followed by a unit is a duration; `5m` is never a number then an identifier.+ tokens.push({ kind: 'duration', value: duration[0], pos: i })+ i += duration[0].length+ continue+ }+ const number = NUMBER_RE.exec(rest)+ if (number && /[0-9.]/.test(ch)) {+ tokens.push({ kind: 'number', value: number[0], pos: i })+ i += number[0].length+ continue+ }+ const ident = IDENT_RE.exec(rest)+ if (ident) {+ let value = ident[0]+ // Lenient: an OTel name typed without quotes (http.server.duration) reads as one identifier.+ const dotted = /^(\.[a-zA-Z0-9_:]+)+/.exec(rest.slice(value.length))+ if (dotted) {+ value += dotted[0]+ }+ tokens.push({ kind: 'ident', value, pos: i })+ i += value.length+ continue+ }+ const op = OPERATORS.find((candidate) => rest.startsWith(candidate))+ if (op) {+ tokens.push({ kind: 'op', value: op, pos: i })+ i += op.length+ continue+ }+ throw new PromQLParseError(`Unexpected character "${ch}"`, i)+ }+ tokens.push({ kind: 'eof', value: '', pos: input.length })+ return tokens+}++// Binary operator precedence, lowest first. `^` is right-associative.+const BINARY_PRECEDENCE: Record<string, number> = {+ or: 1,+ and: 2,+ unless: 2,+ '==': 3,+ '!=': 3,+ '<=': 3,+ '<': 3,+ '>=': 3,+ '>': 3,+ '+': 4,+ '-': 4,+ '*': 5,+ '/': 5,+ '%': 5,+ atan2: 5,+ '^': 6,+}+export const COMPARISON_OPS = new Set(['==', '!=', '<=', '<', '>=', '>'])+export const SET_OPS = new Set(['and', 'or', 'unless'])++export function binaryPrecedence(op: string): number {+ return BINARY_PRECEDENCE[op] ?? 0+}++class Parser {+ private index = 0++ constructor(private tokens: Token[]) {}++ private peek(offset = 0): Token {+ return this.tokens[Math.min(this.index + offset, this.tokens.length - 1)]+ }++ private next(): Token {+ const token = this.peek()+ this.index+++ return token+ }++ private isOp(value: string, offset = 0): boolean {+ const token = this.peek(offset)+ return token.kind === 'op' && token.value === value+ }++ private isKeyword(value: string): boolean {+ const token = this.peek()+ return token.kind === 'ident' && token.value.toLowerCase() === value+ }++ private expectOp(value: string): Token {+ const token = this.next()+ if (token.kind !== 'op' || token.value !== value) {+ throw new PromQLParseError(`Expected "${value}" but found "${token.value || 'end of query'}"`, token.pos)+ }+ return token+ }++ parse(): PromExpr {+ const expr = this.parseBinary(0)+ const token = this.peek()+ if (token.kind !== 'eof') {+ throw new PromQLParseError(`Unexpected "${token.value}"`, token.pos)+ }+ return expr+ }++ private binaryOperator(): string | null {+ const token = this.peek()+ if (token.kind === 'op' && token.value in BINARY_PRECEDENCE) {+ return token.value+ }+ if (token.kind === 'ident' && ['and', 'or', 'unless', 'atan2'].includes(token.value.toLowerCase())) {+ return token.value.toLowerCase()+ }+ return null+ }++ private parseBinary(minPrecedence: number): PromExpr {+ let lhs = this.parseUnary()+ for (;;) {+ const op = this.binaryOperator()+ if (!op || binaryPrecedence(op) < minPrecedence) {+ return lhs+ }+ this.next()+ let bool = false+ if (this.isKeyword('bool')) {+ this.next()+ bool = true+ }+ const matching = this.parseVectorMatching()+ const nextMin = op === '^' ? binaryPrecedence(op) : binaryPrecedence(op) + 1+ const rhs = this.parseBinary(nextMin)+ lhs = {+ type: 'binary',+ op,+ lhs,+ rhs,+ ...(bool ? { bool } : {}),+ ...(matching ? { matching } : {}),+ }+ }+ }++ private parseVectorMatching(): VectorMatching | undefined {+ if (!this.isKeyword('on') && !this.isKeyword('ignoring')) {+ return undefined+ }+ const on = this.next().value.toLowerCase() === 'on'+ const labels = this.parseLabelList()+ const matching: VectorMatching = { card: 'one-to-one', on, labels, include: [] }+ if (this.isKeyword('group_left') || this.isKeyword('group_right')) {+ matching.card = this.next().value.toLowerCase() === 'group_left' ? 'many-to-one' : 'one-to-many'+ if (this.isOp('(')) {+ matching.include = this.parseLabelList()+ }+ }+ return matching+ }++ private parseLabelList(): string[] {+ this.expectOp('(')+ const labels: string[] = []+ while (!this.isOp(')')) {+ const token = this.next()+ if (token.kind !== 'ident' && token.kind !== 'string') {+ throw new PromQLParseError(`Expected a label name but found "${token.value}"`, token.pos)+ }+ labels.push(token.value)+ if (!this.isOp(',')) {+ break+ }+ this.next()+ }+ this.expectOp(')')+ return labels+ }++ private parseUnary(): PromExpr {+ if (this.isOp('-') || this.isOp('+')) {+ const op = this.next().value as '-' | '+'+ // Unary binds tighter than * but looser than ^, as in Prometheus: -2^2 is -(2^2).+ const expr = this.parseBinary(binaryPrecedence('^'))+ if (expr.type === 'number') {+ return { type: 'number', value: op === '-' ? -expr.value : expr.value }+ }+ return { type: 'unary', op, expr }+ }+ return this.parsePostfix(this.parsePrimary())+ }++ private parsePostfix(expr: PromExpr): PromExpr {+ for (;;) {+ if (this.isOp('[')) {+ const open = this.next()+ const range = this.expectDuration()+ if (this.isOp(':')) {+ this.next()+ const step = this.peek().kind === 'duration' ? this.expectDuration() : undefined+ this.expectOp(']')+ expr = { type: 'subquery', expr, range, ...(step ? { step } : {}) }+ continue+ }+ this.expectOp(']')+ if (expr.type !== 'selector' || expr.range) {+ throw new PromQLParseError('A range can only follow a selector', open.pos)+ }+ expr = { ...expr, range }+ continue+ }+ if (this.isKeyword('offset')) {+ this.next()+ const negative = this.isOp('-') ? (this.next(), '-') : ''+ const offset = negative + this.expectDuration()+ expr = expr.type === 'selector' ? { ...expr, offset } : { type: 'offset', expr, offset }+ continue+ }+ if (this.isOp('@')) {+ const atToken = this.next()+ if (expr.type !== 'selector' && expr.type !== 'subquery') {+ throw new PromQLParseError('The @ modifier can only follow a selector or a subquery', atToken.pos)+ }+ const token = this.next()+ let at = token.value+ if (token.kind === 'ident') {+ this.expectOp('(')+ this.expectOp(')')+ at += '()'+ }+ expr = { ...expr, at }+ continue+ }+ return expr+ }+ }++ private expectDuration(): string {+ const token = this.next()+ if (token.kind === 'duration' || token.kind === 'number') {+ return token.value+ }+ throw new PromQLParseError(`Expected a duration but found "${token.value}"`, token.pos)+ }++ private parsePrimary(): PromExpr {+ const token = this.peek()+ if (token.kind === 'number') {+ this.next()+ return { type: 'number', value: Number(token.value) }+ }+ if (token.kind === 'duration') {+ // Durations without units are numbers; with units they are seconds, as in PromQL arithmetic.+ this.next()+ return { type: 'number', value: durationToSeconds(token.value) }+ }+ if (token.kind === 'string') {+ this.next()+ return { type: 'string', value: token.value }+ }+ if (this.isOp('(')) {+ this.next()+ const expr = this.parseBinary(0)+ this.expectOp(')')+ return { type: 'paren', expr }+ }+ if (this.isOp('{')) {+ return this.parseSelector(null)+ }+ if (token.kind === 'ident') {+ const lower = token.value.toLowerCase()+ if (lower === 'inf' || lower === 'nan') {+ this.next()+ return { type: 'number', value: lower === 'inf' ? Infinity : NaN }+ }+ if (AGGREGATION_OPS.has(lower) && (this.isOp('(', 1) || this.isGroupingKeyword(1))) {+ return this.parseAggregate()+ }+ if (this.isOp('(', 1)) {+ return this.parseCall()+ }+ this.next()+ return this.parseSelector(token.value)+ }+ throw new PromQLParseError(`Unexpected "${token.value || 'end of query'}"`, token.pos)+ }++ private isGroupingKeyword(offset: number): boolean {+ const token = this.peek(offset)+ return token.kind === 'ident' && ['by', 'without'].includes(token.value.toLowerCase())+ }++ private parseGrouping(): { without: boolean; labels: string[] } {+ const without = this.next().value.toLowerCase() === 'without'+ return { without, labels: this.parseLabelList() }+ }++ private parseAggregate(): PromExpr {+ const op = this.next().value.toLowerCase()+ let grouping = this.isGroupingKeyword(0) ? this.parseGrouping() : undefined+ this.expectOp('(')+ const args: PromExpr[] = []+ while (!this.isOp(')')) {+ args.push(this.parseBinary(0))+ if (!this.isOp(',')) {+ break+ }+ this.next()+ }+ const close = this.expectOp(')')+ if (!grouping && this.isGroupingKeyword(0)) {+ grouping = this.parseGrouping()+ }+ const hasParam = PARAM_AGGREGATION_OPS.has(op)+ if (args.length !== (hasParam ? 2 : 1) && op !== 'median') {+ throw new PromQLParseError(`${op} expects ${hasParam ? 2 : 1} argument(s)`, close.pos)+ }+ return {+ type: 'aggregate',+ op,+ ...(hasParam ? { param: args[0] } : {}),+ expr: hasParam ? args[1] : args[0],+ ...(grouping ? { grouping } : {}),+ }+ }++ private parseCall(): PromExpr {+ const func = this.next().value+ this.expectOp('(')+ const args: PromExpr[] = []+ while (!this.isOp(')')) {+ args.push(this.parseBinary(0))+ if (!this.isOp(',')) {+ break+ }+ this.next()+ }+ this.expectOp(')')+ return { type: 'call', func, args }+ }++ private parseSelector(name: string | null): PromExpr {+ const matchers: Matcher[] = []+ if (this.isOp('{')) {+ this.next()+ while (!this.isOp('}')) {+ const labelToken = this.next()+ if (labelToken.kind !== 'ident' && labelToken.kind !== 'string') {+ throw new PromQLParseError(`Expected a label name but found "${labelToken.value}"`, labelToken.pos)+ }+ // A lone quoted string inside braces is the Prometheus 3 form of the metric name.+ if (labelToken.kind === 'string' && (this.isOp(',') || this.isOp('}'))) {+ if (name !== null) {+ throw new PromQLParseError('A selector can only have one metric name', labelToken.pos)+ }+ name = labelToken.value+ } else {+ const opToken = this.next()+ if (opToken.kind !== 'op' || !['=', '!=', '=~', '!~'].includes(opToken.value)) {+ throw new PromQLParseError(`Expected a label matcher but found "${opToken.value}"`, opToken.pos)+ }+ const valueToken = this.next()+ if (valueToken.kind !== 'string') {+ throw new PromQLParseError('A label value must be a quoted string', valueToken.pos)+ }+ matchers.push({ label: labelToken.value, op: opToken.value as MatchOp, value: valueToken.value })+ }+ if (!this.isOp(',')) {+ break+ }+ this.next()+ }+ this.expectOp('}')+ }+ if (name === null && matchers.length === 0) {+ throw new PromQLParseError('A selector needs a metric name or a label matcher', this.peek().pos)+ }+ // `{__name__="x"}` and `x{}` are the same selector; keep one form so they compare equal.+ const nameMatcher = name === null ? matchers.findIndex((m) => m.label === '__name__' && m.op === '=') : -1+ if (nameMatcher >= 0) {+ name = matchers[nameMatcher].value+ matchers.splice(nameMatcher, 1)+ }+ return { type: 'selector', name, matchers }+ }+}++const DURATION_UNITS: Record<string, number> = {+ ms: 0.001,+ s: 1,+ m: 60,+ h: 3600,+ d: 86400,+ w: 604800,+ y: 31536000,+}++/** Seconds in a PromQL duration such as `1h30m`. Step units (`4i`) and unitless values are read as seconds. */+export function durationToSeconds(duration: string): number {+ let total = 0+ let matched = false+ for (const match of duration.matchAll(/(\d+(?:\.\d+)?)(ms|s|m|h|d|w|y|i)?/g)) {+ if (!match[0]) {+ continue+ }+ matched = true+ total += Number(match[1]) * (match[2] && match[2] !== 'i' ? DURATION_UNITS[match[2]] : 1)+ }+ return matched ? total : NaN+}++export function parsePromQL(input: string): PromExpr {+ return new Parser(tokenize(input)).parse()+}++/** Removes redundant parentheses so structural matching does not have to look through them. */+export function unwrapParens(expr: PromExpr): PromExpr {+ while (expr.type === 'paren') {+ expr = expr.expr+ }+ return expr+}diff --git a/products/metrics/frontend/queryLanguages/promqlPrinter.ts b/products/metrics/frontend/queryLanguages/promqlPrinter.tsnew file mode 100644index 000000000000..67b1d2cfad5a--- /dev/null+++ b/products/metrics/frontend/queryLanguages/promqlPrinter.ts@@ -0,0 +1,127 @@+import { type Matcher, type PromExpr, binaryPrecedence } from './promqlParser'+import { plainNumber } from './types'++const LEGACY_METRIC_NAME = /^[a-zA-Z_:][a-zA-Z0-9_:]*$/+const LEGACY_LABEL_NAME = /^[a-zA-Z_][a-zA-Z0-9_]*$/++export function quotePromString(value: string): string {+ return JSON.stringify(value)+}++/** A label name as PromQL needs it: bare when it is a legacy name, quoted (Prometheus 3) otherwise. */+export function printLabelName(label: string): string {+ return LEGACY_LABEL_NAME.test(label) ? label : quotePromString(label)+}++function printMatcher(matcher: Matcher): string {+ return `${printLabelName(matcher.label)}${matcher.op}${quotePromString(matcher.value)}`+}++function printSelector(expr: Extract<PromExpr, { type: 'selector' }>): string {+ const matchers = expr.matchers.map(printMatcher)+ let out: string+ if (expr.name !== null && LEGACY_METRIC_NAME.test(expr.name)) {+ out = expr.name + (matchers.length ? `{${matchers.join(', ')}}` : '')+ } else if (expr.name !== null) {+ out = `{${[quotePromString(expr.name), ...matchers].join(', ')}}`+ } else {+ out = `{${matchers.join(', ')}}`+ }+ if (expr.range) {+ out += `[${expr.range}]`+ }+ if (expr.offset) {+ out += ` offset ${expr.offset}`+ }+ if (expr.at) {+ out += ` @ ${expr.at}`+ }+ return out+}++function printNumber(value: number): string {+ if (Number.isNaN(value)) {+ return 'NaN'+ }+ if (!Number.isFinite(value)) {+ return value > 0 ? 'Inf' : '-Inf'+ }+ return plainNumber(value)+}++function printLabelList(labels: string[]): string {+ return `(${labels.map(printLabelName).join(', ')})`+}++// Precedence of an expression as an operand, so the printer adds only the parentheses it needs.+function precedenceOf(expr: PromExpr): number {+ if (expr.type === 'binary') {+ return binaryPrecedence(expr.op)+ }+ if (expr.type === 'unary') {+ return binaryPrecedence('^') - 0.5+ }+ if (expr.type === 'number' && expr.value < 0) {+ return binaryPrecedence('^') - 0.5+ }+ return Infinity+}++function printOperand(expr: PromExpr, parentPrecedence: number, right: boolean, parentOp: string): string {+ const precedence = precedenceOf(expr)+ const rightAssociative = parentOp === '^'+ const needsParens =+ precedence < parentPrecedence ||+ (precedence === parentPrecedence && (rightAssociative ? !right : right) && expr.type === 'binary')+ const printed = printPromQL(expr)+ return needsParens ? `(${printed})` : printed+}++export function printPromQL(expr: PromExpr): string {+ switch (expr.type) {+ case 'number':+ return printNumber(expr.value)+ case 'string':+ return quotePromString(expr.value)+ case 'selector':+ return printSelector(expr)+ case 'paren':+ return `(${printPromQL(expr.expr)})`+ case 'unary':+ return `${expr.op}${printOperand(expr.expr, binaryPrecedence('^'), false, '')}`+ case 'offset':+ return `${printOperand(expr.expr, Infinity, false, '')} offset ${expr.offset}`+ case 'subquery':+ return `${printOperand(expr.expr, Infinity, false, '')}[${expr.range}:${expr.step ?? ''}]${+ expr.offset ? ` offset ${expr.offset}` : ''+ }${expr.at ? ` @ ${expr.at}` : ''}`+ case 'call':+ return `${expr.func}(${expr.args.map(printPromQL).join(', ')})`+ case 'aggregate': {+ const grouping = expr.grouping+ ? ` ${expr.grouping.without ? 'without' : 'by'} ${printLabelList(expr.grouping.labels)}`+ : ''+ const args = [...(expr.param ? [printPromQL(expr.param)] : []), printPromQL(expr.expr)]+ return `${expr.op}${grouping}${grouping ? ' ' : ''}(${args.join(', ')})`+ }+ case 'binary': {+ const precedence = binaryPrecedence(expr.op)+ let modifiers = expr.bool ? ' bool' : ''+ if (expr.matching) {+ modifiers += ` ${expr.matching.on ? 'on' : 'ignoring'}${printLabelList(expr.matching.labels)}`+ if (expr.matching.card !== 'one-to-one') {+ modifiers += ` ${expr.matching.card === 'many-to-one' ? 'group_left' : 'group_right'}`+ if (expr.matching.include.length) {+ modifiers += printLabelList(expr.matching.include)+ }+ }+ }+ return `${printOperand(expr.lhs, precedence, false, expr.op)} ${expr.op}${modifiers} ${printOperand(+ expr.rhs,+ precedence,+ true,+ expr.op+ )}`+ }+ }+}diff --git a/products/metrics/frontend/queryLanguages/promqlToBuilder.ts b/products/metrics/frontend/queryLanguages/promqlToBuilder.tsnew file mode 100644index 000000000000..a8a6c08cea9b--- /dev/null+++ b/products/metrics/frontend/queryLanguages/promqlToBuilder.ts@@ -0,0 +1,426 @@+import type { MetricsQueryFilter } from '~/queries/schema/schema-general'++import { COMPARISON_OPS, type PromExpr, PromQLParseError, SET_OPS, parsePromQL, unwrapParens } from './promqlParser'+import { printPromQL } from './promqlPrinter'+import { promRegexToBuilderRegex } from './regex'+import {+ type BuilderClause,+ type BuilderQuery,+ CLAUSE_LABEL,+ type ConversionResult,+ ENGINE_QUANTILE,+ MAX_CONVERTED_CLAUSES,+ clauseAlias,+ plainNumber,+} from './types'++type ClauseShape = Omit<BuilderClause, 'name'>+type SelectorExpr = Extract<PromExpr, { type: 'selector' }>++const MATCH_OP_TO_FILTER_OP: Record<string, MetricsQueryFilter['op']> = {+ '=': 'eq',+ '!=': 'neq',+ '=~': 'regex',+ '!~': 'not_regex',+}+const SIMPLE_AGGREGATIONS = new Set(['sum', 'avg', 'min', 'max', 'count'])+const COUNTER_FUNCTIONS = new Set(['rate', 'increase', 'irate'])+const FORMULA_OPS = new Set(['+', '-', '*', '/'])+// These keep or drop whole series rather than combine them.+const SELECTION_AGGREGATIONS = new Set(['topk', 'bottomk', 'limitk', 'limit_ratio'])++class ClauseReader {+ constructor(private issues: string[]) {}++ private note(issue: string): void {+ if (!this.issues.includes(issue)) {+ this.issues.push(issue)+ }+ }++ /** Metric name and label filters of a selector. */+ private selectorFields(selector: SelectorExpr): Pick<ClauseShape, 'metricName' | 'filters'> | null {+ let metricName = selector.name+ const filters: MetricsQueryFilter[] = []+ for (const matcher of selector.matchers) {+ if (matcher.label === '__name__') {+ if (matcher.op === '=' && metricName === null) {+ metricName = matcher.value+ } else {+ this.note(`The metric name matcher __name__${matcher.op}"${matcher.value}" is not supported.`)+ }+ continue+ }+ const op = MATCH_OP_TO_FILTER_OP[matcher.op]+ filters.push({+ key: matcher.label,+ op,+ value: op === 'regex' || op === 'not_regex' ? promRegexToBuilderRegex(matcher.value) : matcher.value,+ })+ }+ if (!metricName) {+ this.note('A selector without a metric name cannot be converted.')+ return null+ }+ if (selector.offset) {+ this.note(`The offset ${selector.offset} is dropped.`)+ }+ if (selector.at) {+ this.note(`The @ ${selector.at} modifier is dropped.`)+ }+ return { metricName, ...(filters.length ? { filters } : {}) }+ }++ private rangeNote(selector: SelectorExpr): void {+ if (selector.range && !['$__rate_interval', '$__interval'].includes(selector.range)) {+ this.note(`The range [${selector.range}] is replaced by the chart interval.`)+ }+ }++ private groupBy(grouping: { without: boolean; labels: string[] } | undefined): Pick<ClauseShape, 'groupBy'> {+ if (!grouping) {+ return {}+ }+ if (grouping.without) {+ this.note(`"without (${grouping.labels.join(', ')})" is not supported; the series are not grouped.`)+ return {}+ }+ return grouping.labels.length ? { groupBy: grouping.labels.map((key) => ({ key })) } : {}+ }++ /** A counter function over a selector, such as `rate(x[5m])`. */+ private counterCall(expr: PromExpr): { rangeFunction: 'rate' | 'increase'; selector: SelectorExpr } | null {+ expr = unwrapParens(expr)+ if (expr.type !== 'call' || !COUNTER_FUNCTIONS.has(expr.func) || expr.args.length !== 1) {+ return null+ }+ let arg = unwrapParens(expr.args[0])+ if (arg.type === 'subquery' && unwrapParens(arg.expr).type === 'selector') {+ this.note(`The subquery [${arg.range}:${arg.step ?? ''}] is dropped.`)+ arg = unwrapParens(arg.expr)+ }+ if (arg.type !== 'selector') {+ return null+ }+ if (expr.func === 'irate') {+ this.note('irate() becomes rate() over each chart interval.')+ }+ this.rangeNote(arg)+ return { rangeFunction: expr.func === 'increase' ? 'increase' : 'rate', selector: arg }+ }++ private numberParam(param: PromExpr | undefined): number | null {+ const value = param ? unwrapParens(param) : undefined+ return value?.type === 'number' && value.value > 0 && value.value < 1 ? value.value : null+ }++ read(expr: PromExpr): ClauseShape | null {+ expr = unwrapParens(expr)+ switch (expr.type) {+ case 'selector': {+ this.rangeNote(expr)+ // Without an aggregation, each series is its own line, as in the builder.+ return this.selectorFields(expr)+ }+ case 'offset':+ this.note(`The offset ${expr.offset} is dropped.`)+ return this.read(expr.expr)+ case 'subquery':+ this.note(`The subquery [${expr.range}:${expr.step ?? ''}] is dropped.`)+ if (expr.at) {+ this.note(`The @ ${expr.at} modifier is dropped.`)+ }+ return this.read(expr.expr)+ case 'aggregate':+ return this.readAggregate(expr)+ case 'call':+ return this.readCall(expr)+ default:+ return null+ }+ }++ private readAggregate(expr: Extract<PromExpr, { type: 'aggregate' }>): ClauseShape | null {+ const inner = unwrapParens(expr.expr)+ const groupBy = this.groupBy(expr.grouping)++ if (SELECTION_AGGREGATIONS.has(expr.op)) {+ this.note(`${expr.op}() is dropped; every series is shown.`)+ return this.read(inner)+ }++ if (expr.op === 'quantile' || expr.op === 'median') {+ const quantile = expr.op === 'median' ? 0.5 : this.numberParam(expr.param)+ if (quantile !== ENGINE_QUANTILE) {+ this.note(`Metrics support only quantile ${ENGINE_QUANTILE}; ${expr.op}() uses it.`)+ }+ const counter = inner.type === 'selector' ? null : this.counterCall(inner)+ const selector = inner.type === 'selector' ? inner : counter?.selector+ if (selector) {+ this.rangeNote(selector)+ const fields = this.selectorFields(selector)+ return (+ fields && {+ ...fields,+ aggregation: 'quantile',+ quantile: ENGINE_QUANTILE,+ ...(counter ? { rangeFunction: counter.rangeFunction } : {}),+ ...groupBy,+ }+ )+ }+ this.note(`Only a plain selector or rate() can be inside ${expr.op}(); the inner function is dropped.`)+ const clause = this.read(inner)+ return clause && { ...clause, aggregation: 'quantile', quantile: ENGINE_QUANTILE, ...groupBy }+ }++ if (!SIMPLE_AGGREGATIONS.has(expr.op)) {+ this.note(`${expr.op}() is not supported; it becomes sum().`)+ }+ const op = SIMPLE_AGGREGATIONS.has(expr.op) ? (expr.op as ClauseShape['aggregation']) : 'sum'++ if (inner.type === 'selector') {+ this.rangeNote(inner)+ const fields = this.selectorFields(inner)+ return fields && { ...fields, aggregation: op, ...groupBy }+ }++ const counter = this.counterCall(inner)+ if (counter) {+ const fields = this.selectorFields(counter.selector)+ return fields && { ...fields, aggregation: op, rangeFunction: counter.rangeFunction, ...groupBy }+ }++ const nested = this.read(inner)+ if (!nested) {+ return null+ }+ if (!nested.aggregation) {+ // The inner part kept each series, so this aggregation combines them.+ return { ...nested, aggregation: op, ...groupBy }+ }+ this.note(`${expr.op}() over another aggregation is not supported; only the inner aggregation is kept.`)+ const { groupBy: _innerGroupBy, ...rest } = nested+ return { ...rest, ...groupBy }+ }++ private readCall(expr: Extract<PromExpr, { type: 'call' }>): ClauseShape | null {+ if (expr.func === 'histogram_quantile' && expr.args.length === 2) {+ return this.readHistogramQuantile(expr.args[0], expr.args[1])+ }+ const counter = this.counterCall(expr)+ if (counter) {+ // Without an aggregation, the range function applies to each series, which stays its own line.+ const fields = this.selectorFields(counter.selector)+ return fields && { ...fields, rangeFunction: counter.rangeFunction }+ }+ const vectorArg = expr.args.find((arg) => !['number', 'string'].includes(unwrapParens(arg).type))+ this.note(`${expr.func}() is not supported and is dropped.`)+ return vectorArg ? this.read(vectorArg) : null+ }++ private readHistogramQuantile(param: PromExpr, buckets: PromExpr): ClauseShape | null {+ const quantile = this.numberParam(param)+ if (quantile === null) {+ this.note('histogram_quantile() needs a number between 0 and 1; 0.95 is used.')+ }+ buckets = unwrapParens(buckets)+ let groupBy: Pick<ClauseShape, 'groupBy'> = {}+ let counterExpr: PromExpr = buckets+ if (buckets.type === 'aggregate') {+ if (buckets.op !== 'sum') {+ this.note(`histogram_quantile() over ${buckets.op}() is read as over sum().`)+ }+ const labels = buckets.grouping && !buckets.grouping.without ? buckets.grouping.labels : []+ if (!labels.includes('le')) {+ this.note('The buckets are not grouped by "le", so the quantile can differ.')+ }+ groupBy = this.groupBy(+ buckets.grouping && { ...buckets.grouping, labels: labels.filter((label) => label !== 'le') }+ )+ counterExpr = buckets.expr+ } else {+ this.note('histogram_quantile() over buckets that are not summed by "le" adds the buckets of all series.')+ }+ const counter = this.counterCall(counterExpr)+ if (!counter) {+ this.note('histogram_quantile() needs rate() or increase() of a bucket metric.')+ return null+ }+ const fields = this.selectorFields(counter.selector)+ if (!fields) {+ return null+ }+ const metricName = fields.metricName.endsWith('_bucket') ? fields.metricName.slice(0, -7) : fields.metricName+ return { ...fields, metricName, aggregation: 'histogram_quantile', quantile: quantile ?? 0.95, ...groupBy }+ }+}++const clauseKey = (clause: ClauseShape): string => JSON.stringify(clause)++class FormulaBuilder {+ clauses: BuilderClause[] = []+ private aliases = new Map<string, string>()+ private reader: ClauseReader++ constructor(private issues: string[]) {+ this.reader = new ClauseReader(issues)+ }++ private note(issue: string): void {+ if (!this.issues.includes(issue)) {+ this.issues.push(issue)+ }+ }++ addClause(expr: PromExpr, alias?: string): string | null {+ const clause = this.reader.read(expr)+ if (!clause) {+ return null+ }+ const key = clauseKey(clause)+ const existing = this.aliases.get(key)+ if (existing && !alias) {+ return existing+ }+ if (this.clauses.length >= MAX_CONVERTED_CLAUSES) {+ this.note(`A query can have at most ${MAX_CONVERTED_CLAUSES} series; the others are dropped.`)+ return null+ }+ const name = alias ?? clauseAlias(this.clauses.length)+ this.aliases.set(key, name)+ this.clauses.push({ name, ...clause })+ return name+ }++ /** The builder formula for an expression, creating clauses for its vector parts. */+ formula(expr: PromExpr): string | null {+ switch (expr.type) {+ case 'number':+ return Number.isFinite(expr.value) ? plainNumber(expr.value) : null+ case 'paren': {+ const inner = this.formula(expr.expr)+ return inner === null ? null : `(${inner})`+ }+ case 'unary': {+ const inner = this.formula(expr.expr)+ return inner === null ? null : expr.op === '-' ? `-${inner}` : inner+ }+ case 'binary':+ return this.binaryFormula(expr)+ case 'aggregate': {+ const inner = unwrapParens(expr.expr)+ if (inner.type === 'binary' && FORMULA_OPS.has(inner.op) && !expr.param) {+ return this.distributeAggregate(expr, inner)+ }+ return this.addClause(expr)+ }+ default:+ return this.addClause(expr)+ }+ }++ /** `max(a / b)` → `max(a) / max(b)`: the builder aggregates each series before the formula. */+ private distributeAggregate(+ aggregate: Extract<PromExpr, { type: 'aggregate' }>,+ binary: Extract<PromExpr, { type: 'binary' }>+ ): string | null {+ const isNumber = (side: PromExpr): boolean => unwrapParens(side).type === 'number'+ const exact =+ aggregate.op === 'sum' &&+ (['+', '-'].includes(binary.op) ||+ (isNumber(binary.rhs) && ['*', '/'].includes(binary.op)) ||+ (isNumber(binary.lhs) && binary.op === '*'))+ if (!exact) {+ this.note(+ `${aggregate.op}() is applied to each side of "${binary.op}" before the formula, so the result can differ.`+ )+ }+ const wrap = (side: PromExpr): PromExpr => (isNumber(side) ? side : { ...aggregate, expr: side })+ return this.formula({ ...binary, lhs: wrap(binary.lhs), rhs: wrap(binary.rhs) })+ }++ private binaryFormula(expr: Extract<PromExpr, { type: 'binary' }>): string | null {+ if (COMPARISON_OPS.has(expr.op) || SET_OPS.has(expr.op)) {+ this.note(`The "${expr.op} ${printPromQL(expr.rhs)}" part is dropped.`)+ return this.formula(expr.lhs)+ }+ if (!FORMULA_OPS.has(expr.op)) {+ this.note(`The "${expr.op}" operator is not supported; only its left side is kept.`)+ return this.formula(expr.lhs)+ }+ // The builder spreads an ungrouped series over the other side, which is what on() group_x does.+ const broadcast = expr.matching?.on && expr.matching.labels.length === 0 && expr.matching.card !== 'one-to-one'+ if (expr.matching && !broadcast) {+ this.note(+ 'Vector matching (on, ignoring, group_left, group_right) is not supported; series match by all labels.'+ )+ }+ if (expr.bool) {+ this.note('The bool modifier is dropped.')+ }+ const lhs = this.formula(expr.lhs)+ const rhs = this.formula(expr.rhs)+ if (lhs === null || rhs === null) {+ return lhs ?? rhs+ }+ // The parse tree keeps explicit parentheses, so operands print in the order PromQL grouped them.+ return `${lhs} ${expr.op} ${rhs}`+ }+}++/** `label_replace(expr, "clause", "a", "", "")`, the form builderToPromql gives each series of a multi-series query. */+const labelledClause = (expr: PromExpr): { alias: string; expr: PromExpr } | null => {+ expr = unwrapParens(expr)+ if (expr.type !== 'call' || expr.func !== 'label_replace' || expr.args.length !== 5) {+ return null+ }+ const [inner, label, value, source, regex] = expr.args.map(unwrapParens)+ const isString = (arg: PromExpr, expected?: string): arg is Extract<PromExpr, { type: 'string' }> =>+ arg.type === 'string' && (expected === undefined || arg.value === expected)+ if (isString(label, CLAUSE_LABEL) && isString(value) && isString(source, '') && isString(regex, '')) {+ return /^[a-z_][a-z0-9_]*$/.test(value.value) ? { alias: value.value, expr: inner } : null+ }+ return null+}++const orOperands = (expr: PromExpr): PromExpr[] => {+ const unwrapped = unwrapParens(expr)+ return unwrapped.type === 'binary' && unwrapped.op === 'or' && !unwrapped.matching+ ? [...orOperands(unwrapped.lhs), ...orOperands(unwrapped.rhs)]+ : [expr]+}++export function promqlToBuilder(text: string): ConversionResult<BuilderQuery> {+ if (!text.trim()) {+ return { value: { clauses: [] }, issues: [] }+ }+ let parsed: PromExpr+ try {+ parsed = parsePromQL(text)+ } catch (error) {+ const message = error instanceof PromQLParseError ? error.message : String(error)+ return { value: null, issues: [`The PromQL cannot be read: ${message}`] }+ }+ const issues: string[] = []+ const builder = new FormulaBuilder(issues)++ const operands = orOperands(parsed)+ if (operands.length > 1) {+ const labelled = operands.map(labelledClause)+ if (labelled.every((operand) => operand !== null)) {+ labelled.forEach((operand) => builder.addClause(operand!.expr, operand!.alias))+ } else {+ issues.push('Each side of "or" becomes its own series; series with the same labels are not merged.')+ operands.forEach((operand) => builder.addClause(operand))+ }+ return builder.clauses.length ? { value: { clauses: builder.clauses }, issues } : { value: null, issues }+ }++ const formula = builder.formula(parsed)+ if (!builder.clauses.length || formula === null) {+ return { value: null, issues: issues.length ? issues : ['The PromQL has no metric to chart.'] }+ }+ const isSingleAlias = builder.clauses.length === 1 && formula === builder.clauses[0].name+ return { value: { clauses: builder.clauses, ...(isSingleAlias ? {} : { formula }) }, issues }+}diff --git a/products/metrics/frontend/queryLanguages/queryLanguages.test.ts b/products/metrics/frontend/queryLanguages/queryLanguages.test.tsnew file mode 100644index 000000000000..5a3b003b330f--- /dev/null+++ b/products/metrics/frontend/queryLanguages/queryLanguages.test.ts@@ -0,0 +1,1015 @@+import fs from 'fs'+import path from 'path'++import { NodeKind } from '~/queries/schema/schema-general'+import type { MetricsQuery } from '~/queries/schema/schema-general'++import { builderToPromql } from './builderToPromql'+import { builderToSql } from './builderToSql'+import { GENERIC_LOSS_ISSUE, canonicalBuilder, canonicalPromQL, convertMetricsQuery } from './convert'+import { PromQLParseError, parsePromQL } from './promqlParser'+import { printPromQL } from './promqlPrinter'+import { promqlToBuilder } from './promqlToBuilder'+import { builderRegexToPromRegex, promRegexToBuilderRegex } from './regex'+import { sqlToBuilder } from './sqlToBuilder'+import type { BuilderClause, BuilderQuery } from './types'++const clause = (fields: Partial<BuilderClause> & Pick<BuilderClause, 'metricName'>): BuilderClause => ({+ name: 'a',+ aggregation: 'sum',+ ...fields,+})++// Builder queries that every language can hold exactly. Each one must survive builder → PromQL → builder+// and builder → SQL → builder without a reported issue.+export const LOSSLESS_BUILDER_FIXTURES: Record<string, BuilderQuery> = {+ 'gauge sum': { clauses: [clause({ metricName: 'queue_depth' })] },+ 'gauge avg': { clauses: [clause({ metricName: 'process.cpu.utilization', aggregation: 'avg' })] },+ 'gauge min': { clauses: [clause({ metricName: 'free_disk_bytes', aggregation: 'min' })] },+ 'gauge max': { clauses: [clause({ metricName: 'jvm.memory.used', aggregation: 'max' })] },+ 'series count': { clauses: [clause({ metricName: 'up', aggregation: 'count' })] },+ p95: { clauses: [clause({ metricName: 'request_latency_ms', aggregation: 'quantile', quantile: 0.95 })] },+ 'counter rate': {+ clauses: [clause({ metricName: 'http.server.request.count', aggregation: 'sum', rangeFunction: 'rate' })],+ },+ 'legacy increase aggregation': {+ clauses: [clause({ metricName: 'jobs_processed_total', aggregation: 'increase' })],+ },+ 'max of per-series increase by service': {+ clauses: [+ clause({+ metricName: 'jobs_processed_total',+ aggregation: 'max',+ rangeFunction: 'increase',+ groupBy: [{ key: 'service_name' }],+ }),+ ],+ },+ 'count of per-series rate': {+ clauses: [clause({ metricName: 'http.server.request.count', aggregation: 'count', rangeFunction: 'rate' })],+ },+ 'histogram p99': {+ clauses: [clause({ metricName: 'http.server.duration', aggregation: 'histogram_quantile', quantile: 0.99 })],+ },+ 'histogram p50 by service': {+ clauses: [+ clause({+ metricName: 'http.server.duration',+ aggregation: 'histogram_quantile',+ quantile: 0.5,+ groupBy: [{ key: 'service_name' }],+ }),+ ],+ },+ 'eq filter': {+ clauses: [clause({ metricName: 'queue_depth', filters: [{ key: 'service_name', op: 'eq', value: 'api' }] })],+ },+ 'neq filter on dotted key': {+ clauses: [+ clause({+ metricName: 'http.server.request.count',+ aggregation: 'rate',+ filters: [{ key: 'http.request.method', op: 'neq', value: 'OPTIONS' }],+ }),+ ],+ },+ 'multi-value chip regex': {+ clauses: [+ clause({+ metricName: 'queue_depth',+ filters: [{ key: 'service_name', op: 'regex', value: '^(?:api|worker)$' }],+ }),+ ],+ },+ 'unanchored regex': {+ clauses: [clause({ metricName: 'queue_depth', filters: [{ key: 'http.route', op: 'regex', value: 'users' }] })],+ },+ 'prefix regex': {+ clauses: [clause({ metricName: 'queue_depth', filters: [{ key: 'http.route', op: 'regex', value: '^/api' }] })],+ },+ 'suffix not regex': {+ clauses: [+ clause({ metricName: 'queue_depth', filters: [{ key: 'http.route', op: 'not_regex', value: 'health$' }] }),+ ],+ },+ 'empty service pattern': {+ clauses: [clause({ metricName: 'queue_depth', filters: [{ key: 'service_name', op: 'regex', value: '^$' }] })],+ },+ 'value with quotes and backslashes': {+ clauses: [+ clause({+ metricName: 'queue_depth',+ filters: [{ key: 'queue', op: 'eq', value: `it's a "quoted" \\ value` }],+ }),+ ],+ },+ 'several filters': {+ clauses: [+ clause({+ metricName: 'http.server.request.count',+ aggregation: 'increase',+ filters: [+ { key: 'service_name', op: 'eq', value: 'api' },+ { key: 'http.response.status_code', op: 'regex', value: '^5' },+ { key: 'http.route', op: 'neq', value: '/health' },+ ],+ }),+ ],+ },+ 'regex with an escaped dot': {+ clauses: [+ clause({+ metricName: 'build_info',+ aggregation: 'count',+ filters: [{ key: 'version', op: 'regex', value: '^v1\\.2' }],+ }),+ ],+ },+ 'non-ASCII and spaced names': {+ clauses: [+ clause({+ metricName: 'größe_bytes',+ filters: [{ key: 'queue name', op: 'eq', value: 'é' }],+ groupBy: [{ key: 'région' }],+ }),+ ],+ },+ 'group by one': { clauses: [clause({ metricName: 'queue_depth', groupBy: [{ key: 'service_name' }] })] },+ 'group by two dotted': {+ clauses: [+ clause({+ metricName: 'http.server.request.count',+ aggregation: 'rate',+ groupBy: [{ key: 'http.route' }, { key: 'http.request.method' }],+ }),+ ],+ },+ 'error ratio formula': {+ clauses: [+ clause({+ name: 'a',+ metricName: 'http.server.request.count',+ aggregation: 'rate',+ filters: [{ key: 'http.response.status_code', op: 'regex', value: '^5' }],+ }),+ clause({ name: 'b', metricName: 'http.server.request.count', aggregation: 'rate' }),+ ],+ formula: 'a / b * 100',+ },+ 'parenthesized formula': {+ clauses: [+ clause({ name: 'a', metricName: 'queue_depth' }),+ clause({ name: 'b', metricName: 'retry_queue_depth' }),+ ],+ formula: '(a + b) / 2',+ },+ 'grouped formula with the same labels': {+ clauses: [+ clause({+ name: 'a',+ metricName: 'errors_total',+ aggregation: 'increase',+ groupBy: [{ key: 'service_name' }],+ }),+ clause({+ name: 'b',+ metricName: 'requests_total',+ aggregation: 'increase',+ groupBy: [{ key: 'service_name' }],+ }),+ ],+ formula: 'a / b',+ },+ 'right-nested formula': {+ clauses: [+ clause({ name: 'a', metricName: 'queue_depth' }),+ clause({ name: 'b', metricName: 'retry_queue_depth' }),+ clause({ name: 'c', metricName: 'dead_queue_depth' }),+ ],+ formula: 'a - (b - c)',+ },+ 'unary minus formula': {+ clauses: [clause({ name: 'a', metricName: 'queue_depth' })],+ formula: '-a',+ },+ 'two series without formula': {+ clauses: [+ clause({ name: 'a', metricName: 'queue_depth' }),+ clause({ name: 'b', metricName: 'process.cpu.utilization', aggregation: 'avg' }),+ ],+ },+ 'three series with groups': {+ clauses: [+ clause({ name: 'a', metricName: 'queue_depth', groupBy: [{ key: 'service_name' }] }),+ clause({ name: 'b', metricName: 'http.server.request.count', aggregation: 'rate' }),+ clause({ name: 'c', metricName: 'up', aggregation: 'count', groupBy: [{ key: 'service_name' }] }),+ ],+ },+ // The backend seeds these metrics so that a series stops reporting, a service is missing, or a value is 0.+ 'series that stops reporting': {+ clauses: [clause({ name: 'a', metricName: 'sparse_queue_depth', groupBy: [{ key: 'service_name' }] })],+ },+ 'formula over different label sets': {+ clauses: [+ clause({ name: 'a', metricName: 'queue_depth', groupBy: [{ key: 'service_name' }] }),+ clause({ name: 'b', metricName: 'api_queue_depth', groupBy: [{ key: 'service_name' }] }),+ ],+ formula: 'a - b',+ },+ 'share of total, spreading a series without labels': {+ clauses: [+ clause({ name: 'a', metricName: 'queue_depth', groupBy: [{ key: 'service_name' }] }),+ clause({ name: 'b', metricName: 'queue_depth' }),+ ],+ formula: 'a / b',+ },+ 'histogram share, spreading a series without labels': {+ clauses: [+ clause({+ name: 'a',+ metricName: 'http.server.duration',+ aggregation: 'histogram_quantile',+ quantile: 0.5,+ groupBy: [{ key: 'service_name' }],+ }),+ clause({ name: 'b', metricName: 'http.server.duration', aggregation: 'histogram_quantile', quantile: 0.5 }),+ ],+ formula: 'a / b',+ },+ 'formula with a small constant': {+ clauses: [clause({ name: 'a', metricName: 'queue_depth' })],+ formula: 'a * 0.0000001',+ },+ 'formula with a zero denominator': {+ clauses: [+ clause({ name: 'a', metricName: 'queue_depth' }),+ clause({ name: 'b', metricName: 'idle_queue_depth' }),+ ],+ formula: 'a / b',+ },+}++const PROMQL_CASES: [string, BuilderQuery | null, 'lossless' | 'lossy'][] = [+ ['sum(queue_depth)', { clauses: [clause({ metricName: 'queue_depth' })] }, 'lossless'],+ [+ 'sum(queue_depth) by (service_name)',+ { clauses: [clause({ metricName: 'queue_depth', groupBy: [{ key: 'service_name' }] })] },+ 'lossless',+ ],+ [+ 'avg by (service_name) (process_cpu_usage)',+ {+ clauses: [+ clause({ metricName: 'process_cpu_usage', aggregation: 'avg', groupBy: [{ key: 'service_name' }] }),+ ],+ },+ 'lossless',+ ],+ [+ 'max(jvm_memory_used_bytes{area="heap"})',+ {+ clauses: [+ clause({+ metricName: 'jvm_memory_used_bytes',+ aggregation: 'max',+ filters: [{ key: 'area', op: 'eq', value: 'heap' }],+ }),+ ],+ },+ 'lossless',+ ],+ [+ 'min(free_disk_bytes{mount!="/boot"})',+ {+ clauses: [+ clause({+ metricName: 'free_disk_bytes',+ aggregation: 'min',+ filters: [{ key: 'mount', op: 'neq', value: '/boot' }],+ }),+ ],+ },+ 'lossless',+ ],+ [+ 'count(up{job=~"api.*"})',+ {+ clauses: [+ clause({+ metricName: 'up',+ aggregation: 'count',+ filters: [{ key: 'job', op: 'regex', value: '^api' }],+ }),+ ],+ },+ 'lossless',+ ],+ [+ 'sum(queue_depth{queue!~"dead|retry"})',+ {+ clauses: [+ clause({+ metricName: 'queue_depth',+ filters: [{ key: 'queue', op: 'not_regex', value: '^(?:dead|retry)$' }],+ }),+ ],+ },+ 'lossless',+ ],+ [+ 'quantile(0.95, request_latency_ms)',+ { clauses: [clause({ metricName: 'request_latency_ms', aggregation: 'quantile', quantile: 0.95 })] },+ 'lossless',+ ],+ [+ 'quantile by (service_name) (0.95, request_latency_ms)',+ {+ clauses: [+ clause({+ metricName: 'request_latency_ms',+ aggregation: 'quantile',+ quantile: 0.95,+ groupBy: [{ key: 'service_name' }],+ }),+ ],+ },+ 'lossless',+ ],+ [+ 'sum(rate(http_requests_total))',+ { clauses: [clause({ metricName: 'http_requests_total', aggregation: 'rate' })] },+ 'lossless',+ ],+ [+ 'sum(rate(http_requests_total[5m]))',+ { clauses: [clause({ metricName: 'http_requests_total', aggregation: 'rate' })] },+ 'lossy',+ ],+ [+ 'sum(rate(http_requests_total[$__rate_interval])) by (job)',+ { clauses: [clause({ metricName: 'http_requests_total', aggregation: 'rate', groupBy: [{ key: 'job' }] })] },+ 'lossless',+ ],+ [+ 'sum(increase(jobs_total[1h]))',+ { clauses: [clause({ metricName: 'jobs_total', aggregation: 'increase' })] },+ 'lossy',+ ],+ [+ 'sum by (http.route) (rate({"http.server.request.count"}))',+ {+ clauses: [+ clause({+ metricName: 'http.server.request.count',+ aggregation: 'rate',+ groupBy: [{ key: 'http.route' }],+ }),+ ],+ },+ 'lossless',+ ],+ [+ 'sum by ("http.route") (rate({"http.server.request.count", "http.request.method"="GET"}))',+ {+ clauses: [+ clause({+ metricName: 'http.server.request.count',+ aggregation: 'rate',+ groupBy: [{ key: 'http.route' }],+ filters: [{ key: 'http.request.method', op: 'eq', value: 'GET' }],+ }),+ ],+ },+ 'lossless',+ ],+ ['sum(http.server.request.count)', { clauses: [clause({ metricName: 'http.server.request.count' })] }, 'lossless'],+ [+ "sum(queue_depth{queue='main', path=`C:\\tmp`})",+ {+ clauses: [+ clause({+ metricName: 'queue_depth',+ filters: [+ { key: 'queue', op: 'eq', value: 'main' },+ { key: 'path', op: 'eq', value: 'C:\\tmp' },+ ],+ }),+ ],+ },+ 'lossless',+ ],+ [+ 'sum(queue_depth{queue="caf\\xc3\\xa9", region="\\u00e9u", zone="\\303\\251"})',+ {+ clauses: [+ clause({+ metricName: 'queue_depth',+ filters: [+ { key: 'queue', op: 'eq', value: 'café' },+ { key: 'region', op: 'eq', value: 'éu' },+ { key: 'zone', op: 'eq', value: 'é' },+ ],+ }),+ ],+ },+ 'lossless',+ ],+ [+ 'sum({__name__="queue_depth", queue="main"})',+ { clauses: [clause({ metricName: 'queue_depth', filters: [{ key: 'queue', op: 'eq', value: 'main' }] })] },+ 'lossless',+ ],+ [+ 'sum(rate(http_requests_total{service_name="api", http_route=~"/api/.*"}))',+ {+ clauses: [+ clause({+ metricName: 'http_requests_total',+ aggregation: 'rate',+ filters: [+ { key: 'service_name', op: 'eq', value: 'api' },+ { key: 'http_route', op: 'regex', value: '^/api/' },+ ],+ }),+ ],+ },+ 'lossless',+ ],+ [+ 'histogram_quantile(0.99, sum by (le) (rate(http_server_duration_bucket[5m])))',+ {+ clauses: [+ clause({ metricName: 'http_server_duration', aggregation: 'histogram_quantile', quantile: 0.99 }),+ ],+ },+ 'lossy',+ ],+ [+ 'histogram_quantile(0.5, sum by (le, service_name) (rate({"http.server.duration_bucket"})))',+ {+ clauses: [+ clause({+ metricName: 'http.server.duration',+ aggregation: 'histogram_quantile',+ quantile: 0.5,+ groupBy: [{ key: 'service_name' }],+ }),+ ],+ },+ 'lossless',+ ],+ [+ 'histogram_quantile(0.99, rate(latency_bucket))',+ { clauses: [clause({ metricName: 'latency', aggregation: 'histogram_quantile', quantile: 0.99 })] },+ 'lossy',+ ],+ ['histogram_quantile(0.9, latency)', null, 'lossy'],+ [+ 'histogram_quantile(0.9, sum(rate(latency_bucket)) by (le))',+ { clauses: [clause({ metricName: 'latency', aggregation: 'histogram_quantile', quantile: 0.9 })] },+ 'lossless',+ ],+ [+ 'sum(rate(errors_total)) / sum(rate(requests_total))',+ {+ clauses: [+ clause({ name: 'a', metricName: 'errors_total', aggregation: 'rate' }),+ clause({ name: 'b', metricName: 'requests_total', aggregation: 'rate' }),+ ],+ formula: 'a / b',+ },+ 'lossless',+ ],+ [+ 'sum(rate(errors_total)) / sum(rate(requests_total)) * 100',+ {+ clauses: [+ clause({ name: 'a', metricName: 'errors_total', aggregation: 'rate' }),+ clause({ name: 'b', metricName: 'requests_total', aggregation: 'rate' }),+ ],+ formula: 'a / b * 100',+ },+ 'lossless',+ ],+ [+ '100 * (1 - sum(rate(errors_total)) / sum(rate(requests_total)))',+ {+ clauses: [+ clause({ name: 'a', metricName: 'errors_total', aggregation: 'rate' }),+ clause({ name: 'b', metricName: 'requests_total', aggregation: 'rate' }),+ ],+ formula: '100 * (1 - a / b)',+ },+ 'lossless',+ ],+ [+ '(sum(queue_depth) + sum(retry_queue_depth)) / 2',+ {+ clauses: [+ clause({ name: 'a', metricName: 'queue_depth' }),+ clause({ name: 'b', metricName: 'retry_queue_depth' }),+ ],+ formula: '(a + b) / 2',+ },+ 'lossless',+ ],+ ['-sum(queue_depth)', { clauses: [clause({ metricName: 'queue_depth' })], formula: '-a' }, 'lossless'],+ [+ 'sum(queue_depth) - sum(queue_depth)',+ { clauses: [clause({ metricName: 'queue_depth' })], formula: 'a - a' },+ 'lossless',+ ],+ [+ 'sum by (job) (rate(errors_total)) / on() group_left sum(rate(requests_total))',+ {+ clauses: [+ clause({ name: 'a', metricName: 'errors_total', aggregation: 'rate', groupBy: [{ key: 'job' }] }),+ clause({ name: 'b', metricName: 'requests_total', aggregation: 'rate' }),+ ],+ formula: 'a / b',+ },+ 'lossless',+ ],+ [+ 'label_replace(sum(queue_depth), "clause", "a", "", "") or label_replace(avg(cpu), "clause", "b", "", "")',+ {+ clauses: [+ clause({ name: 'a', metricName: 'queue_depth' }),+ clause({ name: 'b', metricName: 'cpu', aggregation: 'avg' }),+ ],+ },+ 'lossless',+ ],+ [+ 'max by (instance) (fs_avail_bytes{mountpoint="/"} / fs_size_bytes{mountpoint="/"})',+ {+ clauses: [+ clause({+ name: 'a',+ metricName: 'fs_avail_bytes',+ aggregation: 'max',+ filters: [{ key: 'mountpoint', op: 'eq', value: '/' }],+ groupBy: [{ key: 'instance' }],+ }),+ clause({+ name: 'b',+ metricName: 'fs_size_bytes',+ aggregation: 'max',+ filters: [{ key: 'mountpoint', op: 'eq', value: '/' }],+ groupBy: [{ key: 'instance' }],+ }),+ ],+ formula: 'a / b',+ },+ 'lossy',+ ],+ [+ 'sum(queue_depth) or sum(retry_queue_depth)',+ {+ clauses: [+ clause({ name: 'a', metricName: 'queue_depth' }),+ clause({ name: 'b', metricName: 'retry_queue_depth' }),+ ],+ },+ 'lossy',+ ],+ [+ 'sum by (job) (rate(errors_total)) / ignoring(instance) sum by (job) (rate(requests_total))',+ {+ clauses: [+ clause({ name: 'a', metricName: 'errors_total', aggregation: 'rate', groupBy: [{ key: 'job' }] }),+ clause({ name: 'b', metricName: 'requests_total', aggregation: 'rate', groupBy: [{ key: 'job' }] }),+ ],+ formula: 'a / b',+ },+ 'lossy',+ ],+ ['sum(errors_total) % sum(requests_total)', { clauses: [clause({ metricName: 'errors_total' })] }, 'lossy'],+ [+ 'label_replace(sum(queue_depth), "queue_alias", "$1", "queue", "(.*)")',+ { clauses: [clause({ metricName: 'queue_depth' })] },+ 'lossy',+ ],+ ['avg(sum by (job) (queue_depth))', { clauses: [clause({ metricName: 'queue_depth' })] }, 'lossy'],+ ['sum(queue_depth) offset 1h', { clauses: [clause({ metricName: 'queue_depth' })] }, 'lossy'],+ ['sum(queue_depth offset 1h)', { clauses: [clause({ metricName: 'queue_depth' })] }, 'lossy'],+ ['sum(queue_depth) > 5', { clauses: [clause({ metricName: 'queue_depth' })] }, 'lossy'],+ [+ 'topk(5, sum by (queue) (queue_depth))',+ { clauses: [clause({ metricName: 'queue_depth', groupBy: [{ key: 'queue' }] })] },+ 'lossy',+ ],+ ['sum without (instance) (queue_depth)', { clauses: [clause({ metricName: 'queue_depth' })] }, 'lossy'],+ ['queue_depth', { clauses: [clause({ metricName: 'queue_depth', aggregation: undefined })] }, 'lossless'],+ [+ 'rate(http_requests_total)',+ { clauses: [clause({ metricName: 'http_requests_total', aggregation: undefined, rangeFunction: 'rate' })] },+ 'lossless',+ ],+ [+ 'rate(http_requests_total[1m])',+ { clauses: [clause({ metricName: 'http_requests_total', aggregation: undefined, rangeFunction: 'rate' })] },+ 'lossy',+ ],+ [+ 'sum(irate(http_requests_total[1m]))',+ { clauses: [clause({ metricName: 'http_requests_total', aggregation: 'rate' })] },+ 'lossy',+ ],+ [+ 'avg(rate(http_requests_total))',+ { clauses: [clause({ metricName: 'http_requests_total', aggregation: 'avg', rangeFunction: 'rate' })] },+ 'lossless',+ ],+ ['abs(sum(queue_depth))', { clauses: [clause({ metricName: 'queue_depth' })] }, 'lossy'],+ ['sum(avg_over_time(queue_depth[5m]))', { clauses: [clause({ metricName: 'queue_depth' })] }, 'lossy'],+ ['stddev(queue_depth)', { clauses: [clause({ metricName: 'queue_depth' })] }, 'lossy'],+ [+ 'median(queue_depth)',+ { clauses: [clause({ metricName: 'queue_depth', aggregation: 'quantile', quantile: 0.95 })] },+ 'lossy',+ ],+ [+ 'quantile(0.99, request_latency_ms)',+ { clauses: [clause({ metricName: 'request_latency_ms', aggregation: 'quantile', quantile: 0.95 })] },+ 'lossy',+ ],+ [+ 'sum(rate(http_requests_total[5m:1m]))',+ { clauses: [clause({ metricName: 'http_requests_total', aggregation: 'rate' })] },+ 'lossy',+ ],+ ['up == 1', { clauses: [clause({ metricName: 'up', aggregation: undefined })] }, 'lossy'],+ ['sum({__name__=~"queue_.*"})', null, 'lossy'],+ ['vector(1)', null, 'lossy'],+ ['sum(', null, 'lossy'],+ ['sum by (a (x)', null, 'lossy'],+ ['x{a=b}', null, 'lossy'],+ ['sum(x{a="unterminated})', null, 'lossy'],+]++// A comma join: the reader once looped on it without end.+const COMMA_JOIN_SQL =+ "SELECT toStartOfInterval(m.timestamp, {interval}) AS time, sum(m.value) AS value FROM posthog.metrics m, posthog.metric_series s WHERE m.metric_name = 'x' GROUP BY time"++const metricsQuery = (fields: Partial<MetricsQuery>): MetricsQuery => ({+ kind: NodeKind.MetricsQuery,+ clauses: [],+ dateRange: { date_from: '-6h' },+ interval: 'minute_5',+ ...fields,+})++describe('metrics query languages', () => {+ describe('PromQL parser and printer', () => {+ it.each([+ 'sum by (service_name) (rate(http_requests_total{code=~"5.."}[5m]))',+ 'histogram_quantile(0.99, sum by (le) (rate({"http.server.duration_bucket", "http.route"="/"}[5m])))',+ 'a / on() group_left sum(b)',+ '-sum(x) ^ 2',+ '(a + b) * c',+ 'a - (b - c)',+ '2 ^ 3 ^ 2',+ 'sum(x) offset 1h',+ 'x > bool 1',+ 'quantile by (k) (0.9, x)',+ 'label_replace(x, "clause", "a", "", "") or y',+ 'x @ 1700000000',+ 'rate(x[5m:30s])',+ 'max_over_time(x[1h:5m] @ end())',+ 'count_values("version", build_info)',+ ])('prints %s so that it parses back to the same tree', (text) => {+ const parsed = parsePromQL(text)+ expect(parsePromQL(printPromQL(parsed))).toEqual(parsed)+ })++ it.each(['sum(', 'x{a=b}', 'x{a="b}', 'sum by (a (x)', '}', 'x[5m', '', 'sum(x) @ end()'])(+ 'rejects %j with a position',+ (text) => {+ expect(() => parsePromQL(text)).toThrow(PromQLParseError)+ }+ )++ it('reads quoted UTF-8 metric and label names', () => {+ expect(parsePromQL('{"http.server.duration", "http.route"="/x"}')).toEqual({+ type: 'selector',+ name: 'http.server.duration',+ matchers: [{ label: 'http.route', op: '=', value: '/x' }],+ })+ })+ })++ describe('regex anchoring', () => {+ it.each(['^(?:a|b)$', 'users', '^/api', 'health$', '^$', 'a|b', '^foo.*bar$', '(?:a|b)$', '^foo|bar$', '^a|b'])(+ 'keeps %j through PromQL',+ (pattern) => {+ expect(promRegexToBuilderRegex(builderRegexToPromRegex(pattern))).toEqual(pattern)+ }+ )++ it.each([+ ['users', '.*users.*'],+ ['^(?:a|b)$', 'a|b'],+ ['a|b', '.*(?:a|b).*'],+ ['^/api', '/api.*'],+ ['^foo|bar$', '.*(?:^foo|bar$).*'],+ ])('anchors builder regex %j as PromQL %j', (builder, prom) => {+ expect(builderRegexToPromRegex(builder)).toEqual(prom)+ })++ it.each([+ ['a|b', '^(?:a|b)$'],+ ['.*a|b.*', '^(?:.*a|b.*)$'],+ ])('reads PromQL regex %j as builder regex %j', (prom, builder) => {+ expect(promRegexToBuilderRegex(prom)).toEqual(builder)+ expect(builderRegexToPromRegex(builder)).toEqual(prom)+ })+ })++ describe('PromQL → builder', () => {+ it.each(PROMQL_CASES)('%s', (text, expected, kind) => {+ const result = promqlToBuilder(text)+ if (expected === null) {+ expect(result.value).toBeNull()+ expect(result.issues.length).toBeGreaterThan(0)+ return+ }+ expect(result.value).not.toBeNull()+ expect(canonicalBuilder(result.value!)).toEqual(canonicalBuilder(expected))+ if (kind === 'lossless') {+ expect(result.issues).toEqual([])+ } else {+ expect(result.issues.length).toBeGreaterThan(0)+ }+ })++ it.each(+ PROMQL_CASES.filter(+ ([, expected, kind]) =>+ expected &&+ kind === 'lossless' &&+ expected.clauses.every((clause) => clause.aggregation !== 'histogram_quantile')+ )+ )('switching %s to the builder and back is lossless', (text) => {+ const conversion = convertMetricsQuery(metricsQuery({ language: 'promql', promql: text }), 'builder')+ expect(conversion.issues).toEqual([])+ const back = convertMetricsQuery(conversion.query, 'promql')+ expect(back.issues).toEqual([])+ expect(canonicalPromQL(back.query.promql!)).toEqual(canonicalPromQL(text))+ })+ })++ describe('builder → PromQL', () => {+ it.each([+ ['gauge sum', 'sum(queue_depth)'],+ ['gauge avg', 'avg({"process.cpu.utilization"})'],+ ['counter rate', 'sum(rate({"http.server.request.count"}))'],+ ['max of per-series increase by service', 'max by (service_name) (increase(jobs_processed_total))'],+ ['p95', 'quantile(0.95, request_latency_ms)'],+ ['histogram p99', 'histogram_quantile(0.99, sum by (le) (rate({"http.server.duration_bucket"})))'],+ ['multi-value chip regex', 'sum(queue_depth{service_name=~"api|worker"})'],+ [+ 'group by two dotted',+ 'sum by ("http.route", "http.request.method") (rate({"http.server.request.count"}))',+ ],+ [+ 'error ratio formula',+ 'sum(rate({"http.server.request.count", "http.response.status_code"=~"5.*"})) / sum(rate({"http.server.request.count"})) * 100',+ ],+ ['parenthesized formula', '(sum(queue_depth) + sum(retry_queue_depth)) / 2'],+ [+ 'two series without formula',+ 'label_replace(sum(queue_depth), "clause", "a", "", "") or label_replace(avg({"process.cpu.utilization"}), "clause", "b", "", "")',+ ],+ ])('writes %s as %s', (name, expected) => {+ expect(builderToPromql(LOSSLESS_BUILDER_FIXTURES[name])).toEqual({ value: expected, issues: [] })+ })++ it('spreads an ungrouped series over a grouped one with on() group_left', () => {+ const result = builderToPromql({+ clauses: [+ clause({ name: 'a', metricName: 'errors', aggregation: 'rate', groupBy: [{ key: 'job' }] }),+ clause({ name: 'b', metricName: 'requests', aggregation: 'rate' }),+ ],+ formula: 'a / b',+ })+ expect(result).toEqual({+ value: 'sum by (job) (rate(errors)) / on() group_left sum(rate(requests))',+ issues: [],+ })+ })+ })++ describe('round trips', () => {+ it.each(Object.keys(LOSSLESS_BUILDER_FIXTURES))('%s: builder → PromQL → builder', (name) => {+ const builder = LOSSLESS_BUILDER_FIXTURES[name]+ const promql = builderToPromql(builder)+ expect(promql.issues).toEqual([])+ const back = promqlToBuilder(promql.value!)+ expect(back.issues).toEqual([])+ expect(canonicalBuilder(back.value!)).toEqual(canonicalBuilder(builder))+ })++ it.each(Object.keys(LOSSLESS_BUILDER_FIXTURES))('%s: builder → SQL → builder', (name) => {+ const builder = LOSSLESS_BUILDER_FIXTURES[name]+ const sql = builderToSql(builder)+ expect(sql.issues).toEqual([])+ const back = sqlToBuilder(sql.value!)+ expect(back.issues).toEqual([])+ expect(canonicalBuilder(back.value!)).toEqual(canonicalBuilder(builder))+ })++ it.each(Object.keys(LOSSLESS_BUILDER_FIXTURES))('%s: PromQL → SQL → PromQL', (name) => {+ const promql = builderToPromql(LOSSLESS_BUILDER_FIXTURES[name]).value!+ const toSql = convertMetricsQuery(metricsQuery({ language: 'promql', promql }), 'sql')+ expect(toSql.issues).toEqual([])+ const back = convertMetricsQuery(toSql.query, 'promql')+ expect(back.issues).toEqual([])+ expect(back.query.promql).toEqual(promql)+ })++ it('keeps the date range, interval and display', () => {+ const query = metricsQuery({+ clauses: LOSSLESS_BUILDER_FIXTURES['gauge sum'].clauses,+ display: { type: 'bar' },+ })+ const { query: converted } = convertMetricsQuery(query, 'sql')+ expect(converted).toMatchObject({+ dateRange: query.dateRange,+ interval: 'minute_5',+ display: { type: 'bar' },+ })+ expect(converted.clauses).toEqual([])+ expect(converted.language).toEqual('sql')+ })+ })++ describe('lossy switches', () => {+ it.each<[string, MetricsQuery, 'builder' | 'promql' | 'sql']>([+ [+ 'a resource-scoped filter to PromQL',+ metricsQuery({+ clauses: [+ clause({+ metricName: 'queue_depth',+ filters: [{ key: 'host.name', op: 'eq', value: 'a', scope: 'resource' }],+ }),+ ],+ }),+ 'promql',+ ],+ [+ 'a series the formula does not use',+ metricsQuery({+ clauses: [clause({ name: 'a', metricName: 'x' }), clause({ name: 'b', metricName: 'y' })],+ formula: 'a * 2',+ }),+ 'promql',+ ],+ [+ 'series with different group-by labels in a formula, to SQL',+ metricsQuery({+ clauses: [+ clause({ name: 'a', metricName: 'x', groupBy: [{ key: 'job' }] }),+ clause({ name: 'b', metricName: 'y', groupBy: [{ key: 'service_name' }] }),+ ],+ formula: 'a / b',+ }),+ 'sql',+ ],+ ['a fixed range window', metricsQuery({ language: 'promql', promql: 'sum(rate(x[10m]))' }), 'sql'],+ [+ 'handwritten SQL that averages raw samples',+ metricsQuery({+ language: 'sql',+ sql: "SELECT toStartOfInterval(timestamp, {interval}) AS time, avg(value) AS value FROM posthog.metrics WHERE metric_name = 'cpu' AND timestamp >= {date_from} AND timestamp < {date_to} GROUP BY time",+ }),+ 'promql',+ ],+ [+ 'handwritten SQL that counts samples in fixed buckets',+ metricsQuery({+ language: 'sql',+ sql: "select toStartOfMinute(timestamp) as time, count() as value from posthog.metrics where metric_name = 'up' group by time limit 10",+ }),+ 'builder',+ ],+ [+ 'a histogram quantile, which the builder can chart but not edit',+ metricsQuery({+ language: 'promql',+ promql: 'histogram_quantile(0.5, sum by (le) (rate({"http.server.duration_bucket"})))',+ }),+ 'builder',+ ],+ [+ 'SQL from another table',+ metricsQuery({ language: 'sql', sql: 'SELECT timestamp AS time, 1 AS value FROM events' }),+ 'builder',+ ],+ ['PromQL that cannot be read', metricsQuery({ language: 'promql', promql: 'sum(' }), 'sql'],+ ['SQL that joins tables with a comma', metricsQuery({ language: 'sql', sql: COMMA_JOIN_SQL }), 'builder'],+ [+ 'a grouped formula that is not 0 where a label set has no data, to SQL',+ metricsQuery({+ clauses: LOSSLESS_BUILDER_FIXTURES['formula over different label sets'].clauses,+ formula: 'a + 1',+ }),+ 'sql',+ ],+ [+ 'a grouped formula that is not 0 where a label set has no data, from SQL',+ metricsQuery({+ language: 'sql',+ sql: builderToSql({+ clauses: LOSSLESS_BUILDER_FIXTURES['formula over different label sets'].clauses,+ formula: 'a + 1',+ }).value!,+ }),+ 'builder',+ ],+ [+ 'a series without labels subtracted from a grouped one, to SQL',+ metricsQuery({+ clauses: LOSSLESS_BUILDER_FIXTURES['share of total, spreading a series without labels'].clauses,+ formula: 'a - b',+ }),+ 'sql',+ ],+ [+ 'a formula number in exponent notation, from SQL',+ metricsQuery({+ language: 'sql',+ sql: builderToSql(LOSSLESS_BUILDER_FIXTURES['formula with a small constant']).value!.replace(+ '0.0000001',+ '1e-7'+ ),+ }),+ 'builder',+ ],+ ])('warns about %s', (_name, query, to) => {+ expect(convertMetricsQuery(query, to).issues.length).toBeGreaterThan(0)+ })++ it('names per-series SQL by fingerprint and reads it back as per-series', () => {+ const perSeries: BuilderQuery = {+ clauses: [+ clause({ metricName: 'jobs_processed_total', aggregation: undefined, rangeFunction: 'rate' }),+ ],+ }+ const sql = builderToSql(perSeries)+ expect(sql.issues).toEqual(['SQL names each series of a by its fingerprint, not by its attributes.'])+ const back = sqlToBuilder(sql.value!)+ expect(back.issues).toEqual([])+ expect(canonicalBuilder(back.value!)).toEqual(canonicalBuilder(perSeries))+ })++ it('reports an edit to generated SQL that the builder cannot hold', () => {+ const sql = builderToSql(LOSSLESS_BUILDER_FIXTURES['gauge sum']).value!.replace(+ 'ORDER BY time',+ 'ORDER BY time DESC'+ )+ expect(convertMetricsQuery(metricsQuery({ language: 'sql', sql }), 'builder').issues).toEqual([+ GENERIC_LOSS_ISSUE,+ ])+ })++ it('reads a handwritten SQL query with a group-by', () => {+ const result = sqlToBuilder(`+ SELECT toStartOfInterval(timestamp, {interval}) AS time, service_name, max(value) AS value+ FROM posthog.metrics+ WHERE metric_name = 'queue_depth' AND service_name IN ('api', 'worker')+ AND timestamp >= {date_from} AND timestamp < {date_to}+ GROUP BY time, service_name+ `)+ expect(result.value).toEqual({+ clauses: [+ clause({+ metricName: 'queue_depth',+ aggregation: 'max',+ filters: [{ key: 'service_name', op: 'regex', value: '^(?:api|worker)$' }],+ groupBy: [{ key: 'service_name' }],+ }),+ ],+ })+ expect(result.issues).toHaveLength(1)+ })+ })++ // The backend runs every fixture's SQL in SQL mode and compares it with the builder result+ // (products/metrics/backend/tests/test_metrics_query_languages.py). Set UPDATE_METRICS_SQL_FIXTURES=1 to refresh it.+ it('keeps the SQL fixtures for the backend in sync', () => {+ const fixturePath = path.join(__dirname, '__fixtures__', 'builder_sql.json')+ const generated = Object.fromEntries(+ Object.entries(LOSSLESS_BUILDER_FIXTURES).map(([name, builder]) => [+ name,+ { builder, sql: builderToSql(builder).value },+ ])+ )+ if (process.env.UPDATE_METRICS_SQL_FIXTURES) {+ fs.mkdirSync(path.dirname(fixturePath), { recursive: true })+ fs.writeFileSync(fixturePath, JSON.stringify(generated, null, 4) + '\n')+ }+ expect(JSON.parse(fs.readFileSync(fixturePath, 'utf-8'))).toEqual(generated)+ })+})diff --git a/products/metrics/frontend/queryLanguages/regex.ts b/products/metrics/frontend/queryLanguages/regex.tsnew file mode 100644index 000000000000..63df55dc284b--- /dev/null+++ b/products/metrics/frontend/queryLanguages/regex.ts@@ -0,0 +1,89 @@+// The builder matches a regex anywhere in the value (ClickHouse `match`), PromQL anchors it at both+// ends. These two functions translate between the two, so that a builder regex survives a round trip+// through PromQL as the same string.++const hasTopLevelAlternation = (pattern: string): boolean => {+ let depth = 0+ let inClass = false+ for (let i = 0; i < pattern.length; i++) {+ const ch = pattern[i]+ if (ch === '\\') {+ i+++ } else if (inClass) {+ inClass = ch !== ']'+ } else if (ch === '[') {+ inClass = true+ } else if (ch === '(') {+ depth+++ } else if (ch === ')') {+ depth--+ } else if (ch === '|' && depth === 0) {+ return true+ }+ }+ return false+}++/** `(?:X)` → `X` when the group spans the whole pattern. */+const unwrapGroup = (pattern: string): string => {+ if (!pattern.startsWith('(?:') || !pattern.endsWith(')')) {+ return pattern+ }+ let depth = 0+ for (let i = 0; i < pattern.length; i++) {+ const ch = pattern[i]+ if (ch === '\\') {+ i+++ } else if (ch === '(') {+ depth+++ } else if (ch === ')') {+ depth--+ if (depth === 0 && i !== pattern.length - 1) {+ return pattern+ }+ }+ }+ return pattern.slice(3, -1)+}++const group = (pattern: string): string => (hasTopLevelAlternation(pattern) ? `(?:${pattern})` : pattern)++const endsWithUnescaped = (pattern: string, suffix: string): boolean => {+ if (!pattern.endsWith(suffix)) {+ return false+ }+ let backslashes = 0+ for (let i = pattern.length - suffix.length - 1; i >= 0 && pattern[i] === '\\'; i--) {+ backslashes+++ }+ return backslashes % 2 === 0+}++export function builderRegexToPromRegex(pattern: string): string {+ // In `^a|b$` each anchor belongs to one branch, so the pattern is searched as a whole.+ if (hasTopLevelAlternation(pattern)) {+ return `.*(?:${pattern}).*`+ }+ const anchoredStart = pattern.startsWith('^')+ const anchoredEnd = endsWithUnescaped(pattern, '$') && pattern.length > (anchoredStart ? 1 : 0)+ const core = pattern.slice(anchoredStart ? 1 : 0, anchoredEnd ? -1 : undefined)+ if (anchoredStart && anchoredEnd) {+ return unwrapGroup(core)+ }+ return `${anchoredStart ? '' : '.*'}${group(core)}${anchoredEnd ? '' : '.*'}`+}++export function promRegexToBuilderRegex(pattern: string): string {+ // In `.*a|b.*` each `.*` belongs to one branch, so the whole pattern must match the value.+ if (hasTopLevelAlternation(pattern)) {+ return `^(?:${pattern})$`+ }+ const openStart = pattern.startsWith('.*')+ const rest = openStart ? pattern.slice(2) : pattern+ const openEnd = rest.length >= 2 && endsWithUnescaped(rest, '.*')+ const core = openEnd ? rest.slice(0, -2) : rest+ if (openStart && openEnd) {+ return unwrapGroup(core)+ }+ return `${openStart ? '' : '^'}${group(core)}${openEnd ? '' : '$'}`+}diff --git a/products/metrics/frontend/queryLanguages/sqlToBuilder.ts b/products/metrics/frontend/queryLanguages/sqlToBuilder.tsnew file mode 100644index 000000000000..e3b2a057115b--- /dev/null+++ b/products/metrics/frontend/queryLanguages/sqlToBuilder.ts@@ -0,0 +1,862 @@+import type { MetricsAttributeScope, MetricsQueryFilter, MetricsQueryGroupBy } from '~/queries/schema/schema-general'++import { PER_SERIES_COLUMN } from './builderToSql'+import {+ type BuilderClause,+ type BuilderQuery,+ type ConversionResult,+ ENGINE_QUANTILE,+ MAX_CONVERTED_CLAUSES,+ clauseAlias,+} from './types'++/**+ * SQL → builder, best effort.+ *+ * This is not a SQL parser. It splits the statement into its SELECT parts and recognizes the+ * shapes builderToSql writes, plus the simple queries people write by hand+ * (`SELECT toStartOfInterval(timestamp, {interval}) AS time, avg(value) AS value FROM posthog.metrics …`).+ * Every part it does not recognize becomes an issue, so the caller can warn before it drops it.+ */++type TokenType = 'word' | 'quoted' | 'string' | 'number' | 'placeholder' | 'punct'++interface Token {+ type: TokenType+ value: string+}++export class SqlReadError extends Error {}++const PUNCTUATION = [+ '!=',+ '>=',+ '<=',+ '<>',+ '==',+ '->',+ '(',+ ')',+ ',',+ '.',+ '=',+ '<',+ '>',+ '+',+ '-',+ '*',+ '/',+ '[',+ ']',+ '%',+]++function tokenize(sql: string): Token[] {+ const tokens: Token[] = []+ let i = 0+ while (i < sql.length) {+ const ch = sql[i]+ const rest = sql.slice(i)+ if (/\s/.test(ch)) {+ i+++ } else if (rest.startsWith('--')) {+ const end = sql.indexOf('\n', i)+ i = end === -1 ? sql.length : end+ } else if (rest.startsWith('/*')) {+ const end = sql.indexOf('*/', i + 2)+ i = end === -1 ? sql.length : end + 2+ } else if (ch === "'" || ch === '`' || ch === '"') {+ let value = ''+ let j = i + 1+ while (j < sql.length && sql[j] !== ch) {+ if (sql[j] === '\\' && j + 1 < sql.length) {+ value += sql[j + 1]+ j += 2+ continue+ }+ value += sql[j]+ j+++ }+ if (j >= sql.length) {+ throw new SqlReadError('The SQL has a quote that is not closed.')+ }+ tokens.push({ type: ch === "'" ? 'string' : 'quoted', value })+ i = j + 1+ } else if (ch === '{') {+ const end = sql.indexOf('}', i)+ if (end === -1) {+ throw new SqlReadError('The SQL has a placeholder that is not closed.')+ }+ tokens.push({ type: 'placeholder', value: sql.slice(i + 1, end).trim() })+ i = end + 1+ } else if (/[0-9]/.test(ch) || (ch === '.' && /[0-9]/.test(sql[i + 1] ?? ''))) {+ const match = /^(\d+\.?\d*|\.\d+)([eE][+-]?\d+)?/.exec(rest)!+ tokens.push({ type: 'number', value: match[0] })+ i += match[0].length+ } else if (/[a-zA-Z_]/.test(ch)) {+ const match = /^[a-zA-Z_][a-zA-Z0-9_$]*/.exec(rest)!+ tokens.push({ type: 'word', value: match[0] })+ i += match[0].length+ } else {+ const op = PUNCTUATION.find((candidate) => rest.startsWith(candidate))+ if (!op) {+ throw new SqlReadError(`The SQL has a character that cannot be read: "${ch}".`)+ }+ tokens.push({ type: 'punct', value: op })+ i += op.length+ }+ }+ return tokens+}++const isWord = (token: Token | undefined, ...words: string[]): boolean =>+ token?.type === 'word' && words.includes(token.value.toUpperCase())+const isPunct = (token: Token | undefined, value: string): boolean => token?.type === 'punct' && token.value === value++/** Canonical text of a token run, for comparing expressions without caring about spacing or quoting style. */+function canon(tokens: Token[]): string {+ return tokens+ .map((token, i) => {+ const text =+ token.type === 'string'+ ? JSON.stringify(token.value)+ : token.type === 'quoted'+ ? `\`${token.value}\``+ : token.type === 'placeholder'+ ? `{${token.value}}`+ : token.value+ const previous = tokens[i - 1]+ const needsSpace =+ previous && /^[a-zA-Z0-9_]/.test(text) && previous.type !== 'punct' && previous.type !== 'placeholder'+ return needsSpace ? ` ${text}` : text+ })+ .join('')+}++/** Splits a token run at depth-0 tokens that `isSeparator` accepts, dropping the separators. */+function splitTopLevel(tokens: Token[], isSeparator: (tokens: Token[], index: number) => number): Token[][] {+ const parts: Token[][] = []+ let current: Token[] = []+ let depth = 0+ for (let i = 0; i < tokens.length; i++) {+ const token = tokens[i]+ if (isPunct(token, '(') || isPunct(token, '[')) {+ depth+++ } else if (isPunct(token, ')') || isPunct(token, ']')) {+ depth--+ }+ const width = depth === 0 ? isSeparator(tokens, i) : 0+ if (width > 0) {+ parts.push(current)+ current = []+ i += width - 1+ continue+ }+ current.push(token)+ }+ parts.push(current)+ return parts+}++const commaSeparator = (tokens: Token[], i: number): number => (isPunct(tokens[i], ',') ? 1 : 0)+const andSeparator = (tokens: Token[], i: number): number => (isWord(tokens[i], 'AND') ? 1 : 0)+const unionSeparator = (tokens: Token[], i: number): number =>+ isWord(tokens[i], 'UNION') && isWord(tokens[i + 1], 'ALL') ? 2 : 0++/** Removes parentheses that wrap the whole run. */+function unwrap(tokens: Token[]): Token[] {+ while (tokens.length >= 2 && isPunct(tokens[0], '(') && isPunct(tokens[tokens.length - 1], ')')) {+ let depth = 0+ let closesAtEnd = true+ for (let i = 0; i < tokens.length; i++) {+ if (isPunct(tokens[i], '(')) {+ depth+++ } else if (isPunct(tokens[i], ')')) {+ depth--+ if (depth === 0 && i !== tokens.length - 1) {+ closesAtEnd = false+ break+ }+ }+ }+ if (!closesAtEnd) {+ break+ }+ tokens = tokens.slice(1, -1)+ }+ return tokens+}++interface Column {+ expr: Token[]+ alias: string | null+}++interface Join {+ source: Source+ alias: string | null+}++type Source = { kind: 'table'; name: string } | { kind: 'subquery'; tokens: Token[] }++interface SelectParts {+ columns: Column[]+ source: Source | null+ sourceAlias: string | null+ joins: Join[]+ where: Token[][]+ groupBy: Token[][]+ having: Token[]+ limit: Token[]+}++const CLAUSE_KEYWORDS = ['FROM', 'WHERE', 'GROUP', 'HAVING', 'ORDER', 'LIMIT', 'SETTINGS']+const JOIN_WORDS = ['LEFT', 'RIGHT', 'INNER', 'FULL', 'CROSS', 'JOIN', 'OUTER', 'ANY', 'ALL', 'ASOF', 'SEMI', 'ANTI']++function parseColumn(tokens: Token[]): Column {+ const last = tokens[tokens.length - 1]+ if (+ tokens.length >= 3 &&+ isWord(tokens[tokens.length - 2], 'AS') &&+ (last.type === 'word' || last.type === 'quoted')+ ) {+ return { expr: tokens.slice(0, -2), alias: last.value }+ }+ if (tokens.length === 1 && tokens[0].type === 'word') {+ return { expr: tokens, alias: tokens[0].value }+ }+ if (tokens.length === 3 && isPunct(tokens[1], '.') && (tokens[2].type === 'word' || tokens[2].type === 'quoted')) {+ return { expr: tokens, alias: tokens[2].value }+ }+ return { expr: tokens, alias: null }+}++/** Reads `<table or (subquery)> [AS] alias`, returning the source and the tokens after it. */+function parseSource(tokens: Token[]): { source: Source; alias: string | null; rest: Token[] } {+ let index = 0+ let source: Source+ if (isPunct(tokens[0], '(')) {+ let depth = 0+ for (; index < tokens.length; index++) {+ if (isPunct(tokens[index], '(')) {+ depth+++ } else if (isPunct(tokens[index], ')') && --depth === 0) {+ break+ }+ }+ source = { kind: 'subquery', tokens: tokens.slice(1, index) }+ index+++ } else {+ const name: string[] = []+ while (index < tokens.length && (tokens[index].type === 'word' || tokens[index].type === 'quoted')) {+ if (isWord(tokens[index], ...JOIN_WORDS, 'AS', 'ON') && name.length) {+ break+ }+ name.push(tokens[index].value)+ index+++ if (!isPunct(tokens[index], '.')) {+ break+ }+ index+++ }+ if (!name.length) {+ throw new SqlReadError(+ isPunct(tokens[0], ',')+ ? 'Tables joined with a comma are not supported. Use JOIN.'+ : 'The FROM part of the SQL cannot be read.'+ )+ }+ source = { kind: 'table', name: name.join('.') }+ }+ let alias: string | null = null+ if (isWord(tokens[index], 'AS')) {+ index+++ }+ if (+ tokens[index] &&+ (tokens[index].type === 'word' || tokens[index].type === 'quoted') &&+ !isWord(tokens[index], ...JOIN_WORDS, 'ON')+ ) {+ alias = tokens[index].value+ index+++ }+ return { source, alias, rest: tokens.slice(index) }+}++function parseSelect(tokens: Token[]): SelectParts {+ tokens = unwrap(tokens)+ if (isWord(tokens[0], 'WITH')) {+ throw new SqlReadError('Common table expressions (WITH) are not supported.')+ }+ if (!isWord(tokens[0], 'SELECT')) {+ throw new SqlReadError('The SQL must start with SELECT.')+ }+ const sections: Record<string, Token[]> = {}+ let current = 'SELECT'+ let depth = 0+ sections[current] = []+ for (let i = 1; i < tokens.length; i++) {+ const token = tokens[i]+ if (isPunct(token, '(')) {+ depth+++ } else if (isPunct(token, ')')) {+ depth--+ }+ if (depth === 0 && isWord(token, ...CLAUSE_KEYWORDS)) {+ current = token.value.toUpperCase()+ if ((current === 'GROUP' || current === 'ORDER') && isWord(tokens[i + 1], 'BY')) {+ i+++ }+ sections[current] = []+ continue+ }+ sections[current].push(token)+ }+ if (isWord(sections.SELECT[0], 'DISTINCT')) {+ throw new SqlReadError('SELECT DISTINCT is not supported.')+ }++ let source: Source | null = null+ let sourceAlias: string | null = null+ const joins: Join[] = []+ if (sections.FROM?.length) {+ const parsed = parseSource(sections.FROM)+ source = parsed.source+ sourceAlias = parsed.alias+ let rest = parsed.rest+ while (rest.length) {+ while (rest.length && isWord(rest[0], ...JOIN_WORDS)) {+ rest = rest.slice(1)+ }+ const join = parseSource(rest)+ joins.push({ source: join.source, alias: join.alias })+ rest = join.rest+ if (isWord(rest[0], 'ON', 'USING')) {+ const next = rest.findIndex(+ (token, i) => i > 0 && isWord(token, 'LEFT', 'RIGHT', 'INNER', 'FULL', 'CROSS', 'JOIN')+ )+ rest = next === -1 ? [] : rest.slice(next)+ }+ }+ }+ return {+ columns: splitTopLevel(sections.SELECT, commaSeparator).map(parseColumn),+ source,+ sourceAlias,+ joins,+ where: sections.WHERE ? splitTopLevel(sections.WHERE, andSeparator) : [],+ groupBy: sections.GROUP ? splitTopLevel(sections.GROUP, commaSeparator) : [],+ having: sections.HAVING ?? [],+ limit: sections.LIMIT ?? [],+ }+}++const STRING = `"(?:[^"\\\\]|\\\\.)*"`+const FIELD_PATTERNS: [RegExp, (match: RegExpExecArray) => { key: string; scope?: MetricsAttributeScope }][] = [+ [/^(?:\w+\.)?service_name$/i, () => ({ key: 'service_name' })],+ [+ new RegExp(`^arrayElement\\((resource_attributes|attributes),(${STRING})\\)$`, 'i'),+ (m) => ({ key: JSON.parse(m[2]), scope: m[1].toLowerCase() === 'attributes' ? 'attribute' : 'resource' }),+ ],+ [+ new RegExp(`^(resource_attributes|attributes)\\[(${STRING})\\]$`, 'i'),+ (m) => ({ key: JSON.parse(m[2]), scope: m[1].toLowerCase() === 'attributes' ? 'attribute' : 'resource' }),+ ],+ [+ new RegExp(+ `^if\\(arrayElement\\(resource_attributes,(${STRING})\\)!="",arrayElement\\(resource_attributes,\\1\\),arrayElement\\(attributes,\\1\\)\\)$`,+ 'i'+ ),+ (m) => ({ key: JSON.parse(m[1]) }),+ ],+ [/^toString\((.*)\)$/i, (m) => readField(m[1]) ?? { key: '' }],+]++function readField(text: string): { key: string; scope?: MetricsAttributeScope } | null {+ for (const [pattern, read] of FIELD_PATTERNS) {+ const match = pattern.exec(text)+ if (match) {+ const field = read(match)+ return field.key ? field : null+ }+ }+ return null+}++const withScope = <T extends { key: string }>(item: T, scope: MetricsAttributeScope | undefined): T =>+ scope && scope !== 'auto' ? { ...item, scope } : item++const toBuilderRegex = (values: string[]): string =>+ `^(?:${values.map((value) => value.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')).join('|')})$`++class ClauseSqlReader {+ clause: Partial<BuilderClause> & { filters: MetricsQueryFilter[] } = { filters: [] }++ constructor(private issues: string[]) {}++ private note(issue: string): void {+ if (!this.issues.includes(issue)) {+ this.issues.push(issue)+ }+ }++ /** One WHERE condition of the points query or the series subquery. */+ private readCondition(tokens: Token[]): void {+ const text = canon(unwrap(tokens))+ const nameMatch = new RegExp(`^metric_name=(${STRING})$`, 'i').exec(text)+ if (nameMatch) {+ const name = JSON.parse(nameMatch[1])+ if (this.clause.metricName && this.clause.metricName !== name) {+ this.note(+ `The SQL reads more than one metric (${this.clause.metricName}, ${name}); only the first is kept.`+ )+ } else {+ this.clause.metricName = name+ }+ return+ }+ const typeMatch = new RegExp(`^metric_type=(${STRING})$`, 'i').exec(text)+ if (typeMatch) {+ this.clause.metricType = JSON.parse(typeMatch[1])+ return+ }+ // Time bounds come from the chart's date range and interval.+ if (+ /^(timestamp|last_seen|time_bucket)(>=|<|<=|>)/i.test(text) ||+ /^notEmpty\(histogram_counts\)$/i.test(text)+ ) {+ if (!/\{(date_from|date_to)\}/.test(text) && !/histogram_counts/.test(text)) {+ this.note(`The fixed time bound "${text}" is replaced by the chart date range.`)+ }+ return+ }+ const scoped = /^series_fingerprint IN\((.*)\)$/i.exec(text)+ if (scoped) {+ this.readSeriesSubquery(unwrap(tokens).slice(2))+ return+ }+ if (this.readFilter(text)) {+ return+ }+ this.note(`The condition "${text}" is not supported and is dropped.`)+ }++ private readFilter(text: string): boolean {+ const negated = /^NOT\s*/i.exec(text)+ const body = negated ? text.slice(negated[0].length) : text+ const match = new RegExp(`^match\\((.*),(${STRING})\\)$`, 'i').exec(body)+ if (match) {+ const field = readField(match[1].trim())+ if (field) {+ this.clause.filters.push(+ withScope(+ { key: field.key, op: negated ? 'not_regex' : 'regex', value: JSON.parse(match[2]) },+ field.scope+ )+ )+ return true+ }+ }+ if (negated) {+ return false+ }+ const comparison = new RegExp(`^(.*?)(!=|<>|==|=)(${STRING})$`).exec(text)+ if (comparison) {+ const field = readField(comparison[1].trim())+ if (field) {+ this.clause.filters.push(+ withScope(+ {+ key: field.key,+ op: comparison[2] === '=' || comparison[2] === '==' ? 'eq' : 'neq',+ value: JSON.parse(comparison[3]),+ },+ field.scope+ )+ )+ return true+ }+ }+ const inList = new RegExp(`^(.*?)(NOT IN|IN)\\(((?:${STRING},?)+)\\)$`, 'i').exec(text)+ if (inList) {+ const field = readField(inList[1].trim())+ const values = [...inList[3].matchAll(new RegExp(STRING, 'g'))].map((m) => JSON.parse(m[0]) as string)+ if (field && values.length) {+ const op = inList[2].toUpperCase() === 'IN' ? 'regex' : 'not_regex'+ this.clause.filters.push(withScope({ key: field.key, op, value: toBuilderRegex(values) }, field.scope))+ return true+ }+ }+ return false+ }++ private readSeriesSubquery(tokens: Token[]): void {+ const select = parseSelect(unwrap(tokens))+ if (select.source?.kind !== 'table' || !/(^|\.)metric_series$/i.test(select.source.name)) {+ this.note('A series filter that does not read posthog.metric_series is dropped.')+ return+ }+ select.where.forEach((condition) => this.readCondition(condition))+ }++ readPoints(select: SelectParts): void {+ select.where.forEach((condition) => this.readCondition(condition))+ }+}++const isMetricsTable = (source: Source | null): boolean =>+ source?.kind === 'table' && /(^|\.)(metrics|metric_samples)$/i.test(source.name)++const SIMPLE_AGGREGATIONS: Record<string, BuilderClause['aggregation']> = {+ sum: 'sum',+ avg: 'avg',+ min: 'min',+ max: 'max',+ count: 'count',+}++// Result columns, and the histogram columns builderToSql passes between its selects.+const NON_LABEL_COLUMNS = new Set([+ 'time',+ 'value',+ 'clause',+ 'bounds',+ 'layouts',+ 'counts',+ 'series_fingerprints',+ PER_SERIES_COLUMN,+])++interface ReadClause {+ clause: BuilderClause+ /** Alias from a `'a' AS clause` column. */+ label: string | null+}++/** Reads one clause from a single SELECT and the subqueries in its FROM. */+function readClauseSelect(tokens: Token[], issues: string[]): ReadClause | null {+ const note = (issue: string): void => {+ if (!issues.includes(issue)) {+ issues.push(issue)+ }+ }+ const chain: SelectParts[] = [parseSelect(tokens)]+ while (chain[chain.length - 1].source?.kind === 'subquery') {+ const source = chain[chain.length - 1].source as Extract<Source, { kind: 'subquery' }>+ if (splitTopLevel(source.tokens, unionSeparator).length > 1) {+ note('A UNION inside a series is not supported.')+ return null+ }+ chain.push(parseSelect(source.tokens))+ }+ const points = chain[chain.length - 1]+ if (!isMetricsTable(points.source)) {+ note('The SQL does not read posthog.metrics.')+ return null+ }+ const reader = new ClauseSqlReader(issues)+ reader.readPoints(points)+ if (!reader.clause.metricName) {+ note('The SQL has no metric_name condition, so there is no metric to chart.')+ return null+ }++ const allText = chain.flatMap((select) => select.columns.map((column) => canon(column.expr))).join(' ')+ const outer = chain[0]+ const valueColumn = outer.columns.find((column) => column.alias?.toLowerCase() === 'value')+ if (!valueColumn) {+ note('The SQL has no "value" column.')+ return null+ }+ const valueText = canon(valueColumn.expr).replace(/^toFloat(?:64)?\((.*)\)$/i, '$1')+ const timeColumn = outer.columns.find((column) => column.alias?.toLowerCase() === 'time')+ if (+ !timeColumn ||+ (!/\{interval\}/.test(canon(timeColumn.expr)) && !/^(\w+\.)?time$/i.test(canon(timeColumn.expr)))+ ) {+ note('The time buckets are replaced by the chart interval.')+ }+ if (chain.some((select) => select.limit.length)) {+ note('LIMIT is dropped.')+ }++ let aggregation: BuilderClause['aggregation']+ let rangeFunction: BuilderClause['rangeFunction']+ let quantile: number | undefined+ if (/histogram_counts|sumForEach/i.test(allText)) {+ aggregation = 'histogram_quantile'+ const rank = /(\d*\.?\d+)\*arraySum\(counts\)/i.exec(allText)+ quantile = rank ? Number(rank[1]) : 0.95+ if (!rank) {+ note('The histogram quantile cannot be found; 0.95 is used.')+ }+ } else {+ const counter = /lagInFrame/i.test(allText)+ if (counter) {+ rangeFunction = /\/\{interval_seconds\}/.test(allText) ? 'rate' : 'increase'+ }+ const quantileMatch = /^quantile\((\d*\.?\d+)\)\((.*)\)$/i.exec(valueText)+ const simpleMatch = /^(\w+)\((.*)\)$/.exec(valueText)+ if (/^(\w+\.)?series_value$/i.test(valueText)) {+ // Each series stays its own line.+ aggregation = undefined+ } else if (counter && /^sum\((\w+\.)?contribution\)/i.test(valueText)) {+ // Summing every sample's contribution sums the per-series values.+ aggregation = 'sum'+ } else if (quantileMatch) {+ aggregation = 'quantile'+ quantile = ENGINE_QUANTILE+ if (Number(quantileMatch[1]) !== ENGINE_QUANTILE) {+ note(`Metrics support only quantile ${ENGINE_QUANTILE}; quantile(${quantileMatch[1]}) uses it.`)+ }+ } else if (simpleMatch && SIMPLE_AGGREGATIONS[simpleMatch[1].toLowerCase()]) {+ aggregation = SIMPLE_AGGREGATIONS[simpleMatch[1].toLowerCase()]+ } else {+ note(`The value "${valueText}" is not a supported aggregation; sum is used.`)+ aggregation = 'sum'+ }+ // The builder reduces each series to one value per bucket before it aggregates.+ if (chain.length === 1 && !counter) {+ note(+ aggregation === 'count'+ ? 'The SQL counts samples; the builder counts series.'+ : 'The SQL aggregates every sample; the builder aggregates the last value of each series in each interval.'+ )+ }+ }++ // Group-by labels: the select that joins posthog.metric_series names them group_0, group_1, …+ // Without a join, the outer select reads label columns directly.+ const groupBy: MetricsQueryGroupBy[] = []+ let label: string | null = null+ const labelSelect = chain.find((select) => select.joins.some((join) => join.source.kind === 'subquery')) ?? outer+ const groupFields = new Map<string, { key: string; scope?: MetricsAttributeScope }>()+ for (const join of labelSelect.joins) {+ if (join.source.kind !== 'subquery') {+ continue+ }+ for (const column of parseSelect(join.source.tokens).columns) {+ const field = /^any\((.*)\)$/i.exec(canon(column.expr))+ const read = field ? readField(field[1]) : null+ if (column.alias && read) {+ groupFields.set(column.alias, read)+ }+ }+ }+ for (const column of labelSelect.columns) {+ const alias = column.alias?.toLowerCase()+ if (alias === 'clause' && column.expr.length === 1 && column.expr[0].type === 'string') {+ label = column.expr[0].value+ continue+ }+ if (!alias || NON_LABEL_COLUMNS.has(alias)) {+ continue+ }+ const text = canon(column.expr)+ // A column that passes on a label an inner select sets to '' is not a group-by.+ const emptyInside = chain.some((select) =>+ select.columns.some((inner) => inner.alias?.toLowerCase() === alias && canon(inner.expr) === '""')+ )+ if (emptyInside && /^(?:\w+\.)?(?:\w+|`[^`]*`)$/.test(text)) {+ continue+ }+ const groupMatch = /^(?:\w+\.)?(group_\d+)$/.exec(text)+ const field = groupMatch ? groupFields.get(groupMatch[1]) : readField(text)+ if (field) {+ groupBy.push(withScope({ key: field.key }, field.scope))+ } else if (text !== '""') {+ note(`The column "${column.alias}" is not a label the builder can group by and is dropped.`)+ }+ }++ const { metricName, metricType, filters } = reader.clause+ return {+ clause: {+ name: '',+ metricName: metricName!,+ ...(aggregation ? { aggregation } : {}),+ ...(rangeFunction ? { rangeFunction } : {}),+ ...(metricType ? { metricType } : {}),+ ...(filters.length ? { filters } : {}),+ ...(groupBy.length ? { groupBy } : {}),+ ...(quantile !== undefined ? { quantile } : {}),+ } as BuilderClause,+ label,+ }+}++const isZero = (token: Token | undefined): boolean => token?.type === 'number' && Number(token.value) === 0++/**+ * The builder formula of the value expression builderToSql writes: `+ - * /` over clause aliases and+ * numbers, where `if(r = 0, 0, l / r)` is the division `l / r`. Null for any other SQL.+ */+function formulaFromSql(tokens: Token[]): string | null {+ let i = 0+ const expr = (): string | null => {+ let lhs = term()+ while (lhs !== null && (isPunct(tokens[i], '+') || isPunct(tokens[i], '-'))) {+ const op = tokens[i++].value+ const rhs = term()+ lhs = rhs === null ? null : `${lhs} ${op} ${rhs}`+ }+ return lhs+ }+ const term = (): string | null => {+ let lhs = factor()+ while (lhs !== null && (isPunct(tokens[i], '*') || isPunct(tokens[i], '/'))) {+ const op = tokens[i++].value+ const rhs = factor()+ lhs = rhs === null ? null : `${lhs} ${op} ${rhs}`+ }+ return lhs+ }+ const factor = (): string | null => {+ const token = tokens[i]+ if (isPunct(token, '-') || isPunct(token, '+')) {+ i+++ const inner = factor()+ return inner === null ? null : `${token.value}${inner}`+ }+ // The builder formula has no exponent notation.+ if (token?.type === 'number' && !/e/i.test(token.value)) {+ i+++ return token.value+ }+ if (isPunct(token, '(')) {+ i+++ const inner = expr()+ if (inner === null || !isPunct(tokens[i], ')')) {+ return null+ }+ i+++ return `(${inner})`+ }+ if (isWord(token, 'IF') && isPunct(tokens[i + 1], '(')) {+ i += 2+ const divisor = expr()+ if (+ divisor === null ||+ !isPunct(tokens[i], '=') ||+ !isZero(tokens[i + 1]) ||+ !isPunct(tokens[i + 2], ',') ||+ !isZero(tokens[i + 3]) ||+ !isPunct(tokens[i + 4], ',')+ ) {+ return null+ }+ i += 5+ const division = expr()+ if (division === null || !isPunct(tokens[i], ')') || !division.endsWith(` / ${divisor}`)) {+ return null+ }+ i+++ return division+ }+ if (token?.type === 'word') {+ i+++ return token.value.toLowerCase()+ }+ return null+ }+ const formula = expr()+ return formula !== null && i === tokens.length ? formula : null+}++export function sqlToBuilder(sql: string): ConversionResult<BuilderQuery> {+ if (!sql.trim()) {+ return { value: { clauses: [] }, issues: [] }+ }+ const issues: string[] = []+ const tooCustom = (): ConversionResult<BuilderQuery> => ({+ value: null,+ issues: [...issues, 'This SQL cannot be converted.'],+ })+ try {+ const tokens = tokenize(sql.trim().replace(/;\s*$/, ''))+ const branches = splitTopLevel(tokens, unionSeparator)++ if (branches.length > 1) {+ const clauses: BuilderClause[] = []+ for (const branch of branches.slice(0, MAX_CONVERTED_CLAUSES)) {+ const read = readClauseSelect(branch, issues)+ if (!read) {+ return tooCustom()+ }+ clauses.push({ ...read.clause, name: read.label ?? clauseAlias(clauses.length) })+ }+ if (branches.length > MAX_CONVERTED_CLAUSES) {+ issues.push(`A query can have at most ${MAX_CONVERTED_CLAUSES} series; the others are dropped.`)+ }+ return { value: { clauses: dedupeNames(clauses) }, issues }+ }++ const formula = readFormula(tokens, issues)+ if (formula) {+ return formula.value ? formula : tooCustom()+ }+ const read = readClauseSelect(tokens, issues)+ return read ? { value: { clauses: [{ ...read.clause, name: 'a' }] }, issues } : tooCustom()+ } catch (error) {+ if (error instanceof SqlReadError) {+ issues.push(error.message)+ return tooCustom()+ }+ throw error+ }+}++const dedupeNames = (clauses: BuilderClause[]): BuilderClause[] => {+ const seen = new Set<string>()+ return clauses.map((clause, index) => {+ const name = /^[a-z_][a-z0-9_]*$/.test(clause.name) && !seen.has(clause.name) ? clause.name : clauseAlias(index)+ seen.add(name)+ return { ...clause, name }+ })+}++/**+ * The formula shape builderToSql writes: an outer formula over per-clause sums of a UNION ALL, which+ * keeps the label sets every series has. Null when it is not that shape.+ */+function readFormula(tokens: Token[], issues: string[]): ConversionResult<BuilderQuery> | null {+ const outer = parseSelect(tokens)+ if (outer.source?.kind !== 'subquery') {+ return null+ }+ const middle = parseSelect(outer.source.tokens)+ if (middle.source?.kind !== 'subquery') {+ return null+ }+ const branches = splitTopLevel(middle.source.tokens, unionSeparator)+ // `sum(sum(x)) OVER (PARTITION BY time)` spreads a series without labels over every label set.+ const sums = middle.columns.filter((column) =>+ /^sum\((?:[a-z_][a-z0-9_]*|sum\([a-z_][a-z0-9_]*\)\)OVER\(PARTITION BY time)\)$/i.test(canon(column.expr))+ )+ if (branches.length < 1 || sums.length === 0 || sums.length !== branches.length) {+ return null+ }+ const valueColumn = outer.columns.find((column) => column.alias?.toLowerCase() === 'value')+ if (!valueColumn) {+ return null+ }+ const clauses: BuilderClause[] = []+ for (const branch of branches) {+ const select = parseSelect(branch)+ const own = select.columns.find((column) => canon(column.expr).toLowerCase() === 'value' && column.alias)+ if (!own || select.source?.kind !== 'subquery') {+ return null+ }+ const read = readClauseSelect(select.source.tokens, issues)+ if (!read) {+ return { value: null, issues }+ }+ clauses.push({ ...read.clause, name: own.alias!.toLowerCase() })+ }+ const formula = formulaFromSql(valueColumn.expr)+ if (formula === null) {+ issues.push(`The formula "${canon(valueColumn.expr)}" uses SQL the builder formula does not support.`)+ return { value: null, issues }+ }+ return { value: { clauses, formula }, issues }+}diff --git a/products/metrics/frontend/queryLanguages/types.ts b/products/metrics/frontend/queryLanguages/types.tsnew file mode 100644index 000000000000..dd9a9173f17e--- /dev/null+++ b/products/metrics/frontend/queryLanguages/types.ts@@ -0,0 +1,61 @@+import type { MetricsQuery, MetricsQueryClause } from '~/queries/schema/schema-general'++/** The builder form of a metrics query: the pivot every conversion goes through. */+export type BuilderQuery = Pick<MetricsQuery, 'clauses' | 'formula'>++export type BuilderClause = MetricsQueryClause++/** A clause in the builder's current form: the legacy `rate` and `increase` aggregations mean `sum` over that range function. */+export const normalizeClause = (clause: BuilderClause): BuilderClause =>+ clause.aggregation === 'rate' || clause.aggregation === 'increase'+ ? { ...clause, aggregation: 'sum', rangeFunction: clause.aggregation }+ : clause++/**+ * The result of a best-effort conversion. `value` is null when nothing usable came out.+ * Each issue names one part of the source that the target cannot express or that changes meaning.+ * No issues means the conversion is lossless.+ */+export interface ConversionResult<T> {+ value: T | null+ issues: string[]+}++/** A finite number in plain decimal form: the builder formula has no exponent notation. */+export function plainNumber(value: number): string {+ const match = /^(-?)(\d)(?:\.(\d+))?e([+-]\d+)$/.exec(String(value))+ if (!match) {+ return String(value)+ }+ const [, sign, first, rest = '', exponent] = match+ const digits = first + rest+ const point = 1 + Number(exponent)+ if (point <= 0) {+ return `${sign}0.${'0'.repeat(-point)}${digits}`+ }+ return point >= digits.length+ ? sign + digits + '0'.repeat(point - digits.length)+ : `${sign}${digits.slice(0, point)}.${digits.slice(point)}`+}++/** Alias for the n-th clause a conversion creates, matching the builder's a, b, c… */+export const clauseAlias = (index: number): string => String.fromCharCode('a'.charCodeAt(0) + index)++/** The engine runs `quantile` only at 0.95, the builder's p95. */+export const ENGINE_QUANTILE = 0.95++// Mirrors MAX_CLAUSES in metricsViewerLogic and the backend's MAX_CLAUSES_PER_QUERY.+export const MAX_CONVERTED_CLAUSES = 10++/** Ingestion stores `service.name` in its own column, and both PromQL and SQL call it `service_name`. */+export const normalizeLabelKey = (key: string): string => (key === 'service.name' ? 'service_name' : key)++// The PromQL label that keeps the series of a multi-series query apart, as the builder's clause alias does.+export const CLAUSE_LABEL = 'clause'++// The backend fills an interval with no SQL row with 0. The builder calculates the formula there.+export const SQL_EMPTY_INTERVAL_ISSUE =+ 'Where a label set has no data in an interval, SQL shows 0, but the builder calculates the formula with those series at 0.'++/** Issues about values the target computes differently. The query itself converts without change. */+export const VALUE_ONLY_ISSUES = new Set([SQL_EMPTY_INTERVAL_ISSUE])diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.tsindex b9bec8382ff1..d6345e0a8dc7 100644--- a/services/mcp/src/api/generated.ts+++ b/services/mcp/src/api/generated.ts@@ -56191,6 +56191,15 @@ export namespace Schemas {yAxis?: MetricsYAxisSettings | null;}+ export type MetricsQueryLanguage = typeof MetricsQueryLanguage[keyof typeof MetricsQueryLanguage];+++ export const MetricsQueryLanguage = {+ Builder: 'builder',+ Promql: 'promql',+ Sql: 'sql',+ } as const;+export interface MetricsQueryPoint {/** Bucket start, ISO 8601 */time: string;@@ -56237,6 +56246,7 @@ export namespace Schemas {}export interface MetricsQuery {+ /** Empty when `language` is `promql` or `sql`. */clauses: MetricsQueryClause[];/** Defaults to the last 24 hours when omitted; dashboard date filters override it */dateRange?: DateRange | null;@@ -56247,9 +56257,15 @@ export namespace Schemas {/** Bucket size, one of: second_15, second_30, minute, minute_5, minute_15, minute_30, hour, hour_6, day, week; auto-picked from the range when omitted. Coarsened when the range would need more than 10,000 buckets. */interval?: string | null;kind?: 'MetricsQuery';+ /** How the query is written; the builder when unset. */+ language?: MetricsQueryLanguage | null;/** Modifiers used when performing the query */modifiers?: HogQLQueryModifiers | null;+ /** PromQL expression, run as a range query. Used when `language` is `promql`. */+ promql?: string | null;response?: MetricsQueryResponse | null;+ /** HogQL SELECT over the posthog.metric* tables. Used when `language` is `sql`. It must return a `time` and a `value` column; every other column is a series label. `{date_from}`, `{date_to}`, `{interval}` and `{interval_seconds}` are filled in from the date range and interval. */+ sql?: string | null;tags?: QueryLogTags | null;/** version of the node, used for schema migrations */version?: number | null;