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): stamp per-row retention as a pipeline stage (#77338)

Frank Hamandca88c074a622
diff --git a/nodejs/src/logs/config.ts b/nodejs/src/logs/config.ts
index 7f70e2d33068..555a2f48e448 100644
--- a/nodejs/src/logs/config.ts
+++ b/nodejs/src/logs/config.ts
@@ -61,6 +61,10 @@ export type LogsIngestionConsumerConfig = {
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
+ /** Comma-separated team IDs, or `*` for all teams, or empty to disable per-row retention rule evaluation entirely. */
+ LOGS_RETENTION_ENABLED_TEAMS: string
+ /** When `true`, retention rules are never evaluated (rows keep the team default via the batch header). */
+ LOGS_RETENTION_KILLSWITCH: boolean
/**
* 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
@@ -109,6 +113,9 @@ export function getDefaultLogsIngestionConsumerConfig(): LogsIngestionConsumerCo
LOGS_METRICS_RULES_ENABLED_TEAMS: isProdEnv() ? '' : '*',
LOGS_METRICS_RULES_KILLSWITCH: false,
LOGS_METRICS_RULES_EXPORT_URL: '',
+ // Off in prod until per-team rollout; on in dev for local end-to-end testing.
+ LOGS_RETENTION_ENABLED_TEAMS: isProdEnv() ? '' : '*',
+ LOGS_RETENTION_KILLSWITCH: false,
LOGS_BILLING_PRORATE_ENABLED: false,
LOGS_TRANSFORMATIONS_ENABLED_TEAMS: '',
LOGS_TRANSFORMATIONS_KILLSWITCH: false,
diff --git a/nodejs/src/logs/log-record-avro.ts b/nodejs/src/logs/log-record-avro.ts
index a63de2f73da9..1aa2112e7308 100644
--- a/nodejs/src/logs/log-record-avro.ts
+++ b/nodejs/src/logs/log-record-avro.ts
@@ -50,6 +50,9 @@ export interface LogRecord {
event_name: string | null
attributes: Record<string, string> | null
bytes_uncompressed?: number | null
+ /** Per-row retention in days, stamped by the retention stage from team retention rules. Null/undefined
+ * leaves ClickHouse to fall back to the batch `retention-days` header (the team default). */
+ retention_days?: number | null
}
export async function decodeLogRecords(buffer: Buffer): Promise<[avro.Type | undefined, string, LogRecord[]]> {
diff --git a/nodejs/src/logs/logs-ingestion-consumer.ts b/nodejs/src/logs/logs-ingestion-consumer.ts
index 5ac4738bab38..2f26447f90c7 100644
--- a/nodejs/src/logs/logs-ingestion-consumer.ts
+++ b/nodejs/src/logs/logs-ingestion-consumer.ts
@@ -34,6 +34,9 @@ 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 { EMPTY_DROP_STATS, type PipelineStage } from './pipeline/log-processing-pipeline'
+import type { CompiledRetentionRuleSet } from './retention/evaluate-retention'
+import { RetentionRulesCache } from './retention/retention-rules-cache'
+import { makeRetentionStage } from './retention/retention-stage'
import type { CompiledRuleSet } from './sampling/evaluate'
import { LogsSamplingService } from './sampling/logs-sampling.service'
import { SamplingRulesCache } from './sampling/sampling-rules-cache'
@@ -52,6 +55,8 @@ export interface LogsIngestionConsumerDeps {
metricsEmitter?: LogsMetricsEmitter
/** When set, enabled teams run hog log transformations after the built-in processing. */
logsTransformer?: LogsTransformerService
+ /** When set, enabled teams stamp per-row retention from retention rules before produce. */
+ retentionRulesCache?: RetentionRulesCache
/**
* Resolved outputs registry — must include `LOGS_OUTPUT`, `LOGS_DLQ_OUTPUT`,
* and `APP_METRICS_OUTPUT`. The producer + topic for each is wired by the
@@ -302,6 +307,8 @@ export class LogsIngestionConsumer {
private readonly metricRulesKillswitch: boolean
private readonly transformationsEnabledTeamsRaw: string
private readonly transformationsKillswitch: boolean
+ private readonly retentionEnabledTeamsRaw: string
+ private readonly retentionKillswitch: boolean
protected groupId: string
protected topic: string
@@ -349,6 +356,8 @@ export class LogsIngestionConsumer {
this.metricRulesKillswitch = mergedConfig.LOGS_METRICS_RULES_KILLSWITCH
this.transformationsEnabledTeamsRaw = mergedConfig.LOGS_TRANSFORMATIONS_ENABLED_TEAMS
this.transformationsKillswitch = mergedConfig.LOGS_TRANSFORMATIONS_KILLSWITCH
+ this.retentionEnabledTeamsRaw = mergedConfig.LOGS_RETENTION_ENABLED_TEAMS
+ this.retentionKillswitch = mergedConfig.LOGS_RETENTION_KILLSWITCH
}
private isSamplingEvalEnabledForTeam(teamId: number): boolean {
@@ -358,6 +367,13 @@ export class LogsIngestionConsumer {
return teamIdMatchesCsv(this.samplingEnabledTeamsRaw, teamId)
}
+ private isRetentionEvalEnabledForTeam(teamId: number): boolean {
+ if (this.retentionKillswitch) {
+ return false
+ }
+ return teamIdMatchesCsv(this.retentionEnabledTeamsRaw, teamId)
+ }
+
private isMetricRulesEnabledForTeam(teamId: number): boolean {
if (this.metricRulesKillswitch || !this.deps.metricRulesCache || !this.deps.metricsEmitter) {
return false
@@ -432,9 +448,22 @@ export class LogsIngestionConsumer {
const useSamplingPipeline = Boolean(ruleSet && ruleSet.rules.length > 0)
const recordsTransform = await this.buildRecordsTransform(message, batchBudget)
- // Assemble the ordered decode → transform → encode pipeline: sampling drop rules + rate
- // limits first, hog transformations last. An empty list (with no metric visitor) leaves the
- // buffer as a no-decode passthrough inside `processLogMessageBuffer`.
+ // Per-row retention: resolve the team's retention rules when enabled. Any matching rule stamps
+ // `retention_days` per surviving record (falling back to the team default), which ClickHouse
+ // reads in place of the batch `retention-days` header. With no rules the header — still emitted
+ // below — carries the team default, keeping this a no-decode passthrough.
+ const retentionCache = this.deps.retentionRulesCache
+ const retentionEvalEnabled = this.isRetentionEvalEnabledForTeam(message.teamId)
+ let retentionRuleSet: CompiledRetentionRuleSet | null = null
+ if (retentionCache && retentionEvalEnabled) {
+ retentionRuleSet = await retentionCache.getCompiledRuleSet(message.teamId)
+ }
+ const useRetention = Boolean(retentionRuleSet && retentionRuleSet.rules.length > 0)
+
+ // Assemble the ordered decode → transform → encode pipeline: sampling drop rules + rate limits
+ // first, hog transformations next, per-row retention stamping last (so it only stamps
+ // survivors). An empty list (with no metric visitor) leaves the buffer as a no-decode passthrough
+ // inside `processLogMessageBuffer`.
const stages: PipelineStage[] = []
if (useSamplingPipeline && ruleSet) {
stages.push(this.samplingService.makeSamplingStage(ruleSet, message.teamId, message.bytesUncompressed))
@@ -442,6 +471,10 @@ export class LogsIngestionConsumer {
if (recordsTransform) {
stages.push(makeTransformStage(recordsTransform))
}
+ if (useRetention && retentionRuleSet) {
+ const defaultRetentionDays = logsSettings.retention_days ?? DEFAULT_LOGS_RETENTION_DAYS
+ stages.push(makeRetentionStage(retentionRuleSet, message.teamId, defaultRetentionDays))
+ }
trace.getActiveSpan()?.setAttributes({
'logs.sampling.killswitch': this.samplingKillswitch,
@@ -451,6 +484,10 @@ export class LogsIngestionConsumer {
'logs.sampling.eval_enabled_for_team': samplingEvalEnabled,
'logs.sampling.compiled_rule_count': ruleSet?.rules.length ?? 0,
'logs.transformations.enabled_for_team': Boolean(recordsTransform),
+ 'logs.retention.cache_present': Boolean(retentionCache),
+ 'logs.retention.eval_enabled_for_team': retentionEvalEnabled,
+ 'logs.retention.compiled_rule_count': retentionRuleSet?.rules.length ?? 0,
+ 'logs.retention.use_retention': useRetention,
'logs.sampling.pipeline': useSamplingPipeline
? 'decode_sample_encode'
: recordsTransform
diff --git a/nodejs/src/logs/retention/compile-retention-rules.ts b/nodejs/src/logs/retention/compile-retention-rules.ts
new file mode 100644
index 000000000000..ee56c78df31a
--- /dev/null
+++ b/nodejs/src/logs/retention/compile-retention-rules.ts
@@ -0,0 +1,40 @@
+import { parseFilterGroup } from '../sampling/compile-rules'
+import { type CompiledRetentionRule, type CompiledRetentionRuleSet, VALID_RETENTION_DAYS } from './evaluate-retention'
+
+/**
+ * Defensive cap on enabled retention rules compiled (and thus scanned per record) for one team.
+ * `evaluateRetentionDays` runs O(rules × filter-nodes) for every log line on the shared ingestion
+ * worker, so an unbounded rule set is a cross-team DoS vector. The fetch also applies this as a SQL
+ * `LIMIT`; keeping first-match order (priority ASC, created_at ASC) means the cap keeps the
+ * highest-priority rules. This is a worker-protection backstop independent of any product-facing
+ * maximum the API may enforce at write time.
+ */
+export const MAX_ENABLED_RETENTION_RULES = 100
+
+export type RetentionRuleRow = {
+ id: string
+ config: Record<string, unknown>
+ /** Row version from DB; used by the cache watermark only, ignored by compileRetentionRuleSet. */
+ version?: number
+}
+
+export function compileRetentionRuleSet(rows: RetentionRuleRow[]): CompiledRetentionRuleSet {
+ const rules: CompiledRetentionRule[] = []
+ for (const row of rows.slice(0, MAX_ENABLED_RETENTION_RULES)) {
+ const config = row.config ?? {}
+ const retentionDays = config.retention_days
+ // Skip rows the API validator would have rejected — robustness against legacy or
+ // hand-crafted rows. A `true` boolean is not accepted (typeof true === 'boolean').
+ if (typeof retentionDays !== 'number' || !Number.isInteger(retentionDays)) {
+ continue
+ }
+ if (!VALID_RETENTION_DAYS.has(retentionDays)) {
+ continue
+ }
+ // parseFilterGroup bounds depth/breadth and pre-compiles regex leaves; returns null for
+ // a missing/malformed group, which evaluateRetentionDays treats as match-nothing.
+ const filterGroup = parseFilterGroup(config.filter_group)
+ rules.push({ id: row.id, filterGroup, retentionDays })
+ }
+ return { rules }
+}
diff --git a/nodejs/src/logs/retention/evaluate-retention.test.ts b/nodejs/src/logs/retention/evaluate-retention.test.ts
new file mode 100644
index 000000000000..3606db2b77c8
--- /dev/null
+++ b/nodejs/src/logs/retention/evaluate-retention.test.ts
@@ -0,0 +1,80 @@
+import type { LogRecord } from '~/logs/log-record-avro'
+
+import { MAX_ENABLED_RETENTION_RULES, compileRetentionRuleSet } from './compile-retention-rules'
+import { evaluateRetentionDays, safeEvaluateRetentionDays } from './evaluate-retention'
+
+describe('logs retention rules', () => {
+ const record = (overrides: Partial<LogRecord> = {}): LogRecord => ({
+ uuid: null,
+ trace_id: null,
+ span_id: null,
+ trace_flags: null,
+ timestamp: null,
+ observed_timestamp: null,
+ body: 'x',
+ severity_text: 'info',
+ severity_number: 9,
+ service_name: 'api',
+ resource_attributes: null,
+ instrumentation_scope: null,
+ event_name: null,
+ attributes: null,
+ ...overrides,
+ })
+
+ const serviceRule = (id: string, service: string, retentionDays: number) => ({
+ id,
+ config: {
+ retention_days: retentionDays,
+ filter_group: {
+ type: 'AND',
+ values: [
+ {
+ type: 'AND',
+ values: [
+ { key: 'service.name', type: 'log_resource_attribute', operator: 'exact', value: service },
+ ],
+ },
+ ],
+ },
+ },
+ })
+
+ it('returns the first matching rule in priority order', () => {
+ // Rows arrive pre-ordered by priority; a later rule also matching must not win.
+ const ruleSet = compileRetentionRuleSet([serviceRule('a', 'api', 90), serviceRule('b', 'api', 30)])
+ expect(evaluateRetentionDays(ruleSet, record({ service_name: 'api' }))).toBe(90)
+ })
+
+ it('returns null when no rule matches so the caller applies the team default', () => {
+ const ruleSet = compileRetentionRuleSet([serviceRule('a', 'billing', 90)])
+ expect(evaluateRetentionDays(ruleSet, record({ service_name: 'api' }))).toBeNull()
+ })
+
+ it('drops rows whose retention_days is not an allowed tier', () => {
+ const ruleSet = compileRetentionRuleSet([serviceRule('a', 'api', 45), serviceRule('b', 'api', 30)])
+ expect(ruleSet.rules).toHaveLength(1)
+ expect(evaluateRetentionDays(ruleSet, record({ service_name: 'api' }))).toBe(30)
+ })
+
+ it('ignores a rule with a missing filter_group (matches nothing)', () => {
+ const ruleSet = compileRetentionRuleSet([{ id: 'a', config: { retention_days: 30 } }])
+ expect(evaluateRetentionDays(ruleSet, record({ service_name: 'api' }))).toBeNull()
+ })
+
+ it('caps compiled rules at MAX_ENABLED_RETENTION_RULES to bound per-record work', () => {
+ const rows = Array.from({ length: MAX_ENABLED_RETENTION_RULES + 50 }, (_, i) =>
+ serviceRule(`r${i}`, `svc${i}`, 30)
+ )
+ expect(compileRetentionRuleSet(rows).rules).toHaveLength(MAX_ENABLED_RETENTION_RULES)
+ })
+
+ it('fails open to null when evaluation throws', () => {
+ const poisoned = { rules: [{ id: 'a', retentionDays: 30, filterGroup: {} as any }] }
+ const spy = jest.spyOn(require('../sampling/filter-group-match'), 'matchFilterGroup').mockImplementation(() => {
+ throw new Error('boom')
+ })
+ expect(safeEvaluateRetentionDays(poisoned as any, record(), 1)).toBeNull()
+ spy.mockRestore()
+ })
+})
diff --git a/nodejs/src/logs/retention/evaluate-retention.ts b/nodejs/src/logs/retention/evaluate-retention.ts
new file mode 100644
index 000000000000..c029e9995dbe
--- /dev/null
+++ b/nodejs/src/logs/retention/evaluate-retention.ts
@@ -0,0 +1,68 @@
+import { Counter } from 'prom-client'
+
+import { logger } from '~/common/utils/logger'
+import type { LogRecord } from '~/logs/log-record-avro'
+
+import { type FilterGroupNode, matchFilterGroup } from '../sampling/filter-group-match'
+
+/**
+ * Retention tiers a rule may assign. Kept in sync with `VALID_RETENTION_DAYS` in
+ * `products/logs/backend/presentation/views/retention_api.py` (write-time validation) and
+ * `RETENTION_USAGE_TIERS` in `logs-ingestion-consumer.ts`. Rows outside these tiers are
+ * dropped at compile time so a hand-crafted or legacy row can't stamp an arbitrary value.
+ */
+export const VALID_RETENTION_DAYS = new Set([14, 30, 90])
+
+export type CompiledRetentionRule = {
+ id: string
+ /** Selector for the logs this rule applies to. A rule with a null group matches nothing. */
+ filterGroup: FilterGroupNode | null
+ retentionDays: number
+}
+
+export type CompiledRetentionRuleSet = {
+ rules: CompiledRetentionRule[]
+}
+
+/**
+ * Incremented when a per-record retention evaluation throws. The record falls back to the
+ * team default (fail-open) so a malformed rule can never break ingestion, but the counter
+ * makes the silent failure observable.
+ */
+export const logsRetentionEvalErrorCounter = new Counter({
+ name: 'logs_ingestion_retention_eval_error_total',
+ help: 'Per-record retention evaluation threw an exception; record fell back to the team default (fail-open).',
+ labelNames: ['team_id'],
+})
+
+/**
+ * First matching rule (rules are pre-ordered by priority ASC, created_at ASC) sets the
+ * record's retention. Returns null when no rule matches — the caller then applies the team
+ * default. A rule with a null filterGroup matches nothing: never silently override retention
+ * for all traffic (the API requires an explicit filter_group).
+ */
+export function evaluateRetentionDays(ruleSet: CompiledRetentionRuleSet | null, record: LogRecord): number | null {
+ if (!ruleSet || ruleSet.rules.length === 0) {
+ return null
+ }
+ for (const rule of ruleSet.rules) {
+ if (rule.filterGroup && matchFilterGroup(rule.filterGroup, record)) {
+ return rule.retentionDays
+ }
+ }
+ return null
+}
+
+export function safeEvaluateRetentionDays(
+ ruleSet: CompiledRetentionRuleSet | null,
+ record: LogRecord,
+ teamId: number
+): number | null {
+ try {
+ return evaluateRetentionDays(ruleSet, record)
+ } catch (err) {
+ logsRetentionEvalErrorCounter.inc({ team_id: String(teamId) })
+ logger.warn('[logs-retention] evaluateRetentionDays threw — falling back to team default', { teamId, err })
+ return null
+ }
+}
diff --git a/nodejs/src/logs/retention/retention-rules-cache.test.ts b/nodejs/src/logs/retention/retention-rules-cache.test.ts
new file mode 100644
index 000000000000..042437f74131
--- /dev/null
+++ b/nodejs/src/logs/retention/retention-rules-cache.test.ts
@@ -0,0 +1,43 @@
+import { PostgresRouter } from '~/common/utils/db/postgres'
+
+import { RetentionRulesCache } from './retention-rules-cache'
+
+describe('RetentionRulesCache', () => {
+ let query: jest.Mock
+ let cache: RetentionRulesCache
+
+ const rows = (retentionDays: number): { rows: { id: string; config: unknown; version: string }[] } => ({
+ rows: [{ id: 'r1', config: { retention_days: retentionDays }, version: '1' }],
+ })
+
+ beforeEach(() => {
+ query = jest.fn()
+ cache = new RetentionRulesCache({ query } as unknown as PostgresRouter)
+ })
+
+ afterEach(() => {
+ jest.restoreAllMocks()
+ })
+
+ it('compiles rules fetched from Postgres', async () => {
+ query.mockResolvedValueOnce(rows(30))
+ const compiled = await cache.getCompiledRuleSet(1)
+ expect(compiled.rules).toEqual([{ id: 'r1', filterGroup: null, retentionDays: 30 }])
+ })
+
+ 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)
+ expect(compiled.rules).toEqual([])
+ })
+
+ it('serves the last-known rules when a later refresh throws', async () => {
+ query.mockResolvedValueOnce(rows(30))
+ await cache.getCompiledRuleSet(1)
+
+ jest.spyOn(Date, 'now').mockReturnValue(Date.now() + 60_000)
+ query.mockRejectedValueOnce(new Error('pg down'))
+ const stale = await cache.getCompiledRuleSet(1)
+ expect(stale.rules).toEqual([{ id: 'r1', filterGroup: null, retentionDays: 30 }])
+ })
+})
diff --git a/nodejs/src/logs/retention/retention-rules-cache.ts b/nodejs/src/logs/retention/retention-rules-cache.ts
new file mode 100644
index 000000000000..2aa3e450d432
--- /dev/null
+++ b/nodejs/src/logs/retention/retention-rules-cache.ts
@@ -0,0 +1,97 @@
+import { trace } from '@opentelemetry/api'
+
+import { instrumentFn } from '~/common/tracing/tracing-utils'
+import { PostgresRouter, PostgresUse } from '~/common/utils/db/postgres'
+import { logger } from '~/common/utils/logger'
+
+import { MAX_ENABLED_RETENTION_RULES, type RetentionRuleRow, compileRetentionRuleSet } from './compile-retention-rules'
+import type { CompiledRetentionRuleSet } from './evaluate-retention'
+
+const REFRESH_MS = 30_000
+
+const retentionCacheInstrumentOpts = { measureTime: false, sendException: false } as const
+
+type CacheEntry = {
+ compiled: CompiledRetentionRuleSet
+ versionWatermark: number
+ fetchedAtMs: number
+}
+
+export class RetentionRulesCache {
+ private cache = new Map<number, CacheEntry>()
+
+ constructor(private postgres: PostgresRouter) {}
+
+ public async getCompiledRuleSet(teamId: number): Promise<CompiledRetentionRuleSet> {
+ return instrumentFn(
+ {
+ key: 'logsIngestion.retention.getCompiledRuleSet',
+ ...retentionCacheInstrumentOpts,
+ getLoggingContext: () => ({ team_id: teamId }),
+ },
+ async () => {
+ const now = Date.now()
+ const existing = this.cache.get(teamId)
+ if (existing && now - existing.fetchedAtMs < REFRESH_MS) {
+ trace.getActiveSpan()?.setAttributes({
+ 'logs.retention.cache_hit': true,
+ 'logs.retention.rule_count': existing.compiled.rules.length,
+ 'logs.retention.version_watermark': existing.versionWatermark,
+ })
+ return existing.compiled
+ }
+ let rows: RetentionRuleRow[]
+ try {
+ rows = await this.fetchRules(teamId)
+ } catch (error) {
+ // Fail open: this runs in the ingestion hot path, so a rules-fetch failure
+ // (e.g. a Postgres blip) must never propagate and DLQ otherwise-valid logs.
+ // Serve the last-known compiled rules when we have them; otherwise fall back to
+ // no rules so the caller applies the team default via the batch `retention-days`
+ // header. The stale `fetchedAtMs` means the next message retries the fetch.
+ logger.warn('[logs-retention] rules fetch failed — falling back', {
+ teamId,
+ error: String(error),
+ })
+ trace.getActiveSpan()?.setAttributes({
+ 'logs.retention.fetch_failed': true,
+ 'logs.retention.served_stale': Boolean(existing),
+ })
+ return existing?.compiled ?? compileRetentionRuleSet([])
+ }
+ const compiled = compileRetentionRuleSet(rows)
+ 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({
+ 'logs.retention.cache_hit': false,
+ 'logs.retention.db_row_count': rows.length,
+ 'logs.retention.rule_count': compiled.rules.length,
+ 'logs.retention.version_watermark': vw,
+ })
+ return compiled
+ }
+ )
+ }
+
+ private async fetchRules(teamId: number): Promise<RetentionRuleRow[]> {
+ const res = await this.postgres.query<{
+ id: string
+ config: Record<string, unknown>
+ version: string
+ }>(
+ PostgresUse.COMMON_READ,
+ `SELECT id::text AS id, config, version
+ FROM logs_logsretentionrule
+ WHERE team_id = $1 AND enabled = true
+ ORDER BY priority ASC, created_at ASC
+ LIMIT ${MAX_ENABLED_RETENTION_RULES}`,
+ [teamId],
+ 'logs-retention-rules-fetch'
+ )
+ return res.rows.map((r) => ({
+ id: r.id,
+ config: r.config ?? {},
+ version: parseInt(r.version, 10) || 0,
+ }))
+ }
+}
diff --git a/nodejs/src/logs/retention/retention-stage.test.ts b/nodejs/src/logs/retention/retention-stage.test.ts
new file mode 100644
index 000000000000..136dfbf4dab3
--- /dev/null
+++ b/nodejs/src/logs/retention/retention-stage.test.ts
@@ -0,0 +1,52 @@
+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'
+
+describe('makeRetentionStage', () => {
+ const record = (service: string): LogRecord => ({
+ uuid: null,
+ trace_id: null,
+ span_id: null,
+ trace_flags: null,
+ timestamp: null,
+ observed_timestamp: null,
+ body: 'x',
+ severity_text: 'info',
+ severity_number: 9,
+ service_name: service,
+ resource_attributes: null,
+ instrumentation_scope: null,
+ event_name: null,
+ attributes: null,
+ })
+
+ const serviceRule = (id: string, service: string, retentionDays: number) => ({
+ id,
+ config: {
+ retention_days: retentionDays,
+ filter_group: {
+ type: 'AND',
+ values: [
+ {
+ type: 'AND',
+ values: [
+ { key: 'service.name', type: 'log_resource_attribute', operator: 'exact', value: service },
+ ],
+ },
+ ],
+ },
+ },
+ })
+
+ it('stamps the matched rule value and the team default on non-matching records', async () => {
+ const ruleSet = compileRetentionRuleSet([serviceRule('a', 'api', 30)])
+ const { kept } = await runPipelineStages(
+ [record('api'), record('billing')],
+ [makeRetentionStage(ruleSet, 1, 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])
+ })
+})
diff --git a/nodejs/src/logs/retention/retention-stage.ts b/nodejs/src/logs/retention/retention-stage.ts
new file mode 100644
index 000000000000..53f462fb9c99
--- /dev/null
+++ b/nodejs/src/logs/retention/retention-stage.ts
@@ -0,0 +1,25 @@
+import type { PipelineStage } from '~/logs/pipeline/log-processing-pipeline'
+
+import { type CompiledRetentionRuleSet, safeEvaluateRetentionDays } from './evaluate-retention'
+
+/**
+ * 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`.
+ * ClickHouse reads the per-row value and falls back to the batch `retention-days` header when it is
+ * absent, so stamping the team default here keeps mixed and unmatched rows consistent.
+ */
+export function makeRetentionStage(
+ ruleSet: CompiledRetentionRuleSet,
+ teamId: number,
+ defaultRetentionDays: number
+): PipelineStage {
+ return {
+ kind: 'mutate',
+ name: 'retention',
+ run: (records) => {
+ for (const record of records) {
+ record.retention_days = safeEvaluateRetentionDays(ruleSet, record, teamId) ?? defaultRetentionDays
+ }
+ },
+ }
+}
diff --git a/nodejs/src/servers/ingestion-logs-server.ts b/nodejs/src/servers/ingestion-logs-server.ts
index 1da804a65969..cd75b7be13e1 100644
--- a/nodejs/src/servers/ingestion-logs-server.ts
+++ b/nodejs/src/servers/ingestion-logs-server.ts
@@ -24,6 +24,7 @@ import {
getDefaultKafkaWarpstreamLogsProducerEnvConfig,
} from '~/logs/outputs/producers'
import { createLogsOutputsRegistry } from '~/logs/outputs/registry'
+import { RetentionRulesCache } from '~/logs/retention/retention-rules-cache'
import { SamplingRulesCache } from '~/logs/sampling/sampling-rules-cache'
import { LogsTransformerService } from '~/logs/transformations/logs-transformer.service'
@@ -125,6 +126,7 @@ export class IngestionLogsServer implements NodeServer {
const metricsEmitter = this.config.LOGS_METRICS_RULES_EXPORT_URL
? new LogsMetricsEmitter(this.config.LOGS_METRICS_RULES_EXPORT_URL)
: undefined
+ const retentionRulesCache = new RetentionRulesCache(this.postgres)
// 2. Resolve outputs (topic + producer per logical name, env-controlled)
const outputs = createLogsOutputsRegistry().build(this.producerRegistry, this.config)
@@ -160,6 +162,7 @@ export class IngestionLogsServer implements NodeServer {
metricRulesCache,
metricsEmitter,
logsTransformer,
+ retentionRulesCache,
})
await consumer.start()
return consumer.service