Skip to content

: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.

feat(logs): span-based metrics reusing the log metric-rules pipeline (#94331)

Daniel Visca35d6d3c76fd5
diff --git a/nodejs/src/logs/config.ts b/nodejs/src/logs/config.ts
index 86801bcd18e6..a5c779477af0 100644
--- a/nodejs/src/logs/config.ts
+++ b/nodejs/src/logs/config.ts
@@ -156,6 +156,9 @@ export type TracesIngestionConsumerConfig = {
TRACES_LIMITER_TTL_SECONDS: number
TRACES_LIMITER_TEAM_BUCKET_SIZE_KB: string
TRACES_LIMITER_TEAM_REFILL_RATE_KB_PER_SECOND: string
+ TRACES_METRICS_RULES_ENABLED_TEAMS: string
+ TRACES_METRICS_RULES_KILLSWITCH: boolean
+ TRACES_METRICS_RULES_EXPORT_URL: string
REDIS_URL: string
REDIS_POOL_MIN_SIZE: number
REDIS_POOL_MAX_SIZE: number
@@ -180,6 +183,11 @@ export function getDefaultTracesIngestionConsumerConfig(): TracesIngestionConsum
TRACES_LIMITER_TTL_SECONDS: 60 * 60 * 24,
TRACES_LIMITER_TEAM_BUCKET_SIZE_KB: '',
TRACES_LIMITER_TEAM_REFILL_RATE_KB_PER_SECOND: '',
+ // Mirror the logs default: enabled for all teams on the dev stack so a span rule
+ // works out of the box locally, off in prod until explicitly enabled per team.
+ TRACES_METRICS_RULES_ENABLED_TEAMS: isProdEnv() ? '' : '*',
+ TRACES_METRICS_RULES_KILLSWITCH: false,
+ TRACES_METRICS_RULES_EXPORT_URL: '',
// Overlapping fields with CommonConfig, included for standalone usage
// ok to connect to localhost over plaintext
// nosemgrep: trailofbits.generic.redis-unencrypted-transport.redis-unencrypted-transport
diff --git a/nodejs/src/logs/logs-ingestion-consumer.ts b/nodejs/src/logs/logs-ingestion-consumer.ts
index 2dc98670a271..1f82226bf47c 100644
--- a/nodejs/src/logs/logs-ingestion-consumer.ts
+++ b/nodejs/src/logs/logs-ingestion-consumer.ts
@@ -37,7 +37,7 @@ import {
bufferProcessingMode,
processLogMessageBuffer,
} from './log-record-avro'
-import type { CompiledMetricRule } from './metrics-rules/compile-metric-rules'
+import type { CompiledMetricRule, MetricRuleSource } from './metrics-rules/compile-metric-rules'
import { MetricRulesCache } from './metrics-rules/metric-rules-cache'
import { LogsMetricsEmitter } from './metrics-rules/metrics-emitter'
import { buildMetricRulesOtlpPayload } from './metrics-rules/otlp-payload'
@@ -347,6 +347,11 @@ export class LogsIngestionConsumer {
// Billing identity for quota enforcement and usage metering; overridden by subclasses (e.g. traces).
protected quotaResource: QuotaResource = 'logs_mb_ingested'
protected appSource = 'logs'
+ // Record source this consumer tallies metric rules for. `appSource` is the
+ // billing/telemetry identity ('logs' | 'traces'); metric rules are tagged with the
+ // record source ('logs' | 'spans') instead, so map between the two explicitly
+ // rather than comparing across vocabularies. TracesIngestionConsumer overrides to 'spans'.
+ protected metricRuleSource: MetricRuleSource = 'logs'
protected kafkaConsumer: KafkaConsumerInterface
private appMetricsAggregator: AppMetricsAggregator
private redis: RedisV2
@@ -812,7 +817,10 @@ export class LogsIngestionConsumer {
if (!state) {
let rules: CompiledMetricRule[]
try {
- rules = await this.deps.metricRulesCache!.getCompiledRules(message.teamId)
+ const all = await this.deps.metricRulesCache!.getCompiledRules(message.teamId)
+ // Each consumer tallies only its own record source: the logs consumer runs
+ // `logs` rules, the traces consumer runs `spans` rules.
+ rules = all.filter((r) => r.source === this.metricRuleSource)
} catch (error) {
// Fail open: metric rules are a purely additive side feature, so a rules-fetch
// failure (e.g. a Postgres blip) must never DLQ or block the log records —
diff --git a/nodejs/src/logs/metrics-rules/compile-metric-rules.ts b/nodejs/src/logs/metrics-rules/compile-metric-rules.ts
index ca3a07b07a4d..4ffffcc939bc 100644
--- a/nodejs/src/logs/metrics-rules/compile-metric-rules.ts
+++ b/nodejs/src/logs/metrics-rules/compile-metric-rules.ts
@@ -1,9 +1,19 @@
import { parseFilterGroup } from '../sampling/compile-rules'
import type { FilterGroupNode } from '../sampling/filter-group-match'
+import { SPAN_VALUE_DURATION_MS } from './tally'
/** Mirrors `MAX_METRIC_RULE_GROUP_BY_KEYS` in `products/logs/backend/models.py`. */
export const MAX_GROUP_BY_KEYS = 5
+/** Record source a rule tallies. Mirrors `LogsMetricRule.RecordSource` in models.py. */
+export type MetricRuleSource = 'logs' | 'spans'
+
+/** Top-level keys usable as span group-by dimensions (log-only keys like severity_text excluded). */
+export const SPAN_GROUP_BY_TOP_LEVEL_KEYS = new Set(['service_name', 'name', 'status_code', 'kind'])
+
+/** Top-level keys usable as log group-by dimensions (span-only keys like name/status_code excluded). */
+export const LOG_GROUP_BY_TOP_LEVEL_KEYS = new Set(['service_name', 'severity_text', 'event_name'])
+
/** Raw row shape from `logs_logsmetricrule` (see `MetricRulesCache.fetchRules`). */
export type MetricRuleRow = {
id: string
@@ -11,6 +21,8 @@ export type MetricRuleRow = {
filter_group: unknown
value_attribute: string | null
group_by: unknown
+ /** Record source; absent rows are log rules (pre-source schema default). */
+ source?: string
/** Row version from DB; used by cache watermark only, ignored by compileMetricRules. */
version?: number
}
@@ -18,6 +30,7 @@ export type MetricRuleRow = {
export type CompiledMetricRule = {
id: string
metricName: string
+ source: MetricRuleSource
/** null = every ingested log record matches. */
filterGroup: FilterGroupNode | null
/** Log attribute key holding the numeric value to aggregate; null = count records. */
@@ -31,6 +44,7 @@ export function compileMetricRules(rows: MetricRuleRow[]): CompiledMetricRule[]
if (typeof row.metric_name !== 'string' || row.metric_name === '') {
continue
}
+ const source: MetricRuleSource = row.source === 'spans' ? 'spans' : 'logs'
let filterGroup: FilterGroupNode | null = null
if (row.filter_group != null) {
filterGroup = parseFilterGroup(row.filter_group)
@@ -44,12 +58,47 @@ export function compileMetricRules(rows: MetricRuleRow[]): CompiledMetricRule[]
const groupBy = Array.isArray(row.group_by)
? row.group_by.filter((k): k is string => typeof k === 'string' && k !== '').slice(0, MAX_GROUP_BY_KEYS)
: []
+ const valueAttribute =
+ typeof row.value_attribute === 'string' && row.value_attribute !== '' ? row.value_attribute : null
+ if (source === 'spans') {
+ // Fail closed: a span rule carrying a log-only top-level key would silently emit
+ // empty-label series, so drop the rule instead of tallying garbage.
+ const hasLogOnlyKey = groupBy.some(
+ (k) =>
+ !SPAN_GROUP_BY_TOP_LEVEL_KEYS.has(k) &&
+ !k.startsWith('attributes.') &&
+ !k.startsWith('resource_attributes.')
+ )
+ if (hasLogOnlyKey) {
+ continue
+ }
+ } else {
+ // Mirror for log rules: span-only top-level keys (`name`, `status_code`) have no
+ // log column, so a log rule grouping by them would collapse every record onto an
+ // empty-label series. Attribute-map keys stay valid for either source.
+ const hasSpanOnlyKey = groupBy.some(
+ (k) =>
+ !LOG_GROUP_BY_TOP_LEVEL_KEYS.has(k) &&
+ !k.startsWith('attributes.') &&
+ !k.startsWith('resource_attributes.')
+ )
+ if (hasSpanOnlyKey) {
+ continue
+ }
+ // `duration_ms` is a span pseudo-key (end_time - timestamp); a log record has no
+ // end_time, so the serializer rejects it — but anything written without the
+ // serializer (data migration, fixture) would otherwise take the span branch in
+ // tally. Skip it here too, matching the group-by handling.
+ if (valueAttribute === SPAN_VALUE_DURATION_MS) {
+ continue
+ }
+ }
out.push({
id: row.id,
metricName: row.metric_name,
+ source,
filterGroup,
- valueAttribute:
- typeof row.value_attribute === 'string' && row.value_attribute !== '' ? row.value_attribute : null,
+ valueAttribute,
groupBy,
})
}
diff --git a/nodejs/src/logs/metrics-rules/metric-rules-cache.ts b/nodejs/src/logs/metrics-rules/metric-rules-cache.ts
index 242fbdddbd3e..c533e4c25bf2 100644
--- a/nodejs/src/logs/metrics-rules/metric-rules-cache.ts
+++ b/nodejs/src/logs/metrics-rules/metric-rules-cache.ts
@@ -34,9 +34,10 @@ export class MetricRulesCache {
filter_group: unknown
value_attribute: string | null
group_by: unknown
+ source: string
}>(
PostgresUse.COMMON_READ,
- `SELECT id::text AS id, metric_name, filter_group, value_attribute, group_by
+ `SELECT id::text AS id, metric_name, filter_group, value_attribute, group_by, source
FROM logs_logsmetricrule
WHERE team_id = $1 AND enabled = true
ORDER BY created_at ASC`,
diff --git a/nodejs/src/logs/metrics-rules/span-metrics.test.ts b/nodejs/src/logs/metrics-rules/span-metrics.test.ts
new file mode 100644
index 000000000000..b4ea18b8d961
--- /dev/null
+++ b/nodejs/src/logs/metrics-rules/span-metrics.test.ts
@@ -0,0 +1,178 @@
+import type { LogRecord } from '../log-record-avro'
+import { type MetricRuleRow, compileMetricRules } from './compile-metric-rules'
+import { SPAN_VALUE_DURATION_MS, createBatchTallies, tallyRecords } from './tally'
+
+const NOW_MS = 1_700_000_000_000
+
+/** Span-shaped record: the traces consumer decodes KafkaTraceRow through the same
+ * Avro path, so a span arrives as a LogRecord carrying `name`, `kind`, `status_code`
+ * and an `end_time` after `timestamp` (both Avro timestamp-micros). */
+const spanRecord = (overrides: Record<string, unknown> = {}): LogRecord =>
+ ({
+ uuid: null,
+ trace_id: null,
+ span_id: null,
+ trace_flags: null,
+ timestamp: NOW_MS * 1000, // start, avro micros
+ end_time: NOW_MS * 1000 + 250_000, // start + 250ms
+ observed_timestamp: null,
+ body: null,
+ severity_text: null,
+ severity_number: null,
+ service_name: 'api',
+ resource_attributes: { 'k8s.pod': 'pod-1' },
+ instrumentation_scope: null,
+ event_name: null,
+ attributes: { 'http.status_code': '200', 'http.route': '/checkout' },
+ name: 'GET /checkout',
+ kind: 2, // SERVER
+ status_code: 2, // ERROR
+ status_message: 'boom',
+ ...overrides,
+ }) as unknown as LogRecord
+
+const errorSpansFilter = {
+ type: 'AND',
+ values: [
+ {
+ type: 'AND',
+ values: [{ key: 'status_code', operator: 'exact', value: '2', type: 'span_attribute' }],
+ },
+ ],
+}
+
+const spanRuleRow = (overrides: Partial<MetricRuleRow> = {}): MetricRuleRow => ({
+ id: 'span-rule-1',
+ metric_name: 'span.errors',
+ source: 'spans',
+ filter_group: errorSpansFilter,
+ value_attribute: null,
+ group_by: [],
+ version: 1,
+ ...overrides,
+})
+
+describe('span-based metric rules', () => {
+ describe('compileMetricRules', () => {
+ it('keeps a span rule and tags it with source spans', () => {
+ const rules = compileMetricRules([spanRuleRow()])
+ expect(rules).toHaveLength(1)
+ expect(rules[0]!.source).toBe('spans')
+ })
+
+ it('defaults a rule without a source to logs', () => {
+ const rules = compileMetricRules([spanRuleRow({ source: undefined })])
+ expect(rules[0]!.source).toBe('logs')
+ })
+
+ it('rejects a span rule with an unknown top-level group-by key', () => {
+ // severity_text is a log-only top-level key; spans do not carry it.
+ const rules = compileMetricRules([spanRuleRow({ group_by: ['severity_text'] })])
+ expect(rules).toHaveLength(0)
+ })
+
+ it('accepts span top-level group-by keys', () => {
+ const rules = compileMetricRules([spanRuleRow({ group_by: ['name', 'status_code', 'service_name'] })])
+ expect(rules).toHaveLength(1)
+ expect(rules[0]!.groupBy).toEqual(['name', 'status_code', 'service_name'])
+ })
+
+ it.each([['name'], ['status_code']])('rejects a log rule grouping by span-only key %s', (key) => {
+ const rules = compileMetricRules([spanRuleRow({ source: 'logs', group_by: [key] })])
+ expect(rules).toHaveLength(0)
+ })
+
+ it('rejects a log rule aggregating the duration_ms span pseudo-key', () => {
+ const rules = compileMetricRules([spanRuleRow({ source: 'logs', value_attribute: SPAN_VALUE_DURATION_MS })])
+ expect(rules).toHaveLength(0)
+ })
+
+ it('partitions a mixed rule set by record source', () => {
+ const rules = compileMetricRules([spanRuleRow(), spanRuleRow({ id: 'log-rule-1', source: 'logs' })])
+ expect(rules.filter((r) => r.source === 'spans').map((r) => r.id)).toEqual(['span-rule-1'])
+ expect(rules.filter((r) => r.source === 'logs').map((r) => r.id)).toEqual(['log-rule-1'])
+ })
+ })
+
+ describe('tallyRecords for spans', () => {
+ it('counts matching spans via a span filter group', () => {
+ const rules = compileMetricRules([spanRuleRow()])
+ const tallies = createBatchTallies()
+ tallyRecords(rules, [spanRecord(), spanRecord({ status_code: 1 })], tallies, NOW_MS)
+ const entries = [...tallies.byRule.get('span-rule-1')!.values()]
+ expect(entries).toHaveLength(1)
+ expect(entries[0]!.count).toBe(1) // only the ERROR span matched
+ })
+
+ it('aggregates span duration via the duration_ms pseudo-key', () => {
+ const rules = compileMetricRules([spanRuleRow({ value_attribute: SPAN_VALUE_DURATION_MS })])
+ const tallies = createBatchTallies()
+ tallyRecords(rules, [spanRecord()], tallies, NOW_MS)
+ const entries = [...tallies.byRule.get('span-rule-1')!.values()]
+ expect(entries[0]!.sum).toBe(250) // end_time - timestamp = 250ms
+ })
+
+ it('resolves span top-level group-by keys from the record', () => {
+ const rules = compileMetricRules([spanRuleRow({ group_by: ['name', 'status_code'] })])
+ const tallies = createBatchTallies()
+ tallyRecords(rules, [spanRecord()], tallies, NOW_MS)
+ const entries = [...tallies.byRule.get('span-rule-1')!.values()]
+ expect(entries[0]!.labelValues).toEqual(['GET /checkout', 'ERROR'])
+ })
+
+ it('labels status_code with the OTel enum name, falling back to the raw value for unknown codes', () => {
+ const rules = compileMetricRules([spanRuleRow({ filter_group: null, group_by: ['status_code'] })])
+ const tallies = createBatchTallies()
+ tallyRecords(
+ rules,
+ [spanRecord({ status_code: 0 }), spanRecord({ status_code: 1 }), spanRecord({ status_code: 99 })],
+ tallies,
+ NOW_MS
+ )
+ const labels = [...tallies.byRule.get('span-rule-1')!.values()].map((e) => e.labelValues[0])
+ expect(labels).toEqual(['UNSET', 'OK', '99'])
+ })
+
+ it('accepts kind as a span group-by key and labels it with the OTel kind name', () => {
+ const rules = compileMetricRules([spanRuleRow({ filter_group: null, group_by: ['kind'] })])
+ expect(rules).toHaveLength(1)
+ const tallies = createBatchTallies()
+ tallyRecords(rules, [spanRecord({ kind: 2 }), spanRecord({ kind: 3 })], tallies, NOW_MS)
+ const labels = [...tallies.byRule.get('span-rule-1')!.values()].map((e) => e.labelValues[0])
+ expect(labels).toEqual(['SERVER', 'CLIENT'])
+ })
+
+ it('measures staleness from end_time, so a long-running span that just ended still tallies', () => {
+ // A 25-minute batch-job span: start is older than MAX_RECORD_AGE_MS but the span
+ // ended just now. Gating on start time would drop it and truncate the latency
+ // tail a duration_ms rule exists to show.
+ const rules = compileMetricRules([spanRuleRow({ value_attribute: SPAN_VALUE_DURATION_MS })])
+ const tallies = createBatchTallies()
+ tallyRecords(
+ rules,
+ [spanRecord({ timestamp: (NOW_MS - 25 * 60 * 1000) * 1000, end_time: NOW_MS * 1000 })],
+ tallies,
+ NOW_MS
+ )
+ const entries = [...tallies.byRule.get('span-rule-1')!.values()]
+ expect(entries).toHaveLength(1)
+ })
+
+ it('still drops a replayed span whose end_time is older than the staleness window', () => {
+ const rules = compileMetricRules([spanRuleRow()])
+ const tallies = createBatchTallies()
+ tallyRecords(
+ rules,
+ [
+ spanRecord({
+ timestamp: (NOW_MS - 60 * 60 * 1000) * 1000,
+ end_time: (NOW_MS - 30 * 60 * 1000) * 1000,
+ }),
+ ],
+ tallies,
+ NOW_MS
+ )
+ expect(tallies.byRule.get('span-rule-1')).toBeUndefined()
+ })
+ })
+})
diff --git a/nodejs/src/logs/metrics-rules/tally.ts b/nodejs/src/logs/metrics-rules/tally.ts
index c4a8c505e779..6e0fa34db1ca 100644
--- a/nodejs/src/logs/metrics-rules/tally.ts
+++ b/nodejs/src/logs/metrics-rules/tally.ts
@@ -15,6 +15,20 @@ export const MAX_LABEL_VALUE_LENGTH = 256
*/
export const MAX_RECORD_AGE_MS = 20 * 60 * 1000
+/** OTel span status codes (`StatusCode` in the span Avro schema). Anything outside
+ * this map falls back to the raw numeric string so an unknown future code still
+ * emits a distinguishable label. */
+export const SPAN_STATUS_CODE_LABELS: Record<number, string> = { 0: 'UNSET', 1: 'OK', 2: 'ERROR' }
+
+/** OTel span kinds (`SpanKind` in the span Avro schema), 1-based per the spec. */
+export const SPAN_KIND_LABELS: Record<number, string> = {
+ 1: 'INTERNAL',
+ 2: 'SERVER',
+ 3: 'CLIENT',
+ 4: 'PRODUCER',
+ 5: 'CONSUMER',
+}
+
export type MetricTallyEntry = {
/** Group-by values in the rule's `groupBy` key order. */
labelValues: string[]
@@ -41,6 +55,14 @@ export function createBatchTallies(): BatchTallies {
const ATTRIBUTES_PREFIX = 'attributes.'
const RESOURCE_ATTRIBUTES_PREFIX = 'resource_attributes.'
+/**
+ * Pseudo value-attribute key resolving to the span's wall-clock duration in
+ * milliseconds, computed from `end_time - timestamp`. Lets a span rule emit a
+ * latency distribution without any SDK attribute convention. Meaningful only
+ * for `source === 'spans'` rules.
+ */
+export const SPAN_VALUE_DURATION_MS = 'duration_ms'
+
function lookupKey(key: string, record: LogRecord): string | null | undefined {
if (key === 'service_name') {
return record.service_name
@@ -51,6 +73,23 @@ function lookupKey(key: string, record: LogRecord): string | null | undefined {
if (key === 'event_name') {
return record.event_name
}
+ // Span top-level keys. A span arrives as a LogRecord through the shared Avro
+ // decode path, carrying these extra fields (absent on log records).
+ if (key === 'name') {
+ return (record as { name?: string | null }).name
+ }
+ if (key === 'status_code') {
+ // Emit the OTel enum name as the series label (`ERROR`, not `2`) so dashboards
+ // and alerts read without knowing the wire encoding. Filter matching keeps the
+ // numeric form — see filter-group-match.ts, where users write `value: '2'`.
+ const code = (record as { status_code?: number | null }).status_code
+ return code == null ? undefined : (SPAN_STATUS_CODE_LABELS[code] ?? String(code))
+ }
+ if (key === 'kind') {
+ // Same enum-label treatment as status_code: `SERVER`, not `2`.
+ const kind = (record as { kind?: number | null }).kind
+ return kind == null ? undefined : (SPAN_KIND_LABELS[kind] ?? String(kind))
+ }
if (key.startsWith(ATTRIBUTES_PREFIX)) {
return decodedAttr(record.attributes, key.slice(ATTRIBUTES_PREFIX.length))
}
@@ -76,6 +115,15 @@ function resolveLabelValue(key: string, record: LogRecord): string {
}
function resolveNumericValue(key: string, record: LogRecord): number | null {
+ // Span wall-clock duration from Avro timestamp-micros, no attribute lookup.
+ if (key === SPAN_VALUE_DURATION_MS) {
+ const r = record as { timestamp?: number | null; end_time?: number | null }
+ if (r.timestamp == null || r.end_time == null) {
+ return null
+ }
+ const durationMs = (r.end_time - r.timestamp) / 1000
+ return Number.isFinite(durationMs) && durationMs >= 0 ? durationMs : null
+ }
const raw = lookupKey(key, record)
if (raw == null || raw === '') {
return null
@@ -124,9 +172,15 @@ export function tallyRecords(
return
}
for (const record of records) {
- // timestamp is Avro timestamp-micros; null means "no producer timestamp", which
+ // For a span, `timestamp` is the START time and the record is not exported until
+ // the span ends — so gating on `timestamp` would measure span duration + export
+ // lag, not staleness, and silently drop long-running spans (truncating exactly
+ // the latency tail a duration_ms rule exists to show). Gate on `end_time` when
+ // present, falling back to `timestamp` for logs and spans without an end.
+ // Both are Avro timestamp-micros; null means "no producer timestamp", which
// ingestion treats as now — so it passes the staleness gate.
- if (record.timestamp != null && nowMs - record.timestamp / 1000 > MAX_RECORD_AGE_MS) {
+ const observedAtMicros = (record as { end_time?: number | null }).end_time ?? record.timestamp
+ if (observedAtMicros != null && nowMs - observedAtMicros / 1000 > MAX_RECORD_AGE_MS) {
continue
}
for (const rule of rules) {
diff --git a/nodejs/src/logs/sampling/filter-group-match.test.ts b/nodejs/src/logs/sampling/filter-group-match.test.ts
index 7a86e425215f..7edf719af552 100644
--- a/nodejs/src/logs/sampling/filter-group-match.test.ts
+++ b/nodejs/src/logs/sampling/filter-group-match.test.ts
@@ -182,6 +182,82 @@ describe('matchFilterGroup', () => {
const g = group({ values: [{ key: 'http.route', operator: 'exact', value: '/healthz' }] })
expect(matchFilterGroup(g, baseRecord())).toBe(false)
})
+
+ // Regression for the span top-level branches in lookupRecordValue: they must be
+ // gated on `span_attribute` so an existing `log_attribute` rule keyed `status_code`
+ // / `name` keeps resolving through the attribute map instead of reading the absent
+ // span column and silently stopping.
+ it('log_attribute status_code reads the attribute map, not the absent span column', () => {
+ const g = group({
+ values: [{ key: 'status_code', type: 'log_attribute', operator: 'exact', value: '500' }],
+ })
+ expect(matchFilterGroup(g, baseRecord({ attributes: { status_code: '500' } }))).toBe(true)
+ expect(matchFilterGroup(g, baseRecord({ attributes: { status_code: '200' } }))).toBe(false)
+ })
+ it('log_attribute name reads the attribute map, not the absent span column', () => {
+ const g = group({ values: [{ key: 'name', type: 'log_attribute', operator: 'exact', value: 'api' }] })
+ expect(matchFilterGroup(g, baseRecord({ attributes: { name: 'api' } }))).toBe(true)
+ expect(matchFilterGroup(g, baseRecord({ attributes: { name: 'other' } }))).toBe(false)
+ })
+ it('span_attribute status_code reads the span column', () => {
+ const g = group({ values: [{ key: 'status_code', type: 'span_attribute', operator: 'exact', value: '2' }] })
+ const span = baseRecord({ attributes: { status_code: '9' } }) as LogRecord & { status_code: number }
+ span.status_code = 2
+ expect(matchFilterGroup(g, span)).toBe(true)
+ const okSpan = baseRecord({}) as LogRecord & { status_code: number }
+ okSpan.status_code = 1
+ expect(matchFilterGroup(g, okSpan)).toBe(false)
+ })
+ it('span_attribute status_code falls back to the attribute map when the column is unset', () => {
+ const g = group({ values: [{ key: 'status_code', type: 'span_attribute', operator: 'exact', value: '2' }] })
+ // Span record whose status_code column is unset but the attribute is present.
+ expect(matchFilterGroup(g, baseRecord({ attributes: { status_code: '2' } }))).toBe(true)
+ })
+ it('span_attribute name reads the span column', () => {
+ const g = group({ values: [{ key: 'name', type: 'span_attribute', operator: 'exact', value: 'GET /x' }] })
+ const span = baseRecord({}) as LogRecord & { name: string }
+ span.name = 'GET /x'
+ expect(matchFilterGroup(g, span)).toBe(true)
+ const other = baseRecord({}) as LogRecord & { name: string }
+ other.name = 'POST /y'
+ expect(matchFilterGroup(g, other)).toBe(false)
+ })
+ it('span_attribute name falls back to the attribute map when the column is unset', () => {
+ const g = group({ values: [{ key: 'name', type: 'span_attribute', operator: 'exact', value: 'GET /x' }] })
+ expect(matchFilterGroup(g, baseRecord({ attributes: { name: 'GET /x' } }))).toBe(true)
+ })
+ it('span_attribute kind reads the span column', () => {
+ const g = group({ values: [{ key: 'kind', type: 'span_attribute', operator: 'exact', value: '2' }] })
+ const span = baseRecord({}) as LogRecord & { kind: number }
+ span.kind = 2
+ expect(matchFilterGroup(g, span)).toBe(true)
+ const other = baseRecord({}) as LogRecord & { kind: number }
+ other.kind = 3
+ expect(matchFilterGroup(g, other)).toBe(false)
+ })
+ it('span_attribute kind falls back to the attribute map when the column is unset', () => {
+ const g = group({ values: [{ key: 'kind', type: 'span_attribute', operator: 'exact', value: '2' }] })
+ expect(matchFilterGroup(g, baseRecord({ attributes: { kind: '2' } }))).toBe(true)
+ })
+ it('span_resource_attribute reads the resource map only, not a same-named span attribute', () => {
+ // Regression: without a dedicated branch this leaf fell through to the untyped
+ // fallback, which reads span attributes first — so a span attribute named like
+ // the resource attribute shadowed it.
+ const g = group({
+ values: [
+ {
+ key: 'deployment.environment',
+ type: 'span_resource_attribute',
+ operator: 'exact',
+ value: 'staging',
+ },
+ ],
+ })
+ expect(
+ matchFilterGroup(g, baseRecord({ resource_attributes: { 'deployment.environment': 'staging' } }))
+ ).toBe(true)
+ expect(matchFilterGroup(g, baseRecord({ attributes: { 'deployment.environment': 'staging' } }))).toBe(false)
+ })
})
describe('wire-encoded attribute values', () => {
diff --git a/nodejs/src/logs/sampling/filter-group-match.ts b/nodejs/src/logs/sampling/filter-group-match.ts
index f3e6ea8b729b..596554ed008b 100644
--- a/nodejs/src/logs/sampling/filter-group-match.ts
+++ b/nodejs/src/logs/sampling/filter-group-match.ts
@@ -23,6 +23,8 @@ export type FilterGroupNode = {
const PROPERTY_FILTER_TYPE_LOG = 'log'
const PROPERTY_FILTER_TYPE_LOG_ATTRIBUTE = 'log_attribute'
const PROPERTY_FILTER_TYPE_LOG_RESOURCE_ATTRIBUTE = 'log_resource_attribute'
+const PROPERTY_FILTER_TYPE_SPAN_ATTRIBUTE = 'span_attribute'
+const PROPERTY_FILTER_TYPE_SPAN_RESOURCE_ATTRIBUTE = 'span_resource_attribute'
/**
* Hard ceiling on filter-group nesting depth. The drop-rules UI surfaces at
@@ -102,10 +104,38 @@ function lookupRecordValue(filter: PropertyFilterLeaf, record: LogRecord): strin
return record.body ?? undefined
}
- if (filter.type === PROPERTY_FILTER_TYPE_LOG_RESOURCE_ATTRIBUTE) {
+ // Span top-level keys (traces consumer decodes spans through the same Avro path, so
+ // these arrive on the record). Restricted to `span_attribute`-typed filters: a
+ // `log_attribute` filter named `status_code` / `name` must keep resolving through the
+ // attribute map, or an existing log drop/sampling rule would read the absent span
+ // column and silently stop matching. Falls back to the attribute map for spans whose
+ // column is unset, mirroring the service_name / severity_text handling above.
+ if (filter.type === PROPERTY_FILTER_TYPE_SPAN_ATTRIBUTE) {
+ if (key === 'status_code') {
+ const code = (record as { status_code?: number | null }).status_code
+ return code == null ? decodedAttr(record.attributes, key) : String(code)
+ }
+ if (key === 'name') {
+ return (record as { name?: string | null }).name ?? decodedAttr(record.attributes, key)
+ }
+ if (key === 'kind') {
+ const kind = (record as { kind?: number | null }).kind
+ return kind == null ? decodedAttr(record.attributes, key) : String(kind)
+ }
+ }
+
+ if (
+ filter.type === PROPERTY_FILTER_TYPE_LOG_RESOURCE_ATTRIBUTE ||
+ filter.type === PROPERTY_FILTER_TYPE_SPAN_RESOURCE_ATTRIBUTE
+ ) {
+ // Span resource attributes live on the same resource_attributes map (a span
+ // arrives as a LogRecord through the shared Avro decode path). Without this
+ // branch a span_resource_attribute leaf fell through to the untyped fallback,
+ // which reads span *attributes* first — so a same-named span attribute would
+ // shadow the resource attribute the filter asked for.
return decodedAttr(record.resource_attributes, key)
}
- if (filter.type === PROPERTY_FILTER_TYPE_LOG_ATTRIBUTE) {
+ if (filter.type === PROPERTY_FILTER_TYPE_LOG_ATTRIBUTE || filter.type === PROPERTY_FILTER_TYPE_SPAN_ATTRIBUTE) {
return decodedAttr(record.attributes, key)
}
return decodedAttr(record.attributes, key) ?? decodedAttr(record.resource_attributes, key)
diff --git a/nodejs/src/logs/traces-ingestion-consumer.ts b/nodejs/src/logs/traces-ingestion-consumer.ts
index 342995cb1973..7902e5ecae6a 100644
--- a/nodejs/src/logs/traces-ingestion-consumer.ts
+++ b/nodejs/src/logs/traces-ingestion-consumer.ts
@@ -1,11 +1,14 @@
import { LogsIngestionConsumerConfig, TracesIngestionConsumerConfig } from './config'
import { LogsIngestionConsumer, LogsIngestionConsumerDeps } from './logs-ingestion-consumer'
+import type { MetricRuleSource } from './metrics-rules/compile-metric-rules'
export class TracesIngestionConsumer extends LogsIngestionConsumer {
protected override name = 'TracesIngestionConsumer'
// Meter and quota-limit traces against their own billing identity, not logs'.
protected override quotaResource = 'traces_mb_ingested' as const
protected override appSource = 'traces'
+ // Traces records are spans, so this consumer tallies the `spans` metric rules.
+ protected override metricRuleSource: MetricRuleSource = 'spans'
constructor(config: LogsIngestionConsumerConfig & TracesIngestionConsumerConfig, deps: LogsIngestionConsumerDeps) {
// Topics are wired into `deps.outputs` by the server, so the only consumer-level
@@ -27,6 +30,11 @@ export class TracesIngestionConsumer extends LogsIngestionConsumer {
LOGS_LIMITER_TTL_SECONDS: config.TRACES_LIMITER_TTL_SECONDS,
LOGS_LIMITER_TEAM_BUCKET_SIZE_KB: config.TRACES_LIMITER_TEAM_BUCKET_SIZE_KB,
LOGS_LIMITER_TEAM_REFILL_RATE_KB_PER_SECOND: config.TRACES_LIMITER_TEAM_REFILL_RATE_KB_PER_SECOND,
+ // Span metric rules gate on traces-specific env config so they roll out
+ // independently of log metric rules.
+ LOGS_METRICS_RULES_ENABLED_TEAMS: config.TRACES_METRICS_RULES_ENABLED_TEAMS,
+ LOGS_METRICS_RULES_KILLSWITCH: config.TRACES_METRICS_RULES_KILLSWITCH,
+ LOGS_METRICS_RULES_EXPORT_URL: config.TRACES_METRICS_RULES_EXPORT_URL,
},
// Own Redis key namespace so traces token buckets don't share per-team state with logs.
'traces-rate-limiter'
diff --git a/nodejs/src/servers/ingestion-traces-server.ts b/nodejs/src/servers/ingestion-traces-server.ts
index d66bdfeb5f10..8852808f037a 100644
--- a/nodejs/src/servers/ingestion-traces-server.ts
+++ b/nodejs/src/servers/ingestion-traces-server.ts
@@ -14,6 +14,8 @@ import {
TracesIngestionConsumerConfig,
getDefaultLogsIngestionOutputsConfig,
} from '~/logs/config'
+import { MetricRulesCache } from '~/logs/metrics-rules/metric-rules-cache'
+import { LogsMetricsEmitter } from '~/logs/metrics-rules/metrics-emitter'
import { createProducerRegistry } from '~/logs/outputs/producer-registry'
import {
KafkaWarpstreamIngestionProducerEnvConfig,
@@ -106,6 +108,15 @@ export class IngestionTracesServer implements NodeServer {
const teamManager = new TeamManager(this.postgres)
const quotaLimiting = new QuotaLimiting(this.posthogRedisPool, teamManager)
+ // Span-based metric rules share the log rules table + OTLP emitter; the traces
+ // consumer filters to `source=spans`. Inert without a traces export URL.
+ const metricRulesCache = this.config.TRACES_METRICS_RULES_EXPORT_URL
+ ? new MetricRulesCache(this.postgres)
+ : undefined
+ const metricsEmitter = this.config.TRACES_METRICS_RULES_EXPORT_URL
+ ? new LogsMetricsEmitter(this.config.TRACES_METRICS_RULES_EXPORT_URL)
+ : undefined
+
// 2. Resolve outputs (topic + producer per logical name, env-controlled)
const outputs = createTracesOutputsRegistry().build(this.producerRegistry, this.config)
@@ -122,6 +133,8 @@ export class IngestionTracesServer implements NodeServer {
quotaLimiting,
outputs,
usageBatch,
+ metricRulesCache,
+ metricsEmitter,
})
await consumer.start()
return consumer.service
diff --git a/products/logs/backend/models.py b/products/logs/backend/models.py
index ce40d5a200c0..73c5887a65e2 100644
--- a/products/logs/backend/models.py
+++ b/products/logs/backend/models.py
@@ -412,9 +412,9 @@ MAX_METRIC_RULE_GROUP_BY_KEYS = 5
METRIC_RULE_GROUP_BY_TOP_LEVEL_KEYS = ("service_name", "severity_text", "event_name")
# Top-level span fields allowed as group-by dimensions for `source=spans` rules. Spans
-# carry no severity/event columns, so the log-only keys are excluded; `name` and
-# `status_code` are span columns.
-METRIC_RULE_GROUP_BY_SPAN_TOP_LEVEL_KEYS = ("service_name", "name", "status_code")
+# carry no severity/event columns, so the log-only keys are excluded; `name`,
+# `status_code` and `kind` are span columns.
+METRIC_RULE_GROUP_BY_SPAN_TOP_LEVEL_KEYS = ("service_name", "name", "status_code", "kind")
class LogsMetricRule(ModelActivityMixin, TeamScopedRootMixin, CreatedMetaFields, UpdatedMetaFields, UUIDModel):
diff --git a/products/logs/backend/presentation/views/metric_rules_api.py b/products/logs/backend/presentation/views/metric_rules_api.py
index 493294ec3c32..dd6c763f031a 100644
--- a/products/logs/backend/presentation/views/metric_rules_api.py
+++ b/products/logs/backend/presentation/views/metric_rules_api.py
@@ -27,6 +27,7 @@ from products.access_control.backend.facade.user_access_control import UserAcces
from products.logs.backend.models import (
MAX_ENABLED_METRIC_RULES,
MAX_METRIC_RULE_GROUP_BY_KEYS,
+ METRIC_RULE_GROUP_BY_SPAN_TOP_LEVEL_KEYS,
METRIC_RULE_GROUP_BY_TOP_LEVEL_KEYS,
LogsMetricRule,
)
@@ -116,9 +117,11 @@ class LogsMetricRuleSerializer(serializers.ModelSerializer):
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."
+ "Attribute key holding a numeric value to aggregate into a distribution (count + sum), e.g. "
+ "`attributes.duration_ms` or `resource_attributes.batch.size`, prefixed with `attributes.` / "
+ "`resource_attributes.`. For `source=spans` rules, the span pseudo-key `duration_ms` (span wall-clock "
+ "duration) is also allowed. Omit to count matching records instead. Immutable after creation — it "
+ "determines the emitted metric type."
),
)
group_by = serializers.ListField(
@@ -127,9 +130,22 @@ class LogsMetricRuleSerializer(serializers.ModelSerializer):
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."
+ f"metric series. For `source=logs` rules allowed: {', '.join(METRIC_RULE_GROUP_BY_TOP_LEVEL_KEYS)}; "
+ f"for `source=spans` rules allowed: {', '.join(METRIC_RULE_GROUP_BY_SPAN_TOP_LEVEL_KEYS)}; for either, "
+ "map keys prefixed with `attributes.` / `resource_attributes.`. Avoid high-cardinality keys (user IDs, "
+ "request IDs) — excess series are dropped at ingestion. For `source=spans` rules, note that `name` is "
+ "high-cardinality on poorly instrumented services (route params or SQL fragments in the span name), so "
+ "grouping by `name` can overflow the per-rule series cap on its own."
+ ),
+ )
+ # `source` collides with DRF's Field.source typing (the attribute lookup), hence the ignore.
+ source: serializers.ChoiceField = serializers.ChoiceField( # type: ignore[assignment]
+ choices=LogsMetricRule.RecordSource.choices,
+ default=LogsMetricRule.RecordSource.LOGS,
+ help_text=(
+ "Record source the rule tallies: `logs` (default) evaluates in the logs consumer, `spans` in the "
+ "traces consumer. Immutable after creation — it decides which keys are valid and which pipeline "
+ "runs the rule."
),
)
version = serializers.IntegerField(
@@ -147,6 +163,7 @@ class LogsMetricRuleSerializer(serializers.ModelSerializer):
"filter_group",
"value_attribute",
"group_by",
+ "source",
"version",
"created_by",
"created_at",
@@ -164,20 +181,29 @@ class LogsMetricRuleSerializer(serializers.ModelSerializer):
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.")
+ allowed = (
+ METRIC_RULE_GROUP_BY_SPAN_TOP_LEVEL_KEYS
+ if self._effective_source() == LogsMetricRule.RecordSource.SPANS
+ else METRIC_RULE_GROUP_BY_TOP_LEVEL_KEYS
+ )
for key in value:
- if key in METRIC_RULE_GROUP_BY_TOP_LEVEL_KEYS:
+ if key in allowed:
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.`."
+ f"Invalid group-by key {key!r}. Use one of {', '.join(allowed)}, 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
+ # `duration_ms` is a span pseudo-key (end_time - timestamp) resolved by the worker,
+ # valid only for `source=spans`; that source check runs in validate().
+ if value == "duration_ms":
+ 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
@@ -208,17 +234,45 @@ class LogsMetricRuleSerializer(serializers.ModelSerializer):
)
return value
+ def _effective_source(self) -> str:
+ # On update the immutable source comes from the existing row (defaults in attrs
+ # would mis-report it); on create it comes from the submitted value.
+ if self.instance is not None:
+ return self.instance.source
+ source = self.initial_data.get("source")
+ return source if source is not None else LogsMetricRule.RecordSource.LOGS
+
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)
+ # `source` is immutable and defaults to LOGS, so a PUT that omits it would
+ # otherwise write the default over an existing spans rule. Pin it to the
+ # instance so updates can never change the record source.
+ attrs["source"] = self.instance.source
+ self._validate_source_specific_keys(attrs)
return attrs
+ def _validate_source_specific_keys(self, attrs: dict[str, Any]) -> None:
+ source = self._effective_source()
+ is_spans = source == LogsMetricRule.RecordSource.SPANS
+ value_attribute = attrs.get("value_attribute")
+ if value_attribute == "duration_ms" and not is_spans:
+ raise ValidationError(
+ {"value_attribute": "duration_ms is a span pseudo-key and only valid for `source=spans` rules."}
+ )
+ if not is_spans:
+ return
+ group_by = attrs.get("group_by") or []
+ for key in group_by:
+ if key in METRIC_RULE_GROUP_BY_TOP_LEVEL_KEYS and key not in METRIC_RULE_GROUP_BY_SPAN_TOP_LEVEL_KEYS:
+ raise ValidationError({"group_by": f"{key!r} is a log-only group-by key; spans carry no such column."})
+
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"):
+ for field in ("metric_name", "value_attribute", "source"):
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."})
@@ -250,11 +304,33 @@ class LogsMetricRuleViewSet(TeamAndOrgViewSetMixin, viewsets.ModelViewSet):
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.
+ # writes need authority over both resources. Span rules additionally publish span
+ # attribute values, so they need tracing authority too — the effective source is
+ # the submitted value on create and the loaded row's on update/destroy (source is
+ # immutable, so they cannot disagree).
if self.action in ("create", "update", "partial_update", "destroy"):
- return ["logs:write", "metrics:write"]
+ scopes = ["logs:write", "metrics:write"]
+ if self._write_targets_spans(request):
+ scopes.append("tracing:read")
+ return scopes
return None
+ def _write_targets_spans(self, request: Request) -> bool:
+ if self.action == "create":
+ # drf-spectacular calls this with a mock request during schema generation;
+ # a missing body means "no submitted source", not a crash.
+ data = getattr(request, "data", None) or {}
+ return data.get("source") == LogsMetricRule.RecordSource.SPANS
+ if self.action in ("update", "partial_update", "destroy"):
+ try:
+ instance = self.get_object()
+ except Exception:
+ # get_object() needs a resolved team (schema generation has none) — a 404
+ # is a failed lookup too, and in both cases there is no spans rule to gate.
+ return False
+ return instance.source == LogsMetricRule.RecordSource.SPANS
+ return False
+
def safely_get_queryset(self, queryset: QuerySet) -> QuerySet:
return queryset.filter(team_id=self.canonical_team_id)
@@ -267,13 +343,31 @@ class LogsMetricRuleViewSet(TeamAndOrgViewSetMixin, viewsets.ModelViewSet):
if not user_access_control.check_access_level_for_resource("metrics", "editor"):
raise PermissionDenied("Managing metric rules requires editor access to metrics.")
+ def _assert_tracing_access_for_span_rules(self, user: User, source: str) -> None:
+ # A spans rule's emitted series carry span attribute values, readable by anyone
+ # with metrics access — so a user denied tracing access must not be able to publish
+ # span data past the tracing permission boundary.
+ if source != LogsMetricRule.RecordSource.SPANS:
+ return
+ 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("tracing", "editor"):
+ raise PermissionDenied("Managing span metric rules requires editor access to tracing.")
+
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():
+ # On update the immutable source is the existing row's; on create it's the submitted
+ # value (validated_data carries the field default when the client omits it, which
+ # would run the uniqueness query against the wrong source).
+ if serializer.instance is not None:
+ source = serializer.instance.source
+ else:
+ source = serializer.validated_data.get("source", LogsMetricRule.RecordSource.LOGS)
+ if metric_name and team_rules.filter(metric_name=metric_name, source=source).exists():
raise ValidationError({"metric_name": "A rule already emits this metric name in this project."})
wants_enabled = serializer.validated_data.get("enabled")
@@ -295,6 +389,9 @@ class LogsMetricRuleViewSet(TeamAndOrgViewSetMixin, viewsets.ModelViewSet):
s = cast(LogsMetricRuleSerializer, serializer)
user = cast(User, self.request.user)
self._assert_metrics_editor_access(user)
+ self._assert_tracing_access_for_span_rules(
+ user, s.validated_data.get("source", LogsMetricRule.RecordSource.LOGS)
+ )
with transaction.atomic():
self._lock_team_rules()
self._validate_team_limits(s)
@@ -316,6 +413,7 @@ class LogsMetricRuleViewSet(TeamAndOrgViewSetMixin, viewsets.ModelViewSet):
user = cast(User, self.request.user)
assert s.instance is not None
self._assert_metrics_editor_access(user)
+ self._assert_tracing_access_for_span_rules(user, s.instance.source)
with transaction.atomic():
self._lock_team_rules()
self._validate_team_limits(s, exclude_pk=s.instance.pk)
@@ -337,6 +435,7 @@ class LogsMetricRuleViewSet(TeamAndOrgViewSetMixin, viewsets.ModelViewSet):
# 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)
+ self._assert_tracing_access_for_span_rules(user, instance.source)
report_user_action(
user,
"logs metric rule deleted",
diff --git a/products/logs/backend/test/test_metric_rules_api.py b/products/logs/backend/test/test_metric_rules_api.py
index f7204d10c9c2..31f91796db95 100644
--- a/products/logs/backend/test/test_metric_rules_api.py
+++ b/products/logs/backend/test/test_metric_rules_api.py
@@ -1,5 +1,5 @@
from posthog.test.base import APIBaseTest
-from unittest.mock import patch
+from unittest.mock import Mock, patch
from django.test import SimpleTestCase
@@ -13,7 +13,7 @@ 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
+from products.logs.backend.presentation.views.metric_rules_api import LogsMetricRuleSerializer, LogsMetricRuleViewSet
VALID_FILTER_GROUP = {
"type": "AND",
@@ -91,6 +91,67 @@ class TestLogsMetricRuleSerializerValidation(SimpleTestCase):
assert s.is_valid(), s.errors
assert s.validated_data.get("value_attribute") is None
+ def test_source_defaults_to_logs(self):
+ s = self._serializer()
+ assert s.is_valid(), s.errors
+ assert s.validated_data.get("source") == LogsMetricRule.RecordSource.LOGS
+
+ def test_span_rule_accepts_span_top_level_group_by_keys(self):
+ s = self._serializer(
+ source="spans",
+ group_by=["service_name", "name", "status_code", "kind", "attributes.http.route"],
+ )
+ assert s.is_valid(), s.errors
+
+ @parameterized.expand(
+ [
+ ("severity_text", ["severity_text"]),
+ ("event_name", ["event_name"]),
+ ]
+ )
+ def test_span_rule_rejects_log_only_group_by_keys(self, _label, group_by):
+ s = self._serializer(source="spans", group_by=group_by)
+ assert not s.is_valid()
+ assert "group_by" in s.errors
+
+ @parameterized.expand(
+ [
+ ("name", ["name"]),
+ ("status_code", ["status_code"]),
+ ("kind", ["kind"]),
+ ]
+ )
+ def test_log_rule_rejects_span_only_group_by_keys(self, _label, group_by):
+ s = self._serializer(source="logs", group_by=group_by)
+ assert not s.is_valid()
+ assert "group_by" in s.errors
+
+ def test_span_rule_accepts_duration_ms_value_attribute(self):
+ s = self._serializer(source="spans", value_attribute="duration_ms")
+ assert s.is_valid(), s.errors
+
+ def test_log_rule_rejects_duration_ms_value_attribute(self):
+ s = self._serializer(source="logs", value_attribute="duration_ms")
+ assert not s.is_valid()
+ assert "value_attribute" in s.errors
+
+ def test_source_immutable_on_update(self):
+ instance = LogsMetricRule(metric_name="span.errors", source=LogsMetricRule.RecordSource.SPANS)
+ s = LogsMetricRuleSerializer(instance=instance, data={"source": "logs"}, partial=True)
+ assert not s.is_valid()
+ assert "source" in s.errors
+
+ def test_full_update_omitting_source_keeps_existing_source(self):
+ # A PUT that omits `source` must not overwrite an existing spans rule with the
+ # field default (logs) — the record source is immutable and pinned to the instance.
+ instance = LogsMetricRule(metric_name="span.errors", source=LogsMetricRule.RecordSource.SPANS)
+ s = LogsMetricRuleSerializer(
+ instance=instance,
+ data={"name": "Renamed", "metric_name": "span.errors", "filter_group": VALID_FILTER_GROUP},
+ )
+ assert s.is_valid(), s.errors
+ assert s.validated_data["source"] == LogsMetricRule.RecordSource.SPANS
+
def test_null_filter_group_matches_all_logs(self):
s = self._serializer(filter_group=None)
assert s.is_valid(), s.errors
@@ -369,6 +430,106 @@ class TestLogsMetricRulesAPI(APIBaseTest):
assert response.status_code == status.HTTP_403_FORBIDDEN, response.json()
assert self.client.get(detail_url).status_code == status.HTTP_200_OK
+ def test_create_span_rule_requires_tracing_editor_access(self):
+ # A spans rule's emitted series carry span attribute values readable by anyone
+ # with metrics access — a user denied tracing access must not publish span data
+ # past the tracing permission boundary through this side door.
+ def deny_tracing_only(resource, required_level=None, *args, **kwargs):
+ return resource != "tracing"
+
+ with patch(
+ "products.logs.backend.presentation.views.metric_rules_api.UserAccessControl.check_access_level_for_resource",
+ side_effect=deny_tracing_only,
+ ) as mock_check:
+ response = self.client.post(self.base_url, self._payload(source="spans"), format="json")
+
+ assert response.status_code == status.HTTP_403_FORBIDDEN, response.json()
+ mock_check.assert_any_call("tracing", "editor")
+
+ def test_create_logs_rule_does_not_require_tracing_access(self):
+ def deny_tracing_only(resource, required_level=None, *args, **kwargs):
+ return resource != "tracing"
+
+ with patch(
+ "products.logs.backend.presentation.views.metric_rules_api.UserAccessControl.check_access_level_for_resource",
+ side_effect=deny_tracing_only,
+ ):
+ response = self.client.post(self.base_url, self._payload(source="logs"), format="json")
+
+ assert response.status_code == status.HTTP_201_CREATED, response.json()
+
+ def test_update_span_rule_requires_tracing_editor_access(self):
+ created = self.client.post(self.base_url, self._payload(source="spans"), format="json").json()
+ detail_url = f"{self.base_url}{created['id']}/"
+
+ def deny_tracing_only(resource, required_level=None, *args, **kwargs):
+ return resource != "tracing"
+
+ with patch(
+ "products.logs.backend.presentation.views.metric_rules_api.UserAccessControl.check_access_level_for_resource",
+ side_effect=deny_tracing_only,
+ ):
+ response = self.client.patch(detail_url, {"name": "renamed"}, format="json")
+
+ assert response.status_code == status.HTTP_403_FORBIDDEN, response.json()
+
+ def test_delete_span_rule_requires_tracing_editor_access(self):
+ created = self.client.post(self.base_url, self._payload(source="spans"), format="json").json()
+ detail_url = f"{self.base_url}{created['id']}/"
+
+ def deny_tracing_only(resource, required_level=None, *args, **kwargs):
+ return resource != "tracing"
+
+ with patch(
+ "products.logs.backend.presentation.views.metric_rules_api.UserAccessControl.check_access_level_for_resource",
+ side_effect=deny_tracing_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
+
+ def test_required_scopes_survive_schema_generation_context(self):
+ # drf-spectacular calls dangerously_get_required_scopes with a mock request and
+ # no team context for every action. It must not crash (KeyError on team_id) —
+ # regressing this broke `hogli build:openapi`.
+ view = LogsMetricRuleViewSet()
+ view.action_map = {}
+ for action in ("create", "update", "partial_update", "destroy", "list"):
+ view.action = action
+ view.kwargs = {}
+ scopes = view.dangerously_get_required_scopes(Mock(data={}), view)
+ if action in ("create", "update", "partial_update", "destroy"):
+ assert scopes == ["logs:write", "metrics:write"], (action, scopes)
+ else:
+ assert scopes is None, (action, scopes)
+
+ def test_span_rule_write_scopes_include_tracing_read(self):
+ key_value = generate_random_token_personal()
+ PersonalAPIKey.objects.create(
+ label="no-tracing-scope",
+ user=self.user,
+ secure_value=hash_key_value(key_value),
+ scopes=["logs:write", "metrics:write"],
+ scoped_teams=[self.team.pk],
+ )
+
+ response = self.client.post(
+ self.base_url,
+ self._payload(source="spans"),
+ format="json",
+ HTTP_AUTHORIZATION=f"Bearer {key_value}",
+ )
+ assert response.status_code == status.HTTP_403_FORBIDDEN, response.json()
+
+ response = self.client.post(
+ self.base_url,
+ self._payload(source="logs"),
+ format="json",
+ HTTP_AUTHORIZATION=f"Bearer {key_value}",
+ )
+ assert response.status_code == status.HTTP_201_CREATED, response.json()
+
@parameterized.expand(
[
(["logs:write"], status.HTTP_403_FORBIDDEN),
diff --git a/products/logs/frontend/generated/api.schemas.ts b/products/logs/frontend/generated/api.schemas.ts
index 2ddfc18fa0db..078824275143 100644
--- a/products/logs/frontend/generated/api.schemas.ts
+++ b/products/logs/frontend/generated/api.schemas.ts
@@ -1803,6 +1803,18 @@ export interface _LogsImpactResponseApi {
personGroupKey: _LogsImpactGroupKeyApi | null
}
+/**
+ * * `logs` - Logs
+ * * `spans` - Spans
+ */
+export type LogsMetricRuleRecordSourceEnumApi =
+ (typeof LogsMetricRuleRecordSourceEnumApi)[keyof typeof LogsMetricRuleRecordSourceEnumApi]
+
+export const LogsMetricRuleRecordSourceEnumApi = {
+ Logs: 'logs',
+ Spans: 'spans',
+} as const
+
export interface LogsMetricRuleApi {
/** Unique identifier for this metric rule. */
readonly id: string
@@ -1821,16 +1833,21 @@ export interface LogsMetricRuleApi {
/** 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.
+ * Attribute key holding a numeric value to aggregate into a distribution (count + sum), e.g. `attributes.duration_ms` or `resource_attributes.batch.size`, prefixed with `attributes.` / `resource_attributes.`. For `source=spans` rules, the span pseudo-key `duration_ms` (span wall-clock duration) is also allowed. Omit to count matching 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.
+ * Up to 5 dimension keys; each distinct value combination becomes its own metric series. For `source=logs` rules allowed: service_name, severity_text, event_name; for `source=spans` rules allowed: service_name, name, status_code, kind; for either, map keys prefixed with `attributes.` / `resource_attributes.`. Avoid high-cardinality keys (user IDs, request IDs) — excess series are dropped at ingestion. For `source=spans` rules, note that `name` is high-cardinality on poorly instrumented services (route params or SQL fragments in the span name), so grouping by `name` can overflow the per-rule series cap on its own.
* @items.maxLength 512
*/
group_by?: string[]
+ /** Record source the rule tallies: `logs` (default) evaluates in the logs consumer, `spans` in the traces consumer. Immutable after creation — it decides which keys are valid and which pipeline runs the rule.
+ *
+ * * `logs` - Logs
+ * * `spans` - Spans */
+ source?: LogsMetricRuleRecordSourceEnumApi
/** Incremented on each update for worker cache coherency. */
readonly version: number
readonly created_by: number
@@ -1866,16 +1883,21 @@ export interface PatchedLogsMetricRuleApi {
/** 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.
+ * Attribute key holding a numeric value to aggregate into a distribution (count + sum), e.g. `attributes.duration_ms` or `resource_attributes.batch.size`, prefixed with `attributes.` / `resource_attributes.`. For `source=spans` rules, the span pseudo-key `duration_ms` (span wall-clock duration) is also allowed. Omit to count matching 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.
+ * Up to 5 dimension keys; each distinct value combination becomes its own metric series. For `source=logs` rules allowed: service_name, severity_text, event_name; for `source=spans` rules allowed: service_name, name, status_code, kind; for either, map keys prefixed with `attributes.` / `resource_attributes.`. Avoid high-cardinality keys (user IDs, request IDs) — excess series are dropped at ingestion. For `source=spans` rules, note that `name` is high-cardinality on poorly instrumented services (route params or SQL fragments in the span name), so grouping by `name` can overflow the per-rule series cap on its own.
* @items.maxLength 512
*/
group_by?: string[]
+ /** Record source the rule tallies: `logs` (default) evaluates in the logs consumer, `spans` in the traces consumer. Immutable after creation — it decides which keys are valid and which pipeline runs the rule.
+ *
+ * * `logs` - Logs
+ * * `spans` - Spans */
+ source?: LogsMetricRuleRecordSourceEnumApi
/** Incremented on each update for worker cache coherency. */
readonly version?: number
readonly created_by?: number
diff --git a/products/logs/frontend/generated/api.zod.ts b/products/logs/frontend/generated/api.zod.ts
index 54d8541c437d..5d94500a5245 100644
--- a/products/logs/frontend/generated/api.zod.ts
+++ b/products/logs/frontend/generated/api.zod.ts
@@ -1128,6 +1128,8 @@ export const logsMetricRulesCreateBodyValueAttributeMax = 512
export const logsMetricRulesCreateBodyGroupByItemMax = 512
+export const logsMetricRulesCreateBodySourceDefault = `logs`
+
export const LogsMetricRulesCreateBody = /* @__PURE__ */ zod.object({
name: zod.string().max(logsMetricRulesCreateBodyNameMax).describe('User-visible label for this rule.'),
metric_name: zod
@@ -1153,13 +1155,20 @@ export const LogsMetricRulesCreateBody = /* @__PURE__ */ zod.object({
.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.'
+ 'Attribute key holding a numeric value to aggregate into a distribution (count + sum), e.g. `attributes.duration_ms` or `resource_attributes.batch.size`, prefixed with `attributes.` \/ `resource_attributes.`. For `source=spans` rules, the span pseudo-key `duration_ms` (span wall-clock duration) is also allowed. Omit to count matching 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.'
+ 'Up to 5 dimension keys; each distinct value combination becomes its own metric series. For `source=logs` rules allowed: service_name, severity_text, event_name; for `source=spans` rules allowed: service_name, name, status_code, kind; for either, map keys prefixed with `attributes.` \/ `resource_attributes.`. Avoid high-cardinality keys (user IDs, request IDs) — excess series are dropped at ingestion. For `source=spans` rules, note that `name` is high-cardinality on poorly instrumented services (route params or SQL fragments in the span name), so grouping by `name` can overflow the per-rule series cap on its own.'
+ ),
+ source: zod
+ .enum(['logs', 'spans'])
+ .describe('\* `logs` - Logs\n\* `spans` - Spans')
+ .default(logsMetricRulesCreateBodySourceDefault)
+ .describe(
+ 'Record source the rule tallies: `logs` (default) evaluates in the logs consumer, `spans` in the traces consumer. Immutable after creation — it decides which keys are valid and which pipeline runs the rule.\n\n\* `logs` - Logs\n\* `spans` - Spans'
),
})
@@ -1172,6 +1181,8 @@ export const logsMetricRulesUpdateBodyValueAttributeMax = 512
export const logsMetricRulesUpdateBodyGroupByItemMax = 512
+export const logsMetricRulesUpdateBodySourceDefault = `logs`
+
export const LogsMetricRulesUpdateBody = /* @__PURE__ */ zod.object({
name: zod.string().max(logsMetricRulesUpdateBodyNameMax).describe('User-visible label for this rule.'),
metric_name: zod
@@ -1197,13 +1208,20 @@ export const LogsMetricRulesUpdateBody = /* @__PURE__ */ zod.object({
.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.'
+ 'Attribute key holding a numeric value to aggregate into a distribution (count + sum), e.g. `attributes.duration_ms` or `resource_attributes.batch.size`, prefixed with `attributes.` \/ `resource_attributes.`. For `source=spans` rules, the span pseudo-key `duration_ms` (span wall-clock duration) is also allowed. Omit to count matching 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.'
+ 'Up to 5 dimension keys; each distinct value combination becomes its own metric series. For `source=logs` rules allowed: service_name, severity_text, event_name; for `source=spans` rules allowed: service_name, name, status_code, kind; for either, map keys prefixed with `attributes.` \/ `resource_attributes.`. Avoid high-cardinality keys (user IDs, request IDs) — excess series are dropped at ingestion. For `source=spans` rules, note that `name` is high-cardinality on poorly instrumented services (route params or SQL fragments in the span name), so grouping by `name` can overflow the per-rule series cap on its own.'
+ ),
+ source: zod
+ .enum(['logs', 'spans'])
+ .describe('\* `logs` - Logs\n\* `spans` - Spans')
+ .default(logsMetricRulesUpdateBodySourceDefault)
+ .describe(
+ 'Record source the rule tallies: `logs` (default) evaluates in the logs consumer, `spans` in the traces consumer. Immutable after creation — it decides which keys are valid and which pipeline runs the rule.\n\n\* `logs` - Logs\n\* `spans` - Spans'
),
})
@@ -1216,6 +1234,8 @@ export const logsMetricRulesPartialUpdateBodyValueAttributeMax = 512
export const logsMetricRulesPartialUpdateBodyGroupByItemMax = 512
+export const logsMetricRulesPartialUpdateBodySourceDefault = `logs`
+
export const LogsMetricRulesPartialUpdateBody = /* @__PURE__ */ zod.object({
name: zod
.string()
@@ -1246,13 +1266,20 @@ export const LogsMetricRulesPartialUpdateBody = /* @__PURE__ */ zod.object({
.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.'
+ 'Attribute key holding a numeric value to aggregate into a distribution (count + sum), e.g. `attributes.duration_ms` or `resource_attributes.batch.size`, prefixed with `attributes.` \/ `resource_attributes.`. For `source=spans` rules, the span pseudo-key `duration_ms` (span wall-clock duration) is also allowed. Omit to count matching 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.'
+ 'Up to 5 dimension keys; each distinct value combination becomes its own metric series. For `source=logs` rules allowed: service_name, severity_text, event_name; for `source=spans` rules allowed: service_name, name, status_code, kind; for either, map keys prefixed with `attributes.` \/ `resource_attributes.`. Avoid high-cardinality keys (user IDs, request IDs) — excess series are dropped at ingestion. For `source=spans` rules, note that `name` is high-cardinality on poorly instrumented services (route params or SQL fragments in the span name), so grouping by `name` can overflow the per-rule series cap on its own.'
+ ),
+ source: zod
+ .enum(['logs', 'spans'])
+ .describe('\* `logs` - Logs\n\* `spans` - Spans')
+ .default(logsMetricRulesPartialUpdateBodySourceDefault)
+ .describe(
+ 'Record source the rule tallies: `logs` (default) evaluates in the logs consumer, `spans` in the traces consumer. Immutable after creation — it decides which keys are valid and which pipeline runs the rule.\n\n\* `logs` - Logs\n\* `spans` - Spans'
),
})
diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.ts
index c8d02d19450e..545cb574c6f3 100644
--- a/services/mcp/src/api/generated.ts
+++ b/services/mcp/src/api/generated.ts
@@ -50502,6 +50502,18 @@ export namespace Schemas {
config?: LogsListWidgetConfig;
}
+ /**
+ * * `logs` - Logs
+ * * `spans` - Spans
+ */
+ export type LogsMetricRuleRecordSourceEnum = typeof LogsMetricRuleRecordSourceEnum[keyof typeof LogsMetricRuleRecordSourceEnum];
+
+
+ export const LogsMetricRuleRecordSourceEnum = {
+ Logs: 'logs',
+ Spans: 'spans',
+ } as const;
+
export interface LogsMetricRule {
/** Unique identifier for this metric rule. */
readonly id: string;
@@ -50520,16 +50532,21 @@ export namespace Schemas {
/** 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.
+ * Attribute key holding a numeric value to aggregate into a distribution (count + sum), e.g. `attributes.duration_ms` or `resource_attributes.batch.size`, prefixed with `attributes.` / `resource_attributes.`. For `source=spans` rules, the span pseudo-key `duration_ms` (span wall-clock duration) is also allowed. Omit to count matching 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.
+ * Up to 5 dimension keys; each distinct value combination becomes its own metric series. For `source=logs` rules allowed: service_name, severity_text, event_name; for `source=spans` rules allowed: service_name, name, status_code, kind; for either, map keys prefixed with `attributes.` / `resource_attributes.`. Avoid high-cardinality keys (user IDs, request IDs) — excess series are dropped at ingestion. For `source=spans` rules, note that `name` is high-cardinality on poorly instrumented services (route params or SQL fragments in the span name), so grouping by `name` can overflow the per-rule series cap on its own.
* @items.maxLength 512
*/
group_by?: string[];
+ /** Record source the rule tallies: `logs` (default) evaluates in the logs consumer, `spans` in the traces consumer. Immutable after creation — it decides which keys are valid and which pipeline runs the rule.
+ *
+ * * `logs` - Logs
+ * * `spans` - Spans */
+ source?: LogsMetricRuleRecordSourceEnum;
/** Incremented on each update for worker cache coherency. */
readonly version: number;
readonly created_by: number;
@@ -66251,16 +66268,21 @@ export namespace Schemas {
/** 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.
+ * Attribute key holding a numeric value to aggregate into a distribution (count + sum), e.g. `attributes.duration_ms` or `resource_attributes.batch.size`, prefixed with `attributes.` / `resource_attributes.`. For `source=spans` rules, the span pseudo-key `duration_ms` (span wall-clock duration) is also allowed. Omit to count matching 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.
+ * Up to 5 dimension keys; each distinct value combination becomes its own metric series. For `source=logs` rules allowed: service_name, severity_text, event_name; for `source=spans` rules allowed: service_name, name, status_code, kind; for either, map keys prefixed with `attributes.` / `resource_attributes.`. Avoid high-cardinality keys (user IDs, request IDs) — excess series are dropped at ingestion. For `source=spans` rules, note that `name` is high-cardinality on poorly instrumented services (route params or SQL fragments in the span name), so grouping by `name` can overflow the per-rule series cap on its own.
* @items.maxLength 512
*/
group_by?: string[];
+ /** Record source the rule tallies: `logs` (default) evaluates in the logs consumer, `spans` in the traces consumer. Immutable after creation — it decides which keys are valid and which pipeline runs the rule.
+ *
+ * * `logs` - Logs
+ * * `spans` - Spans */
+ source?: LogsMetricRuleRecordSourceEnum;
/** Incremented on each update for worker cache coherency. */
readonly version?: number;
readonly created_by?: number;