: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): add retention rule observability metrics (#80564)
Frank Hamandd4673a58acba
diff --git a/nodejs/src/logs/retention/retention-rules-cache.test.ts b/nodejs/src/logs/retention/retention-rules-cache.test.tsindex 042437f74131..ed46b5e1d569 100644--- a/nodejs/src/logs/retention/retention-rules-cache.test.ts+++ b/nodejs/src/logs/retention/retention-rules-cache.test.ts@@ -1,6 +1,11 @@import { PostgresRouter } from '~/common/utils/db/postgres'-import { RetentionRulesCache } from './retention-rules-cache'+import { RetentionRulesCache, logsRetentionRulesDroppedCounter } from './retention-rules-cache'++async function droppedCount(teamId: string): Promise<number> {+ const metric = await logsRetentionRulesDroppedCounter.get()+ return metric.values.find((v) => v.labels.team_id === teamId)?.value ?? 0+}describe('RetentionRulesCache', () => {let query: jest.Mock@@ -25,6 +30,16 @@ describe('RetentionRulesCache', () => {expect(compiled.rules).toEqual([{ id: 'r1', filterGroup: null, retentionDays: 30 }])})+ it('surfaces rules discarded at compile via the dropped counter', async () => {+ // 45 is not a valid retention tier, so compile discards the row: the rule is enabled and+ // fetched but never stamped — the counter is the only signal of that silent drop.+ query.mockResolvedValueOnce(rows(45))+ const before = await droppedCount('7')+ const compiled = await cache.getCompiledRuleSet(7)+ expect(compiled.rules).toEqual([])+ expect((await droppedCount('7')) - before).toBe(1)+ })+it('fails open to no rules when the fetch throws and nothing is cached', async () => {query.mockRejectedValueOnce(new Error('pg down'))const compiled = await cache.getCompiledRuleSet(1)diff --git a/nodejs/src/logs/retention/retention-rules-cache.ts b/nodejs/src/logs/retention/retention-rules-cache.tsindex 2aa3e450d432..fe947f3bcc8c 100644--- a/nodejs/src/logs/retention/retention-rules-cache.ts+++ b/nodejs/src/logs/retention/retention-rules-cache.ts@@ -1,4 +1,5 @@import { trace } from '@opentelemetry/api'+import { Counter } from 'prom-client'import { instrumentFn } from '~/common/tracing/tracing-utils'import { PostgresRouter, PostgresUse } from '~/common/utils/db/postgres'@@ -9,6 +10,18 @@ import type { CompiledRetentionRuleSet } from './evaluate-retention'const REFRESH_MS = 30_000+/**+ * Enabled rules fetched from Postgres that `compileRetentionRuleSet` discarded — a `retention_days`+ * outside the valid tiers or otherwise malformed config. A non-zero value for a team explains the+ * "rule saved but ignored" symptom that is otherwise silent (the row exists and is enabled, yet no+ * per-row retention is stamped).+ */+export const logsRetentionRulesDroppedCounter = new Counter({+ name: 'logs_ingestion_retention_rules_dropped_total',+ help: 'Enabled retention rules fetched but discarded at compile time (invalid retention_days tier or malformed config).',+ labelNames: ['team_id'],+})+const retentionCacheInstrumentOpts = { measureTime: false, sendException: false } as consttype CacheEntry = {@@ -60,6 +73,15 @@ export class RetentionRulesCache {return existing?.compiled ?? compileRetentionRuleSet([])}const compiled = compileRetentionRuleSet(rows)+ const droppedCount = rows.length - compiled.rules.length+ if (droppedCount > 0) {+ logsRetentionRulesDroppedCounter.inc({ team_id: String(teamId) }, droppedCount)+ logger.warn('[logs-retention] enabled rules discarded at compile — check retention_days tier', {+ teamId,+ fetched: rows.length,+ dropped: droppedCount,+ })+ }const vw = rows.reduce((m, r) => Math.max(m, r.version ?? 0), 0)this.cache.set(teamId, { compiled, versionWatermark: vw, fetchedAtMs: now })trace.getActiveSpan()?.setAttributes({diff --git a/nodejs/src/logs/retention/retention-stage.test.ts b/nodejs/src/logs/retention/retention-stage.test.tsindex 136dfbf4dab3..96e3f1ead1e8 100644--- a/nodejs/src/logs/retention/retention-stage.test.ts+++ b/nodejs/src/logs/retention/retention-stage.test.ts@@ -2,7 +2,12 @@ import type { LogRecord } from '~/logs/log-record-avro'import { runPipelineStages } from '~/logs/pipeline/log-processing-pipeline'import { compileRetentionRuleSet } from './compile-retention-rules'-import { makeRetentionStage } from './retention-stage'+import { logsRetentionRowsStampedCounter, makeRetentionStage } from './retention-stage'++async function stampedCount(teamId: string, matched: 'true' | 'false'): Promise<number> {+ const metric = await logsRetentionRowsStampedCounter.get()+ return metric.values.find((v) => v.labels.team_id === teamId && v.labels.matched === matched)?.value ?? 0+}describe('makeRetentionStage', () => {const record = (service: string): LogRecord => ({@@ -44,9 +49,12 @@ describe('makeRetentionStage', () => {const ruleSet = compileRetentionRuleSet([serviceRule('a', 'api', 30)])const { kept } = await runPipelineStages([record('api'), record('billing')],- [makeRetentionStage(ruleSet, 1, 14)]+ [makeRetentionStage(ruleSet, 4242, 14)])// 'api' matches the 30-day rule; 'billing' matches nothing so it takes the team default.expect(kept.map((r) => r.retention_days)).toEqual([30, 14])+ // The counter split mirrors matching: one rule-matched row, one team-default row.+ expect(await stampedCount('4242', 'true')).toBe(1)+ expect(await stampedCount('4242', 'false')).toBe(1)})})diff --git a/nodejs/src/logs/retention/retention-stage.ts b/nodejs/src/logs/retention/retention-stage.tsindex 53f462fb9c99..336024622b54 100644--- a/nodejs/src/logs/retention/retention-stage.ts+++ b/nodejs/src/logs/retention/retention-stage.ts@@ -1,7 +1,21 @@+import { Counter } from 'prom-client'+import type { PipelineStage } from '~/logs/pipeline/log-processing-pipeline'import { type CompiledRetentionRuleSet, safeEvaluateRetentionDays } from './evaluate-retention'+/**+ * Rows stamped with a per-row retention value, split by `matched`: `true` when a rule matched the+ * row, `false` when no rule matched and the team default was applied. A team whose rules are working+ * shows `matched="true"` traffic; a team seeing only `matched="false"` has rules that never match;+ * no traffic at all means the stage never ran (rule disabled, not fetched, or gating off).+ */+export const logsRetentionRowsStampedCounter = new Counter({+ name: 'logs_ingestion_retention_rows_stamped_total',+ help: 'Log rows stamped with a per-row retention value, labelled by whether a rule matched (matched=true) or the team default was applied (matched=false).',+ labelNames: ['team_id', 'matched'],+})+/*** Per-row retention `mutate` stage. Runs last in the pipeline (after sampling and hog transforms) so* it only stamps surviving records: `retention_days = firstMatchingRule ?? defaultRetentionDays`.@@ -17,8 +31,22 @@ export function makeRetentionStage(kind: 'mutate',name: 'retention',run: (records) => {+ let matchedCount = 0for (const record of records) {- record.retention_days = safeEvaluateRetentionDays(ruleSet, record, teamId) ?? defaultRetentionDays+ const ruleValue = safeEvaluateRetentionDays(ruleSet, record, teamId)+ record.retention_days = ruleValue ?? defaultRetentionDays+ if (ruleValue !== null) {+ matchedCount+++ }+ }+ // One increment per batch (not per record) to keep the hot path cheap.+ const teamLabel = String(teamId)+ if (matchedCount > 0) {+ logsRetentionRowsStampedCounter.inc({ team_id: teamLabel, matched: 'true' }, matchedCount)+ }+ const defaultCount = records.length - matchedCount+ if (defaultCount > 0) {+ logsRetentionRowsStampedCounter.inc({ team_id: teamLabel, matched: 'false' }, defaultCount)}},}