: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): add SQL editor scene for the alpha metrics product (#60374)
Daniel Visca52e565e59620
diff --git a/frontend/src/lib/api.ts b/frontend/src/lib/api.tsindex 34c26b6d6b7c..1a5dd65ebd67 100644--- a/frontend/src/lib/api.ts+++ b/frontend/src/lib/api.ts@@ -730,6 +730,15 @@ export class ApiRequest {return this.logs(projectId).addPathComponent('export')}+ // # Metrics+ public metrics(projectId?: ProjectType['id']): ApiRequest {+ return this.environmentsDetail(projectId).addPathComponent('metrics')+ }++ public metricsHasMetrics(projectId?: ProjectType['id']): ApiRequest {+ return this.metrics(projectId).addPathComponent('has_metrics')+ }+// # Tracingpublic tracingSpans(): ApiRequest {return this.environmentsDetail().addPathComponent('tracing').addPathComponent('spans')@@ -2785,6 +2794,15 @@ const api = {},},+ metrics: {+ async hasMetrics(): Promise<boolean> {+ return new ApiRequest()+ .metricsHasMetrics()+ .get()+ .then((response) => Boolean(response.hasMetrics))+ },+ },+tracing: {async listSpans(query: {diff --git a/frontend/src/lib/scopes.tsx b/frontend/src/lib/scopes.tsxindex 57ec4c33b6ff..f31498160b0f 100644--- a/frontend/src/lib/scopes.tsx+++ b/frontend/src/lib/scopes.tsx@@ -70,6 +70,7 @@ export const API_SCOPES: APIScope[] = [{ key: 'llm_skill', objectName: 'LLM skill', objectPlural: 'LLM skills' },{ key: 'logs', objectName: 'Logs', objectPlural: 'logs' },{ key: 'marketing_analytics', objectName: 'Marketing analytics', objectPlural: 'marketing analytics' },+ { key: 'metrics', objectName: 'Metrics', objectPlural: 'metrics' },{ key: 'notebook', objectName: 'Notebook', objectPlural: 'notebooks' },{ key: 'organization', objectName: 'Organization', objectPlural: 'organizations', disabledWhenProjectScoped: true },{diff --git a/frontend/src/queries/schema.json b/frontend/src/queries/schema.jsonindex 605d6bdd5650..0b208ef795bb 100644--- a/frontend/src/queries/schema.json+++ b/frontend/src/queries/schema.json@@ -28397,6 +28397,7 @@"logs_docs_viewed","logs_set_filters","logs_settings_opened",+ "metrics_docs_viewed","taxonomic filter empty state","create_experiment_from_funnel_button","web_analytics_insight",diff --git a/frontend/src/queries/schema/schema-general.ts b/frontend/src/queries/schema/schema-general.tsindex 79cb798d4e9d..ccdddc32be04 100644--- a/frontend/src/queries/schema/schema-general.ts+++ b/frontend/src/queries/schema/schema-general.ts@@ -6608,6 +6608,9 @@ export enum ProductIntentContext {LOGS_SET_FILTERS = 'logs_set_filters',LOGS_SETTINGS_OPENED = 'logs_settings_opened',+ // Metrics+ METRICS_DOCS_VIEWED = 'metrics_docs_viewed',+// Product AnalyticsTAXONOMIC_FILTER_EMPTY_STATE = 'taxonomic filter empty state',CREATE_EXPERIMENT_FROM_FUNNEL_BUTTON = 'create_experiment_from_funnel_button',diff --git a/frontend/src/types.ts b/frontend/src/types.tsindex 6fc5d95fa048..218c4dd466fb 100644--- a/frontend/src/types.ts+++ b/frontend/src/types.ts@@ -5376,6 +5376,7 @@ export type APIScopeObject =| 'llm_skill'| 'logs'| 'marketing_analytics'+ | 'metrics'| 'notebook'| 'organization'| 'organization_integration'diff --git a/pnpm-lock.yaml b/pnpm-lock.yamlindex 5c66650d5b1c..45513a943f96 100644--- a/pnpm-lock.yaml+++ b/pnpm-lock.yaml@@ -448,7 +448,7 @@ importers:version: 7.6.24([email protected])([email protected]([email protected]))([email protected])([email protected])'@storybook/react-webpack5':specifier: ^7.6.4- version: 7.6.4(@babel/[email protected])(@swc/[email protected])([email protected])([email protected])([email protected])([email protected]([email protected]))([email protected])([email protected])([email protected])([email protected])([email protected])+ version: 7.6.4(@babel/[email protected])(@swc/[email protected])([email protected])([email protected])([email protected]([email protected]))([email protected])([email protected])([email protected])([email protected])([email protected])'@storybook/test-runner':specifier: ^0.16.0version: 0.16.0([email protected])@@ -502,7 +502,7 @@ importers:version: 2.0.0([email protected])webpack:specifier: ^5.88.2webpack-cli:specifier: ^5.1.4version: 5.1.4([email protected])@@ -1474,7 +1474,7 @@ importers:version: 0.4.8([email protected])'@segment/action-destinations':specifier: ^3.383.0- version: 3.387.0([email protected])([email protected])+ version: 3.387.0([email protected])([email protected])'@temporalio/activity':specifier: 1.15.0version: 1.15.0@@ -3078,6 +3078,9 @@ importers:kea-router:specifier: 'catalog:'version: 3.4.1([email protected]([email protected]))+ posthog-js:+ specifier: 'catalog:'+ version: 1.376.3react:specifier: 18.3.1version: 18.3.1@@ -23190,8 +23193,8 @@ packages:resolution: {integrity: sha512-gptHNQghINnc/vTGIk0SOFGFNXw7JVrlRUtConJRlvaw6DuX0wO5Jeko9sWrMBhh+PsYAZ7oXAiOnf/UKogyiw==}engines: {node: '>= 10.0.0'}- resolution: {integrity: sha512-g2Btv3iOmCRIW2VGXOjBAeXAEDk6IoftdXewS1+spkRp2OTCHJOJCp3dZoSSKPLyFBF5hwoekBJ7WSdvLNCn8Q==}+ resolution: {integrity: sha512-vt6MkgpgiEYSAPzZBhxvUKoTaRtFTVm1/gh+UKmB+b95iiqs47Qz1XffA0N/kRihzuvs6E2XkQHbImX1QDLlIQ==}resolution: {integrity: sha512-pjy2bYhSsufwWlKwPc+l3cN7+wuJlK6uz0YdJEOlQDbl6jo/YlPi4mb8agUkVC8BF7V8NuzeyPNqRksA3hztKQ==}@@ -32385,7 +32388,7 @@ snapshots:react-refresh: 0.14.0schema-utils: 3.3.0source-map: 0.7.6optionalDependencies:type-fest: 4.41.0webpack-hot-middleware: 2.25.4@@ -33600,7 +33603,7 @@ snapshots:'@segment/[email protected]': {}dependencies:'@amplitude/ua-parser-js': 0.7.33'@aws-sdk/client-eventbridge': 3.806.0@@ -33610,7 +33613,7 @@ snapshots:'@segment/actions-core': 3.153.0([email protected])'@segment/actions-shared': 1.134.0([email protected])'@types/node': 22.18.8- ajv-formats: 2.1.1([email protected])+ ajv-formats: 2.1.1([email protected])aws4: 1.13.2cheerio: 1.0.0dayjs: 1.11.11(patch_hash=2e3e09d22bbc20d8961e0392c318f12ffada0babb6422f03b5538af8b2707852)@@ -34424,7 +34427,7 @@ snapshots:- encoding- supports-color- '@storybook/[email protected]([email protected])([email protected])([email protected])([email protected])([email protected])':+ '@storybook/[email protected]([email protected])([email protected])([email protected])([email protected])':dependencies:'@babel/core': 7.29.0'@storybook/channels': 7.6.4@@ -34454,12 +34457,12 @@ snapshots:semver: 7.7.4style-loader: 3.3.3([email protected])swc-loader: 0.2.3(@swc/[email protected])([email protected])- terser-webpack-plugin: 5.6.0(@swc/[email protected])([email protected])([email protected])([email protected])ts-dedent: 2.2.0url: 0.11.1util: 0.12.5util-deprecate: 1.0.2webpack-dev-middleware: 6.1.3([email protected])webpack-hot-middleware: 2.25.4webpack-virtual-modules: 0.5.0@@ -34548,7 +34551,7 @@ snapshots:get-port: 5.1.1giget: 1.2.5globby: 11.1.0- jscodeshift: 0.15.2(@babel/[email protected](@babel/[email protected]))+ jscodeshift: 0.15.2(@babel/[email protected](@babel/[email protected]))leven: 3.1.0ora: 5.4.1prettier: 2.8.8@@ -34594,7 +34597,7 @@ snapshots:'@types/cross-spawn': 6.0.6cross-spawn: 7.0.6globby: 11.1.0- jscodeshift: 0.15.2(@babel/[email protected](@babel/[email protected]))+ jscodeshift: 0.15.2(@babel/[email protected](@babel/[email protected]))lodash: 4.18.1prettier: 2.8.8recast: 0.23.11@@ -34934,7 +34937,7 @@ snapshots:'@storybook/[email protected]': {}- '@storybook/[email protected](@babel/[email protected])(@swc/[email protected])([email protected])([email protected])([email protected])([email protected]([email protected]))([email protected])([email protected])([email protected])([email protected])([email protected])':+ '@storybook/[email protected](@babel/[email protected])(@swc/[email protected])([email protected])([email protected])([email protected]([email protected]))([email protected])([email protected])([email protected])([email protected])([email protected])':dependencies:'@babel/preset-flow': 7.23.3(@babel/[email protected])'@babel/preset-react': 7.23.3(@babel/[email protected])@@ -34954,7 +34957,7 @@ snapshots:react-dom: 18.3.1([email protected])react-refresh: 0.14.0semver: 7.7.4optionalDependencies:'@babel/core': 7.26.0typescript: 6.0.3@@ -35063,7 +35066,7 @@ snapshots:react-docgen-typescript: 2.2.2([email protected])tslib: 2.8.1typescript: 6.0.3transitivePeerDependencies:- supports-color@@ -35097,10 +35100,10 @@ snapshots:- typescript- vite-plugin-glimmerx- '@storybook/[email protected](@babel/[email protected])(@swc/[email protected])([email protected])([email protected])([email protected])([email protected]([email protected]))([email protected])([email protected])([email protected])([email protected])([email protected])':+ '@storybook/[email protected](@babel/[email protected])(@swc/[email protected])([email protected])([email protected])([email protected]([email protected]))([email protected])([email protected])([email protected])([email protected])([email protected])':dependencies:- '@storybook/builder-webpack5': 7.6.4([email protected])([email protected])([email protected])([email protected])([email protected])- '@storybook/preset-react-webpack': 7.6.4(@babel/[email protected])(@swc/[email protected])([email protected])([email protected])([email protected])([email protected]([email protected]))([email protected])([email protected])([email protected])([email protected])([email protected])+ '@storybook/builder-webpack5': 7.6.4([email protected])([email protected])([email protected])([email protected])+ '@storybook/preset-react-webpack': 7.6.4(@babel/[email protected])(@swc/[email protected])([email protected])([email protected])([email protected]([email protected]))([email protected])([email protected])([email protected])([email protected])([email protected])'@storybook/react': 7.6.4([email protected])([email protected]([email protected]))([email protected])([email protected])'@types/node': 18.19.130react: 18.3.1@@ -37672,17 +37675,17 @@ snapshots:dependencies:webpack-cli: 5.1.4([email protected])dependencies:webpack-cli: 5.1.4([email protected])dependencies:webpack-cli: 5.1.4([email protected])'@xmldom/[email protected]': {}@@ -38287,14 +38290,14 @@ snapshots:loader-utils: 2.0.4make-dir: 3.1.0schema-utils: 2.7.1dependencies:'@babel/core': 7.29.0find-cache-dir: 4.0.0schema-utils: 4.3.3@@ -39518,7 +39521,7 @@ snapshots:postcss-value-parser: 4.2.0schema-utils: 2.7.1semver: 6.3.1dependencies:@@ -39530,7 +39533,7 @@ snapshots:postcss-modules-values: 4.0.0([email protected])postcss-value-parser: 4.2.0semver: 7.8.0dependencies:@@ -41307,7 +41310,7 @@ snapshots:dependencies:loader-utils: 2.0.4schema-utils: 3.3.0dependencies:@@ -41465,7 +41468,7 @@ snapshots:semver: 7.8.0tapable: 2.3.0typescript: 6.0.3dependencies:@@ -42170,7 +42173,7 @@ snapshots:dependencies:html-webpack-plugin: 5.5.3([email protected])dependencies:@@ -42179,7 +42182,7 @@ snapshots:lodash: 4.18.1pretty-error: 4.0.0tapable: 2.2.1[email protected]([email protected]([email protected]))([email protected])([email protected])([email protected])([email protected])([email protected]):dependencies:@@ -44198,7 +44201,7 @@ snapshots:dependencies:'@babel/core': 7.29.0'@babel/parser': 7.29.3@@ -44221,7 +44224,7 @@ snapshots:temp: 0.8.4write-file-atomic: 2.4.3optionalDependencies:- '@babel/preset-env': 7.23.5(@babel/[email protected])+ '@babel/preset-env': 7.23.5(@babel/[email protected])transitivePeerDependencies:- supports-color@@ -44501,7 +44504,7 @@ snapshots:less: 4.2.2loader-utils: 2.0.4schema-utils: 3.3.0dependencies:@@ -46992,7 +46995,7 @@ snapshots:postcss: 8.5.6schema-utils: 3.3.0semver: 7.7.0dependencies:@@ -47986,7 +47989,7 @@ snapshots:dependencies:loader-utils: 2.0.4schema-utils: 3.3.0dependencies:@@ -48396,7 +48399,7 @@ snapshots:dependencies:react: 18.3.1- unlayer-types: 1.415.0+ unlayer-types: 1.406.0@@ -49125,7 +49128,7 @@ snapshots:neo-async: 2.6.2schema-utils: 3.3.0semver: 7.7.0optionalDependencies:sass: 1.56.0@@ -49855,11 +49858,11 @@ snapshots:dependencies:loader-utils: 2.0.4schema-utils: 3.3.0dependencies:@@ -50063,7 +50066,7 @@ snapshots:dependencies:'@swc/core': 1.15.18@@ -50251,28 +50254,27 @@ snapshots:ansi-escapes: 4.3.2supports-hyperlinks: 2.3.0- [email protected](@swc/[email protected])([email protected])([email protected])([email protected]):+ [email protected](@swc/[email protected])([email protected])([email protected])([email protected](@swc/[email protected])([email protected])([email protected])):dependencies:'@jridgewell/trace-mapping': 0.3.29jest-worker: 27.5.1schema-utils: 4.3.3terser: 5.46.0optionalDependencies:'@swc/core': 1.15.18- esbuild: 0.18.20+ esbuild: 0.27.7postcss: 8.5.6- [email protected](@swc/[email protected])([email protected])([email protected])([email protected](@swc/[email protected])([email protected])([email protected])):dependencies:'@jridgewell/trace-mapping': 0.3.29jest-worker: 27.5.1schema-utils: 4.3.3terser: 5.46.0optionalDependencies:'@swc/core': 1.15.18- esbuild: 0.27.7postcss: 8.5.6@@ -50937,7 +50939,7 @@ snapshots:- [email protected]: {}+ [email protected]: {}@@ -51517,7 +51519,7 @@ snapshots:import-local: 3.1.0interpret: 3.1.1rechoir: 0.8.0webpack-merge: 5.8.0@@ -51528,7 +51530,7 @@ snapshots:range-parser: 1.2.1schema-utils: 4.3.3optionalDependencies:dependencies:@@ -51588,7 +51590,7 @@ snapshots:- postcss- uglify-js- [email protected](@swc/[email protected])([email protected])([email protected])([email protected]):dependencies:'@types/eslint-scope': 3.7.4'@types/estree': 1.0.1@@ -51611,7 +51613,7 @@ snapshots:neo-async: 2.6.2schema-utils: 3.3.0tapable: 2.2.1- terser-webpack-plugin: 5.6.0(@swc/[email protected])([email protected])([email protected])([email protected])watchpack: 2.4.0webpack-sources: 3.2.3optionalDependencies:diff --git a/posthog/api/__init__.py b/posthog/api/__init__.pyindex 453b93a402be..50a1be25fe34 100644--- a/posthog/api/__init__.py+++ b/posthog/api/__init__.py@@ -40,6 +40,7 @@ import products.surveys.backend.api.survey as surveyimport products.revenue_analytics.backend.api as revenue_analyticsimport products.business_knowledge.backend.api as business_knowledgeimport products.marketing_analytics.backend.api as marketing_analytics+import products.metrics.backend.presentation.api as metricsimport products.early_access_features.backend.api as early_access_featureimport products.wizard.backend.presentation.views as wizard_sessionsimport products.customer_analytics.backend.api.views as customer_analytics@@ -1373,6 +1374,11 @@ register_grandfathered_environment_nested_viewset()environments_router.register(r"logs/views", logs.LogsViewViewSet, "environment_logs_views", ["team_id"])+# Metrics endpoints+register_grandfathered_environment_nested_viewset(+ r"metrics", metrics.MetricsViewSet, "environment_metrics", ["team_id"]+)+environments_router.register(r"logs/explainLogWithAI",logs.LogExplainViewSet,diff --git a/posthog/clickhouse/query_tagging.py b/posthog/clickhouse/query_tagging.pyindex 2140d6cce555..6cb6401d8eae 100644--- a/posthog/clickhouse/query_tagging.py+++ b/posthog/clickhouse/query_tagging.py@@ -44,6 +44,7 @@ class Product(StrEnum):LOGS = "logs"MARKETING_ANALYTICS = "marketing_analytics"MAX_AI = "max_ai"+ METRICS = "metrics"MCP = "mcp" # queries originating through the MCP server (agent tool calls)MCP_ANALYTICS = "mcp_analytics" # queries from the MCP analytics product (insights, dashboards, sessions)MESSAGING = "messaging"@@ -125,6 +126,7 @@ SCENE_TO_TAGS: dict[str, FallbackTags | None] = {"EndpointScene": {"product": Product.ENDPOINTS, "feature": Feature.QUERY},"EndpointsScene": {"product": Product.ENDPOINTS, "feature": Feature.QUERY},"Logs": {"product": Product.LOGS, "feature": Feature.QUERY},+ "Metrics": {"product": Product.METRICS, "feature": Feature.QUERY},"EventDefinition": {"product": Product.PRODUCT_ANALYTICS, "feature": Feature.EVENT_DEFINITION_SCENE},"EventDefinitionEdit": {"product": Product.PRODUCT_ANALYTICS, "feature": Feature.EVENT_DEFINITION_SCENE},"EventDefinitions": {"product": Product.PRODUCT_ANALYTICS, "feature": Feature.EVENT_DEFINITION_SCENE},@@ -592,6 +594,7 @@ EVENT_TAG_MATCHERS: frozenset[str] = frozenset().union(*(matchers for matchers,_TABLE_TO_TAGS: tuple[tuple[frozenset[str], FallbackTags], ...] = ((frozenset({"session_replay_events", "raw_session_replay_events"}), {"product": Product.REPLAY}),(frozenset({"logs", "log_attributes"}), {"product": Product.LOGS}),+ (frozenset({"metrics", "metric_attributes"}), {"product": Product.METRICS}),(frozenset({"events"}), {"product": Product.PRODUCT_ANALYTICS}),)diff --git a/posthog/schema.py b/posthog/schema.pyindex 9c02dccead09..4acdf39a7932 100644--- a/posthog/schema.py+++ b/posthog/schema.py@@ -3843,6 +3843,7 @@ class ProductIntentContext(StrEnum):LOGS_DOCS_VIEWED = "logs_docs_viewed"LOGS_SET_FILTERS = "logs_set_filters"LOGS_SETTINGS_OPENED = "logs_settings_opened"+ METRICS_DOCS_VIEWED = "metrics_docs_viewed"TAXONOMIC_FILTER_EMPTY_STATE = "taxonomic filter empty state"CREATE_EXPERIMENT_FROM_FUNNEL_BUTTON = "create_experiment_from_funnel_button"WEB_ANALYTICS_INSIGHT = "web_analytics_insight"diff --git a/posthog/scopes.py b/posthog/scopes.pyindex 74a16bd5f4a8..48fc3cd1b01d 100644--- a/posthog/scopes.py+++ b/posthog/scopes.py@@ -69,6 +69,7 @@ APIScopeObject = Literal["llm_skill","logs","marketing_analytics",+ "metrics","notebook","organization","organization_integration",@@ -128,7 +129,7 @@ INTERNAL_API_SCOPE_OBJECTS: frozenset[APIScopeObject] = frozenset({"clickhouse_t# OAuth metadata. Used for alpha / not-yet-public products where a user can# manually paste the scope into a PAT but where we don't want OAuth-based# clients (the consent screen, MCP, third-party apps) to discover it.-OAUTH_HIDDEN_SCOPE_OBJECTS: frozenset[APIScopeObject] = frozenset({"wizard_session"})+OAUTH_HIDDEN_SCOPE_OBJECTS: frozenset[APIScopeObject] = frozenset({"metrics", "wizard_session"})PROJECT_SECRET_API_KEY_ALLOWED_API_SCOPE_ACTION: list[tuple[APIScopeObject, APIScopeActions]] = [("endpoint", "read")]diff --git a/products/metrics/backend/facade/api.py b/products/metrics/backend/facade/api.pyindex 931372b0079a..cb26bf447b71 100644--- a/products/metrics/backend/facade/api.py+++ b/products/metrics/backend/facade/api.py@@ -1,24 +1,15 @@-"""-Facade for metrics.+"""Facade for metrics.-This is the ONLY module other products are allowed to import.+This is the ONLY module other products (and the presentation layer) are+allowed to import. Internal modules (query runners) stay behind this seam+so import-linter's strict-mode contract holds.+"""-Responsibilities:-- Accept frozen dataclasses as input parameters-- Call business logic (logic.py)-- Convert Django models to frozen dataclasses before returning-- Enforce transactions where needed-- Remain thin and stable+from posthog.models import Team-Do NOT:-- Implement business logic here (use logic.py)-- Import DRF, serializers, or HTTP concerns-- Return ORM instances or QuerySets-"""+from products.metrics.backend.has_metrics_query_runner import team_has_metrics as _team_has_metrics-# --- Converters (model -> frozen dataclass) ----#-# These look repetitive when fields align 1:1. The value is having ONE place-# where "internal" becomes "external contract". When models and contracts drift,-# the mapper absorbs the change instead of it leaking everywhere.+def team_has_metrics(team: Team) -> bool:+ """Return True if the given team has ingested at least one metric."""+ return _team_has_metrics(team)diff --git a/products/metrics/backend/has_metrics_query_runner.py b/products/metrics/backend/has_metrics_query_runner.pynew file mode 100644index 000000000000..b54e82667759--- /dev/null+++ b/products/metrics/backend/has_metrics_query_runner.py@@ -0,0 +1,44 @@+import datetime as dt++from django.core.cache import cache++from posthog.hogql import ast+from posthog.hogql.parser import parse_select+from posthog.hogql.query import execute_hogql_query++from posthog.clickhouse.client.connection import Workload+from posthog.models import Team++HAS_METRICS_CACHE_TTL = int(dt.timedelta(days=7).total_seconds())+++class HasMetricsQueryRunner:+ def __init__(self, team: Team) -> None:+ self.team = team++ def run(self) -> bool:+ # `metrics` is only registered under the `posthog.` HogQL namespace+ # (posthog/hogql/database/database.py), so unlike `logs` it must be+ # referenced fully qualified.+ query = parse_select("SELECT 1 FROM posthog.metrics LIMIT 1")+ assert isinstance(query, ast.SelectQuery)++ response = execute_hogql_query(+ query_type="HasMetricsQuery",+ query=query,+ team=self.team,+ workload=Workload.LOGS,+ )++ return len(response.results) > 0+++def team_has_metrics(team: Team) -> bool:+ cache_key = f"team:{team.id}:has_metrics"+ if cache.get(cache_key) is True:+ return True++ has_metrics = HasMetricsQueryRunner(team).run()+ if has_metrics:+ cache.set(cache_key, True, HAS_METRICS_CACHE_TTL)+ return has_metricsdiff --git a/products/metrics/backend/presentation/api.py b/products/metrics/backend/presentation/api.pynew file mode 100644index 000000000000..ebc0e48232a4--- /dev/null+++ b/products/metrics/backend/presentation/api.py@@ -0,0 +1,44 @@+"""DRF views for the alpha metrics product.++Mirrors the shape of `products/logs/backend/api.py` so the two surfaces stay+recognisable. Today we only expose `has_metrics` — query/sparkline/etc. land+in follow-up PRs.+"""++from drf_spectacular.types import OpenApiTypes+from drf_spectacular.utils import extend_schema+from rest_framework import status, viewsets+from rest_framework.decorators import action+from rest_framework.request import Request+from rest_framework.response import Response++from posthog.api.documentation import _FallbackSerializer+from posthog.api.routing import TeamAndOrgViewSetMixin+from posthog.clickhouse.query_tagging import Feature, Product, tag_queries+from posthog.event_usage import report_user_action++from products.metrics.backend.facade.api import team_has_metrics++__all__ = ["MetricsViewSet"]+++@extend_schema(tags=["metrics"])+class MetricsViewSet(TeamAndOrgViewSetMixin, viewsets.ViewSet):+ scope_object = "metrics"+ serializer_class = _FallbackSerializer++ @extend_schema(responses={200: OpenApiTypes.OBJECT})+ @action(detail=False, methods=["GET"], required_scopes=["metrics:read"])+ def has_metrics(self, request: Request, *args, **kwargs) -> Response:+ tag_queries(product=Product.METRICS, feature=Feature.QUERY)+ has_metrics = team_has_metrics(self.team)++ report_user_action(+ request.user,+ "metrics has_metrics checked",+ {"has_metrics": has_metrics},+ team=self.team,+ request=request,+ )++ return Response({"hasMetrics": has_metrics}, status=status.HTTP_200_OK)diff --git a/products/metrics/backend/tests/test_has_metrics_query_runner.py b/products/metrics/backend/tests/test_has_metrics_query_runner.pynew file mode 100644index 000000000000..a8f7772cc45c--- /dev/null+++ b/products/metrics/backend/tests/test_has_metrics_query_runner.py@@ -0,0 +1,140 @@+import json++from posthog.test.base import APIBaseTest, ClickhouseTestMixin+from unittest.mock import patch++from django.core.cache import cache++from rest_framework import status++from posthog.clickhouse.client import sync_execute++from products.metrics.backend.has_metrics_query_runner import HasMetricsQueryRunner+++def _insert_metric_row(*, team_id: int) -> None:+ """Insert a minimal row into the local `metrics1` storage table.++ `metrics` is a Distributed proxy over `metrics1`; INSERTs forward+ through Distributed but TRUNCATEs must hit the local table directly+ (Distributed doesn't support TRUNCATE).+ """+ row = {+ "uuid": "019e6bc4-4897-77d0-ab21-56ba3e2fe535",+ "team_id": team_id,+ "trace_id": "",+ "span_id": "",+ "trace_flags": 0,+ "timestamp": "2026-05-27 00:00:00.000000",+ "observed_timestamp": "2026-05-27 00:00:00.000000",+ "service_name": "test-service",+ "metric_name": "test.metric",+ "metric_type": "gauge",+ "value": 1.0,+ "count": 1,+ "histogram_bounds": [],+ "histogram_counts": [],+ "unit": "",+ "aggregation_temporality": "cumulative",+ "is_monotonic": False,+ "resource_attributes": {},+ "instrumentation_scope": "",+ "attributes_map_str": {},+ "attributes_map_float": {},+ }+ sync_execute(f"INSERT INTO metrics1 FORMAT JSONEachRow {json.dumps(row)}")+++class TestHasMetricsQueryRunner(ClickhouseTestMixin, APIBaseTest):+ CLASS_DATA_LEVEL_SETUP = True++ def setUp(self):+ super().setUp()+ cache.delete(f"team:{self.team.id}:has_metrics")++ def test_has_metrics_returns_false_when_no_metrics(self):+ sync_execute("TRUNCATE TABLE IF EXISTS metrics1")+ cache.delete(f"team:{self.team.id}:has_metrics")++ runner = HasMetricsQueryRunner(self.team)+ self.assertFalse(runner.run())++ def test_has_metrics_returns_true_when_metrics_exist(self):+ sync_execute("TRUNCATE TABLE IF EXISTS metrics1")+ cache.delete(f"team:{self.team.id}:has_metrics")+ _insert_metric_row(team_id=self.team.id)++ runner = HasMetricsQueryRunner(self.team)+ self.assertTrue(runner.run())++ def test_has_metrics_respects_team_isolation(self):+ sync_execute("TRUNCATE TABLE IF EXISTS metrics1")+ cache.delete(f"team:{self.team.id}:has_metrics")+ # Row belongs to a different team — the HogQL team_id auto-filter+ # should make our team's runner return False.+ _insert_metric_row(team_id=99999)++ runner = HasMetricsQueryRunner(self.team)+ self.assertFalse(runner.run())+++class TestHasMetricsAPI(ClickhouseTestMixin, APIBaseTest):+ CLASS_DATA_LEVEL_SETUP = True++ def setUp(self):+ super().setUp()+ cache.delete(f"team:{self.team.id}:has_metrics")++ def test_has_metrics_api_returns_false_when_no_metrics(self):+ sync_execute("TRUNCATE TABLE IF EXISTS metrics1")+ cache.delete(f"team:{self.team.id}:has_metrics")++ response = self.client.get(f"/api/projects/{self.team.id}/metrics/has_metrics")+ self.assertEqual(response.status_code, status.HTTP_200_OK)+ self.assertEqual(response.json(), {"hasMetrics": False})++ def test_has_metrics_api_requires_authentication(self):+ self.client.logout()+ response = self.client.get(f"/api/projects/{self.team.id}/metrics/has_metrics")+ self.assertEqual(response.status_code, status.HTTP_401_UNAUTHORIZED)++ def test_has_metrics_api_caches_positive_results(self):+ cache.clear()++ with (+ patch("products.metrics.backend.has_metrics_query_runner.HasMetricsQueryRunner") as mock_runner,+ patch("products.metrics.backend.presentation.api.report_user_action") as mock_report,+ ):+ mock_runner.return_value.run.return_value = True++ response = self.client.get(f"/api/projects/{self.team.id}/metrics/has_metrics")+ self.assertEqual(response.status_code, status.HTTP_200_OK)+ self.assertEqual(response.json(), {"hasMetrics": True})+ self.assertEqual(mock_runner.return_value.run.call_count, 1)++ assert mock_report.call_args[0][1] == "metrics has_metrics checked"+ assert mock_report.call_args[0][2]["has_metrics"] is True++ # Second call hits the cache, not the runner+ response = self.client.get(f"/api/projects/{self.team.id}/metrics/has_metrics")+ self.assertEqual(response.status_code, status.HTTP_200_OK)+ self.assertEqual(response.json(), {"hasMetrics": True})+ self.assertEqual(mock_runner.return_value.run.call_count, 1)++ assert mock_report.call_count == 2++ def test_has_metrics_api_does_not_cache_negative_results(self):+ cache.clear()++ with patch("products.metrics.backend.has_metrics_query_runner.HasMetricsQueryRunner") as mock_runner:+ mock_runner.return_value.run.return_value = False++ response = self.client.get(f"/api/projects/{self.team.id}/metrics/has_metrics")+ self.assertEqual(response.status_code, status.HTTP_200_OK)+ self.assertEqual(response.json(), {"hasMetrics": False})+ self.assertEqual(mock_runner.return_value.run.call_count, 1)++ response = self.client.get(f"/api/projects/{self.team.id}/metrics/has_metrics")+ self.assertEqual(response.status_code, status.HTTP_200_OK)+ self.assertEqual(response.json(), {"hasMetrics": False})+ self.assertEqual(mock_runner.return_value.run.call_count, 2)diff --git a/products/metrics/frontend/MetricsScene.tsx b/products/metrics/frontend/MetricsScene.tsxindex 8630bb9a2bf8..be847901c365 100644--- a/products/metrics/frontend/MetricsScene.tsx+++ b/products/metrics/frontend/MetricsScene.tsx@@ -1,22 +1,66 @@-import { SceneExport } from 'scenes/sceneTypes'+import { useValues } from 'kea'++import { LemonBanner } from '@posthog/lemon-ui'++import { sceneConfigurations } from 'scenes/scenes'+import { Scene, SceneExport } from 'scenes/sceneTypes'import { SceneContent } from '~/layout/scenes/components/SceneContent'import { SceneTitleSection } from '~/layout/scenes/components/SceneTitleSection'import { ProductKey } from '~/queries/schema/schema-general'+import { MetricsSetupPrompt } from './components/MetricsSetupPrompt'+import { MetricsSqlEditor } from './components/MetricsSqlEditor'+import { metricsIngestionLogic } from './metricsIngestionLogic'+import { metricsSceneLogic } from './metricsSceneLogic'++export const METRICS_LOGIC_KEY = 'metrics'+export const scene: SceneExport = {component: MetricsScene,+ logic: metricsSceneLogic,productKey: ProductKey.METRICS,}-function MetricsScene(): JSX.Element {+export function MetricsScene(): JSX.Element {return (- <SceneContent>+ <SceneContent className="h-[calc(var(--scene-layout-rect-height,_100vh)_-_1rem)]">+ <MetricsSceneContent />+ </SceneContent>+ )+}++const MetricsSceneContent = (): JSX.Element => {+ const { tabId } = useValues(metricsSceneLogic)+ const { teamHasMetricsCheckFailed } = useValues(metricsIngestionLogic)++ return (+ <><SceneTitleSection- name="Metrics"- description="Monitor and analyze application metrics to understand system performance and health."- resourceType={{ type: 'metrics' }}+ name={sceneConfigurations[Scene.Metrics].name}+ description={sceneConfigurations[Scene.Metrics].description}+ resourceType={{+ type: sceneConfigurations[Scene.Metrics].iconType || 'default_icon_type',+ }}/>- </SceneContent>+ {teamHasMetricsCheckFailed && (+ <LemonBanner+ type="info"+ dismissKey="metrics-setup-hint-banner"+ action={{+ to: 'https://posthog.com/docs/metrics',+ targetBlank: true,+ children: 'Setup guide',+ }}+ >+ Unable to verify metrics setup. If you haven't configured metrics yet, check out our setup guide.+ </LemonBanner>+ )}+ <MetricsSetupPrompt>+ <div className="flex flex-col gap-2 py-2 flex-1 min-h-0">+ <MetricsSqlEditor id={tabId} />+ </div>+ </MetricsSetupPrompt>+ </>)}diff --git a/products/metrics/frontend/components/MetricsSetupPrompt.tsx b/products/metrics/frontend/components/MetricsSetupPrompt.tsxnew file mode 100644index 000000000000..8d75fbbf6af8--- /dev/null+++ b/products/metrics/frontend/components/MetricsSetupPrompt.tsx@@ -0,0 +1,119 @@+import { useActions, useValues } from 'kea'+import posthog from 'posthog-js'+import { useEffect } from 'react'++import { LemonButton, Link, Spinner } from '@posthog/lemon-ui'++import { ListHog } from 'lib/components/hedgehogs'+import { ProductIntroduction } from 'lib/components/ProductIntroduction/ProductIntroduction'+import { useInterval } from 'lib/hooks/useInterval'+import { teamLogic } from 'scenes/teamLogic'++import { ProductIntentContext, ProductKey } from '~/queries/schema/schema-general'++import { metricsIngestionLogic } from '../metricsIngestionLogic'++const POLLING_INTERVAL_MS = 5000++export const MetricsSetupPrompt = ({+ children,+ className,+}: {+ children: React.ReactNode+ className?: string+}): JSX.Element => {+ const { hasMetrics, teamHasMetricsLoading, teamHasMetricsCheckFailed } = useValues(metricsIngestionLogic)+ const { currentTeam } = useValues(teamLogic)++ if ((teamHasMetricsLoading && hasMetrics === undefined) || !currentTeam) {+ return (+ <div className="flex justify-center">+ <Spinner />+ </div>+ )+ }++ if (teamHasMetricsCheckFailed || hasMetrics === undefined) {+ return <>{children}</>+ }++ if (!hasMetrics) {+ return <NoMetricsPrompt className={className} />+ }++ return <>{children}</>+}++const NoMetricsPrompt = ({ className }: { className?: string }): JSX.Element | null => {+ const { addProductIntent } = useActions(teamLogic)+ const { hasMetrics } = useValues(metricsIngestionLogic)+ const { loadTeamHasMetrics } = useActions(metricsIngestionLogic)++ useEffect(() => {+ posthog.capture('metrics setup prompt viewed')+ }, [])++ useInterval(() => {+ if (!hasMetrics) {+ loadTeamHasMetrics()+ }+ }, POLLING_INTERVAL_MS)++ const onDocsLinkClick = (docsType: string): void => {+ posthog.capture('metrics onboarding docs clicked', { docs_type: docsType })+ addProductIntent({+ product_type: ProductKey.METRICS,+ intent_context: ProductIntentContext.METRICS_DOCS_VIEWED,+ })+ }++ return (+ <ProductIntroduction+ productName="Metrics"+ thingName="metric"+ titleOverride="You haven't sent any metrics yet"+ description="PostHog metrics works with any OpenTelemetry-compatible client. You don't need any PostHog-specific packages – just use standard OpenTelemetry libraries to send metrics via OTLP."+ isEmpty={true}+ productKey={ProductKey.METRICS}+ className={className}+ customHog={ListHog}+ actionElementOverride={+ <div className="flex flex-col items-start gap-4">+ <p className="text-sm text-secondary m-0">+ Read our{' '}+ <Link to="https://posthog.com/docs/metrics" onClick={() => onDocsLinkClick('Metrics')}>+ metrics docs+ </Link>{' '}+ or learn more about{' '}+ <Link+ to="https://opentelemetry.io/docs/what-is-opentelemetry/"+ target="_blank"+ disableDocsPanel+ onClick={() => onDocsLinkClick('OpenTelemetry')}+ >+ OpenTelemetry+ </Link>+ .+ </p>+ <div className="flex items-center gap-4">+ <div className="flex items-center gap-2 px-3 py-1.5 border border-accent rounded">+ <div className="relative flex items-center justify-center">+ <div className="absolute w-3 h-3 border-2 border-accent rounded-full animate-ping" />+ <div className="w-2 h-2 bg-accent rounded-full" />+ </div>+ <span className="text-sm">Watching for metrics</span>+ </div>+ <LemonButton+ type="secondary"+ size="small"+ to="https://posthog.com/docs/metrics"+ onClick={() => onDocsLinkClick('Docs')}+ >+ View docs+ </LemonButton>+ </div>+ </div>+ }+ />+ )+}diff --git a/products/metrics/frontend/components/MetricsSqlEditor.tsx b/products/metrics/frontend/components/MetricsSqlEditor.tsxnew file mode 100644index 000000000000..7b18a9058b2c--- /dev/null+++ b/products/metrics/frontend/components/MetricsSqlEditor.tsx@@ -0,0 +1,55 @@+import { useActions, useMountedLogic, useValues } from 'kea'+import { useEffect } from 'react'++import { SQLEditor } from 'scenes/data-warehouse/editor/SQLEditor'+import { sqlEditorLogic } from 'scenes/data-warehouse/editor/sqlEditorLogic'+import { SQLEditorMode } from 'scenes/data-warehouse/editor/sqlEditorModes'++import { NodeKind } from '~/queries/schema/schema-general'+import { ChartDisplayType } from '~/types'++import { getMetricsSqlEditorTabId, metricsSceneLogic } from '../metricsSceneLogic'+import { metricsSqlEditorTrackingLogic } from './metricsSqlEditorTrackingLogic'++// `metrics` is only registered under the `posthog.` HogQL namespace+// (posthog/hogql/database/database.py), so unlike `logs` it must be+// referenced fully qualified.+const DEFAULT_METRICS_QUERY = 'SELECT * FROM posthog.metrics LIMIT 10'++export interface MetricsSqlEditorProps {+ id: string+}++export const MetricsSqlEditor = ({ id }: MetricsSqlEditorProps): JSX.Element => {+ const sqlEditorTabId = getMetricsSqlEditorTabId(id)+ const { keepSqlEditorMounted } = useActions(metricsSceneLogic)+ const logic = sqlEditorLogic({ tabId: sqlEditorTabId, mode: SQLEditorMode.Embedded })+ const { queryInput } = useValues(logic)+ const { setQueryInput, setSourceQuery, runQuery } = useActions(logic)+ useMountedLogic(metricsSqlEditorTrackingLogic({ sqlEditorTabId }))++ useEffect(() => {+ keepSqlEditorMounted(sqlEditorTabId)+ }, [sqlEditorTabId]) // eslint-disable-line react-hooks/exhaustive-deps++ useEffect(() => {+ if (queryInput === null) {+ setQueryInput(DEFAULT_METRICS_QUERY)+ setSourceQuery({+ kind: NodeKind.DataVisualizationNode,+ source: {+ kind: NodeKind.HogQLQuery,+ query: DEFAULT_METRICS_QUERY,+ },+ display: ChartDisplayType.ActionsLineGraph,+ })+ runQuery(DEFAULT_METRICS_QUERY)+ }+ }, [queryInput]) // eslint-disable-line react-hooks/exhaustive-deps++ return (+ <div className="flex flex-col flex-1 min-h-0 min-w-0 border rounded overflow-hidden">+ <SQLEditor tabId={sqlEditorTabId} mode={SQLEditorMode.Embedded} defaultShowDatabaseTree={false} />+ </div>+ )+}diff --git a/products/metrics/frontend/components/metricsSqlEditorTrackingLogic.ts b/products/metrics/frontend/components/metricsSqlEditorTrackingLogic.tsnew file mode 100644index 000000000000..f7d2507a3bb3--- /dev/null+++ b/products/metrics/frontend/components/metricsSqlEditorTrackingLogic.ts@@ -0,0 +1,48 @@+import { connect, kea, key, listeners, path, props } from 'kea'+import posthog from 'posthog-js'++import { SaveAsMenuItem } from 'scenes/data-warehouse/editor/editorSceneLogic'+import { sqlEditorLogic } from 'scenes/data-warehouse/editor/sqlEditorLogic'+import { SQLEditorMode } from 'scenes/data-warehouse/editor/sqlEditorModes'++import type { metricsSqlEditorTrackingLogicType } from './metricsSqlEditorTrackingLogicType'++export interface MetricsSqlEditorTrackingLogicProps {+ sqlEditorTabId: string+}++const captureSaved = (target: SaveAsMenuItem['action']): void => {+ posthog.capture('metrics sql query saved', { target })+}++export const metricsSqlEditorTrackingLogic = kea<metricsSqlEditorTrackingLogicType>([+ path(['products', 'metrics', 'frontend', 'components', 'metricsSqlEditorTrackingLogic']),+ props({} as MetricsSqlEditorTrackingLogicProps),+ key((props) => props.sqlEditorTabId),+ connect((props: MetricsSqlEditorTrackingLogicProps) => ({+ actions: [+ sqlEditorLogic({ tabId: props.sqlEditorTabId, mode: SQLEditorMode.Embedded }),+ [+ 'runQuery as sqlEditorRunQuery',+ 'saveAsViewSubmit as sqlEditorSaveAsViewSubmit',+ 'saveAsInsightSubmit as sqlEditorSaveAsInsightSubmit',+ 'saveAsEndpointSubmit as sqlEditorSaveAsEndpointSubmit',+ ],+ ],+ })),+ listeners(({ cache }) => ({+ sqlEditorRunQuery: () => {+ // Skip the auto-init runQuery dispatched by MetricsSqlEditor's first mount.+ // Trade-off: on revisit (queryInput already set, no auto-init), the user's first+ // manual run is also skipped. Acceptable under-count for an alpha metric.+ if (!cache.firstRunSeen) {+ cache.firstRunSeen = true+ return+ }+ posthog.capture('metrics sql query run')+ },+ sqlEditorSaveAsViewSubmit: () => captureSaved('view'),+ sqlEditorSaveAsInsightSubmit: () => captureSaved('insight'),+ sqlEditorSaveAsEndpointSubmit: () => captureSaved('endpoint'),+ })),+])diff --git a/products/metrics/frontend/generated/api.schemas.ts b/products/metrics/frontend/generated/api.schemas.tsindex 275a5d3a11fb..09932c511581 100644--- a/products/metrics/frontend/generated/api.schemas.ts+++ b/products/metrics/frontend/generated/api.schemas.ts@@ -22,3 +22,5 @@ export type AppMetricsTotalsResponseApiTotals = { [key: string]: number }export interface AppMetricsTotalsResponseApi {totals: AppMetricsTotalsResponseApiTotals}++export type MetricsHasMetricsRetrieve200 = { [key: string]: unknown }diff --git a/products/metrics/frontend/generated/api.ts b/products/metrics/frontend/generated/api.tsindex 6d6d4f2d7a39..1779f299aa5d 100644--- a/products/metrics/frontend/generated/api.ts+++ b/products/metrics/frontend/generated/api.ts@@ -8,7 +8,7 @@ import { apiMutator } from '../../../../frontend/src/lib/api-orval-mutator'* PostHog API - generated* OpenAPI spec version: 1.0.0*/-import type { AppMetricsResponseApi, AppMetricsTotalsResponseApi } from './api.schemas'+import type { AppMetricsResponseApi, AppMetricsTotalsResponseApi, MetricsHasMetricsRetrieve200 } from './api.schemas'export const getEventFilterMetricsRetrieveUrl = (projectId: string) => {return `/api/environments/${projectId}/event_filter/metrics/`@@ -51,3 +51,17 @@ export const eventFilterMetricsTotalsRetrieve = async (method: 'GET',})}++export const getMetricsHasMetricsRetrieveUrl = (projectId: string) => {+ return `/api/projects/${projectId}/metrics/has_metrics/`+}++export const metricsHasMetricsRetrieve = async (+ projectId: string,+ options?: RequestInit+): Promise<MetricsHasMetricsRetrieve200> => {+ return apiMutator<MetricsHasMetricsRetrieve200>(getMetricsHasMetricsRetrieveUrl(projectId), {+ ...options,+ method: 'GET',+ })+}diff --git a/products/metrics/frontend/metricsIngestionLogic.tsx b/products/metrics/frontend/metricsIngestionLogic.tsxnew file mode 100644index 000000000000..33672fb5b628--- /dev/null+++ b/products/metrics/frontend/metricsIngestionLogic.tsx@@ -0,0 +1,54 @@+import { afterMount, kea, path, reducers, selectors } from 'kea'+import { loaders } from 'kea-loaders'++import api from 'lib/api'+import { retryWithBackoff } from 'lib/utils'++import type { metricsIngestionLogicType } from './metricsIngestionLogicType'++const teamId = window.POSTHOG_APP_CONTEXT?.current_team?.id++export const metricsIngestionLogic = kea<metricsIngestionLogicType>([+ path(['products', 'metrics', 'frontend', 'metricsIngestionLogic']),+ loaders({+ teamHasMetrics: {+ __default: undefined as boolean | undefined,+ loadTeamHasMetrics: async (): Promise<boolean> => {+ return await retryWithBackoff(() => api.metrics.hasMetrics(), { maxAttempts: 3 })+ },+ },+ }),++ reducers({+ teamHasMetricsCheckFailed: [+ false,+ {+ loadTeamHasMetrics: () => false,+ loadTeamHasMetricsSuccess: () => false,+ loadTeamHasMetricsFailure: () => true,+ },+ ],+ cachedTeamHasMetrics: [+ null as boolean | null,+ { persist: true, prefix: `${teamId}__` },+ {+ // Only cache true - metrics don't disappear once ingested+ loadTeamHasMetricsSuccess: (_, { teamHasMetrics }) => teamHasMetrics || null,+ },+ ],+ }),++ selectors({+ hasMetrics: [+ (s) => [s.teamHasMetrics, s.cachedTeamHasMetrics],+ (teamHasMetrics, cachedTeamHasMetrics): boolean | undefined =>+ teamHasMetrics ?? cachedTeamHasMetrics ?? undefined,+ ],+ }),++ afterMount(({ actions, values }) => {+ if (values.cachedTeamHasMetrics !== true) {+ actions.loadTeamHasMetrics()+ }+ }),+])diff --git a/products/metrics/frontend/metricsSceneLogic.tsx b/products/metrics/frontend/metricsSceneLogic.tsxnew file mode 100644index 000000000000..ce1ba457b2d1--- /dev/null+++ b/products/metrics/frontend/metricsSceneLogic.tsx@@ -0,0 +1,37 @@+import { actions, kea, listeners, path, props, selectors } from 'kea'++import { tabAwareScene } from 'lib/logic/scenes/tabAwareScene'+import { sqlEditorLogic } from 'scenes/data-warehouse/editor/sqlEditorLogic'+import { SQLEditorMode } from 'scenes/data-warehouse/editor/sqlEditorModes'++import type { metricsSceneLogicType } from './metricsSceneLogicType'++export const getMetricsSqlEditorTabId = (id: string): string => `metrics-sql-editor-${id}`++export interface MetricsLogicProps {+ tabId: string+}++export const metricsSceneLogic = kea<metricsSceneLogicType>([+ props({} as MetricsLogicProps),+ path(['products', 'metrics', 'frontend', 'metricsSceneLogic']),+ tabAwareScene(),+ actions({+ keepSqlEditorMounted: (editorTabId: string) => ({ editorTabId }),+ }),+ selectors({+ tabId: [(_, p) => [p.tabId], (tabId: string) => tabId],+ }),+ listeners(({ cache }) => ({+ keepSqlEditorMounted: ({ editorTabId }) => {+ if (cache.sqlEditorTabId === editorTabId) {+ return+ }+ cache.unmountSqlEditor?.()+ cache.sqlEditorTabId = editorTabId+ // Intentionally not cleaned up in beforeUnmount: keeps the embedded sqlEditorLogic+ // alive across navigation so the user's query survives leaving and re-entering /metrics.+ cache.unmountSqlEditor = sqlEditorLogic({ tabId: editorTabId, mode: SQLEditorMode.Embedded }).mount()+ },+ })),+])diff --git a/products/metrics/package.json b/products/metrics/package.jsonindex 25e1e413b370..7a495e0c05df 100644--- a/products/metrics/package.json+++ b/products/metrics/package.json@@ -1,12 +1,14 @@{"name": "@posthog/products-metrics","scripts": {- "backend:test": "pytest -c ../../pytest.ini --rootdir ../.. backend/tests -v --tb=short"+ "backend:test": "pytest -c ../../pytest.ini --rootdir ../.. backend/tests -v --tb=short",+ "backend:contract-check": "echo 'Contract files unchanged'"},"dependencies": {"kea": "catalog:","kea-loaders": "catalog:",- "kea-router": "catalog:"+ "kea-router": "catalog:",+ "posthog-js": "catalog:"},"peerDependencies": {"@posthog/icons": "*",diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.tsindex 886f322f7b8e..085beb6edc40 100644--- a/services/mcp/src/api/generated.ts+++ b/services/mcp/src/api/generated.ts@@ -40785,6 +40785,8 @@ export namespace Schemas {Resource: 'resource',} as const;+ export type EnvironmentsMetricsHasMetricsRetrieve200 = { [key: string]: unknown };+export type EnvironmentsPersistedFolderListParams = {/*** Number of results to return per page.@@ -46256,6 +46258,8 @@ export namespace Schemas {Running: 'running',} as const;+ export type MetricsHasMetricsRetrieve200 = { [key: string]: unknown };+export type NotebooksListParams = {/*** Filter for notebooks that match a provided filter.diff --git a/tach.toml b/tach.tomlindex dd992aadf8e7..55b1ec9453c3 100644--- a/tach.toml+++ b/tach.toml@@ -87,6 +87,7 @@ depends_on = ["products.marketing_analytics","products.mcp_store","products.messaging",+ "products.metrics","products.notebooks","products.notifications","products.posthog_ai",@@ -372,10 +373,18 @@ layer = "modules"[[modules]]path = "products.metrics"-depends_on = [-]+depends_on = ["posthog"]layer = "modules"+[[interfaces]]+expose = [+ "backend\\.facade.*",+ "backend\\.presentation\\.api.*",+]+from = [+ "products.metrics",+]+[[modules]]path = "products.notebooks"depends_on = [