:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
feat(logs): generate metrics from logs at ingestion (#72104)
Daniel Viscaf1c3d456b428
diff --git a/.semgrep/rules/security/idor-team-scoped-models.yaml b/.semgrep/rules/security/idor-team-scoped-models.yamlindex b34ccc2cd1dd..b6b51ef37b25 100644--- a/.semgrep/rules/security/idor-team-scoped-models.yaml+++ b/.semgrep/rules/security/idor-team-scoped-models.yaml@@ -186,6 +186,7 @@ rules:|LiveDebuggerBreakpoint|LogsAlertConfiguration|LogsExclusionRule+ |LogsMetricRule|LogsView|LLMModelConfiguration|LLMPromptdiff --git a/frontend/src/lib/constants.tsx b/frontend/src/lib/constants.tsxindex ffdf72ae34d4..247f20b2a723 100644--- a/frontend/src/lib/constants.tsx+++ b/frontend/src/lib/constants.tsx@@ -352,6 +352,7 @@ export const FEATURE_FLAGS = {LOGS_COLUMN_CONFIGURATION: 'logs-column-configuration', // owner: #team-logsLOGS_GROUP_BY: 'logs-group-by', // owner: #team-logsLOGS_IN_ERROR_TRACKING: 'logs-in-error-tracking', // owner: @jonmcwest #team-logs+ LOGS_METRIC_RULES: 'logs-metric-rules', // owner: #team-logsLOGS_PATTERNS_VIEW: 'logs-patterns-view', // owner: #team-logsLOGS_SAVED_VIEWS: 'logs-saved-views', // owner: #team-logsLOGS_SERVICES_VIEW: 'logs-services-view', // owner: #team-logsdiff --git a/frontend/src/scenes/settings/SettingsMap.tsx b/frontend/src/scenes/settings/SettingsMap.tsxindex d906ff104bdf..ba6a7fe9e088 100644--- a/frontend/src/scenes/settings/SettingsMap.tsx+++ b/frontend/src/scenes/settings/SettingsMap.tsx@@ -52,6 +52,7 @@ import { CustomerAnalyticsDashboardEvents } from 'products/customer_analytics/frimport { ExceptionAutocaptureToggle } from 'products/error_tracking/frontend/scenes/ErrorTrackingConfigurationScene/exception_autocapture/ExceptionAutocaptureSettings'import { SuppressionRules } from 'products/error_tracking/frontend/scenes/ErrorTrackingConfigurationScene/suppression_rules/SuppressionRules'import { LogsAlertingSection } from 'products/logs/frontend/components/LogsAlerting/LogsAlertingSection'+import { LogsMetricRulesSection } from 'products/logs/frontend/components/LogsMetricRules/LogsMetricRulesSection'import { LogsSamplingSection } from 'products/logs/frontend/components/LogsSampling/LogsSamplingSection'import { LogsFeatureFlagKeys } from 'products/logs/frontend/logsFeatureFlagKeys'import { WorkflowsEngagementEventsSettings } from 'products/workflows/frontend/scenes/settings/WorkflowsEngagementEventsSettings'@@ -817,6 +818,15 @@ export const SETTINGS_MAP: SettingSection[] = [flag: LogsFeatureFlagKeys.dropRules,keywords: ['drop', 'exclude', 'filter', 'rules', 'path', 'attribute', 'volume', 'noise'],},+ {+ id: 'logs-metric-rules',+ title: 'Metric rules',+ description:+ 'Generate metrics from your logs at ingestion time. Metrics are computed before drop rules, so you can drop noisy logs and keep the trend.',+ component: <LogsMetricRulesSection />,+ flag: LogsFeatureFlagKeys.metricRules,+ keywords: ['metric', 'metrics', 'generate', 'count', 'aggregate', 'logs to metrics'],+ },{id: 'logs-alerting',title: 'Alerting',diff --git a/frontend/src/scenes/settings/types.ts b/frontend/src/scenes/settings/types.tsindex f539cb7b2497..3545e0860715 100644--- a/frontend/src/scenes/settings/types.ts+++ b/frontend/src/scenes/settings/types.ts@@ -180,6 +180,7 @@ export type SettingId =| 'logs-distinct-id-attribute-key'| 'logs-drop-rules'| 'logs-json-parse'+ | 'logs-metric-rules'| 'logs-pii-scrub'| 'logs-retention'| 'logs-session-id-attribute-keys'diff --git a/products/logs/backend/migrations/0017_logsmetricrule.py b/products/logs/backend/migrations/0017_logsmetricrule.pynew file mode 100644index 000000000000..61663faa6f25--- /dev/null+++ b/products/logs/backend/migrations/0017_logsmetricrule.py@@ -0,0 +1,87 @@+# Generated by Django 5.2.14 on 2026-07-17 22:49++import django.db.models.deletion+import django.contrib.postgres.fields+from django.conf import settings+from django.db import migrations, models++import posthog.uuidt+++class Migration(migrations.Migration):+ dependencies = [+ ("logs", "0016_logsview_columns"),+ ("posthog", "1258_duckgressinkschemastate_queue_last_applied_at"),+ migrations.swappable_dependency(settings.AUTH_USER_MODEL),+ ]++ operations = [+ migrations.CreateModel(+ name="LogsMetricRule",+ fields=[+ ("created_at", models.DateTimeField(auto_now_add=True)),+ ("updated_at", models.DateTimeField(auto_now=True, null=True)),+ (+ "id",+ models.UUIDField(+ default=posthog.uuidt.uuid7,+ editable=False,+ primary_key=True,+ serialize=False,+ ),+ ),+ ("name", models.CharField(max_length=255)),+ ("metric_name", models.CharField(max_length=200)),+ ("enabled", models.BooleanField(default=False)),+ ("filter_group", models.JSONField(blank=True, default=None, null=True)),+ (+ "value_attribute",+ models.CharField(blank=True, max_length=512, null=True),+ ),+ (+ "group_by",+ django.contrib.postgres.fields.ArrayField(+ base_field=models.CharField(max_length=512),+ blank=True,+ default=list,+ size=None,+ ),+ ),+ ("version", models.PositiveIntegerField(default=1)),+ (+ "created_by",+ models.ForeignKey(+ blank=True,+ db_constraint=False,+ null=True,+ on_delete=django.db.models.deletion.SET_NULL,+ related_name="+",+ to=settings.AUTH_USER_MODEL,+ ),+ ),+ (+ "team",+ models.ForeignKey(+ db_constraint=False,+ on_delete=django.db.models.deletion.CASCADE,+ to="posthog.team",+ ),+ ),+ ],+ options={+ "db_table": "logs_logsmetricrule",+ "indexes": [+ models.Index(+ fields=["team_id", "enabled"],+ name="logs_metric_team_enabled_idx",+ )+ ],+ "constraints": [+ models.UniqueConstraint(+ fields=("team", "metric_name"),+ name="logs_metric_rule_team_metric_uniq",+ )+ ],+ },+ ),+ ]diff --git a/products/logs/backend/migrations/max_migration.txt b/products/logs/backend/migrations/max_migration.txtindex aa69fa2f352d..b0a032a6f6c6 100644--- a/products/logs/backend/migrations/max_migration.txt+++ b/products/logs/backend/migrations/max_migration.txt@@ -1 +1 @@-0016_logsview_columns+0017_logsmetricrulediff --git a/products/logs/backend/models.py b/products/logs/backend/models.pyindex 5b95ee94714f..ae437a4e2957 100644--- a/products/logs/backend/models.py+++ b/products/logs/backend/models.py@@ -10,6 +10,7 @@ from django.db import modelsfrom django.db.models import Valuefrom posthog.models.activity_logging.model_activity import ModelActivityMixin+from posthog.models.scoping.root_mixin import TeamScopedRootMixinfrom posthog.models.team.extensions import register_team_extension_signalfrom posthog.models.utils import CreatedMetaFields, UpdatedMetaFields, UUIDModelfrom posthog.utils import generate_short_id@@ -298,6 +299,62 @@ class LogsAlertEvent(UUIDModel):return count+# Cap on enabled metric rules per team. Every enabled rule is evaluated against every+# ingested log record in the Node worker, so the cap bounds per-record CPU. Mirrored in+# the serializer so the limit surfaces as a 400 rather than silent worker truncation.+MAX_ENABLED_METRIC_RULES = 10++# Group-by cardinality bounds. Keys beyond the cap multiply the number of emitted metric+# series per rule; the serializer rejects rules exceeding it at write time.+MAX_METRIC_RULE_GROUP_BY_KEYS = 5++# Top-level LogRecord fields allowed as group-by dimensions. Anything else must be+# addressed through the `attributes.` / `resource_attributes.` map prefixes.+METRIC_RULE_GROUP_BY_TOP_LEVEL_KEYS = ("service_name", "severity_text", "event_name")+++class LogsMetricRule(ModelActivityMixin, TeamScopedRootMixin, CreatedMetaFields, UpdatedMetaFields, UUIDModel):+ """Generates a metric from ingested logs: records matching `filter_group` are tallied+ at ingest time (before drop rules) and emitted into the Metrics product under+ `metric_name`. With `value_attribute` unset the rule counts matching records; when set,+ the numeric value of that attribute is aggregated into a distribution (count + sum)."""++ # db_constraint=False on the team/user FKs: posthog_team and posthog_user are hot tables,+ # and creating an FK constraint against them locks the parent — see the hot-table section+ # of safe-django-migrations.md. Enforcement is app-level (Django still cascades in the ORM).+ team = models.ForeignKey("posthog.Team", on_delete=models.CASCADE, db_constraint=False)+ created_by = models.ForeignKey(+ "posthog.User", on_delete=models.SET_NULL, null=True, blank=True, related_name="+", db_constraint=False+ )+ name = models.CharField(max_length=255)+ # Emitted OTLP metric name. Immutable after create (changing it would start a brand-new+ # series and orphan the old one) — enforced in the serializer.+ metric_name = models.CharField(max_length=200)+ enabled = models.BooleanField(default=False)+ # PropertyGroupFilter JSON (same shape as LogsExclusionRule config.filter_group).+ # Null = every ingested log record matches.+ filter_group = models.JSONField(null=True, blank=True, default=None)+ # Log attribute key holding the numeric value to aggregate (`attributes.` /+ # `resource_attributes.` prefixed). Null = count matching records. Immutable after+ # create — it decides the emitted metric type (sum vs histogram).+ value_attribute = models.CharField(max_length=512, null=True, blank=True)+ # Group-by dimension keys; each distinct value combination becomes its own series.+ group_by = ArrayField(models.CharField(max_length=512), default=list, blank=True)+ version = models.PositiveIntegerField(default=1)++ class Meta:+ db_table = "logs_logsmetricrule"+ constraints = [+ models.UniqueConstraint(fields=["team", "metric_name"], name="logs_metric_rule_team_metric_uniq"),+ ]+ indexes = [+ models.Index(fields=["team_id", "enabled"], name="logs_metric_team_enabled_idx"),+ ]++ def __str__(self) -> str:+ return f"{self.name} -> {self.metric_name} (team={self.team_id})"++class LogsExclusionRule(ModelActivityMixin, CreatedMetaFields, UpdatedMetaFields, UUIDModel):"""User-defined rules to drop or exclude log lines before storage (evaluated in ingestion when enabled)."""diff --git a/products/logs/backend/presentation/filter_group_validation.py b/products/logs/backend/presentation/filter_group_validation.pynew file mode 100644index 000000000000..c5d2230d7fa2--- /dev/null+++ b/products/logs/backend/presentation/filter_group_validation.py@@ -0,0 +1,105 @@+from __future__ import annotations++from typing import Any++# Keep aligned with `MAX_FILTER_GROUP_DEPTH` / `MAX_FILTER_GROUP_NODES` in+# `nodejs/src/logs-ingestion/sampling/filter-group-match.ts` and+# `compile-rules.ts`. Both depth and breadth are bounded so an adversarially+# deep or wide filter_group cannot stack-overflow or CPU-burn the per-record+# evaluator in the Node ingestion worker. The breadth cap is the more+# realistic abuse vector — depth 1 with 10k sibling leaves passes the depth+# check but costs O(leaves) per log record.+MAX_FILTER_GROUP_DEPTH = 16+MAX_FILTER_GROUP_NODES = 256++# Leaf-value budget: a single `exact`/`in` leaf carrying a huge value array counts as+# one node but costs O(len(values)) per log record in the worker's matchExact — so the+# aggregate value count and each scalar's size are bounded independently of node count.+MAX_FILTER_GROUP_LEAF_VALUES = 256+MAX_FILTER_GROUP_VALUE_LENGTH = 1024+++def filter_group_depth(node: Any, depth: int = 0) -> int:+ # Short-circuit once we've crossed the cap — we don't need the true depth,+ # just that it exceeds MAX_FILTER_GROUP_DEPTH. Prevents Python RecursionError+ # on adversarial payloads that pass pydantic-core (Rust) validation, which+ # has a more generous recursion limit than ours.+ if depth > MAX_FILTER_GROUP_DEPTH:+ return depth+ if not isinstance(node, dict):+ return depth+ values = node.get("values")+ if not isinstance(values, list) or node.get("type") not in ("AND", "OR"):+ return depth+ max_child = depth+ for child in values:+ d = filter_group_depth(child, depth + 1)+ if d > max_child:+ max_child = d+ return max_child+++def filter_group_node_count(node: Any) -> int:+ """Total node count across the filter group (groups + leaves). Short-circuits+ once the cap is exceeded so adversarial payloads don't get fully traversed."""+ if not isinstance(node, dict):+ return 1+ total = 1+ values = node.get("values")+ if not isinstance(values, list) or node.get("type") not in ("AND", "OR"):+ return total+ for child in values:+ total += filter_group_node_count(child)+ if total > MAX_FILTER_GROUP_NODES:+ return total+ return total+++def filter_group_leaf_value_count(node: Any) -> int:+ """Total count of leaf filter values across the tree (a scalar value counts as 1,+ a value array as its length). Short-circuits once the cap is exceeded."""+ if not isinstance(node, dict):+ return 0+ values = node.get("values")+ if not isinstance(values, list) or node.get("type") not in ("AND", "OR"):+ leaf_value = node.get("value")+ if isinstance(leaf_value, list):+ return len(leaf_value)+ return 0 if leaf_value is None else 1+ total = 0+ for child in values:+ total += filter_group_leaf_value_count(child)+ if total > MAX_FILTER_GROUP_LEAF_VALUES:+ return total+ return total+++def filter_group_has_oversized_value(node: Any) -> bool:+ """True when any leaf filter value's string form exceeds MAX_FILTER_GROUP_VALUE_LENGTH."""+ if not isinstance(node, dict):+ return False+ values = node.get("values")+ if not isinstance(values, list) or node.get("type") not in ("AND", "OR"):+ leaf_value = node.get("value")+ candidates = leaf_value if isinstance(leaf_value, list) else [leaf_value]+ return any(isinstance(v, str) and len(v) > MAX_FILTER_GROUP_VALUE_LENGTH for v in candidates)+ return any(filter_group_has_oversized_value(child) for child in values)+++def filter_group_has_empty_group(node: Any) -> bool:+ """True when any group node in the tree has an empty `values` list. The worker's+ matchFilterGroup treats empty groups as no-match (dropping is irreversible, so+ vacuous filters fail closed), which makes a rule carrying one silently inert —+ worst on rate_limit, where `{"type": "AND", "values": []}` reads like "cap+ everything" but caps nothing.++ Recurses without a depth short-circuit of its own — callers must run the+ MAX_FILTER_GROUP_DEPTH check first so the tree is already bounded."""+ if not isinstance(node, dict):+ return False+ values = node.get("values")+ if not isinstance(values, list) or node.get("type") not in ("AND", "OR"):+ return False+ if len(values) == 0:+ return True+ return any(filter_group_has_empty_group(child) for child in values)diff --git a/products/logs/backend/presentation/views/api.py b/products/logs/backend/presentation/views/api.pyindex 64c06bec22fc..60e820efcb8b 100644--- a/products/logs/backend/presentation/views/api.py+++ b/products/logs/backend/presentation/views/api.py@@ -69,12 +69,20 @@ from products.logs.backend.pattern_diff import run_patterns_difffrom products.logs.backend.patterns_query_runner import PatternsQueryRunnerfrom products.logs.backend.presentation.views.alerts_api import LogsAlertViewSetfrom products.logs.backend.presentation.views.explain import LogExplainViewSet+from products.logs.backend.presentation.views.metric_rules_api import LogsMetricRuleViewSetfrom products.logs.backend.presentation.views.sampling_api import LogsSamplingRuleViewSetfrom products.logs.backend.presentation.views.views_api import LogsViewViewSetfrom products.logs.backend.services_query_runner import ServicesQueryRunnerfrom products.logs.backend.sparkline_query_runner import SparklineQueryRunner-__all__ = ["LogsViewSet", "LogExplainViewSet", "LogsAlertViewSet", "LogsSamplingRuleViewSet", "LogsViewViewSet"]+__all__ = [+ "LogsViewSet",+ "LogExplainViewSet",+ "LogsAlertViewSet",+ "LogsMetricRuleViewSet",+ "LogsSamplingRuleViewSet",+ "LogsViewViewSet",+]tracer = trace.get_tracer(__name__)LOGS_MAX_EXPORT_ROWS = 10_000diff --git a/products/logs/backend/presentation/views/metric_rules_api.py b/products/logs/backend/presentation/views/metric_rules_api.pynew file mode 100644index 000000000000..f51b4d661bc3--- /dev/null+++ b/products/logs/backend/presentation/views/metric_rules_api.py@@ -0,0 +1,344 @@+from __future__ import annotations++import re+from functools import cached_property+from typing import Any, cast++from django.db import connection, transaction+from django.db.models import F, QuerySet++from pydantic import ValidationError as PydanticValidationError+from rest_framework import serializers, viewsets+from rest_framework.exceptions import PermissionDenied, ValidationError+from rest_framework.permissions import BasePermission+from rest_framework.request import Request+from rest_framework.views import APIView++from posthog.schema import PropertyGroupFilter++from posthog.api.routing import TeamAndOrgViewSetMixin+from posthog.auth import OAuthAccessTokenAuthentication, PersonalAPIKeyAuthentication+from posthog.event_usage import report_user_action+from posthog.models.scoping.manager import resolve_effective_team_id+from posthog.models.user import User+from posthog.permissions import PostHogFeatureFlagPermission+from posthog.rbac.user_access_control import UserAccessControl++from products.logs.backend.models import (+ MAX_ENABLED_METRIC_RULES,+ MAX_METRIC_RULE_GROUP_BY_KEYS,+ METRIC_RULE_GROUP_BY_TOP_LEVEL_KEYS,+ LogsMetricRule,+)+from products.logs.backend.presentation.filter_group_validation import (+ MAX_FILTER_GROUP_DEPTH,+ MAX_FILTER_GROUP_LEAF_VALUES,+ MAX_FILTER_GROUP_NODES,+ MAX_FILTER_GROUP_VALUE_LENGTH,+ filter_group_depth,+ filter_group_has_empty_group,+ filter_group_has_oversized_value,+ filter_group_leaf_value_count,+ filter_group_node_count,+)++# OTLP-safe metric name: leading letter, then letters/digits/dot/underscore/dash.+METRIC_NAME_PATTERN = re.compile(r"^[a-zA-Z][a-zA-Z0-9._-]*$")++ATTRIBUTE_KEY_PREFIXES = ("attributes.", "resource_attributes.")++# Advisory-lock namespace for `pg_advisory_xact_lock(ns, canonical_team_id)` — serializes+# metric-rule writes per team so the enabled-rule cap can't be raced past.+_METRIC_RULE_LOCK_NAMESPACE = 0x106_2E7A # "LOG-RULE"-ish; just needs to be unique enough.+++class MetricRuleCanonicalTeamPermission(BasePermission):+ """Authorize against the canonical (data-owning) team, not just the URL environment team.++ LogsMetricRule rows canonicalize to the parent (project-root) team on save, so a request made+ against a child environment reads and writes the PARENT's rules. The default team gate only+ checks membership of the URL team; re-anchor authorization to the canonical team so a+ credential scoped solely to a child environment can't touch the parent's rules. Mirrors+ stamphog's StamphogCanonicalTeamAccessPermission.+ """++ message = "You don't have access to the project that owns this data."++ def has_permission(self, request: Request, view: APIView) -> bool:+ if not request.user.is_authenticated:+ return True # IsAuthenticated handles the unauthenticated case first+ assert isinstance(view, LogsMetricRuleViewSet)+ team = view.team+ if team.parent_team_id is None or team.parent_team_id == team.id or team.parent_team is None:+ return True+ authenticator = request.successful_authenticator+ scoped_teams = None+ if isinstance(authenticator, OAuthAccessTokenAuthentication):+ scoped_teams = authenticator.access_token.scoped_teams+ elif isinstance(authenticator, PersonalAPIKeyAuthentication):+ scoped_teams = authenticator.personal_api_key.scoped_teams+ if scoped_teams and team.parent_team_id not in scoped_teams:+ return False+ level = view.user_permissions.team(team.parent_team).effective_membership_level+ return level is not None+++class LogsMetricRuleSerializer(serializers.ModelSerializer):+ id = serializers.UUIDField(read_only=True, help_text="Unique identifier for this metric rule.")+ name = serializers.CharField(max_length=255, help_text="User-visible label for this rule.")+ metric_name = serializers.CharField(+ max_length=200,+ help_text=(+ "Name of the generated metric as it appears in the Metrics product. Must start with a letter and "+ "contain only letters, digits, dots, underscores, and dashes. Unique per project and immutable "+ "after creation — create a new rule to emit under a different name."+ ),+ )+ enabled = serializers.BooleanField(+ default=False,+ help_text=f"When true, ingestion evaluates this rule against every log record. At most {MAX_ENABLED_METRIC_RULES} rules can be enabled per project.",+ )+ filter_group = serializers.JSONField(+ required=False,+ allow_null=True,+ default=None,+ help_text=(+ "PropertyGroupFilter JSON (AND/OR tree of property predicates) selecting which log records feed the "+ 'metric, e.g. `{"type":"AND","values":[{"type":"AND","values":[{"key":"service.name","operator":"exact",'+ '"value":"api","type":"log_attribute"}]}]}`. Null matches every ingested log record. Every group must '+ "contain at least one filter — empty groups never match."+ ),+ )+ value_attribute = serializers.CharField(+ required=False,+ allow_null=True,+ allow_blank=False,+ max_length=512,+ default=None,+ help_text=(+ "Log attribute key holding a numeric value to aggregate into a distribution (count + sum), e.g. "+ "`attributes.duration_ms` or `resource_attributes.batch.size`. Omit to count matching log records "+ "instead. Immutable after creation — it determines the emitted metric type."+ ),+ )+ group_by = serializers.ListField(+ child=serializers.CharField(max_length=512),+ required=False,+ default=list,+ help_text=(+ f"Up to {MAX_METRIC_RULE_GROUP_BY_KEYS} dimension keys; each distinct value combination becomes its own "+ f"metric series. Allowed: {', '.join(METRIC_RULE_GROUP_BY_TOP_LEVEL_KEYS)}, or map keys prefixed with "+ "`attributes.` / `resource_attributes.`. Avoid high-cardinality keys (user IDs, request IDs) — excess "+ "series are dropped at ingestion."+ ),+ )+ version = serializers.IntegerField(+ read_only=True, help_text="Incremented on each update for worker cache coherency."+ )+ created_by: serializers.PrimaryKeyRelatedField = serializers.PrimaryKeyRelatedField(read_only=True) # ty: ignore[invalid-assignment]++ class Meta:+ model = LogsMetricRule+ fields = [+ "id",+ "name",+ "metric_name",+ "enabled",+ "filter_group",+ "value_attribute",+ "group_by",+ "version",+ "created_by",+ "created_at",+ "updated_at",+ ]+ read_only_fields = ["id", "version", "created_by", "created_at", "updated_at"]++ def validate_metric_name(self, value: str) -> str:+ if not METRIC_NAME_PATTERN.match(value):+ raise ValidationError(+ "Metric name must start with a letter and contain only letters, digits, dots, underscores, and dashes."+ )+ return value++ def validate_group_by(self, value: list[str]) -> list[str]:+ if len(value) > MAX_METRIC_RULE_GROUP_BY_KEYS:+ raise ValidationError(f"At most {MAX_METRIC_RULE_GROUP_BY_KEYS} group-by keys are allowed.")+ for key in value:+ if key in METRIC_RULE_GROUP_BY_TOP_LEVEL_KEYS:+ continue+ if any(key.startswith(prefix) and len(key) > len(prefix) for prefix in ATTRIBUTE_KEY_PREFIXES):+ continue+ raise ValidationError(+ f"Invalid group-by key {key!r}. Use one of {', '.join(METRIC_RULE_GROUP_BY_TOP_LEVEL_KEYS)}, or a "+ "key prefixed with `attributes.` / `resource_attributes.`."+ )+ return value++ def validate_value_attribute(self, value: str | None) -> str | None:+ if value is None:+ return value+ if not any(value.startswith(prefix) and len(value) > len(prefix) for prefix in ATTRIBUTE_KEY_PREFIXES):+ raise ValidationError("value_attribute must be prefixed with `attributes.` or `resource_attributes.`.")+ return value++ def validate_filter_group(self, value: Any) -> Any:+ if value is None:+ return value+ try:+ PropertyGroupFilter.model_validate(value)+ except PydanticValidationError as e:+ raise ValidationError(f"Invalid filter_group shape: {e.errors()[0]['msg']}")+ if filter_group_depth(value) > MAX_FILTER_GROUP_DEPTH:+ raise ValidationError(f"filter_group is nested too deeply (max depth {MAX_FILTER_GROUP_DEPTH}).")+ if filter_group_node_count(value) > MAX_FILTER_GROUP_NODES:+ raise ValidationError(f"filter_group has too many nodes (max {MAX_FILTER_GROUP_NODES} groups + leaves).")+ if filter_group_leaf_value_count(value) > MAX_FILTER_GROUP_LEAF_VALUES:+ raise ValidationError(+ f"filter_group has too many filter values (max {MAX_FILTER_GROUP_LEAF_VALUES} across all filters)."+ )+ if filter_group_has_oversized_value(value):+ raise ValidationError(+ f"filter_group contains a value longer than {MAX_FILTER_GROUP_VALUE_LENGTH} characters."+ )+ if filter_group_has_empty_group(value):+ raise ValidationError(+ "Every group in filter_group must contain at least one filter — an empty group never matches, "+ "so the rule would never produce data points. Omit filter_group to match all logs."+ )+ return value++ def validate(self, attrs: dict[str, Any]) -> dict[str, Any]:+ attrs = super().validate(attrs)+ if self.instance is not None:+ self._validate_immutable_fields(attrs)+ return attrs++ def _validate_immutable_fields(self, attrs: dict[str, Any]) -> None:+ assert self.instance is not None+ # `initial_data` (not validated attrs) distinguishes "field omitted from PATCH"+ # from "field explicitly sent" — defaults would otherwise read as a change.+ for field in ("metric_name", "value_attribute"):+ if field in self.initial_data and attrs.get(field) != getattr(self.instance, field):+ raise ValidationError({field: f"{field} is immutable after creation — create a new rule to change it."})+++class LogsMetricRuleViewSet(TeamAndOrgViewSetMixin, viewsets.ModelViewSet):+ scope_object = "logs"+ # `.unscoped()` because this evaluates at import time, before any team context exists;+ # `safely_get_queryset` re-applies the team filter per request.+ queryset = LogsMetricRule.objects.unscoped().order_by("created_at")+ serializer_class = LogsMetricRuleSerializer+ lookup_field = "id"+ posthog_feature_flag = "logs-metric-rules"+ permission_classes = [PostHogFeatureFlagPermission, MetricRuleCanonicalTeamPermission]++ @cached_property+ def canonical_team_id(self) -> int:+ # RootTeamMixin.save() stores rules under the parent (canonical) team; every read,+ # cap check, and version bump must target that same id or child-environment+ # requests silently miss the rows they just wrote.+ return resolve_effective_team_id(self.team_id)++ def _should_skip_parents_filter(self) -> bool:+ # safely_get_queryset scopes by canonical_team_id; the default parent-lookup filter+ # would AND the raw URL team id back in and hide rows stored under the parent.+ return True++ def dangerously_get_required_scopes(self, request: Request, view: APIView) -> list[str] | None:+ # Metric rules publish log attribute values into the Metrics product, so API-key+ # writes need authority over both resources.+ if self.action in ("create", "update", "partial_update", "destroy"):+ return ["logs:write", "metrics:write"]+ return None++ def safely_get_queryset(self, queryset: QuerySet) -> QuerySet:+ return queryset.filter(team_id=self.canonical_team_id)++ def _assert_metrics_editor_access(self, user: User) -> None:+ # Rule authors export log attribute values as metrics readable by anyone with+ # metrics access — creating or changing a rule therefore requires metrics editor+ # rights, so a logs editor can't publish logs data past a metrics restriction.+ canonical_team = self.team.parent_team or self.team+ user_access_control = UserAccessControl(user=user, team=canonical_team)+ if not user_access_control.check_access_level_for_resource("metrics", "editor"):+ raise PermissionDenied("Managing metric rules requires editor access to metrics.")++ def _validate_team_limits(self, serializer: LogsMetricRuleSerializer, exclude_pk: Any = None) -> None:+ team_rules = LogsMetricRule.objects.filter(team_id=self.canonical_team_id)+ if exclude_pk is not None:+ team_rules = team_rules.exclude(pk=exclude_pk)++ metric_name = serializer.validated_data.get("metric_name")+ if metric_name and team_rules.filter(metric_name=metric_name).exists():+ raise ValidationError({"metric_name": "A rule already emits this metric name in this project."})++ wants_enabled = serializer.validated_data.get("enabled")+ if wants_enabled and team_rules.filter(enabled=True).count() >= MAX_ENABLED_METRIC_RULES:+ raise ValidationError(+ {"enabled": f"At most {MAX_ENABLED_METRIC_RULES} metric rules can be enabled per project."}+ )++ def _lock_team_rules(self) -> None:+ # Advisory xact lock serializes rule writes per canonical team so concurrent+ # requests can't all pass the enabled-rule count before any of them saves.+ # Must run inside transaction.atomic() — the lock releases on commit/rollback.+ with connection.cursor() as cursor:+ cursor.execute(+ "SELECT pg_advisory_xact_lock(%s, %s)", [_METRIC_RULE_LOCK_NAMESPACE, self.canonical_team_id]+ )++ def perform_create(self, serializer: serializers.BaseSerializer) -> None:+ s = cast(LogsMetricRuleSerializer, serializer)+ user = cast(User, self.request.user)+ self._assert_metrics_editor_access(user)+ with transaction.atomic():+ self._lock_team_rules()+ self._validate_team_limits(s)+ instance = s.save(+ team_id=self.canonical_team_id,+ created_by=user if user.is_authenticated else None,+ version=1,+ )+ report_user_action(+ user,+ "logs metric rule created",+ {"rule_id": str(instance.id), "is_distribution": instance.value_attribute is not None},+ team=self.team,+ request=self.request,+ )++ def perform_update(self, serializer: serializers.BaseSerializer) -> None:+ s = cast(LogsMetricRuleSerializer, serializer)+ user = cast(User, self.request.user)+ assert s.instance is not None+ self._assert_metrics_editor_access(user)+ with transaction.atomic():+ self._lock_team_rules()+ self._validate_team_limits(s, exclude_pk=s.instance.pk)+ instance = cast(LogsMetricRule, s.save())+ LogsMetricRule.objects.filter(pk=instance.pk, team_id=self.canonical_team_id).update(+ version=F("version") + 1+ )+ instance.refresh_from_db(fields=["version", "updated_at"])+ report_user_action(+ user,+ "logs metric rule updated",+ {"rule_id": str(instance.id)},+ team=self.team,+ request=self.request,+ )++ def perform_destroy(self, instance: LogsMetricRule) -> None:+ user = cast(User, self.request.user)+ # Same gate as create/update: deleting a rule tears down a metric that metrics+ # users depend on, and AccessControlPermission only evaluates the `logs` scope.+ self._assert_metrics_editor_access(user)+ report_user_action(+ user,+ "logs metric rule deleted",+ {"rule_id": str(instance.id)},+ team=self.team,+ request=self.request,+ )+ super().perform_destroy(instance)diff --git a/products/logs/backend/presentation/views/sampling_api.py b/products/logs/backend/presentation/views/sampling_api.pyindex 0f4f205f9601..47ac915a8e94 100644--- a/products/logs/backend/presentation/views/sampling_api.py+++ b/products/logs/backend/presentation/views/sampling_api.py@@ -21,71 +21,13 @@ from posthog.models.user import Userfrom posthog.permissions import PostHogFeatureFlagPermissionfrom products.logs.backend.models import LogsExclusionRule--# Keep aligned with `MAX_FILTER_GROUP_DEPTH` / `MAX_FILTER_GROUP_NODES` in-# `nodejs/src/logs-ingestion/sampling/filter-group-match.ts` and-# `compile-rules.ts`. Both depth and breadth are bounded so an adversarially-# deep or wide filter_group cannot stack-overflow or CPU-burn the per-record-# evaluator in the Node ingestion worker. The breadth cap is the more-# realistic abuse vector — depth 1 with 10k sibling leaves passes the depth-# check but costs O(leaves) per log record.-MAX_FILTER_GROUP_DEPTH = 16-MAX_FILTER_GROUP_NODES = 256---def _filter_group_depth(node: Any, depth: int = 0) -> int:- # Short-circuit once we've crossed the cap — we don't need the true depth,- # just that it exceeds MAX_FILTER_GROUP_DEPTH. Prevents Python RecursionError- # on adversarial payloads that pass pydantic-core (Rust) validation, which- # has a more generous recursion limit than ours.- if depth > MAX_FILTER_GROUP_DEPTH:- return depth- if not isinstance(node, dict):- return depth- values = node.get("values")- if not isinstance(values, list) or node.get("type") not in ("AND", "OR"):- return depth- max_child = depth- for child in values:- d = _filter_group_depth(child, depth + 1)- if d > max_child:- max_child = d- return max_child---def _filter_group_node_count(node: Any) -> int:- """Total node count across the filter group (groups + leaves). Short-circuits- once the cap is exceeded so adversarial payloads don't get fully traversed."""- if not isinstance(node, dict):- return 1- total = 1- values = node.get("values")- if not isinstance(values, list) or node.get("type") not in ("AND", "OR"):- return total- for child in values:- total += _filter_group_node_count(child)- if total > MAX_FILTER_GROUP_NODES:- return total- return total---def _filter_group_has_empty_group(node: Any) -> bool:- """True when any group node in the tree has an empty `values` list. The worker's- matchFilterGroup treats empty groups as no-match (dropping is irreversible, so- vacuous filters fail closed), which makes a rule carrying one silently inert —- worst on rate_limit, where `{"type": "AND", "values": []}` reads like "cap- everything" but caps nothing.-- Recurses without a depth short-circuit of its own — callers must run the- MAX_FILTER_GROUP_DEPTH check first so the tree is already bounded."""- if not isinstance(node, dict):- return False- values = node.get("values")- if not isinstance(values, list) or node.get("type") not in ("AND", "OR"):- return False- if len(values) == 0:- return True- return any(_filter_group_has_empty_group(child) for child in values)+from products.logs.backend.presentation.filter_group_validation import (+ MAX_FILTER_GROUP_DEPTH,+ MAX_FILTER_GROUP_NODES,+ filter_group_depth,+ filter_group_has_empty_group,+ filter_group_node_count,+)class LogsSamplingRuleSerializer(serializers.ModelSerializer):@@ -268,7 +210,7 @@ class LogsSamplingRuleSerializer(serializers.ModelSerializer):# stack-overflow + CPU footgun on every log line. Matches# `MAX_FILTER_GROUP_DEPTH` in# `nodejs/src/logs-ingestion/sampling/filter-group-match.ts`.- if _filter_group_depth(filter_group) > MAX_FILTER_GROUP_DEPTH:+ if filter_group_depth(filter_group) > MAX_FILTER_GROUP_DEPTH:raise ValidationError({"config": {"filter_group": f"filter_group is nested too deeply (max depth {MAX_FILTER_GROUP_DEPTH})."}})@@ -277,7 +219,7 @@ class LogsSamplingRuleSerializer(serializers.ModelSerializer):# more realistic abuse vector: it passes the depth check but# costs O(leaves) on every log line through the ingestion# worker. Matches `MAX_FILTER_GROUP_NODES` in `compile-rules.ts`.- if _filter_group_node_count(filter_group) > MAX_FILTER_GROUP_NODES:+ if filter_group_node_count(filter_group) > MAX_FILTER_GROUP_NODES:raise ValidationError({"config": {@@ -286,10 +228,10 @@ class LogsSamplingRuleSerializer(serializers.ModelSerializer):})# Well-formed but empty groups pass Pydantic, yet the worker treats them as- # no-match — the rule would be silently inert (see _filter_group_has_empty_group).+ # no-match — the rule would be silently inert (see filter_group_has_empty_group).# Ordering constraint: this walk recurses without its own depth short-circuit,# so it must run only after the depth check above has bounded the tree.- if reject_vacuous and _filter_group_has_empty_group(filter_group):+ if reject_vacuous and filter_group_has_empty_group(filter_group):raise ValidationError({"config": {diff --git a/products/logs/backend/routes.py b/products/logs/backend/routes.pyindex 7d62698e9ef0..24ee3c0d0784 100644--- a/products/logs/backend/routes.py+++ b/products/logs/backend/routes.py@@ -9,6 +9,9 @@ def register_routes(routers: RouterRegistry) -> None:routers.register_legacy_dual_route(r"logs/sampling_rules", logs.LogsSamplingRuleViewSet, "environment_logs_sampling_rules", ["team_id"])+ routers.projects.register(+ r"logs/metric_rules", logs.LogsMetricRuleViewSet, "project_logs_metric_rules", ["team_id"]+ )routers.register_legacy_dual_route(r"logs/views", logs.LogsViewViewSet, "project_logs_views", ["team_id"])routers.register_legacy_dual_route(r"logs/explainLogWithAI", logs.LogExplainViewSet, "project_logs_explain_with_ai", ["team_id"]diff --git a/products/logs/backend/test/test_metric_rules_api.py b/products/logs/backend/test/test_metric_rules_api.pynew file mode 100644index 000000000000..3af7011a1248--- /dev/null+++ b/products/logs/backend/test/test_metric_rules_api.py@@ -0,0 +1,379 @@+from posthog.test.base import APIBaseTest+from unittest.mock import patch++from django.test import SimpleTestCase++from parameterized import parameterized+from rest_framework import status++from posthog.models.personal_api_key import PersonalAPIKey+from posthog.models.scoping import team_scope+from posthog.models.team import Team+from posthog.models.utils import generate_random_token_personal, hash_key_value++from products.logs.backend.models import MAX_ENABLED_METRIC_RULES, LogsMetricRule+from products.logs.backend.presentation.filter_group_validation import MAX_FILTER_GROUP_LEAF_VALUES+from products.logs.backend.presentation.views.metric_rules_api import LogsMetricRuleSerializer++VALID_FILTER_GROUP = {+ "type": "AND",+ "values": [+ {+ "type": "AND",+ "values": [{"key": "service.name", "operator": "exact", "value": "api", "type": "log_attribute"}],+ }+ ],+}+++class TestLogsMetricRuleSerializerValidation(SimpleTestCase):+ def _serializer(self, **overrides):+ data = {+ "name": "API errors",+ "metric_name": "log.api_errors",+ "filter_group": VALID_FILTER_GROUP,+ }+ data.update(overrides)+ return LogsMetricRuleSerializer(data=data)++ @parameterized.expand(+ [+ ("starts_with_digit", "1metric"),+ ("starts_with_dot", ".metric"),+ ("contains_space", "log errors"),+ ("contains_slash", "log/errors"),+ ("empty", ""),+ ]+ )+ def test_rejects_invalid_metric_name(self, _label, metric_name):+ s = self._serializer(metric_name=metric_name)+ assert not s.is_valid()+ assert "metric_name" in s.errors++ @parameterized.expand(+ [+ ("simple", "log_errors"),+ ("dotted", "log.api.errors"),+ ("dashed", "log-errors"),+ ("mixed", "Log.API_errors-2"),+ ]+ )+ def test_accepts_valid_metric_name(self, _label, metric_name):+ s = self._serializer(metric_name=metric_name)+ assert s.is_valid(), s.errors++ def test_rejects_more_than_five_group_by_keys(self):+ s = self._serializer(group_by=[f"attributes.k{i}" for i in range(6)])+ assert not s.is_valid()+ assert "group_by" in s.errors++ @parameterized.expand(+ [+ ("unknown_top_level", ["severity_number"]),+ ("body", ["body"]),+ ("bare_prefix", ["attributes."]),+ ("unprefixed_attribute", ["http.status_code"]),+ ]+ )+ def test_rejects_invalid_group_by_key(self, _label, group_by):+ s = self._serializer(group_by=group_by)+ assert not s.is_valid()+ assert "group_by" in s.errors++ def test_accepts_valid_group_by_keys(self):+ s = self._serializer(+ group_by=["service_name", "severity_text", "attributes.http.status_code", "resource_attributes.k8s.pod"]+ )+ assert s.is_valid(), s.errors++ def test_count_rule_without_value_attribute_is_valid(self):+ s = self._serializer()+ assert s.is_valid(), s.errors+ assert s.validated_data.get("value_attribute") is None++ def test_null_filter_group_matches_all_logs(self):+ s = self._serializer(filter_group=None)+ assert s.is_valid(), s.errors++ @parameterized.expand(+ [+ ("not_a_group", {"key": "service.name"}),+ ("list_shape", [{"type": "AND", "values": []}]),+ ("vacuous_group", {"type": "AND", "values": []}),+ ]+ )+ def test_rejects_malformed_filter_group(self, _label, filter_group):+ s = self._serializer(filter_group=filter_group)+ assert not s.is_valid()+ assert "filter_group" in s.errors++ def test_rejects_too_deep_filter_group(self):+ node: dict = {+ "type": "AND",+ "values": [{"key": "service.name", "operator": "exact", "value": "api", "type": "log_attribute"}],+ }+ for _ in range(20):+ node = {"type": "AND", "values": [node]}+ s = self._serializer(filter_group=node)+ assert not s.is_valid()+ assert "filter_group" in s.errors++ def test_rejects_too_many_filter_leaf_values(self):+ # One `exact` leaf with a huge value array counts as a single node, but+ # matchExact scans the whole array per log record — the leaf-value budget+ # bounds that per-record CPU.+ huge = {+ "type": "AND",+ "values": [+ {+ "type": "AND",+ "values": [+ {+ "key": "service.name",+ "operator": "exact",+ "value": [f"svc-{i}" for i in range(MAX_FILTER_GROUP_LEAF_VALUES + 1)],+ "type": "log_attribute",+ }+ ],+ }+ ],+ }+ s = self._serializer(filter_group=huge)+ assert not s.is_valid()+ assert "filter_group" in s.errors++ def test_rejects_oversized_filter_leaf_value(self):+ oversized = {+ "type": "AND",+ "values": [+ {+ "type": "AND",+ "values": [+ {+ "key": "service.name",+ "operator": "exact",+ "value": "x" * 5000,+ "type": "log_attribute",+ }+ ],+ }+ ],+ }+ s = self._serializer(filter_group=oversized)+ assert not s.is_valid()+ assert "filter_group" in s.errors+++class TestLogsMetricRulesAPI(APIBaseTest):+ def setUp(self):+ super().setUp()+ self.base_url = f"/api/projects/{self.team.pk}/logs/metric_rules/"+ self._ff_patcher = patch("posthoganalytics.feature_enabled", return_value=True)+ self._ff_patcher.start()+ self.addCleanup(self._ff_patcher.stop)++ def _payload(self, **overrides):+ data = {+ "name": "API errors",+ "metric_name": "log.api_errors",+ "filter_group": VALID_FILTER_GROUP,+ }+ data.update(overrides)+ return data++ @patch("products.logs.backend.presentation.views.metric_rules_api.report_user_action")+ def test_create_defaults(self, mock_report):+ response = self.client.post(self.base_url, self._payload(), format="json")+ assert response.status_code == status.HTTP_201_CREATED, response.json()+ body = response.json()+ assert body["enabled"] is False+ assert body["version"] == 1+ assert body["value_attribute"] is None+ assert body["group_by"] == []+ mock_report.assert_called_once()++ def test_list_scoped_to_team(self):+ self.client.post(self.base_url, self._payload(), format="json")+ other_team = self.create_team_with_organization(organization=self.organization)+ with team_scope(other_team.id):+ LogsMetricRule.objects.create(team=other_team, name="other", metric_name="other.metric")++ response = self.client.get(self.base_url)+ assert response.status_code == status.HTTP_200_OK+ results = response.json()["results"]+ assert len(results) == 1+ assert results[0]["metric_name"] == "log.api_errors"++ def test_create_attribute_rule(self):+ response = self.client.post(+ self.base_url,+ self._payload(metric_name="log.request_duration", value_attribute="attributes.duration_ms"),+ format="json",+ )+ assert response.status_code == status.HTTP_201_CREATED, response.json()+ assert response.json()["value_attribute"] == "attributes.duration_ms"++ def test_rejects_duplicate_metric_name_for_team(self):+ assert self.client.post(self.base_url, self._payload(), format="json").status_code == status.HTTP_201_CREATED+ response = self.client.post(self.base_url, self._payload(name="Another"), format="json")+ assert response.status_code == status.HTTP_400_BAD_REQUEST, response.json()++ def test_rejects_enabling_more_than_max_rules(self):+ for i in range(MAX_ENABLED_METRIC_RULES):+ r = self.client.post(+ self.base_url,+ self._payload(name=f"r{i}", metric_name=f"log.m{i}", enabled=True),+ format="json",+ )+ assert r.status_code == status.HTTP_201_CREATED, r.json()+ response = self.client.post(+ self.base_url, self._payload(name="overflow", metric_name="log.overflow", enabled=True), format="json"+ )+ assert response.status_code == status.HTTP_400_BAD_REQUEST, response.json()+ # Disabled rules are not capped.+ response = self.client.post(+ self.base_url, self._payload(name="disabled", metric_name="log.disabled", enabled=False), format="json"+ )+ assert response.status_code == status.HTTP_201_CREATED, response.json()++ def test_metric_name_and_value_attribute_immutable_on_update(self):+ created = self.client.post(self.base_url, self._payload(), format="json").json()+ detail_url = f"{self.base_url}{created['id']}/"++ response = self.client.patch(detail_url, {"metric_name": "log.renamed"}, format="json")+ assert response.status_code == status.HTTP_400_BAD_REQUEST, response.json()++ response = self.client.patch(detail_url, {"value_attribute": "attributes.duration_ms"}, format="json")+ assert response.status_code == status.HTTP_400_BAD_REQUEST, response.json()++ def test_update_filter_and_group_by_bumps_version(self):+ created = self.client.post(self.base_url, self._payload(), format="json").json()+ detail_url = f"{self.base_url}{created['id']}/"++ response = self.client.patch(detail_url, {"group_by": ["severity_text"], "enabled": True}, format="json")+ assert response.status_code == status.HTTP_200_OK, response.json()+ body = response.json()+ assert body["group_by"] == ["severity_text"]+ assert body["enabled"] is True+ assert body["version"] == created["version"] + 1++ def test_requires_feature_flag(self):+ self._ff_patcher.stop()+ with patch("posthoganalytics.feature_enabled", return_value=False):+ response = self.client.post(self.base_url, self._payload(), format="json")+ assert response.status_code == status.HTTP_403_FORBIDDEN+ self._ff_patcher = patch("posthoganalytics.feature_enabled", return_value=True)+ self._ff_patcher.start()++ def test_child_environment_url_targets_canonical_team(self):+ # RootTeamMixin.save() stores rules under the parent (canonical) team, so the+ # viewset must list, cap, and version-bump against that same canonical id — a+ # raw-child filter would hide the row and silently skip the version bump the+ # ingestion worker's cache coherency depends on.+ env = Team.objects.create(organization=self.organization, parent_team=self.team, name="env")+ env_url = f"/api/projects/{env.pk}/logs/metric_rules/"++ created = self.client.post(env_url, self._payload(), format="json")+ assert created.status_code == status.HTTP_201_CREATED, created.json()+ rule = LogsMetricRule.objects.unscoped().get(id=created.json()["id"])+ assert rule.team_id == self.team.pk++ listed = self.client.get(env_url)+ assert listed.status_code == status.HTTP_200_OK+ assert [r["id"] for r in listed.json()["results"]] == [created.json()["id"]]++ updated = self.client.patch(f"{env_url}{created.json()['id']}/", {"enabled": True}, format="json")+ assert updated.status_code == status.HTTP_200_OK, updated.json()+ assert updated.json()["version"] == created.json()["version"] + 1++ def test_child_scoped_personal_api_key_cannot_write_parent_rules(self):+ env = Team.objects.create(organization=self.organization, parent_team=self.team, name="env")+ key_value = generate_random_token_personal()+ PersonalAPIKey.objects.create(+ label="child-scoped",+ user=self.user,+ secure_value=hash_key_value(key_value),+ scopes=["logs:write", "metrics:write"],+ scoped_teams=[env.pk],+ )++ response = self.client.post(+ f"/api/projects/{env.pk}/logs/metric_rules/",+ self._payload(),+ format="json",+ HTTP_AUTHORIZATION=f"Bearer {key_value}",+ )+ assert response.status_code == status.HTTP_403_FORBIDDEN, response.json()+ assert LogsMetricRule.objects.unscoped().filter(team_id=self.team.pk).count() == 0++ def test_enabled_cap_counts_canonical_rows(self):+ # Rules created via the parent URL and a child URL land on the same canonical+ # team, so the cap must hold across both paths.+ env = Team.objects.create(organization=self.organization, parent_team=self.team, name="env")+ for i in range(MAX_ENABLED_METRIC_RULES):+ r = self.client.post(+ self.base_url, self._payload(name=f"r{i}", metric_name=f"log.m{i}", enabled=True), format="json"+ )+ assert r.status_code == status.HTTP_201_CREATED, r.json()++ response = self.client.post(+ f"/api/projects/{env.pk}/logs/metric_rules/",+ self._payload(name="overflow", metric_name="log.overflow", enabled=True),+ format="json",+ )+ assert response.status_code == status.HTTP_400_BAD_REQUEST, response.json()++ def test_write_requires_metrics_editor_access(self):+ # Metric rules publish log attribute values into the Metrics product, so rule+ # authors need authority over metrics too — a logs editor whose org restricted+ # metrics must not be able to export logs data through this side door. RBAC is+ # patched at the core boundary (creating an AccessControl row needs `ee`, which+ # products.logs may not depend on).+ def deny_metrics_only(resource, required_level=None, *args, **kwargs):+ return resource != "metrics"++ with patch(+ "products.logs.backend.presentation.views.metric_rules_api.UserAccessControl.check_access_level_for_resource",+ side_effect=deny_metrics_only,+ ) as mock_check:+ response = self.client.post(self.base_url, self._payload(), format="json")++ assert response.status_code == status.HTTP_403_FORBIDDEN, response.json()+ mock_check.assert_any_call("metrics", "editor")++ def test_delete_requires_metrics_editor_access(self):+ # Deleting a rule tears down a metric that metrics users may depend on, so it+ # is gated like create/update — a logs-only editor must not remove it. The+ # AccessControlPermission layer only evaluates the view's `logs` scope, so the+ # metrics check has to run in perform_destroy itself.+ created = self.client.post(self.base_url, self._payload(), format="json").json()+ detail_url = f"{self.base_url}{created['id']}/"++ def deny_metrics_only(resource, required_level=None, *args, **kwargs):+ return resource != "metrics"++ with patch(+ "products.logs.backend.presentation.views.metric_rules_api.UserAccessControl.check_access_level_for_resource",+ side_effect=deny_metrics_only,+ ):+ response = self.client.delete(detail_url)++ assert response.status_code == status.HTTP_403_FORBIDDEN, response.json()+ assert self.client.get(detail_url).status_code == status.HTTP_200_OK++ @parameterized.expand(+ [+ (["logs:write"], status.HTTP_403_FORBIDDEN),+ (["logs:write", "metrics:write"], status.HTTP_201_CREATED),+ ]+ )+ def test_write_requires_metrics_write_scope_for_api_keys(self, scopes, expected_status):+ key_value = generate_random_token_personal()+ PersonalAPIKey.objects.create(+ label="scoped", user=self.user, secure_value=hash_key_value(key_value), scopes=scopes+ )++ response = self.client.post(+ self.base_url, self._payload(), format="json", HTTP_AUTHORIZATION=f"Bearer {key_value}"+ )+ assert response.status_code == expected_status, response.json()diff --git a/products/logs/frontend/components/LogsMetricRules/LogsMetricRulesSection.tsx b/products/logs/frontend/components/LogsMetricRules/LogsMetricRulesSection.tsxnew file mode 100644index 000000000000..68134a424b8d--- /dev/null+++ b/products/logs/frontend/components/LogsMetricRules/LogsMetricRulesSection.tsx@@ -0,0 +1,224 @@+import { BindLogic, useActions, useValues } from 'kea'+import { Form } from 'kea-forms'++import {+ LemonButton,+ LemonInput,+ LemonInputSelect,+ LemonModal,+ LemonSwitch,+ LemonTable,+ LemonTag,+} from '@posthog/lemon-ui'++import { useFeatureFlag } from 'lib/hooks/useFeatureFlag'+import { More } from 'lib/lemon-ui/LemonButton/More'+import { LemonField } from 'lib/lemon-ui/LemonField'++import { LogsMetricRuleApi } from 'products/logs/frontend/generated/api.schemas'+import { LogsFeatureFlagKeys } from 'products/logs/frontend/logsFeatureFlagKeys'++import { DropRuleFilterEditor } from '../LogsSampling/DropRuleFilterEditor'+import { GROUP_BY_SUGGESTIONS, logsMetricRuleFormLogic } from './logsMetricRuleFormLogic'+import { logsMetricRulesSectionLogic } from './logsMetricRulesSectionLogic'++export function LogsMetricRulesSection(): JSX.Element | null {+ const enabled = useFeatureFlag(LogsFeatureFlagKeys.metricRules)+ if (!enabled) {+ return null+ }+ return (+ <BindLogic logic={logsMetricRulesSectionLogic} props={{}}>+ <div className="space-y-3">+ <p className="text-muted m-0">+ Generate metrics from your logs at ingestion time. Count log lines matching a filter, or aggregate a+ numeric log attribute, and use the result in dashboards, alerts, and queries in the Metrics product.+ Metrics are computed before drop rules, so you can drop noisy logs and keep the trend.+ </p>+ <LogsMetricRulesTable />+ <LogsMetricRuleModal />+ </div>+ </BindLogic>+ )+}++function LogsMetricRulesTable(): JSX.Element {+ const { rules, rulesLoading } = useValues(logsMetricRulesSectionLogic)+ const { openNewRuleModal, openEditRuleModal, deleteRule, setRuleEnabled } = useActions(logsMetricRulesSectionLogic)++ return (+ <div className="space-y-2">+ <LemonTable+ dataSource={rules}+ loading={rulesLoading}+ rowKey="id"+ emptyState="No metric rules yet. Create one to start generating metrics from your logs."+ columns={[+ {+ title: 'Name',+ key: 'name',+ render: (_, rule: LogsMetricRuleApi) => <span className="font-medium">{rule.name}</span>,+ },+ {+ title: 'Metric',+ key: 'metric_name',+ render: (_, rule: LogsMetricRuleApi) => <code>{rule.metric_name}</code>,+ },+ {+ title: 'Type',+ key: 'type',+ render: (_, rule: LogsMetricRuleApi) =>+ rule.value_attribute ? (+ <LemonTag type="highlight">{rule.value_attribute}</LemonTag>+ ) : (+ <LemonTag>count</LemonTag>+ ),+ },+ {+ title: 'Group by',+ key: 'group_by',+ render: (_, rule: LogsMetricRuleApi) =>+ rule.group_by?.length ? rule.group_by.join(', ') : <span className="text-muted">—</span>,+ },+ {+ title: 'Enabled',+ key: 'enabled',+ render: (_, rule: LogsMetricRuleApi) => (+ <LemonSwitch+ checked={rule.enabled ?? false}+ onChange={(checked) => setRuleEnabled(rule, checked)}+ />+ ),+ },+ {+ key: 'actions',+ width: 0,+ render: (_, rule: LogsMetricRuleApi) => (+ <More+ overlay={+ <>+ <LemonButton fullWidth onClick={() => openEditRuleModal(rule)}>+ Edit+ </LemonButton>+ <LemonButton fullWidth status="danger" onClick={() => deleteRule(rule)}>+ Delete+ </LemonButton>+ </>+ }+ />+ ),+ },+ ]}+ />+ <LemonButton type="primary" onClick={openNewRuleModal}>+ New metric rule+ </LemonButton>+ </div>+ )+}++function LogsMetricRuleModal(): JSX.Element | null {+ const { ruleModalOpen, editingRule } = useValues(logsMetricRulesSectionLogic)+ const { closeRuleModal } = useActions(logsMetricRulesSectionLogic)++ if (!ruleModalOpen) {+ return null+ }+ return (+ <LemonModal+ isOpen+ onClose={closeRuleModal}+ title={editingRule ? 'Edit metric rule' : 'New metric rule'}+ width={720}+ footer={null}+ >+ <LogsMetricRuleForm rule={editingRule} />+ </LemonModal>+ )+}++function LogsMetricRuleForm({ rule }: { rule: LogsMetricRuleApi | null }): JSX.Element {+ const logic = logsMetricRuleFormLogic({ rule })+ const { metricRuleForm, isMetricRuleFormSubmitting } = useValues(logic)+ const { setMetricRuleFormValue } = useActions(logic)+ const { closeRuleModal } = useActions(logsMetricRulesSectionLogic)++ const isEdit = rule !== null++ return (+ <Form logic={logsMetricRuleFormLogic} props={{ rule }} formKey="metricRuleForm" enableFormOnSubmit>+ <div className="space-y-4">+ <LemonField name="name" label="Name">+ <LemonInput placeholder="API errors" />+ </LemonField>+ <LemonField+ name="metric_name"+ label="Metric name"+ help={+ isEdit+ ? 'The metric name cannot be changed after creation. Create a new rule instead.'+ : 'How the generated metric appears in the Metrics product.'+ }+ >+ <LemonInput placeholder="log.api_errors" disabled={isEdit} />+ </LemonField>+ <LemonField+ name="value_attribute"+ label="Value attribute (optional)"+ help={+ isEdit+ ? 'The value attribute cannot be changed after creation, since it determines the metric type.'+ : 'Leave empty to count matching log lines. Set a numeric log attribute (e.g. `attributes.duration_ms`) to aggregate its value instead.'+ }+ >+ <LemonInput placeholder="attributes.duration_ms" disabled={isEdit} />+ </LemonField>+ <div className="space-y-1">+ <label className="font-semibold">Filters</label>+ <p className="text-muted text-xs m-0">+ Only log lines matching these filters feed the metric. Leave empty to match all logs.+ </p>+ <DropRuleFilterEditor+ filterGroup={metricRuleForm.filter_group}+ onChange={(group) => setMetricRuleFormValue('filter_group', group)}+ logicKey={`logs-metric-rule:${rule?.id ?? 'new'}`}+ />+ </div>+ <LemonField+ name="group_by"+ label="Group by (optional)"+ help="Each distinct value combination becomes its own metric series. Avoid high-cardinality keys like user or request IDs."+ >+ {({ value, onChange }) => (+ <LemonInputSelect+ mode="multiple"+ allowCustomValues+ value={value}+ onChange={onChange}+ options={GROUP_BY_SUGGESTIONS.map((key) => ({ key, label: key }))}+ placeholder="service_name, severity_text, attributes.…"+ />+ )}+ </LemonField>+ <LemonField name="enabled">+ {({ value, onChange }) => (+ <LemonSwitch checked={value} onChange={onChange} label="Enabled" bordered />+ )}+ </LemonField>+ <div className="flex justify-end gap-2">+ <LemonButton type="secondary" onClick={closeRuleModal}>+ Cancel+ </LemonButton>+ <LemonButton+ type="primary"+ htmlType="submit"+ loading={isMetricRuleFormSubmitting}+ disabledReason={isMetricRuleFormSubmitting ? 'Saving…' : undefined}+ >+ {isEdit ? 'Save changes' : 'Create metric rule'}+ </LemonButton>+ </div>+ </div>+ </Form>+ )+}diff --git a/products/logs/frontend/components/LogsMetricRules/logsMetricRuleFormLogic.ts b/products/logs/frontend/components/LogsMetricRules/logsMetricRuleFormLogic.tsnew file mode 100644index 000000000000..c8096eb89c5f--- /dev/null+++ b/products/logs/frontend/components/LogsMetricRules/logsMetricRuleFormLogic.ts@@ -0,0 +1,238 @@+import { MakeLogicType, connect, kea, key, path, props } from 'kea'+import { forms } from 'kea-forms'+import type { DeepPartial, DeepPartialMap, FieldName, ValidationErrorType } from 'kea-forms'++import { lemonToast } from '@posthog/lemon-ui'++import { teamLogic } from 'scenes/teamLogic'++import { FilterLogicalOperator, UniversalFiltersGroup } from '~/types'++import { logsMetricRulesCreate, logsMetricRulesPartialUpdate } from 'products/logs/frontend/generated/api'+import { LogsMetricRuleApi, PatchedLogsMetricRuleApi } from 'products/logs/frontend/generated/api.schemas'++import { logsMetricRulesSectionLogic } from './logsMetricRulesSectionLogic'++const EMPTY_FILTER_GROUP: UniversalFiltersGroup = {+ type: FilterLogicalOperator.And,+ values: [],+}++// Mirrors METRIC_NAME_PATTERN in products/logs/backend/presentation/views/metric_rules_api.py.+const METRIC_NAME_PATTERN = /^[a-zA-Z][a-zA-Z0-9._-]*$/++export const MAX_GROUP_BY_KEYS = 5+const GROUP_BY_TOP_LEVEL_KEYS = ['service_name', 'severity_text', 'event_name']+const ATTRIBUTE_KEY_PREFIXES = ['attributes.', 'resource_attributes.']++export const GROUP_BY_SUGGESTIONS = GROUP_BY_TOP_LEVEL_KEYS++function isValidGroupByKey(k: string): boolean {+ return (+ GROUP_BY_TOP_LEVEL_KEYS.includes(k) ||+ ATTRIBUTE_KEY_PREFIXES.some((prefix) => k.startsWith(prefix) && k.length > prefix.length)+ )+}++/** Same wrapped `{type, values: [innerGroup]}` wire shape as drop rules (see logsSamplingFormLogic). */+function extractFilterGroup(stored: unknown): UniversalFiltersGroup {+ if (!stored || typeof stored !== 'object') {+ return EMPTY_FILTER_GROUP+ }+ const candidate = stored as { type?: unknown; values?: unknown[] }+ if (!Array.isArray(candidate.values)) {+ return EMPTY_FILTER_GROUP+ }+ const first = candidate.values[0] as { type?: unknown; values?: unknown[] } | undefined+ if (first && Array.isArray(first.values) && typeof first.type === 'string') {+ return first as UniversalFiltersGroup+ }+ return candidate as UniversalFiltersGroup+}++function wrapFilterGroup(inner: UniversalFiltersGroup): UniversalFiltersGroup {+ return { type: FilterLogicalOperator.And, values: [inner] as never }+}++export interface LogsMetricRuleFormType {+ name: string+ metric_name: string+ enabled: boolean+ filter_group: UniversalFiltersGroup+ value_attribute: string+ group_by: string[]+}++const DEFAULT_FORM: LogsMetricRuleFormType = {+ name: '',+ metric_name: '',+ enabled: true,+ filter_group: EMPTY_FILTER_GROUP,+ value_attribute: '',+ group_by: [],+}++export function buildMetricRuleFormDefaults(rule: LogsMetricRuleApi | null): LogsMetricRuleFormType {+ if (!rule) {+ return { ...DEFAULT_FORM }+ }+ return {+ name: rule.name,+ metric_name: rule.metric_name,+ enabled: rule.enabled ?? false,+ filter_group: extractFilterGroup(rule.filter_group),+ value_attribute: rule.value_attribute ?? '',+ group_by: rule.group_by ?? [],+ }+}++export interface LogsMetricRuleFormLogicProps {+ rule: LogsMetricRuleApi | null+}++// Generated by kea-typegen. Update if you're an agent, ignore if you're human.+export interface logsMetricRuleFormLogicValues {+ currentTeamId: number | null // teamLogic+ isMetricRuleFormSubmitting: boolean+ isMetricRuleFormValid: boolean+ metricRuleForm: LogsMetricRuleFormType+ metricRuleFormAllErrors: Record<string, any>+ metricRuleFormChanged: boolean+ metricRuleFormErrors: DeepPartialMap<LogsMetricRuleFormType, ValidationErrorType>+ metricRuleFormHasErrors: boolean+ metricRuleFormManualErrors: Record<string, any>+ metricRuleFormTouched: boolean+ metricRuleFormTouches: Record<string, boolean>+ metricRuleFormValidationErrors: DeepPartialMap<LogsMetricRuleFormType, ValidationErrorType>+ showMetricRuleFormErrors: boolean+}++// Generated by kea-typegen. Update if you're an agent, ignore if you're human.+export interface logsMetricRuleFormLogicActions {+ closeRuleModal: () => {+ value: true+ }+ loadRules: () => any+ resetMetricRuleForm: (values?: LogsMetricRuleFormType) => {+ values?: LogsMetricRuleFormType+ }+ setMetricRuleFormManualErrors: (errors: Record<string, any>) => {+ errors: Record<string, any>+ }+ setMetricRuleFormValue: (+ key: FieldName,+ value: any+ ) => {+ name: FieldName+ value: any+ }+ setMetricRuleFormValues: (values: DeepPartial<LogsMetricRuleFormType>) => {+ values: DeepPartial<LogsMetricRuleFormType>+ }+ submitMetricRuleForm: () => {+ value: boolean+ }+ submitMetricRuleFormFailure: (+ error: Error,+ errors: Record<string, any>+ ) => {+ error: Error+ errors: Record<string, any>+ }+ submitMetricRuleFormRequest: (metricRuleForm: LogsMetricRuleFormType) => {+ metricRuleForm: LogsMetricRuleFormType+ }+ submitMetricRuleFormSuccess: (metricRuleForm: LogsMetricRuleFormType) => {+ metricRuleForm: LogsMetricRuleFormType+ }+ touchMetricRuleFormField: (key: string) => {+ key: string+ }+}++// Generated by kea-typegen. Update if you're an agent, ignore if you're human.+export interface logsMetricRuleFormLogicMeta {+ key: string+}++export type logsMetricRuleFormLogicType = MakeLogicType<+ logsMetricRuleFormLogicValues,+ logsMetricRuleFormLogicActions,+ LogsMetricRuleFormLogicProps,+ logsMetricRuleFormLogicMeta+>++export const logsMetricRuleFormLogic = kea<logsMetricRuleFormLogicType>([+ path(['products', 'logs', 'frontend', 'components', 'LogsMetricRules', 'logsMetricRuleFormLogic']),+ props({} as LogsMetricRuleFormLogicProps),+ key(({ rule }) => rule?.id ?? 'new'),++ connect(() => ({+ values: [teamLogic, ['currentTeamId']],+ actions: [logsMetricRulesSectionLogic, ['loadRules', 'closeRuleModal']],+ })),++ forms(({ actions, props, values }) => ({+ metricRuleForm: {+ defaults: buildMetricRuleFormDefaults(props.rule),+ errors: (form: LogsMetricRuleFormType) => {+ const valueAttribute = form.value_attribute.trim()+ return {+ name: !form.name?.trim() ? 'Name is required' : undefined,+ metric_name: !form.metric_name?.trim()+ ? 'Metric name is required'+ : !METRIC_NAME_PATTERN.test(form.metric_name.trim())+ ? 'Must start with a letter and contain only letters, digits, dots, underscores, and dashes'+ : undefined,+ value_attribute:+ valueAttribute &&+ !ATTRIBUTE_KEY_PREFIXES.some(+ (p) => valueAttribute.startsWith(p) && valueAttribute.length > p.length+ )+ ? 'Must be prefixed with `attributes.` or `resource_attributes.`'+ : undefined,+ // Whole-array error message for an array field; kea-forms types expect+ // per-item errors but render a string fine (same as personalAPIKeysLogic).+ group_by:+ form.group_by.length > MAX_GROUP_BY_KEYS+ ? (`At most ${MAX_GROUP_BY_KEYS} group-by keys` as any)+ : form.group_by.some((k) => !isValidGroupByKey(k))+ ? ('Keys must be service_name, severity_text, event_name, or prefixed with `attributes.` / `resource_attributes.`' as any)+ : undefined,+ }+ },+ submit: async (form: LogsMetricRuleFormType) => {+ const projectId = String(values.currentTeamId)+ const hasFilters = form.filter_group.values.length > 0+ try {+ if (props.rule) {+ // metric_name and value_attribute are immutable after creation — omitted here.+ const patch: PatchedLogsMetricRuleApi = {+ name: form.name.trim(),+ enabled: form.enabled,+ filter_group: hasFilters ? wrapFilterGroup(form.filter_group) : null,+ group_by: form.group_by,+ }+ await logsMetricRulesPartialUpdate(projectId, props.rule.id, patch)+ lemonToast.success('Metric rule updated')+ } else {+ await logsMetricRulesCreate(projectId, {+ name: form.name.trim(),+ metric_name: form.metric_name.trim(),+ enabled: form.enabled,+ filter_group: hasFilters ? wrapFilterGroup(form.filter_group) : null,+ value_attribute: form.value_attribute.trim() || null,+ group_by: form.group_by,+ })+ lemonToast.success('Metric rule created')+ }+ actions.loadRules()+ actions.closeRuleModal()+ } catch (e: any) {+ lemonToast.error(e?.detail ?? e?.message ?? 'Failed to save metric rule')+ throw e+ }+ },+ },+ })),+])diff --git a/products/logs/frontend/components/LogsMetricRules/logsMetricRulesSectionLogic.ts b/products/logs/frontend/components/LogsMetricRules/logsMetricRulesSectionLogic.tsnew file mode 100644index 000000000000..0d9f53d5fe45--- /dev/null+++ b/products/logs/frontend/components/LogsMetricRules/logsMetricRulesSectionLogic.ts@@ -0,0 +1,136 @@+import { MakeLogicType, actions, afterMount, connect, kea, listeners, path, reducers } from 'kea'+import { loaders } from 'kea-loaders'++import { lemonToast } from '@posthog/lemon-ui'++import { teamLogic } from 'scenes/teamLogic'++import {+ logsMetricRulesDestroy,+ logsMetricRulesList,+ logsMetricRulesPartialUpdate,+} from 'products/logs/frontend/generated/api'+import { LogsMetricRuleApi } from 'products/logs/frontend/generated/api.schemas'++// Generated by kea-typegen. Update if you're an agent, ignore if you're human.+export interface logsMetricRulesSectionLogicValues {+ currentTeamId: number | null // teamLogic+ editingRule: LogsMetricRuleApi | null+ ruleModalOpen: boolean+ rules: LogsMetricRuleApi[]+ rulesLoading: boolean+}++// Generated by kea-typegen. Update if you're an agent, ignore if you're human.+export interface logsMetricRulesSectionLogicActions {+ closeRuleModal: () => {+ value: true+ }+ deleteRule: (rule: LogsMetricRuleApi) => {+ rule: LogsMetricRuleApi+ }+ loadRules: () => any+ loadRulesFailure: (+ error: string,+ errorObject?: any+ ) => {+ error: string+ errorObject?: any+ }+ loadRulesSuccess: (+ rules: LogsMetricRuleApi[],+ payload?: any+ ) => {+ rules: LogsMetricRuleApi[]+ payload?: any+ }+ openEditRuleModal: (rule: LogsMetricRuleApi) => {+ rule: LogsMetricRuleApi+ }+ openNewRuleModal: () => {+ value: true+ }+ setRuleEnabled: (+ rule: LogsMetricRuleApi,+ enabled: boolean+ ) => {+ enabled: boolean+ rule: LogsMetricRuleApi+ }+}++export type logsMetricRulesSectionLogicType = MakeLogicType<+ logsMetricRulesSectionLogicValues,+ logsMetricRulesSectionLogicActions+>++export const logsMetricRulesSectionLogic = kea<logsMetricRulesSectionLogicType>([+ path(['products', 'logs', 'frontend', 'components', 'LogsMetricRules', 'logsMetricRulesSectionLogic']),++ connect(() => ({+ values: [teamLogic, ['currentTeamId']],+ })),++ actions({+ openNewRuleModal: true,+ openEditRuleModal: (rule: LogsMetricRuleApi) => ({ rule }),+ closeRuleModal: true,+ deleteRule: (rule: LogsMetricRuleApi) => ({ rule }),+ setRuleEnabled: (rule: LogsMetricRuleApi, enabled: boolean) => ({ rule, enabled }),+ }),++ loaders(({ values }) => ({+ rules: [+ [] as LogsMetricRuleApi[],+ {+ loadRules: async () => {+ const response = await logsMetricRulesList(String(values.currentTeamId))+ return response.results+ },+ },+ ],+ })),++ reducers({+ ruleModalOpen: [+ false,+ {+ openNewRuleModal: () => true,+ openEditRuleModal: () => true,+ closeRuleModal: () => false,+ },+ ],+ editingRule: [+ null as LogsMetricRuleApi | null,+ {+ openNewRuleModal: () => null,+ openEditRuleModal: (_, { rule }) => rule,+ closeRuleModal: () => null,+ },+ ],+ }),++ listeners(({ actions, values }) => ({+ deleteRule: async ({ rule }) => {+ try {+ await logsMetricRulesDestroy(String(values.currentTeamId), rule.id)+ lemonToast.success('Metric rule deleted')+ } catch (e: any) {+ lemonToast.error(e?.detail ?? 'Failed to delete metric rule')+ }+ actions.loadRules()+ },+ setRuleEnabled: async ({ rule, enabled }) => {+ try {+ await logsMetricRulesPartialUpdate(String(values.currentTeamId), rule.id, { enabled })+ } catch (e: any) {+ lemonToast.error(e?.detail ?? 'Failed to update metric rule')+ }+ actions.loadRules()+ },+ })),++ afterMount(({ actions }) => {+ actions.loadRules()+ }),+])diff --git a/products/logs/frontend/generated/api.schemas.ts b/products/logs/frontend/generated/api.schemas.tsindex a68a1710d633..16fc4ac11a2d 100644--- a/products/logs/frontend/generated/api.schemas.ts+++ b/products/logs/frontend/generated/api.schemas.ts@@ -1149,6 +1149,87 @@ export interface _LogsGroupByResponseApi {truncated: boolean}+export interface LogsMetricRuleApi {+ /** Unique identifier for this metric rule. */+ readonly id: string+ /**+ * User-visible label for this rule.+ * @maxLength 255+ */+ name: string+ /**+ * Name of the generated metric as it appears in the Metrics product. Must start with a letter and contain only letters, digits, dots, underscores, and dashes. Unique per project and immutable after creation — create a new rule to emit under a different name.+ * @maxLength 200+ */+ metric_name: string+ /** When true, ingestion evaluates this rule against every log record. At most 10 rules can be enabled per project. */+ enabled?: boolean+ /** PropertyGroupFilter JSON (AND/OR tree of property predicates) selecting which log records feed the metric, e.g. `{"type":"AND","values":[{"type":"AND","values":[{"key":"service.name","operator":"exact","value":"api","type":"log_attribute"}]}]}`. Null matches every ingested log record. Every group must contain at least one filter — empty groups never match. */+ filter_group?: unknown+ /**+ * Log attribute key holding a numeric value to aggregate into a distribution (count + sum), e.g. `attributes.duration_ms` or `resource_attributes.batch.size`. Omit to count matching log records instead. Immutable after creation — it determines the emitted metric type.+ * @maxLength 512+ * @nullable+ */+ value_attribute?: string | null+ /**+ * Up to 5 dimension keys; each distinct value combination becomes its own metric series. Allowed: service_name, severity_text, event_name, or map keys prefixed with `attributes.` / `resource_attributes.`. Avoid high-cardinality keys (user IDs, request IDs) — excess series are dropped at ingestion.+ * @items.maxLength 512+ */+ group_by?: string[]+ /** Incremented on each update for worker cache coherency. */+ readonly version: number+ readonly created_by: number+ readonly created_at: string+ /** @nullable */+ readonly updated_at: string | null+}++export interface PaginatedLogsMetricRuleListApi {+ count: number+ /** @nullable */+ next?: string | null+ /** @nullable */+ previous?: string | null+ results: LogsMetricRuleApi[]+}++export interface PatchedLogsMetricRuleApi {+ /** Unique identifier for this metric rule. */+ readonly id?: string+ /**+ * User-visible label for this rule.+ * @maxLength 255+ */+ name?: string+ /**+ * Name of the generated metric as it appears in the Metrics product. Must start with a letter and contain only letters, digits, dots, underscores, and dashes. Unique per project and immutable after creation — create a new rule to emit under a different name.+ * @maxLength 200+ */+ metric_name?: string+ /** When true, ingestion evaluates this rule against every log record. At most 10 rules can be enabled per project. */+ enabled?: boolean+ /** PropertyGroupFilter JSON (AND/OR tree of property predicates) selecting which log records feed the metric, e.g. `{"type":"AND","values":[{"type":"AND","values":[{"key":"service.name","operator":"exact","value":"api","type":"log_attribute"}]}]}`. Null matches every ingested log record. Every group must contain at least one filter — empty groups never match. */+ filter_group?: unknown+ /**+ * Log attribute key holding a numeric value to aggregate into a distribution (count + sum), e.g. `attributes.duration_ms` or `resource_attributes.batch.size`. Omit to count matching log records instead. Immutable after creation — it determines the emitted metric type.+ * @maxLength 512+ * @nullable+ */+ value_attribute?: string | null+ /**+ * Up to 5 dimension keys; each distinct value combination becomes its own metric series. Allowed: service_name, severity_text, event_name, or map keys prefixed with `attributes.` / `resource_attributes.`. Avoid high-cardinality keys (user IDs, request IDs) — excess series are dropped at ingestion.+ * @items.maxLength 512+ */+ group_by?: string[]+ /** Incremented on each update for worker cache coherency. */+ readonly version?: number+ readonly created_by?: number+ readonly created_at?: string+ /** @nullable */+ readonly updated_at?: string | null+}+export interface _LogsPatternsBodyApi {/** Date range to mine patterns from. Defaults to last hour. */dateRange?: _DateRangeApi@@ -1868,6 +1949,17 @@ export type LogsExportCreate201 = { [key: string]: unknown }export type LogsHasLogsRetrieve200 = { [key: string]: unknown }+export type LogsMetricRulesListParams = {+ /**+ * Number of results to return per page.+ */+ limit?: number+ /**+ * The initial index from which to return the results.+ */+ offset?: number+}+export type LogsSamplingRulesListParams = {/*** Number of results to return per page.diff --git a/products/logs/frontend/generated/api.ts b/products/logs/frontend/generated/api.tsindex cbb6e024a245..ac3effb74381 100644--- a/products/logs/frontend/generated/api.ts+++ b/products/logs/frontend/generated/api.ts@@ -21,6 +21,8 @@ import type {LogsAttributesRetrieveParams,LogsExportCreate201,LogsHasLogsRetrieve200,+ LogsMetricRuleApi,+ LogsMetricRulesListParams,LogsSamplingRuleApi,LogsSamplingRuleReorderApi,LogsSamplingRuleSimulateResponseApi,@@ -31,9 +33,11 @@ import type {LogsViewsListParams,PaginatedLogsAlertConfigurationListApi,PaginatedLogsAlertEventListApi,+ PaginatedLogsMetricRuleListApi,PaginatedLogsSamplingRuleListApi,PaginatedLogsViewListApi,PatchedLogsAlertConfigurationApi,+ PatchedLogsMetricRuleApi,PatchedLogsSamplingRuleApi,PatchedLogsViewApi,_LogsAttributesResponseApi,@@ -434,6 +438,112 @@ export const logsHasLogsRetrieve = async (})}+export const getLogsMetricRulesListUrl = (projectId: string, params?: LogsMetricRulesListParams) => {+ const normalizedParams = new URLSearchParams()++ Object.entries(params || {}).forEach(([key, value]) => {+ if (value !== undefined) {+ normalizedParams.append(key, value === null ? 'null' : String(value))+ }+ })++ const stringifiedParams = normalizedParams.toString()++ return stringifiedParams.length > 0+ ? `/api/projects/${projectId}/logs/metric_rules/?${stringifiedParams}`+ : `/api/projects/${projectId}/logs/metric_rules/`+}++export const logsMetricRulesList = async (+ projectId: string,+ params?: LogsMetricRulesListParams,+ options?: RequestInit+): Promise<PaginatedLogsMetricRuleListApi> => {+ return apiMutator<PaginatedLogsMetricRuleListApi>(getLogsMetricRulesListUrl(projectId, params), {+ ...options,+ method: 'GET',+ })+}++export const getLogsMetricRulesCreateUrl = (projectId: string) => {+ return `/api/projects/${projectId}/logs/metric_rules/`+}++export const logsMetricRulesCreate = async (+ projectId: string,+ logsMetricRuleApi: NonReadonly<LogsMetricRuleApi>,+ options?: RequestInit+): Promise<LogsMetricRuleApi> => {+ return apiMutator<LogsMetricRuleApi>(getLogsMetricRulesCreateUrl(projectId), {+ ...options,+ method: 'POST',+ headers: { 'Content-Type': 'application/json', ...options?.headers },+ body: JSON.stringify(logsMetricRuleApi),+ })+}++export const getLogsMetricRulesRetrieveUrl = (projectId: string, id: string) => {+ return `/api/projects/${projectId}/logs/metric_rules/${id}/`+}++export const logsMetricRulesRetrieve = async (+ projectId: string,+ id: string,+ options?: RequestInit+): Promise<LogsMetricRuleApi> => {+ return apiMutator<LogsMetricRuleApi>(getLogsMetricRulesRetrieveUrl(projectId, id), {+ ...options,+ method: 'GET',+ })+}++export const getLogsMetricRulesUpdateUrl = (projectId: string, id: string) => {+ return `/api/projects/${projectId}/logs/metric_rules/${id}/`+}++export const logsMetricRulesUpdate = async (+ projectId: string,+ id: string,+ logsMetricRuleApi: NonReadonly<LogsMetricRuleApi>,+ options?: RequestInit+): Promise<LogsMetricRuleApi> => {+ return apiMutator<LogsMetricRuleApi>(getLogsMetricRulesUpdateUrl(projectId, id), {+ ...options,+ method: 'PUT',+ headers: { 'Content-Type': 'application/json', ...options?.headers },+ body: JSON.stringify(logsMetricRuleApi),+ })+}++export const getLogsMetricRulesPartialUpdateUrl = (projectId: string, id: string) => {+ return `/api/projects/${projectId}/logs/metric_rules/${id}/`+}++export const logsMetricRulesPartialUpdate = async (+ projectId: string,+ id: string,+ patchedLogsMetricRuleApi?: NonReadonly<PatchedLogsMetricRuleApi>,+ options?: RequestInit+): Promise<LogsMetricRuleApi> => {+ return apiMutator<LogsMetricRuleApi>(getLogsMetricRulesPartialUpdateUrl(projectId, id), {+ ...options,+ method: 'PATCH',+ headers: { 'Content-Type': 'application/json', ...options?.headers },+ body: JSON.stringify(patchedLogsMetricRuleApi),+ })+}++export const getLogsMetricRulesDestroyUrl = (projectId: string, id: string) => {+ return `/api/projects/${projectId}/logs/metric_rules/${id}/`+}++export const logsMetricRulesDestroy = async (projectId: string, id: string, options?: RequestInit): Promise<void> => {+ return apiMutator<void>(getLogsMetricRulesDestroyUrl(projectId, id), {+ ...options,+ method: 'DELETE',+ })+}+export const getLogsPatternsCreateUrl = (projectId: string) => {return `/api/projects/${projectId}/logs/patterns/`}diff --git a/products/logs/frontend/generated/api.zod.ts b/products/logs/frontend/generated/api.zod.tsindex a4275f443539..257bd89df54c 100644--- a/products/logs/frontend/generated/api.zod.ts+++ b/products/logs/frontend/generated/api.zod.ts@@ -818,6 +818,143 @@ export const LogsGroupByCreateBody = /* @__PURE__ */ zod.object({.describe('The group-by query to execute.'),})+export const logsMetricRulesCreateBodyNameMax = 255++export const logsMetricRulesCreateBodyMetricNameMax = 200++export const logsMetricRulesCreateBodyEnabledDefault = false+export const logsMetricRulesCreateBodyValueAttributeMax = 512++export const logsMetricRulesCreateBodyGroupByItemMax = 512++export const LogsMetricRulesCreateBody = /* @__PURE__ */ zod.object({+ name: zod.string().max(logsMetricRulesCreateBodyNameMax).describe('User-visible label for this rule.'),+ metric_name: zod+ .string()+ .max(logsMetricRulesCreateBodyMetricNameMax)+ .describe(+ 'Name of the generated metric as it appears in the Metrics product. Must start with a letter and contain only letters, digits, dots, underscores, and dashes. Unique per project and immutable after creation — create a new rule to emit under a different name.'+ ),+ enabled: zod+ .boolean()+ .default(logsMetricRulesCreateBodyEnabledDefault)+ .describe(+ 'When true, ingestion evaluates this rule against every log record. At most 10 rules can be enabled per project.'+ ),+ filter_group: zod+ .unknown()+ .optional()+ .describe(+ 'PropertyGroupFilter JSON (AND\/OR tree of property predicates) selecting which log records feed the metric, e.g. `{\"type\":\"AND\",\"values\":[{\"type\":\"AND\",\"values\":[{\"key\":\"service.name\",\"operator\":\"exact\",\"value\":\"api\",\"type\":\"log_attribute\"}]}]}`. Null matches every ingested log record. Every group must contain at least one filter — empty groups never match.'+ ),+ value_attribute: zod+ .string()+ .max(logsMetricRulesCreateBodyValueAttributeMax)+ .nullish()+ .describe(+ 'Log attribute key holding a numeric value to aggregate into a distribution (count + sum), e.g. `attributes.duration_ms` or `resource_attributes.batch.size`. Omit to count matching log records instead. Immutable after creation — it determines the emitted metric type.'+ ),+ group_by: zod+ .array(zod.string().max(logsMetricRulesCreateBodyGroupByItemMax))+ .optional()+ .describe(+ 'Up to 5 dimension keys; each distinct value combination becomes its own metric series. Allowed: service_name, severity_text, event_name, or map keys prefixed with `attributes.` \/ `resource_attributes.`. Avoid high-cardinality keys (user IDs, request IDs) — excess series are dropped at ingestion.'+ ),+})++export const logsMetricRulesUpdateBodyNameMax = 255++export const logsMetricRulesUpdateBodyMetricNameMax = 200++export const logsMetricRulesUpdateBodyEnabledDefault = false+export const logsMetricRulesUpdateBodyValueAttributeMax = 512++export const logsMetricRulesUpdateBodyGroupByItemMax = 512++export const LogsMetricRulesUpdateBody = /* @__PURE__ */ zod.object({+ name: zod.string().max(logsMetricRulesUpdateBodyNameMax).describe('User-visible label for this rule.'),+ metric_name: zod+ .string()+ .max(logsMetricRulesUpdateBodyMetricNameMax)+ .describe(+ 'Name of the generated metric as it appears in the Metrics product. Must start with a letter and contain only letters, digits, dots, underscores, and dashes. Unique per project and immutable after creation — create a new rule to emit under a different name.'+ ),+ enabled: zod+ .boolean()+ .default(logsMetricRulesUpdateBodyEnabledDefault)+ .describe(+ 'When true, ingestion evaluates this rule against every log record. At most 10 rules can be enabled per project.'+ ),+ filter_group: zod+ .unknown()+ .optional()+ .describe(+ 'PropertyGroupFilter JSON (AND\/OR tree of property predicates) selecting which log records feed the metric, e.g. `{\"type\":\"AND\",\"values\":[{\"type\":\"AND\",\"values\":[{\"key\":\"service.name\",\"operator\":\"exact\",\"value\":\"api\",\"type\":\"log_attribute\"}]}]}`. Null matches every ingested log record. Every group must contain at least one filter — empty groups never match.'+ ),+ value_attribute: zod+ .string()+ .max(logsMetricRulesUpdateBodyValueAttributeMax)+ .nullish()+ .describe(+ 'Log attribute key holding a numeric value to aggregate into a distribution (count + sum), e.g. `attributes.duration_ms` or `resource_attributes.batch.size`. Omit to count matching log records instead. Immutable after creation — it determines the emitted metric type.'+ ),+ group_by: zod+ .array(zod.string().max(logsMetricRulesUpdateBodyGroupByItemMax))+ .optional()+ .describe(+ 'Up to 5 dimension keys; each distinct value combination becomes its own metric series. Allowed: service_name, severity_text, event_name, or map keys prefixed with `attributes.` \/ `resource_attributes.`. Avoid high-cardinality keys (user IDs, request IDs) — excess series are dropped at ingestion.'+ ),+})++export const logsMetricRulesPartialUpdateBodyNameMax = 255++export const logsMetricRulesPartialUpdateBodyMetricNameMax = 200++export const logsMetricRulesPartialUpdateBodyEnabledDefault = false+export const logsMetricRulesPartialUpdateBodyValueAttributeMax = 512++export const logsMetricRulesPartialUpdateBodyGroupByItemMax = 512++export const LogsMetricRulesPartialUpdateBody = /* @__PURE__ */ zod.object({+ name: zod+ .string()+ .max(logsMetricRulesPartialUpdateBodyNameMax)+ .optional()+ .describe('User-visible label for this rule.'),+ metric_name: zod+ .string()+ .max(logsMetricRulesPartialUpdateBodyMetricNameMax)+ .optional()+ .describe(+ 'Name of the generated metric as it appears in the Metrics product. Must start with a letter and contain only letters, digits, dots, underscores, and dashes. Unique per project and immutable after creation — create a new rule to emit under a different name.'+ ),+ enabled: zod+ .boolean()+ .default(logsMetricRulesPartialUpdateBodyEnabledDefault)+ .describe(+ 'When true, ingestion evaluates this rule against every log record. At most 10 rules can be enabled per project.'+ ),+ filter_group: zod+ .unknown()+ .optional()+ .describe(+ 'PropertyGroupFilter JSON (AND\/OR tree of property predicates) selecting which log records feed the metric, e.g. `{\"type\":\"AND\",\"values\":[{\"type\":\"AND\",\"values\":[{\"key\":\"service.name\",\"operator\":\"exact\",\"value\":\"api\",\"type\":\"log_attribute\"}]}]}`. Null matches every ingested log record. Every group must contain at least one filter — empty groups never match.'+ ),+ value_attribute: zod+ .string()+ .max(logsMetricRulesPartialUpdateBodyValueAttributeMax)+ .nullish()+ .describe(+ 'Log attribute key holding a numeric value to aggregate into a distribution (count + sum), e.g. `attributes.duration_ms` or `resource_attributes.batch.size`. Omit to count matching log records instead. Immutable after creation — it determines the emitted metric type.'+ ),+ group_by: zod+ .array(zod.string().max(logsMetricRulesPartialUpdateBodyGroupByItemMax))+ .optional()+ .describe(+ 'Up to 5 dimension keys; each distinct value combination becomes its own metric series. Allowed: service_name, severity_text, event_name, or map keys prefixed with `attributes.` \/ `resource_attributes.`. Avoid high-cardinality keys (user IDs, request IDs) — excess series are dropped at ingestion.'+ ),+})+export const LogsPatternsCreateBody = /* @__PURE__ */ zod.object({query: zod.object({diff --git a/products/logs/frontend/logsFeatureFlagKeys.ts b/products/logs/frontend/logsFeatureFlagKeys.tsindex 7b459b4701f6..00d3f51c981f 100644--- a/products/logs/frontend/logsFeatureFlagKeys.ts+++ b/products/logs/frontend/logsFeatureFlagKeys.ts@@ -3,4 +3,5 @@ import type { FeatureFlagLookupKey } from 'lib/constants'/** `keyof FEATURE_FLAGS` for `useFeatureFlag` and settings `flag` — not remote slug strings. */export const LogsFeatureFlagKeys = {dropRules: 'LOGS_SETTINGS_DROP_RULES',-} as const satisfies { dropRules: FeatureFlagLookupKey }+ metricRules: 'LOGS_METRIC_RULES',+} as const satisfies { dropRules: FeatureFlagLookupKey; metricRules: FeatureFlagLookupKey }diff --git a/products/logs/mcp/tools.yaml b/products/logs/mcp/tools.yamlindex 8520d6a0d837..d992491cb50f 100644--- a/products/logs/mcp/tools.yaml+++ b/products/logs/mcp/tools.yaml@@ -374,6 +374,24 @@ tools:logs-has-logs-retrieve:operation: logs_has_logs_retrieveenabled: false+ logs-metric-rules-create:+ operation: logs_metric_rules_create+ enabled: false+ logs-metric-rules-destroy:+ operation: logs_metric_rules_destroy+ enabled: false+ logs-metric-rules-list:+ operation: logs_metric_rules_list+ enabled: false+ logs-metric-rules-partial-update:+ operation: logs_metric_rules_partial_update+ enabled: false+ logs-metric-rules-retrieve:+ operation: logs_metric_rules_retrieve+ enabled: false+ logs-metric-rules-update:+ operation: logs_metric_rules_update+ enabled: falselogs-patterns:operation: logs_patterns_createenabled: truediff --git a/pyproject.toml b/pyproject.tomlindex 9cd467ca72ec..45cde62fd5f7 100644--- a/pyproject.toml+++ b/pyproject.toml@@ -566,6 +566,7 @@ ignore_imports = ["products.logs.backend.presentation.views.alerts_api -> products.logs.backend.alert_destinations","products.logs.backend.presentation.views.alerts_api -> products.logs.backend.alert_state_machine","products.logs.backend.presentation.views.alerts_api -> products.logs.backend.models",+ "products.logs.backend.presentation.views.metric_rules_api -> products.logs.backend.models","products.logs.backend.presentation.views.sampling_api -> products.logs.backend.models","products.logs.backend.presentation.views.views_api -> products.logs.backend.models",# logs presentation isolation (temporary): cross-product imports the moved viewsetsdiff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.tsindex d04e759cbd2c..0e54d7229c32 100644--- a/services/mcp/src/api/generated.ts+++ b/services/mcp/src/api/generated.ts@@ -34488,6 +34488,42 @@ export namespace Schemas {config?: LogsListWidgetConfig;}+ export interface LogsMetricRule {+ /** Unique identifier for this metric rule. */+ readonly id: string;+ /**+ * User-visible label for this rule.+ * @maxLength 255+ */+ name: string;+ /**+ * Name of the generated metric as it appears in the Metrics product. Must start with a letter and contain only letters, digits, dots, underscores, and dashes. Unique per project and immutable after creation — create a new rule to emit under a different name.+ * @maxLength 200+ */+ metric_name: string;+ /** When true, ingestion evaluates this rule against every log record. At most 10 rules can be enabled per project. */+ enabled?: boolean;+ /** PropertyGroupFilter JSON (AND/OR tree of property predicates) selecting which log records feed the metric, e.g. `{"type":"AND","values":[{"type":"AND","values":[{"key":"service.name","operator":"exact","value":"api","type":"log_attribute"}]}]}`. Null matches every ingested log record. Every group must contain at least one filter — empty groups never match. */+ filter_group?: unknown;+ /**+ * Log attribute key holding a numeric value to aggregate into a distribution (count + sum), e.g. `attributes.duration_ms` or `resource_attributes.batch.size`. Omit to count matching log records instead. Immutable after creation — it determines the emitted metric type.+ * @maxLength 512+ * @nullable+ */+ value_attribute?: string | null;+ /**+ * Up to 5 dimension keys; each distinct value combination becomes its own metric series. Allowed: service_name, severity_text, event_name, or map keys prefixed with `attributes.` / `resource_attributes.`. Avoid high-cardinality keys (user IDs, request IDs) — excess series are dropped at ingestion.+ * @items.maxLength 512+ */+ group_by?: string[];+ /** Incremented on each update for worker cache coherency. */+ readonly version: number;+ readonly created_by: number;+ readonly created_at: string;+ /** @nullable */+ readonly updated_at: string | null;+ }+export type LogsSamplingRuleScopeAttributeFiltersItem = { [key: string]: unknown };/**@@ -37976,6 +38012,15 @@ export namespace Schemas {results: LogsAlertEvent[];}+ export interface PaginatedLogsMetricRuleList {+ count: number;+ /** @nullable */+ next?: string | null;+ /** @nullable */+ previous?: string | null;+ results: LogsMetricRule[];+ }+export interface PaginatedLogsSamplingRuleList {count: number;/** @nullable */@@ -45655,6 +45700,42 @@ export namespace Schemas {readonly updated_at?: string | null;}+ export interface PatchedLogsMetricRule {+ /** Unique identifier for this metric rule. */+ readonly id?: string;+ /**+ * User-visible label for this rule.+ * @maxLength 255+ */+ name?: string;+ /**+ * Name of the generated metric as it appears in the Metrics product. Must start with a letter and contain only letters, digits, dots, underscores, and dashes. Unique per project and immutable after creation — create a new rule to emit under a different name.+ * @maxLength 200+ */+ metric_name?: string;+ /** When true, ingestion evaluates this rule against every log record. At most 10 rules can be enabled per project. */+ enabled?: boolean;+ /** PropertyGroupFilter JSON (AND/OR tree of property predicates) selecting which log records feed the metric, e.g. `{"type":"AND","values":[{"type":"AND","values":[{"key":"service.name","operator":"exact","value":"api","type":"log_attribute"}]}]}`. Null matches every ingested log record. Every group must contain at least one filter — empty groups never match. */+ filter_group?: unknown;+ /**+ * Log attribute key holding a numeric value to aggregate into a distribution (count + sum), e.g. `attributes.duration_ms` or `resource_attributes.batch.size`. Omit to count matching log records instead. Immutable after creation — it determines the emitted metric type.+ * @maxLength 512+ * @nullable+ */+ value_attribute?: string | null;+ /**+ * Up to 5 dimension keys; each distinct value combination becomes its own metric series. Allowed: service_name, severity_text, event_name, or map keys prefixed with `attributes.` / `resource_attributes.`. Avoid high-cardinality keys (user IDs, request IDs) — excess series are dropped at ingestion.+ * @items.maxLength 512+ */+ group_by?: string[];+ /** Incremented on each update for worker cache coherency. */+ readonly version?: number;+ readonly created_by?: number;+ readonly created_at?: string;+ /** @nullable */+ readonly updated_at?: string | null;+ }+export type PatchedLogsSamplingRuleScopeAttributeFiltersItem = { [key: string]: unknown };export interface PatchedLogsSamplingRule {@@ -76580,6 +76661,17 @@ export namespace Schemas {export type LogsHasLogsRetrieve200 = { [key: string]: unknown };+ export type LogsMetricRulesListParams = {+ /**+ * Number of results to return per page.+ */+ limit?: number;+ /**+ * The initial index from which to return the results.+ */+ offset?: number;+ };+export type LogsSamplingRulesListParams = {/*** Number of results to return per page.