: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): evaluate metric rules at ingestion and emit OTLP metrics (#72108)
Daniel Visca6d8d10cf481b
diff --git a/nodejs/src/logs/config.ts b/nodejs/src/logs/config.tsindex 51547055739b..93ebff2b02e0 100644--- a/nodejs/src/logs/config.ts+++ b/nodejs/src/logs/config.ts@@ -50,6 +50,12 @@ export type LogsIngestionConsumerConfig = {LOGS_SAMPLING_ENABLED_TEAMS: string/** When `true`, sampling always keeps every record (metrics path may still run). */LOGS_SAMPLING_KILLSWITCH: boolean+ /** Comma-separated team IDs, or `*` for all teams, or empty to disable metric-rule evaluation entirely. */+ LOGS_METRICS_RULES_ENABLED_TEAMS: string+ /** When `true`, metric-rule evaluation and emission are skipped for every team. */+ LOGS_METRICS_RULES_KILLSWITCH: boolean+ /** capture-logs OTLP metrics endpoint (e.g. `http://capture-logs:3308/i/v1/metrics`); empty disables emission. */+ LOGS_METRICS_RULES_EXPORT_URL: string/*** When `true`, rows removed by drop rules are credited back to the billed usage metrics* (`bytes_ingested` / `records_ingested`). When `false` (default), the credit is only@@ -83,6 +89,9 @@ export function getDefaultLogsIngestionConsumerConfig(): LogsIngestionConsumerCoLOGS_LIMITER_TEAM_REFILL_RATE_KB_PER_SECOND: '',LOGS_SAMPLING_ENABLED_TEAMS: '*',LOGS_SAMPLING_KILLSWITCH: false,+ LOGS_METRICS_RULES_ENABLED_TEAMS: isProdEnv() ? '' : '*',+ LOGS_METRICS_RULES_KILLSWITCH: false,+ LOGS_METRICS_RULES_EXPORT_URL: '',LOGS_BILLING_PRORATE_ENABLED: false,// Overlapping fields with CommonConfig, included for standalone usage// ok to connect to localhost over plaintextdiff --git a/nodejs/src/logs/log-record-avro.ts b/nodejs/src/logs/log-record-avro.tsindex 6f14a0b2f7dc..931ed4ed33fe 100644--- a/nodejs/src/logs/log-record-avro.ts+++ b/nodejs/src/logs/log-record-avro.ts@@ -303,12 +303,19 @@ export const processLogMessageBuffer = instrumented({...logRecordProcessInstrumentOpts,})(async function processLogMessageBufferImpl(buffer: Buffer,- settings: LogsSettings+ settings: LogsSettings,+ onRecordsDecoded?: (records: LogRecord[]) => void): Promise<{ value: Buffer; pii: PiiScrubStats }> {const jsonParse = settings.json_parse_logs ?? falseconst piiScrub = settings.pii_scrub_logs ?? falseif (!jsonParse && !piiScrub) {+ // Passthrough: the buffer is forwarded untouched. Decode only when a visitor+ // (metric-rule extraction) needs the records — skipping the re-encode either way.+ if (onRecordsDecoded) {+ const [, , records] = await decodeLogRecordsInstrumented(buffer)+ onRecordsDecoded(records)+ }return { value: buffer, pii: EMPTY_PII }}@@ -324,6 +331,7 @@ export const processLogMessageBuffer = instrumented({}const pii = await transformDecodedLogRecordsInPlace(records, settings)+ onRecordsDecoded?.(records)const value = await encodeLogRecordsInstrumented(logRecordType, codec, records)return { value, pii }@@ -337,4 +345,8 @@ export const processLogMessageBuffer = instrumented({logProcessingDurationHistogram.observe(durationLabels, durationSeconds)recordLogProcessingDuration(durationSeconds, durationLabels)}-}) as (buffer: Buffer, settings: LogsSettings) => Promise<{ value: Buffer; pii: PiiScrubStats }>+}) as (+ buffer: Buffer,+ settings: LogsSettings,+ onRecordsDecoded?: (records: LogRecord[]) => void+) => Promise<{ value: Buffer; pii: PiiScrubStats }>diff --git a/nodejs/src/logs/logs-ingestion-consumer.test.ts b/nodejs/src/logs/logs-ingestion-consumer.test.tsindex 83d414a901b9..595ac6856e4a 100644--- a/nodejs/src/logs/logs-ingestion-consumer.test.ts+++ b/nodejs/src/logs/logs-ingestion-consumer.test.ts@@ -40,6 +40,9 @@ import {logsRecordsDroppedCounter,logsRecordsReceivedCounter,} from './logs-ingestion-consumer'+import { compileMetricRules } from './metrics-rules/compile-metric-rules'+import type { MetricRulesCache } from './metrics-rules/metric-rules-cache'+import type { LogsMetricsEmitter } from './metrics-rules/metrics-emitter'import { LOGS_DLQ_OUTPUT, LOGS_OUTPUT, LogsDlqOutput, LogsOutput } from './outputs/outputs'import { compileRuleSet } from './sampling/compile-rules'import type { SamplingRulesCache } from './sampling/sampling-rules-cache'@@ -193,7 +196,9 @@ describe('LogsIngestionConsumer', () => {const createLogsIngestionConsumer = async (hub: Hub,overrides: any = {},- depsPartial: Partial<Pick<LogsIngestionConsumerDeps, 'samplingRulesCache'>> = {}+ depsPartial: Partial<+ Pick<LogsIngestionConsumerDeps, 'samplingRulesCache' | 'metricRulesCache' | 'metricsEmitter'>+ > = {}) => {const consumer = new LogsIngestionConsumer(hub,@@ -1863,6 +1868,150 @@ describe('LogsIngestionConsumer', () => {})})+ describe('metric rules (generate metrics from logs)', () => {+ let mockEmitter: { emit: jest.Mock }+ let mockMetricRulesCache: Pick<MetricRulesCache, 'getCompiledRules'>++ const countBySeverityRules = compileMetricRules([+ {+ id: '00000000-0000-0000-0000-0000000000bb',+ metric_name: 'log.records',+ filter_group: null,+ value_attribute: null,+ group_by: ['severity_text'],+ },+ ])++ const createConsumerWithMetricRules = async (overrides: any = {}, depsPartial: any = {}) => {+ await consumer.stop()+ consumer = await createLogsIngestionConsumer(hub, overrides, {+ metricRulesCache: mockMetricRulesCache as MetricRulesCache,+ metricsEmitter: mockEmitter as unknown as LogsMetricsEmitter,+ ...depsPartial,+ })+ await deleteKeysWithPrefix(consumer['redis'], BASE_REDIS_KEY)+ }++ beforeEach(async () => {+ mockEmitter = { emit: jest.fn().mockResolvedValue(true) }+ mockMetricRulesCache = {+ getCompiledRules: (teamId: number) => Promise.resolve(teamId === team.id ? countBySeverityRules : []),+ }+ await createConsumerWithMetricRules()+ })++ const emittedDataPoints = (): any[] => {+ const payload = mockEmitter.emit.mock.calls[0][2]+ return payload.resourceMetrics[0].scopeMetrics[0].metrics[0].sum.dataPoints+ }++ it('emits one OTLP payload per team with counts grouped by the rule dimensions', async () => {+ const messages = await createKafkaMessages(+ [+ createLogMessage({ level: 'info' }),+ createLogMessage({ level: 'info' }),+ createLogMessage({ level: 'error' }),+ ],+ { token: team.api_token, bytes_uncompressed: '400', record_count: '1' }+ )+ await waitForBackgroundTasks(consumer.processKafkaBatch(messages))++ expect(mockEmitter.emit).toHaveBeenCalledTimes(1)+ const [token, teamId] = mockEmitter.emit.mock.calls[0]+ expect(token).toBe(team.api_token)+ expect(teamId).toBe(team.id)++ const bySeverity = Object.fromEntries(+ emittedDataPoints().map((dp: any) => [dp.attributes[0].value.stringValue, dp.asDouble])+ )+ expect(bySeverity).toEqual({ info: 2, error: 1 })+ })++ it('produces logs normally when the rules cache fetch throws (fail-open)', async () => {+ // Metric rules are a purely additive side feature: a Postgres blip on the+ // rules fetch must not DLQ or block the log records themselves.+ await createConsumerWithMetricRules(+ {},+ {+ metricRulesCache: {+ getCompiledRules: () => Promise.reject(new Error('pg down')),+ } as unknown as MetricRulesCache,+ }+ )++ const messages = await createKafkaMessages([createLogMessage({ level: 'info' })], {+ token: team.api_token,+ bytes_uncompressed: '400',+ record_count: '1',+ })+ await waitForBackgroundTasks(consumer.processKafkaBatch(messages))++ const logsOutput = getProducedKafkaMessages().filter((m) => m.topic === KAFKA_LOGS_CLICKHOUSE)+ expect(logsOutput).toHaveLength(1)+ const dlqOutput = getProducedKafkaMessages().filter((m) => m.topic === KAFKA_LOGS_INGESTION_DLQ)+ expect(dlqOutput).toHaveLength(0)+ expect(mockEmitter.emit).not.toHaveBeenCalled()+ })++ it('still counts records that a drop rule removes (pre-drop semantics)', async () => {+ const droppingSamplingCache: Pick<SamplingRulesCache, 'getCompiledRuleSet'> = {+ getCompiledRuleSet: () =>+ Promise.resolve(+ compileRuleSet([+ {+ id: '00000000-0000-0000-0000-0000000000aa',+ rule_type: 'severity_sampling',+ scope_service: 'test-service',+ scope_path_pattern: null,+ scope_attribute_filters: [],+ config: { actions: { INFO: { type: 'drop' } } },+ },+ ])+ ),+ }+ await createConsumerWithMetricRules({}, { samplingRulesCache: droppingSamplingCache })++ const message = await createMultiRecordKafkaMessage(+ [createLogMessage({ level: 'info' }), createLogMessage({ level: 'error' })],+ { token: team.api_token, bytes_uncompressed: '800', record_count: '2' }+ )+ await waitForBackgroundTasks(consumer.processKafkaBatch([message]))++ // The info row is gone from the ClickHouse-bound output...+ const logsOutput = getProducedKafkaMessages().filter((m) => m.topic === KAFKA_LOGS_CLICKHOUSE)+ expect(logsOutput).toHaveLength(1)+ // ...but both rows fed the generated metric.+ const bySeverity = Object.fromEntries(+ emittedDataPoints().map((dp: any) => [dp.attributes[0].value.stringValue, dp.asDouble])+ )+ expect(bySeverity).toEqual({ info: 1, error: 1 })+ })++ it('does not emit for a team without metric rules', async () => {+ const messages = await createKafkaMessages([createLogMessage()], {+ token: team2.api_token,+ bytes_uncompressed: '400',+ record_count: '1',+ })+ await waitForBackgroundTasks(consumer.processKafkaBatch(messages))+ expect(mockEmitter.emit).not.toHaveBeenCalled()+ })++ it.each([+ ['killswitch', { LOGS_METRICS_RULES_KILLSWITCH: true }],+ ['team gating', { LOGS_METRICS_RULES_ENABLED_TEAMS: '' }],+ ])('does not evaluate rules when disabled via %s', async (_label, overrides) => {+ await createConsumerWithMetricRules(overrides)+ const messages = await createKafkaMessages([createLogMessage()], {+ token: team.api_token,+ bytes_uncompressed: '400',+ record_count: '1',+ })+ await waitForBackgroundTasks(consumer.processKafkaBatch(messages))+ expect(mockEmitter.emit).not.toHaveBeenCalled()+ })+ })+describe('thread relief', () => {jest.setTimeout(30000)diff --git a/nodejs/src/logs/logs-ingestion-consumer.ts b/nodejs/src/logs/logs-ingestion-consumer.tsindex ec182248e31c..df1fba491127 100644--- a/nodejs/src/logs/logs-ingestion-consumer.ts+++ b/nodejs/src/logs/logs-ingestion-consumer.ts@@ -26,7 +26,12 @@ import {recordLogsReceived,} from './ingestion-otel-metrics'import { type PiiScrubStats } from './log-pii-scrub'-import { processLogMessageBuffer } from './log-record-avro'+import { type LogRecord, processLogMessageBuffer } from './log-record-avro'+import type { CompiledMetricRule } 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'+import { type BatchTallies, createBatchTallies, tallyRecords } from './metrics-rules/tally'import { LOGS_DLQ_OUTPUT, LOGS_OUTPUT, LogsDlqOutput, LogsOutput } from './outputs/outputs'import type { CompiledRuleSet } from './sampling/evaluate'import { LogsSamplingService } from './sampling/logs-sampling.service'@@ -39,6 +44,10 @@ export interface LogsIngestionConsumerDeps {quotaLimiting: QuotaLimiting/** When set, enabled teams may run head sampling before ClickHouse Kafka produce. */samplingRulesCache?: SamplingRulesCache+ /** When set (with `metricsEmitter`), enabled teams generate metrics from matching log records. */+ metricRulesCache?: MetricRulesCache+ /** OTLP sender for log-generated metrics; required alongside `metricRulesCache` to activate the feature. */+ metricsEmitter?: LogsMetricsEmitter/*** Resolved outputs registry — must include `LOGS_OUTPUT`, `LOGS_DLQ_OUTPUT`,* and `APP_METRICS_OUTPUT`. The producer + topic for each is wired by the@@ -71,6 +80,22 @@ export type UsageStats = {retentionDays: number}+/** `raw` is a comma-separated team-ID list, `*` for all teams, or empty for none. */+function teamIdMatchesCsv(raw: string, teamId: number): boolean {+ const trimmed = (raw || '').trim()+ if (!trimmed) {+ return false+ }+ if (trimmed === '*') {+ return true+ }+ return trimmed+ .split(',')+ .map((s) => parseInt(s.trim(), 10))+ .filter((n) => !Number.isNaN(n))+ .includes(teamId)+}+const DEFAULT_USAGE_STATS: UsageStats = {bytesReceived: 0,recordsReceived: 0,@@ -168,6 +193,31 @@ export const logsBillingRecordsCreditedCounter = new Counter({labelNames: ['team_id'],})+// --- Metric rules (generate metrics from logs) ---+export const logsMetricRulesRecordsMatchedCounter = new Counter({+ name: 'logs_metrics_rules_records_matched_total',+ help: 'Log records that matched a metric rule and fed a generated metric data point.',+ labelNames: ['team_id'],+})++export const logsMetricRulesValueSkippedCounter = new Counter({+ name: 'logs_metrics_rules_value_skipped_total',+ help: 'Records matching a value-attribute metric rule whose value was missing or non-numeric.',+ labelNames: ['team_id'],+})++export const logsMetricRulesSeriesOverflowCounter = new Counter({+ name: 'logs_metrics_rules_series_overflow_total',+ help: 'Matching records dropped because a metric rule exceeded its per-batch label-set cap.',+ labelNames: ['team_id'],+})++export const logsMetricRulesEvalErrorCounter = new Counter({+ name: 'logs_metrics_rules_eval_error_total',+ help: 'Per-record metric-rule filter evaluations that threw; the record was skipped for that rule.',+ labelNames: ['team_id'],+})+// --- Pro-rate accuracy-confidence signals (Tier 2). No team_id label — kept low-cardinality. ---export const logsBillingProrateDivergenceHistogram = new Histogram({name: 'logs_ingestion_billing_prorate_divergence',@@ -222,6 +272,8 @@ export class LogsIngestionConsumer {private readonly samplingEnabledTeamsRaw: stringprivate readonly samplingKillswitch: booleanprivate readonly billingProrateEnabled: boolean+ private readonly metricRulesEnabledTeamsRaw: string+ private readonly metricRulesKillswitch: booleanprotected groupId: stringprotected topic: string@@ -265,24 +317,22 @@ export class LogsIngestionConsumer {this.samplingEnabledTeamsRaw = mergedConfig.LOGS_SAMPLING_ENABLED_TEAMSthis.samplingKillswitch = mergedConfig.LOGS_SAMPLING_KILLSWITCHthis.billingProrateEnabled = mergedConfig.LOGS_BILLING_PRORATE_ENABLED+ this.metricRulesEnabledTeamsRaw = mergedConfig.LOGS_METRICS_RULES_ENABLED_TEAMS+ this.metricRulesKillswitch = mergedConfig.LOGS_METRICS_RULES_KILLSWITCH}private isSamplingEvalEnabledForTeam(teamId: number): boolean {if (this.samplingKillswitch) {return false}- const raw = (this.samplingEnabledTeamsRaw || '').trim()- if (!raw) {+ return teamIdMatchesCsv(this.samplingEnabledTeamsRaw, teamId)+ }++ private isMetricRulesEnabledForTeam(teamId: number): boolean {+ if (this.metricRulesKillswitch || !this.deps.metricRulesCache || !this.deps.metricsEmitter) {return false}- if (raw === '*') {- return true- }- return raw- .split(',')- .map((s) => parseInt(s.trim(), 10))- .filter((n) => !Number.isNaN(n))- .includes(teamId)+ return teamIdMatchesCsv(this.metricRulesEnabledTeamsRaw, teamId)}/**@@ -291,7 +341,8 @@ export class LogsIngestionConsumer {*/private async resolveLogMessageBufferWithOptionalSampling(message: LogsIngestionMessage,- logsSettings: LogsSettings+ logsSettings: LogsSettings,+ onRecordsDecoded?: (records: LogRecord[]) => void): Promise<| {outcome: 'produce'@@ -339,7 +390,8 @@ export class LogsIngestionConsumer {logsSettings,ruleSet,message.teamId,- message.bytesUncompressed+ message.bytesUncompressed,+ onRecordsDecoded)if (sampled.recordsDropped > 0) {logsSamplingRecordsDroppedCounter.inc({ team_id: message.teamId.toString() }, sampled.recordsDropped)@@ -371,7 +423,7 @@ export class LogsIngestionConsumer {}// Passthrough (sampling disabled / no rules): nothing dropped, so nothing to credit.- const res = await processLogMessageBuffer(message.message.value!, logsSettings)+ const res = await processLogMessageBuffer(message.message.value!, logsSettings, onRecordsDecoded)return {outcome: 'produce',processedValue: res.value,@@ -550,10 +602,93 @@ export class LogsIngestionConsumer {return { rateLimiterAllowedMessages: allowed, rateLimiterDroppedMessages: dropped }}+ /**+ * Per-team metric-rule tally state for one batch. Rules are fetched once per team per+ * batch (30s-cached); tallies accumulate across the batch's messages and are emitted+ * as one OTLP payload per team after produce.+ */+ private async getMetricRuleBatchState(+ byTeam: Map<number, { token: string; rules: CompiledMetricRule[]; tallies: BatchTallies }>,+ message: LogsIngestionMessage+ ): Promise<{ token: string; rules: CompiledMetricRule[]; tallies: BatchTallies } | null> {+ if (!this.isMetricRulesEnabledForTeam(message.teamId)) {+ return null+ }+ let state = byTeam.get(message.teamId)+ if (!state) {+ let rules: CompiledMetricRule[]+ try {+ rules = await this.deps.metricRulesCache!.getCompiledRules(message.teamId)+ } 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 —+ // skip metric generation for this team this batch instead.+ logger.warn('[logs-metric-rules] rules fetch failed — skipping metric rules for batch', {+ teamId: message.teamId,+ error: String(error),+ })+ return null+ }+ // Re-check after the await: concurrent messages for the same team race here,+ // and replacing an existing state would silently drop its accumulated tallies.+ state = byTeam.get(message.teamId)+ if (!state) {+ state = { token: message.token, rules, tallies: createBatchTallies() }+ byTeam.set(message.teamId, state)+ }+ }+ return state.rules.length > 0 ? state : null+ }++ private async emitMetricRuleTallies(+ byTeam: Map<number, { token: string; rules: CompiledMetricRule[]; tallies: BatchTallies }>+ ): Promise<void> {+ for (const [teamId, { token, rules, tallies }] of byTeam) {+ const teamIdLabel = teamId.toString()+ if (tallies.valueSkipped > 0) {+ logsMetricRulesValueSkippedCounter.inc({ team_id: teamIdLabel }, tallies.valueSkipped)+ }+ if (tallies.evalErrors > 0) {+ logsMetricRulesEvalErrorCounter.inc({ team_id: teamIdLabel }, tallies.evalErrors)+ }+ let overflow = 0+ for (const count of tallies.seriesOverflow.values()) {+ overflow += count+ }+ if (overflow > 0) {+ logsMetricRulesSeriesOverflowCounter.inc({ team_id: teamIdLabel }, overflow)+ }+ let matched = 0+ for (const ruleTallies of tallies.byRule.values()) {+ for (const entry of ruleTallies.values()) {+ matched += entry.count+ }+ }+ if (matched > 0) {+ logsMetricRulesRecordsMatchedCounter.inc({ team_id: teamIdLabel }, matched)+ }++ const payload = buildMetricRulesOtlpPayload(rules, tallies, Date.now())+ if (!payload) {+ continue+ }+ try {+ await this.deps.metricsEmitter!.emit(token, teamId, payload)+ } catch (error) {+ // Emission is best-effort: a failing metrics endpoint must never fail log ingestion.+ logger.warn('[logs-metric-rules] emit threw', { teamId, error: String(error) })+ }+ }+ }+private async processAndProduceLogMessages(messages: LogsIngestionMessage[],usageStats: UsageStatsByTeam): Promise<void> {+ const metricTalliesByTeam = new Map<+ number,+ { token: string; rules: CompiledMetricRule[]; tallies: BatchTallies }+ >()const limit = pLimit(MAX_CONCURRENT_MESSAGE_PROCESSES)const results = await Promise.allSettled(messages.map((message) =>@@ -577,6 +712,13 @@ export class LogsIngestionConsumer {if (message.message.value === null) {return Promise.resolve()}++ const metricRuleState = await this.getMetricRuleBatchState(metricTalliesByTeam, message)+ const onRecordsDecoded = metricRuleState+ ? (records: LogRecord[]) =>+ tallyRecords(metricRuleState.rules, records, metricRuleState.tallies, Date.now())+ : undefined+const resolved = await instrumentFn({key: 'logsIngestion.sampling.resolveLogMessageBuffer',@@ -587,7 +729,12 @@ export class LogsIngestionConsumer {inbound_bytes: message.message.value?.length ?? 0,}),},- async () => this.resolveLogMessageBufferWithOptionalSampling(message, logsSettings)+ async () =>+ this.resolveLogMessageBufferWithOptionalSampling(+ message,+ logsSettings,+ onRecordsDecoded+ ))let bytesUncompressedHeaderOverride: number | undefined@@ -712,6 +859,8 @@ export class LogsIngestionConsumer {totalCount: messages.length,})}++ await this.emitMetricRuleTallies(metricTalliesByTeam)}private async produceToDlq(message: LogsIngestionMessage, error: unknown): Promise<void> {diff --git a/nodejs/src/logs/metrics-rules/compile-metric-rules.ts b/nodejs/src/logs/metrics-rules/compile-metric-rules.tsnew file mode 100644index 000000000000..ca3a07b07a4d--- /dev/null+++ b/nodejs/src/logs/metrics-rules/compile-metric-rules.ts@@ -0,0 +1,57 @@+import { parseFilterGroup } from '../sampling/compile-rules'+import type { FilterGroupNode } from '../sampling/filter-group-match'++/** Mirrors `MAX_METRIC_RULE_GROUP_BY_KEYS` in `products/logs/backend/models.py`. */+export const MAX_GROUP_BY_KEYS = 5++/** Raw row shape from `logs_logsmetricrule` (see `MetricRulesCache.fetchRules`). */+export type MetricRuleRow = {+ id: string+ metric_name: string+ filter_group: unknown+ value_attribute: string | null+ group_by: unknown+ /** Row version from DB; used by cache watermark only, ignored by compileMetricRules. */+ version?: number+}++export type CompiledMetricRule = {+ id: string+ metricName: string+ /** null = every ingested log record matches. */+ filterGroup: FilterGroupNode | null+ /** Log attribute key holding the numeric value to aggregate; null = count records. */+ valueAttribute: string | null+ groupBy: string[]+}++export function compileMetricRules(rows: MetricRuleRow[]): CompiledMetricRule[] {+ const out: CompiledMetricRule[] = []+ for (const row of rows) {+ if (typeof row.metric_name !== 'string' || row.metric_name === '') {+ continue+ }+ let filterGroup: FilterGroupNode | null = null+ if (row.filter_group != null) {+ filterGroup = parseFilterGroup(row.filter_group)+ if (!filterGroup) {+ // Unlike drop rules (where an unparseable filter makes the rule inert, which is+ // safe), a metric rule with a null filter means "count everything" — so an+ // unparseable filter must skip the whole rule to fail closed on emission.+ continue+ }+ }+ 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)+ : []+ out.push({+ id: row.id,+ metricName: row.metric_name,+ filterGroup,+ valueAttribute:+ typeof row.value_attribute === 'string' && row.value_attribute !== '' ? row.value_attribute : null,+ groupBy,+ })+ }+ return out+}diff --git a/nodejs/src/logs/metrics-rules/metric-rules-cache.ts b/nodejs/src/logs/metrics-rules/metric-rules-cache.tsnew file mode 100644index 000000000000..242fbdddbd3e--- /dev/null+++ b/nodejs/src/logs/metrics-rules/metric-rules-cache.ts@@ -0,0 +1,48 @@+import { PostgresRouter, PostgresUse } from '~/common/utils/db/postgres'++import { type CompiledMetricRule, type MetricRuleRow, compileMetricRules } from './compile-metric-rules'++const REFRESH_MS = 30_000++type CacheEntry = {+ compiled: CompiledMetricRule[]+ fetchedAtMs: number+}++/** Per-team compiled metric rules with a 30s TTL, mirroring `SamplingRulesCache`. */+export class MetricRulesCache {+ private cache = new Map<number, CacheEntry>()++ constructor(private postgres: PostgresRouter) {}++ public async getCompiledRules(teamId: number): Promise<CompiledMetricRule[]> {+ const now = Date.now()+ const existing = this.cache.get(teamId)+ if (existing && now - existing.fetchedAtMs < REFRESH_MS) {+ return existing.compiled+ }+ const rows = await this.fetchRules(teamId)+ const compiled = compileMetricRules(rows)+ this.cache.set(teamId, { compiled, fetchedAtMs: now })+ return compiled+ }++ private async fetchRules(teamId: number): Promise<MetricRuleRow[]> {+ const res = await this.postgres.query<{+ id: string+ metric_name: string+ filter_group: unknown+ value_attribute: string | null+ group_by: unknown+ }>(+ PostgresUse.COMMON_READ,+ `SELECT id::text AS id, metric_name, filter_group, value_attribute, group_by+ FROM logs_logsmetricrule+ WHERE team_id = $1 AND enabled = true+ ORDER BY created_at ASC`,+ [teamId],+ 'logs-metric-rules-fetch'+ )+ return res.rows+ }+}diff --git a/nodejs/src/logs/metrics-rules/metric-rules.test.ts b/nodejs/src/logs/metrics-rules/metric-rules.test.tsnew file mode 100644index 000000000000..c8e807f2d433--- /dev/null+++ b/nodejs/src/logs/metrics-rules/metric-rules.test.ts@@ -0,0 +1,197 @@+import type { LogRecord } from '../log-record-avro'+import { type MetricRuleRow, compileMetricRules } from './compile-metric-rules'+import { MAX_LABEL_SETS_PER_RULE, MAX_LABEL_VALUE_LENGTH, createBatchTallies, tallyRecords } from './tally'++const NOW_MS = 1_700_000_000_000++const record = (overrides: Partial<LogRecord> = {}): LogRecord => ({+ uuid: null,+ trace_id: null,+ span_id: null,+ trace_flags: null,+ timestamp: NOW_MS * 1000, // avro timestamp-micros+ observed_timestamp: null,+ body: 'hello',+ severity_text: 'ERROR',+ severity_number: 17,+ service_name: 'api',+ resource_attributes: { 'k8s.pod': 'pod-1' },+ instrumentation_scope: null,+ event_name: null,+ attributes: { 'http.status_code': '500', duration_ms: '12.5' },+ ...overrides,+})++const serviceFilterGroup = {+ type: 'AND',+ values: [+ {+ type: 'AND',+ values: [{ key: 'service.name', operator: 'exact', value: 'api', type: 'log_attribute' }],+ },+ ],+}++const ruleRow = (overrides: Partial<MetricRuleRow> = {}): MetricRuleRow => ({+ id: 'rule-1',+ metric_name: 'log.api_errors',+ filter_group: serviceFilterGroup,+ value_attribute: null,+ group_by: [],+ version: 1,+ ...overrides,+})++describe('metric rules compile + tally', () => {+ describe('compileMetricRules', () => {+ it('compiles a count rule and matches records through its filter group', () => {+ const rules = compileMetricRules([ruleRow()])+ expect(rules).toHaveLength(1)+ expect(rules[0]!.metricName).toBe('log.api_errors')+ expect(rules[0]!.valueAttribute).toBeNull()++ const tallies = createBatchTallies()+ tallyRecords(rules, [record(), record({ service_name: 'web' })], tallies, NOW_MS)+ const entries = [...tallies.byRule.get('rule-1')!.values()]+ expect(entries).toHaveLength(1)+ expect(entries[0]!.count).toBe(1)+ })++ it('treats null filter_group as match-all', () => {+ const rules = compileMetricRules([ruleRow({ filter_group: null })])+ const tallies = createBatchTallies()+ tallyRecords(rules, [record(), record({ service_name: 'web' })], tallies, NOW_MS)+ const entries = [...tallies.byRule.get('rule-1')!.values()]+ expect(entries[0]!.count).toBe(2)+ })++ it.each([+ ['non-group shape', { key: 'service.name' }],+ ['string', 'service.name = api'],+ ['array', [serviceFilterGroup]],+ ])('skips a rule whose filter_group is unparseable (%s) instead of matching all logs', (_label, fg) => {+ const rules = compileMetricRules([ruleRow({ filter_group: fg })])+ expect(rules).toHaveLength(0)+ })++ it('normalizes a non-array group_by to no grouping', () => {+ const rules = compileMetricRules([ruleRow({ group_by: 'severity_text' as unknown })])+ expect(rules[0]!.groupBy).toEqual([])+ })+ })++ describe('tallyRecords', () => {+ it('sums the numeric value attribute and skips non-numeric values', () => {+ const rules = compileMetricRules([+ ruleRow({ value_attribute: 'attributes.duration_ms', filter_group: null }),+ ])+ const tallies = createBatchTallies()+ tallyRecords(+ rules,+ [+ record(),+ record({ attributes: { duration_ms: '7.5' } }),+ record({ attributes: { duration_ms: 'not-a-number' } }),+ record({ attributes: {} }),+ ],+ tallies,+ NOW_MS+ )+ const entries = [...tallies.byRule.get('rule-1')!.values()]+ expect(entries).toHaveLength(1)+ expect(entries[0]!.count).toBe(2)+ expect(entries[0]!.sum).toBe(20)+ expect(tallies.valueSkipped).toBe(2)+ })++ it('resolves group-by labels, using empty string for missing keys and truncating long values', () => {+ const longValue = 'x'.repeat(MAX_LABEL_VALUE_LENGTH + 50)+ const rules = compileMetricRules([+ ruleRow({+ filter_group: null,+ group_by: ['severity_text', 'attributes.http.status_code', 'resource_attributes.missing'],+ }),+ ])+ const tallies = createBatchTallies()+ tallyRecords(rules, [record({ severity_text: longValue })], tallies, NOW_MS)+ const entries = [...tallies.byRule.get('rule-1')!.values()]+ expect(entries[0]!.labelValues).toEqual([longValue.slice(0, MAX_LABEL_VALUE_LENGTH), '500', ''])+ })++ it('accumulates records with identical label values into one entry', () => {+ const rules = compileMetricRules([ruleRow({ filter_group: null, group_by: ['severity_text'] })])+ const tallies = createBatchTallies()+ tallyRecords(rules, [record(), record(), record({ severity_text: 'INFO' })], tallies, NOW_MS)+ const ruleTallies = tallies.byRule.get('rule-1')!+ expect(ruleTallies.size).toBe(2)+ const counts = [...ruleTallies.values()].map((e) => e.count).sort()+ expect(counts).toEqual([1, 2])+ })++ it('skips records with timestamps older than the staleness window but keeps null timestamps', () => {+ const rules = compileMetricRules([ruleRow({ filter_group: null })])+ const tallies = createBatchTallies()+ const staleMicros = (NOW_MS - 21 * 60 * 1000) * 1000+ tallyRecords(+ rules,+ [record({ timestamp: staleMicros }), record({ timestamp: null }), record()],+ tallies,+ NOW_MS+ )+ const entries = [...tallies.byRule.get('rule-1')!.values()]+ expect(entries[0]!.count).toBe(2)+ })++ it('caps distinct label sets per rule and counts the overflow', () => {+ const rules = compileMetricRules([ruleRow({ filter_group: null, group_by: ['attributes.request_id'] })])+ const tallies = createBatchTallies()+ const records = Array.from({ length: MAX_LABEL_SETS_PER_RULE + 3 }, (_, i) =>+ record({ attributes: { request_id: `req-${i}` } })+ )+ tallyRecords(rules, records, tallies, NOW_MS)+ expect(tallies.byRule.get('rule-1')!.size).toBe(MAX_LABEL_SETS_PER_RULE)+ expect(tallies.seriesOverflow.get('rule-1')).toBe(3)+ })++ it('captures an exemplar trace id from a matching record and ignores zeroed trace ids', () => {+ const rules = compileMetricRules([ruleRow({ filter_group: null })])+ const tallies = createBatchTallies()+ tallyRecords(+ rules,+ [+ record({ trace_id: Buffer.alloc(16) }),+ record({ trace_id: Buffer.from('0123456789abcdef0123456789abcdef', 'hex') }),+ ],+ tallies,+ NOW_MS+ )+ const entries = [...tallies.byRule.get('rule-1')!.values()]+ expect(entries[0]!.exemplarTraceId).toBe('0123456789abcdef0123456789abcdef')+ })++ // capture-logs writes trace/span ids into the log Avro as base64 TEXT of the raw+ // bytes (observed in posthog.logs32), not the bytes themselves — an exemplar built+ // from the undecoded buffer is malformed and gets filtered by the metrics ingest.+ it('decodes base64-text trace ids (the on-disk log Avro format) and ignores zeroed ones', () => {+ const rules = compileMetricRules([ruleRow({ filter_group: null })])+ const tallies = createBatchTallies()+ const rawTrace = Buffer.from('0123456789abcdef0123456789abcdef', 'hex')+ const rawSpan = Buffer.from('1122334455667788', 'hex')+ tallyRecords(+ rules,+ [+ record({ trace_id: Buffer.from(Buffer.alloc(16).toString('base64'), 'ascii') }),+ record({+ trace_id: Buffer.from(rawTrace.toString('base64'), 'ascii'),+ span_id: Buffer.from(rawSpan.toString('base64'), 'ascii'),+ }),+ ],+ tallies,+ NOW_MS+ )+ const entries = [...tallies.byRule.get('rule-1')!.values()]+ expect(entries[0]!.exemplarTraceId).toBe('0123456789abcdef0123456789abcdef')+ expect(entries[0]!.exemplarSpanId).toBe('1122334455667788')+ })+ })+})diff --git a/nodejs/src/logs/metrics-rules/metrics-emitter.ts b/nodejs/src/logs/metrics-rules/metrics-emitter.tsnew file mode 100644index 000000000000..3ee396e7bd0f--- /dev/null+++ b/nodejs/src/logs/metrics-rules/metrics-emitter.ts@@ -0,0 +1,50 @@+import { Counter } from 'prom-client'++import { logger } from '~/common/utils/logger'+import { internalFetch } from '~/common/utils/request'++export const logsMetricRulesExportFailedCounter = new Counter({+ name: 'logs_metrics_rules_export_failed_total',+ help: 'OTLP export of log-generated metrics failed after retry; the flush window was dropped.',+ labelNames: ['team_id'],+})++const EXPORT_ATTEMPTS = 2++/**+ * POSTs log-generated metric payloads to the capture-logs OTLP metrics endpoint using+ * the team's own token, so the generated series flows through the exact same pipeline+ * (fingerprinting, quota, Kafka, ClickHouse) as customer-sent metrics.+ *+ * Best-effort by design: one retry, then the window's aggregates are dropped with a+ * counter — metric emission must never buffer unboundedly or block log ingestion.+ */+export class LogsMetricsEmitter {+ constructor(private readonly url: string) {}++ public async emit(token: string, teamId: number, payload: Record<string, unknown>): Promise<boolean> {+ const body = JSON.stringify(payload)+ for (let attempt = 1; attempt <= EXPORT_ATTEMPTS; attempt++) {+ try {+ const response = await internalFetch(this.url, {+ method: 'POST',+ headers: { Authorization: `Bearer ${token}`, 'Content-Type': 'application/json' },+ body,+ })+ await response.dump()+ if (response.status >= 200 && response.status < 300) {+ return true+ }+ logger.warn('[logs-metric-rules] OTLP export rejected', {+ teamId,+ status: response.status,+ attempt,+ })+ } catch (error) {+ logger.warn('[logs-metric-rules] OTLP export failed', { teamId, error: String(error), attempt })+ }+ }+ logsMetricRulesExportFailedCounter.inc({ team_id: String(teamId) })+ return false+ }+}diff --git a/nodejs/src/logs/metrics-rules/otlp-payload.test.ts b/nodejs/src/logs/metrics-rules/otlp-payload.test.tsnew file mode 100644index 000000000000..dc26419b4964--- /dev/null+++ b/nodejs/src/logs/metrics-rules/otlp-payload.test.ts@@ -0,0 +1,125 @@+import type { LogRecord } from '../log-record-avro'+import { compileMetricRules } from './compile-metric-rules'+import { buildMetricRulesOtlpPayload } from './otlp-payload'+import { createBatchTallies, tallyRecords } from './tally'++const NOW_MS = 1_700_000_000_123+// Snapped down to the enclosing 10s bucket, in nanos.+const SNAPPED_NANOS = '1700000000000000000'++const record = (overrides: Partial<LogRecord> = {}): LogRecord => ({+ uuid: null,+ trace_id: null,+ span_id: null,+ trace_flags: null,+ timestamp: NOW_MS * 1000,+ observed_timestamp: null,+ body: 'hello',+ severity_text: 'ERROR',+ severity_number: 17,+ service_name: 'api',+ resource_attributes: {},+ instrumentation_scope: null,+ event_name: null,+ attributes: { duration_ms: '12.5' },+ ...overrides,+})++const countRule = {+ id: 'rule-count',+ metric_name: 'log.api_errors',+ filter_group: null,+ value_attribute: null,+ group_by: ['severity_text'],+}++const distributionRule = {+ id: 'rule-dist',+ metric_name: 'log.request_duration',+ filter_group: null,+ value_attribute: 'attributes.duration_ms',+ group_by: [],+}++function build(rows: any[], records: LogRecord[]): any {+ const rules = compileMetricRules(rows)+ const tallies = createBatchTallies()+ tallyRecords(rules, records, tallies, NOW_MS)+ return buildMetricRulesOtlpPayload(rules, tallies, NOW_MS)+}++describe('buildMetricRulesOtlpPayload', () => {+ it('returns null when nothing was tallied', () => {+ expect(build([countRule], [])).toBeNull()+ })++ it('emits a count rule as a delta monotonic sum with 10s-snapped timestamps', () => {+ const payload = build([countRule], [record(), record(), record({ severity_text: 'INFO' })])+ const metrics = payload.resourceMetrics[0].scopeMetrics[0].metrics+ expect(metrics).toHaveLength(1)+ const sum = metrics[0].sum+ expect(metrics[0].name).toBe('log.api_errors')+ expect(sum.aggregationTemporality).toBe(1)+ expect(sum.isMonotonic).toBe(true)+ expect(sum.dataPoints).toHaveLength(2)++ const errorPoint = sum.dataPoints.find((dp: any) => dp.attributes[0].value.stringValue === 'ERROR')+ expect(errorPoint.attributes).toEqual([{ key: 'severity_text', value: { stringValue: 'ERROR' } }])+ expect(errorPoint.asDouble).toBe(2)+ expect(errorPoint.timeUnixNano).toBe(SNAPPED_NANOS)+ })++ it('emits a value-attribute rule as a delta histogram carrying count and sum', () => {+ const payload = build([distributionRule], [record(), record({ attributes: { duration_ms: '7.5' } })])+ const metric = payload.resourceMetrics[0].scopeMetrics[0].metrics[0]+ expect(metric.name).toBe('log.request_duration')+ expect(metric.histogram.aggregationTemporality).toBe(1)+ const dp = metric.histogram.dataPoints[0]+ expect(dp.count).toBe(2)+ expect(dp.sum).toBe(20)+ expect(dp.explicitBounds).toEqual([])+ expect(dp.bucketCounts).toEqual([2])+ expect(dp.timeUnixNano).toBe(SNAPPED_NANOS)+ })++ it('strips the attributes. prefix from group-by label names', () => {+ const payload = build(+ [{ ...countRule, group_by: ['attributes.http.status_code'] }],+ [record({ attributes: { 'http.status_code': '500' } })]+ )+ const dp = payload.resourceMetrics[0].scopeMetrics[0].metrics[0].sum.dataPoints[0]+ expect(dp.attributes).toEqual([{ key: 'http.status_code', value: { stringValue: '500' } }])+ })++ it('partitions service_name group-bys into per-service resource blocks with service.name', () => {+ const payload = build(+ [{ ...countRule, group_by: ['service_name'] }],+ [record(), record({ service_name: 'web' })]+ )+ expect(payload.resourceMetrics).toHaveLength(2)+ const services = payload.resourceMetrics+ .map((rm: any) => rm.resource.attributes[0])+ .map((attr: any) => {+ expect(attr.key).toBe('service.name')+ return attr.value.stringValue+ })+ .sort()+ expect(services).toEqual(['api', 'web'])+ for (const rm of payload.resourceMetrics) {+ const dp = rm.scopeMetrics[0].metrics[0].sum.dataPoints[0]+ expect(dp.asDouble).toBe(1)+ // service is carried on the resource, not duplicated as a data-point attribute+ expect(dp.attributes).toEqual([])+ }+ })++ it('attaches an exemplar with the matching record trace id', () => {+ const payload = build(+ [countRule],+ [record({ trace_id: Buffer.from('0123456789abcdef0123456789abcdef', 'hex') })]+ )+ const dp = payload.resourceMetrics[0].scopeMetrics[0].metrics[0].sum.dataPoints[0]+ expect(dp.exemplars).toHaveLength(1)+ expect(dp.exemplars[0].traceId).toBe('0123456789abcdef0123456789abcdef')+ })+})diff --git a/nodejs/src/logs/metrics-rules/otlp-payload.ts b/nodejs/src/logs/metrics-rules/otlp-payload.tsnew file mode 100644index 000000000000..4858def399a3--- /dev/null+++ b/nodejs/src/logs/metrics-rules/otlp-payload.ts@@ -0,0 +1,163 @@+import type { CompiledMetricRule } from './compile-metric-rules'+import type { BatchTallies, MetricTallyEntry } from './tally'++/**+ * Hand-built OTLP/JSON `ExportMetricsServiceRequest` for log-generated metrics.+ *+ * Wire shape follows what capture-logs parses (same conventions as+ * `~/common/metrics/otlp-json-exporter.ts`): camelCase fields, unix nanos as decimal+ * strings, proto enum value 1 for delta temporality, hex trace/span ids on exemplars.+ * The OTel SDK is not usable here — its meter provider is per-process with a single+ * resource and token, while these payloads are per-team with per-rule label sets.+ */++const SCOPE = { name: 'posthog/logs-metric-rules' }++/** Data points are stamped on 10-second boundaries, matching Datadog's log-based metric granularity. */+const TIME_BUCKET_MS = 10_000++const OTLP_TEMPORALITY_DELTA = 1++const ATTRIBUTE_PREFIXES = ['attributes.', 'resource_attributes.']++/** Label name as it appears on the emitted series: map keys lose their prefix (Datadog drops `@` the same way). */+function labelName(groupByKey: string): string {+ for (const prefix of ATTRIBUTE_PREFIXES) {+ if (groupByKey.startsWith(prefix)) {+ return groupByKey.slice(prefix.length)+ }+ }+ return groupByKey+}++function snapToBucketNanos(nowMs: number): bigint {+ return BigInt(Math.floor(nowMs / TIME_BUCKET_MS) * TIME_BUCKET_MS) * 1_000_000n+}++type RulePoints = { rule: CompiledMetricRule; entries: MetricTallyEntry[] }++export function buildMetricRulesOtlpPayload(+ rules: CompiledMetricRule[],+ tallies: BatchTallies,+ nowMs: number+): Record<string, unknown> | null {+ // Partition label sets by service value: `service_name` group-bys become the OTel+ // resource `service.name` (one resource block per service), so the emitted series+ // carries service identity in the same place every other metric producer puts it —+ // first-class `service_name` column, resource-scoped filters, stable fingerprints.+ const byService = new Map<string, Map<string, RulePoints>>()+ for (const rule of rules) {+ const ruleTallies = tallies.byRule.get(rule.id)+ if (!ruleTallies?.size) {+ continue+ }+ const serviceIndex = rule.groupBy.indexOf('service_name')+ for (const entry of ruleTallies.values()) {+ const service = serviceIndex >= 0 ? (entry.labelValues[serviceIndex] ?? '') : ''+ let ruleMap = byService.get(service)+ if (!ruleMap) {+ ruleMap = new Map()+ byService.set(service, ruleMap)+ }+ let points = ruleMap.get(rule.id)+ if (!points) {+ points = { rule, entries: [] }+ ruleMap.set(rule.id, points)+ }+ points.entries.push(entry)+ }+ }+ if (byService.size === 0) {+ return null+ }++ const timeNanos = snapToBucketNanos(nowMs)+ const timeUnixNano = timeNanos.toString()+ const startTimeUnixNano = (timeNanos - BigInt(TIME_BUCKET_MS) * 1_000_000n).toString()++ const resourceMetrics = [...byService.entries()].map(([service, ruleMap]) => ({+ resource: {+ attributes: service === '' ? [] : [{ key: 'service.name', value: { stringValue: service } }],+ },+ scopeMetrics: [+ {+ scope: SCOPE,+ metrics: [...ruleMap.values()].map(({ rule, entries }) =>+ serializeRuleMetric(rule, entries, startTimeUnixNano, timeUnixNano)+ ),+ },+ ],+ }))++ return { resourceMetrics }+}++function serializeRuleMetric(+ rule: CompiledMetricRule,+ entries: MetricTallyEntry[],+ startTimeUnixNano: string,+ timeUnixNano: string+): Record<string, unknown> {+ if (rule.valueAttribute) {+ return {+ name: rule.metricName,+ histogram: {+ dataPoints: entries.map((entry) => ({+ ...dataPointBase(rule, entry, startTimeUnixNano, timeUnixNano),+ count: entry.count,+ sum: entry.sum,+ // No percentile buckets yet: a single catch-all bucket keeps the shape a+ // valid OTLP histogram while carrying only count + sum.+ bucketCounts: [entry.count],+ explicitBounds: [],+ })),+ aggregationTemporality: OTLP_TEMPORALITY_DELTA,+ },+ }+ }+ return {+ name: rule.metricName,+ sum: {+ dataPoints: entries.map((entry) => ({+ ...dataPointBase(rule, entry, startTimeUnixNano, timeUnixNano),+ asDouble: entry.count,+ })),+ aggregationTemporality: OTLP_TEMPORALITY_DELTA,+ isMonotonic: true,+ },+ }+}++function dataPointBase(+ rule: CompiledMetricRule,+ entry: MetricTallyEntry,+ startTimeUnixNano: string,+ timeUnixNano: string+): Record<string, unknown> {+ const attributes: Record<string, unknown>[] = []+ for (let i = 0; i < rule.groupBy.length; i++) {+ const key = rule.groupBy[i]!+ if (key === 'service_name') {+ continue // carried on the resource block instead+ }+ attributes.push({ key: labelName(key), value: { stringValue: entry.labelValues[i] ?? '' } })+ }+ return {+ attributes,+ startTimeUnixNano,+ timeUnixNano,+ ...(entry.exemplarTraceId+ ? {+ exemplars: [+ {+ filteredAttributes: [],+ timeUnixNano,+ asDouble: rule.valueAttribute ? entry.sum : entry.count,+ traceId: entry.exemplarTraceId,+ ...(entry.exemplarSpanId ? { spanId: entry.exemplarSpanId } : {}),+ },+ ],+ }+ : {}),+ }+}diff --git a/nodejs/src/logs/metrics-rules/tally.ts b/nodejs/src/logs/metrics-rules/tally.tsnew file mode 100644index 000000000000..7a7c333c072e--- /dev/null+++ b/nodejs/src/logs/metrics-rules/tally.ts@@ -0,0 +1,172 @@+import type { LogRecord } from '../log-record-avro'+import { matchFilterGroup } from '../sampling/filter-group-match'+import type { CompiledMetricRule } from './compile-metric-rules'++/** Cap on distinct group-by label sets per rule per batch — bounds emitted series cardinality. */+export const MAX_LABEL_SETS_PER_RULE = 1000++export const MAX_LABEL_VALUE_LENGTH = 256++/**+ * Records with timestamps older than this never feed a metric, so a backfill of+ * historical logs cannot distort the "now" data point (matches Datadog's 20-minute+ * aggregation window for log-based metrics).+ */+export const MAX_RECORD_AGE_MS = 20 * 60 * 1000++export type MetricTallyEntry = {+ /** Group-by values in the rule's `groupBy` key order. */+ labelValues: string[]+ count: number+ sum: number+ exemplarTraceId: string | null+ exemplarSpanId: string | null+}++export type BatchTallies = {+ byRule: Map<string, Map<string, MetricTallyEntry>>+ /** Records that matched but were dropped because the rule hit MAX_LABEL_SETS_PER_RULE. */+ seriesOverflow: Map<string, number>+ /** Records that matched a value-attribute rule but carried a missing/non-numeric value. */+ valueSkipped: number+ /** Per-record filter evaluations that threw; the record is skipped for that rule only. */+ evalErrors: number+}++export function createBatchTallies(): BatchTallies {+ return { byRule: new Map(), seriesOverflow: new Map(), valueSkipped: 0, evalErrors: 0 }+}++const ATTRIBUTES_PREFIX = 'attributes.'+const RESOURCE_ATTRIBUTES_PREFIX = 'resource_attributes.'++function lookupKey(key: string, record: LogRecord): string | null | undefined {+ if (key === 'service_name') {+ return record.service_name+ }+ if (key === 'severity_text') {+ return record.severity_text+ }+ if (key === 'event_name') {+ return record.event_name+ }+ if (key.startsWith(ATTRIBUTES_PREFIX)) {+ return record.attributes?.[key.slice(ATTRIBUTES_PREFIX.length)]+ }+ if (key.startsWith(RESOURCE_ATTRIBUTES_PREFIX)) {+ return record.resource_attributes?.[key.slice(RESOURCE_ATTRIBUTES_PREFIX.length)]+ }+ return undefined+}++function resolveLabelValue(key: string, record: LogRecord): string {+ const value = lookupKey(key, record) ?? ''+ return value.length > MAX_LABEL_VALUE_LENGTH ? value.slice(0, MAX_LABEL_VALUE_LENGTH) : value+}++function resolveNumericValue(key: string, record: LogRecord): number | null {+ const raw = lookupKey(key, record)+ if (raw == null || raw === '') {+ return null+ }+ const parsed = parseFloat(raw)+ return Number.isFinite(parsed) ? parsed : null+}++/**+ * Normalizes a trace/span id from the log Avro into lowercase hex, or null when absent,+ * zeroed, or unparseable. capture-logs writes these fields as base64 TEXT of the raw+ * bytes (not the bytes themselves), so decode when the length doesn't match; raw-byte+ * buffers (tests, future producers) pass through unchanged.+ */+function idToHex(buffer: Buffer | null, expectedBytes: number): string | null {+ if (!buffer || buffer.length === 0) {+ return null+ }+ let bytes = buffer+ if (bytes.length !== expectedBytes) {+ const decoded = Buffer.from(bytes.toString('ascii'), 'base64')+ if (decoded.length !== expectedBytes) {+ return null+ }+ bytes = decoded+ }+ if (!bytes.some((byte) => byte !== 0)) {+ return null+ }+ return bytes.toString('hex')+}++/**+ * Evaluates every rule against every record and accumulates per-(rule, label set)+ * count/sum into `tallies`. Pure accumulation — no I/O, no clock reads (`nowMs` is+ * injected). Any single-record failure is contained: filter evaluation throwing or a+ * non-numeric value skips that record for that rule and increments a tally counter.+ */+export function tallyRecords(+ rules: CompiledMetricRule[],+ records: LogRecord[],+ tallies: BatchTallies,+ nowMs: number+): void {+ if (rules.length === 0 || records.length === 0) {+ return+ }+ for (const record of records) {+ // timestamp is 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) {+ continue+ }+ for (const rule of rules) {+ let matches = true+ if (rule.filterGroup) {+ try {+ matches = matchFilterGroup(rule.filterGroup, record)+ } catch {+ tallies.evalErrors+++ continue+ }+ }+ if (!matches) {+ continue+ }+ let value = 1+ if (rule.valueAttribute) {+ const parsed = resolveNumericValue(rule.valueAttribute, record)+ if (parsed == null) {+ tallies.valueSkipped+++ continue+ }+ value = parsed+ }++ const labelValues = rule.groupBy.map((key) => resolveLabelValue(key, record))+ const labelKey = JSON.stringify(labelValues)++ let ruleTallies = tallies.byRule.get(rule.id)+ if (!ruleTallies) {+ ruleTallies = new Map()+ tallies.byRule.set(rule.id, ruleTallies)+ }+ let entry = ruleTallies.get(labelKey)+ if (!entry) {+ if (ruleTallies.size >= MAX_LABEL_SETS_PER_RULE) {+ tallies.seriesOverflow.set(rule.id, (tallies.seriesOverflow.get(rule.id) ?? 0) + 1)+ continue+ }+ entry = { labelValues, count: 0, sum: 0, exemplarTraceId: null, exemplarSpanId: null }+ ruleTallies.set(labelKey, entry)+ }+ entry.count += 1+ entry.sum += value+ if (!entry.exemplarTraceId) {+ const traceIdHex = idToHex(record.trace_id, 16)+ if (traceIdHex) {+ entry.exemplarTraceId = traceIdHex+ entry.exemplarSpanId = idToHex(record.span_id, 8)+ }+ }+ }+ }+}diff --git a/nodejs/src/logs/sampling/compile-rules.ts b/nodejs/src/logs/sampling/compile-rules.tsindex 4ea4b81a0a15..e85a86b70358 100644--- a/nodejs/src/logs/sampling/compile-rules.ts+++ b/nodejs/src/logs/sampling/compile-rules.ts@@ -12,6 +12,13 @@ import { type PropertyFilterLeaf, compileLeafRegex } from './property-filter-mat*/export const MAX_FILTER_GROUP_NODES = 256+/**+ * Aggregate cap on leaf filter values (a value array counts as its length).+ * Kept in sync with `MAX_FILTER_GROUP_LEAF_VALUES` in+ * `products/logs/backend/presentation/filter_group_validation.py`.+ */+export const MAX_FILTER_GROUP_LEAF_VALUES = 256+export type SamplingRuleRow = {id: stringrule_type: string@@ -105,7 +112,7 @@ function parseRateLimitFromConfig(* Earlier shapes may have stored the bare inner group. Accept either; reject* anything that doesn't look like a group.*/-function parseFilterGroup(raw: unknown): FilterGroupNode | null {+export function parseFilterGroup(raw: unknown): FilterGroupNode | null {if (!raw || typeof raw !== 'object') {return null}@@ -139,6 +146,12 @@ function parseFilterGroup(raw: unknown): FilterGroupNode | null {if (filterGroupNodeCount(parsed) > MAX_FILTER_GROUP_NODES) {return null}+ // And bound leaf VALUES — one `exact`/`in` leaf carrying a huge value array+ // is a single node but costs O(values) per record in matchExact. Matches+ // MAX_FILTER_GROUP_LEAF_VALUES in filter_group_validation.py.+ if (filterGroupLeafValueCount(parsed) > MAX_FILTER_GROUP_LEAF_VALUES) {+ return null+ }// Walk the tree once and stamp pre-compiled regex onto each regex leaf so// the per-record hot path doesn't allocate a fresh `RegExp` per match.// Legacy `pathDropPatterns` already follow this pattern; this brings the@@ -147,6 +160,24 @@ function parseFilterGroup(raw: unknown): FilterGroupNode | null {return parsed}+function filterGroupLeafValueCount(node: FilterGroupNode | PropertyFilterLeaf): number {+ const maybe = node as { type?: unknown; values?: unknown; value?: unknown }+ if (!Array.isArray(maybe.values) || (maybe.type !== 'AND' && maybe.type !== 'OR')) {+ if (Array.isArray(maybe.value)) {+ return maybe.value.length+ }+ return maybe.value === undefined || maybe.value === null ? 0 : 1+ }+ let total = 0+ for (const child of maybe.values as Array<FilterGroupNode | PropertyFilterLeaf>) {+ total += filterGroupLeafValueCount(child)+ if (total > MAX_FILTER_GROUP_LEAF_VALUES) {+ return total+ }+ }+ return total+}+function filterGroupNodeCount(node: FilterGroupNode | PropertyFilterLeaf): number {const maybe = node as { type?: unknown; values?: unknown }if (!Array.isArray(maybe.values) || (maybe.type !== 'AND' && maybe.type !== 'OR')) {diff --git a/nodejs/src/logs/sampling/evaluate.test.ts b/nodejs/src/logs/sampling/evaluate.test.tsindex 45e7e3c58420..ef408b8dd22c 100644--- a/nodejs/src/logs/sampling/evaluate.test.ts+++ b/nodejs/src/logs/sampling/evaluate.test.ts@@ -463,6 +463,33 @@ describe('evaluateLogRecord', () => {expect(evaluateLogRecord(rules, rec).decision).not.toBe(SAMPLING_DECISION_DROP)})+ it('filter_group with one leaf carrying too many values is dropped at compile time', () => {+ // A single `in` leaf with a huge value array is one node, but matchExact+ // scans the whole array per record. Matches MAX_FILTER_GROUP_LEAF_VALUES+ // in compile-rules.ts.+ const hugeLeaf = {+ key: 'service.name',+ operator: 'exact',+ value: Array.from({ length: 300 }, (_, i) => `svc-${i}`),+ }+ const rules = compileRuleSet([+ {+ id: 'oversize-values',+ rule_type: 'path_drop',+ scope_service: null,+ scope_path_pattern: null,+ scope_attribute_filters: [],+ config: {+ patterns: [],+ filter_group: wrap({ type: 'AND', values: [hugeLeaf] }),+ },+ },+ ])+ const rec = baseRecord()+ rec.service_name = 'svc-1'+ expect(evaluateLogRecord(rules, rec).decision).not.toBe(SAMPLING_DECISION_DROP)+ })+it('classifySamplingRecord drops via filter_group match', () => {const rules = compileRuleSet([{diff --git a/nodejs/src/logs/sampling/logs-sampling.service.ts b/nodejs/src/logs/sampling/logs-sampling.service.tsindex ff645d8900f7..6494061215f6 100644--- a/nodejs/src/logs/sampling/logs-sampling.service.ts+++ b/nodejs/src/logs/sampling/logs-sampling.service.ts@@ -114,13 +114,17 @@ export class LogsSamplingService {settings: LogsSettings,ruleSet: CompiledRuleSet,teamId?: number,- headerBytesUncompressed: number = 0+ headerBytesUncompressed: number = 0,+ onRecordsDecoded?: (records: LogRecord[]) => void): Promise<ProcessBufferWithSamplingResult> {const [logRecordType, compressionCodec, records] = await decodeLogRecords(buffer)if (!logRecordType) {throw new Error('avro schema metadata not found')}const pii = await transformDecodedLogRecordsInPlace(records, settings)+ // Metric-rule extraction sees every record post-PII-scrub and pre-drop-rules:+ // dropping a log must not stop it from feeding a generated metric.+ onRecordsDecoded?.(records)const kept: LogRecord[] = []let recordsDropped = 0const recordsDroppedByRuleId = new Map<string, number>()diff --git a/nodejs/src/servers/ingestion-logs-server.ts b/nodejs/src/servers/ingestion-logs-server.tsindex 85e8c2486216..bb99b81bd7ef 100644--- a/nodejs/src/servers/ingestion-logs-server.ts+++ b/nodejs/src/servers/ingestion-logs-server.ts@@ -12,6 +12,8 @@ import {getDefaultLogsIngestionOutputsConfig,} from '~/logs/config'import { LogsIngestionConsumer } from '~/logs/logs-ingestion-consumer'+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,@@ -101,6 +103,14 @@ export class IngestionLogsServer implements NodeServer {const teamManager = new TeamManager(this.postgres)const quotaLimiting = new QuotaLimiting(this.posthogRedisPool, teamManager)const samplingRulesCache = new SamplingRulesCache(this.postgres)+ // Metric rules are inert without an export URL — the consumer also gates on+ // LOGS_METRICS_RULES_ENABLED_TEAMS and the killswitch per team.+ const metricRulesCache = this.config.LOGS_METRICS_RULES_EXPORT_URL+ ? new MetricRulesCache(this.postgres)+ : undefined+ const metricsEmitter = this.config.LOGS_METRICS_RULES_EXPORT_URL+ ? new LogsMetricsEmitter(this.config.LOGS_METRICS_RULES_EXPORT_URL)+ : undefined// 2. Resolve outputs (topic + producer per logical name, env-controlled)const outputs = createLogsOutputsRegistry().build(this.producerRegistry, this.config)@@ -114,6 +124,8 @@ export class IngestionLogsServer implements NodeServer {quotaLimiting,outputs,samplingRulesCache,+ metricRulesCache,+ metricsEmitter,})await consumer.start()return consumer.service