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): wire hog log transformations into logs ingestion (default off) (#75142)

Daniel Visca39d88e3605e5
diff --git a/nodejs/src/logs/config.ts b/nodejs/src/logs/config.ts
index 93ebff2b02e0..14ced98593f5 100644
--- a/nodejs/src/logs/config.ts
+++ b/nodejs/src/logs/config.ts
@@ -4,6 +4,7 @@ import {
KAFKA_LOGS_INGESTION,
KAFKA_LOGS_INGESTION_DLQ,
KAFKA_LOGS_INGESTION_OVERFLOW,
+ KAFKA_LOG_ENTRIES,
KAFKA_TRACES_CLICKHOUSE,
KAFKA_TRACES_INGESTION,
KAFKA_TRACES_INGESTION_DLQ,
@@ -16,6 +17,8 @@ import { LogsProducerName, WARPSTREAM_INGESTION_PRODUCER, WARPSTREAM_LOGS_PRODUC
export type LogsIngestionOutputsConfig = {
LOGS_INGESTION_OUTPUT_APP_METRICS_TOPIC: string
LOGS_INGESTION_OUTPUT_APP_METRICS_PRODUCER: LogsProducerName
+ LOGS_INGESTION_OUTPUT_LOG_ENTRIES_TOPIC: string
+ LOGS_INGESTION_OUTPUT_LOG_ENTRIES_PRODUCER: LogsProducerName
LOGS_INGESTION_OUTPUT_LOGS_PRODUCER: LogsProducerName
LOGS_INGESTION_OUTPUT_DLQ_PRODUCER: LogsProducerName
}
@@ -24,6 +27,8 @@ export function getDefaultLogsIngestionOutputsConfig(): LogsIngestionOutputsConf
return {
LOGS_INGESTION_OUTPUT_APP_METRICS_TOPIC: KAFKA_APP_METRICS_2,
LOGS_INGESTION_OUTPUT_APP_METRICS_PRODUCER: WARPSTREAM_INGESTION_PRODUCER,
+ LOGS_INGESTION_OUTPUT_LOG_ENTRIES_TOPIC: KAFKA_LOG_ENTRIES,
+ LOGS_INGESTION_OUTPUT_LOG_ENTRIES_PRODUCER: WARPSTREAM_INGESTION_PRODUCER,
LOGS_INGESTION_OUTPUT_LOGS_PRODUCER: WARPSTREAM_LOGS_PRODUCER,
LOGS_INGESTION_OUTPUT_DLQ_PRODUCER: WARPSTREAM_LOGS_PRODUCER,
}
@@ -63,6 +68,21 @@ export type LogsIngestionConsumerConfig = {
* (shadow mode) — billing is unchanged.
*/
LOGS_BILLING_PRORATE_ENABLED: boolean
+ /** Comma-separated team IDs, or `*` for all teams, or empty (default) to disable hog log transformations entirely. */
+ LOGS_TRANSFORMATIONS_ENABLED_TEAMS: string
+ /** When `true`, hog log transformations are skipped regardless of the allowlist. */
+ LOGS_TRANSFORMATIONS_KILLSWITCH: boolean
+ /** Hard per-record HogVM kill in milliseconds. */
+ LOGS_TRANSFORMATIONS_HOG_TIMEOUT_MS: number
+ /** Cumulative HogVM time budget per Kafka message; exhaustion skips remaining records (fail-open). */
+ LOGS_TRANSFORMATIONS_MESSAGE_BUDGET_MS: number
+ /** Cumulative HogVM time budget per consumer batch; bounds worst-case added batch latency. */
+ LOGS_TRANSFORMATIONS_BATCH_BUDGET_MS: number
+ /** Max failed invocations whose logs are captured, per function per message. */
+ LOGS_TRANSFORMATIONS_MAX_ERROR_LOGS_PER_FUNCTION: number
+ /** Fraction of messages (0–1) on which HogWatcher state is read and aggregate VM cost reported.
+ * 0 (default) keeps the watcher fully dormant — no Redis traffic. */
+ LOGS_TRANSFORMATIONS_HOG_WATCHER_SAMPLE_RATE: number
REDIS_URL: string
REDIS_POOL_MIN_SIZE: number
REDIS_POOL_MAX_SIZE: number
@@ -93,6 +113,15 @@ export function getDefaultLogsIngestionConsumerConfig(): LogsIngestionConsumerCo
LOGS_METRICS_RULES_KILLSWITCH: false,
LOGS_METRICS_RULES_EXPORT_URL: '',
LOGS_BILLING_PRORATE_ENABLED: false,
+ LOGS_TRANSFORMATIONS_ENABLED_TEAMS: '',
+ LOGS_TRANSFORMATIONS_KILLSWITCH: false,
+ LOGS_TRANSFORMATIONS_HOG_TIMEOUT_MS: 10,
+ // A regex-heavy scrub measured ~95µs/record (see transformations/benchmarks/);
+ // 100ms covers one such function over a full ~1,100-record message.
+ LOGS_TRANSFORMATIONS_MESSAGE_BUDGET_MS: 100,
+ LOGS_TRANSFORMATIONS_BATCH_BUDGET_MS: 2000,
+ LOGS_TRANSFORMATIONS_MAX_ERROR_LOGS_PER_FUNCTION: 3,
+ LOGS_TRANSFORMATIONS_HOG_WATCHER_SAMPLE_RATE: 0,
// 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/log-record-avro.test.ts b/nodejs/src/logs/log-record-avro.test.ts
index f4ec5d430f81..46df7cae8888 100644
--- a/nodejs/src/logs/log-record-avro.test.ts
+++ b/nodejs/src/logs/log-record-avro.test.ts
@@ -429,7 +429,7 @@ describe('log-record-avro', () => {
const inputBuffer = await encodeLogRecords(LOG_RECORD_SCHEMA, 'zstandard', records)
const { value: outputBuffer, pii } = await processLogMessageBuffer(inputBuffer, { json_parse_logs: true })
expect(pii).toEqual({ piiReplacements: 0 })
- const [_, __, decoded] = await decodeLogRecords(outputBuffer)
+ const [_, __, decoded] = await decodeLogRecords(outputBuffer!)
expect(decoded[0]?.attributes).toEqual({
level: '\"info\"',
@@ -478,7 +478,7 @@ describe('log-record-avro', () => {
const inputBuffer = await encodeLogRecords(LOG_RECORD_SCHEMA, 'zstandard', records)
const { value: outputBuffer, pii } = await processLogMessageBuffer(inputBuffer, { json_parse_logs: true })
expect(pii).toEqual({ piiReplacements: 0 })
- const [_, __, decoded] = await decodeLogRecords(outputBuffer)
+ const [_, __, decoded] = await decodeLogRecords(outputBuffer!)
expect(decoded).toHaveLength(2)
expect(decoded[0]?.attributes).toEqual({
@@ -551,7 +551,7 @@ describe('log-record-avro', () => {
expect(outputBuffer).not.toBe(inputBuffer)
expect(pii.piiReplacements).toBeGreaterThanOrEqual(1)
- const [_, __, decoded] = await decodeLogRecords(outputBuffer)
+ const [_, __, decoded] = await decodeLogRecords(outputBuffer!)
expect(decoded[0]?.attributes).toBeNull()
const body = parseJSON(decoded[0]?.body || '{}') as { message?: string }
expect(body.message).not.toContain('example.com')
@@ -585,7 +585,7 @@ describe('log-record-avro', () => {
pii_scrub_logs: true,
})
expect(pii.piiReplacements).toBe(1)
- const [_, __, decoded] = await decodeLogRecords(outputBuffer)
+ const [_, __, decoded] = await decodeLogRecords(outputBuffer!)
expect(decoded[0]?.body).toBe('plain')
expect(decoded[0]?.attributes).toEqual({ note: PII_REDACTED })
})
@@ -617,7 +617,7 @@ describe('log-record-avro', () => {
pii_scrub_logs: true,
})
expect(pii.piiReplacements).toBe(2)
- const [_, __, decoded] = await decodeLogRecords(outputBuffer)
+ const [_, __, decoded] = await decodeLogRecords(outputBuffer!)
expect(decoded[0]?.attributes).toEqual({
level: encodeAttributeCell('info'),
message: encodeAttributeCell(PII_REDACTED),
@@ -733,7 +733,7 @@ describe('log-record-avro', () => {
pii_scrub_logs: true,
})
expect(pii).toEqual({ piiReplacements: 0 })
- const [_, __, decoded] = await decodeLogRecords(outputBuffer)
+ const [_, __, decoded] = await decodeLogRecords(outputBuffer!)
const body = parseJSON(decoded[0]?.body || '{}') as { meta: { api_key: string }; ok: string }
// Body is pattern-scrubbed only; nested JSON keys are not redacted by key name.
expect(body.meta.api_key).toBe('leak-value')
@@ -782,7 +782,7 @@ describe('log-record-avro', () => {
const inputBuffer = await encodeLogRecords(LOG_RECORD_SCHEMA, 'zstandard', records)
const { value: outputBuffer, pii } = await processLogMessageBuffer(inputBuffer, { json_parse_logs: true })
expect(pii).toEqual({ piiReplacements: 0 })
- const [_, __, decoded] = await decodeLogRecords(outputBuffer)
+ const [_, __, decoded] = await decodeLogRecords(outputBuffer!)
expect(Object.keys(decoded[0]?.attributes || {}).length).toBe(50)
})
diff --git a/nodejs/src/logs/log-record-avro.ts b/nodejs/src/logs/log-record-avro.ts
index 931ed4ed33fe..65d628fb266a 100644
--- a/nodejs/src/logs/log-record-avro.ts
+++ b/nodejs/src/logs/log-record-avro.ts
@@ -290,13 +290,22 @@ export async function transformDecodedLogRecordsInPlace(
return pii
}
+/** Applied to decoded records after the built-in transforms; mutates the array in place
+ * (dropped records are removed). Used to run hog log transformations last. */
+export type LogRecordsTransform = (records: LogRecord[]) => Promise<unknown>
+
/**
* Processes an AVRO-encoded log message buffer containing multiple records.
- * Passthrough (no decode) when both json_parse_logs and pii_scrub_logs are off.
- * Otherwise: decode → optional PII scrub on `body` → optional parse bodies → optional JSON enrich → encode.
+ * Passthrough (no decode) when json_parse_logs and pii_scrub_logs are off and no
+ * `recordsTransform` is given.
+ * Otherwise: decode → optional PII scrub on `body` → optional parse bodies → optional JSON enrich
+ * → optional `recordsTransform` (hog log transformations, always last) → encode.
*
* When both `json_parse_logs` and `pii_scrub_logs` are on, scrub runs **before** parse/enrich so flattened JSON
* attributes are derived from the redacted body string. `parseLogBodiesForIngestion` runs only when JSON parse is on.
+ *
+ * `value` is null when `recordsTransform` dropped every record — the caller must not
+ * produce the message downstream.
*/
export const processLogMessageBuffer = instrumented({
key: SPAN_LOGS_PROCESS_BUFFER,
@@ -304,12 +313,13 @@ export const processLogMessageBuffer = instrumented({
})(async function processLogMessageBufferImpl(
buffer: Buffer,
settings: LogsSettings,
- onRecordsDecoded?: (records: LogRecord[]) => void
-): Promise<{ value: Buffer; pii: PiiScrubStats }> {
+ onRecordsDecoded?: (records: LogRecord[]) => void,
+ recordsTransform?: LogRecordsTransform
+): Promise<{ value: Buffer | null; pii: PiiScrubStats }> {
const jsonParse = settings.json_parse_logs ?? false
const piiScrub = settings.pii_scrub_logs ?? false
- if (!jsonParse && !piiScrub) {
+ if (!jsonParse && !piiScrub && !recordsTransform) {
// 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) {
@@ -333,6 +343,13 @@ export const processLogMessageBuffer = instrumented({
const pii = await transformDecodedLogRecordsInPlace(records, settings)
onRecordsDecoded?.(records)
+ if (recordsTransform) {
+ await recordsTransform(records)
+ if (records.length === 0) {
+ return { value: null, pii }
+ }
+ }
+
const value = await encodeLogRecordsInstrumented(logRecordType, codec, records)
return { value, pii }
} finally {
@@ -348,5 +365,6 @@ export const processLogMessageBuffer = instrumented({
}) as (
buffer: Buffer,
settings: LogsSettings,
- onRecordsDecoded?: (records: LogRecord[]) => void
-) => Promise<{ value: Buffer; pii: PiiScrubStats }>
+ onRecordsDecoded?: (records: LogRecord[]) => void,
+ recordsTransform?: LogRecordsTransform
+) => Promise<{ value: Buffer | null; pii: PiiScrubStats }>
diff --git a/nodejs/src/logs/logs-ingestion-consumer.test.ts b/nodejs/src/logs/logs-ingestion-consumer.test.ts
index 595ac6856e4a..ed33618b6704 100644
--- a/nodejs/src/logs/logs-ingestion-consumer.test.ts
+++ b/nodejs/src/logs/logs-ingestion-consumer.test.ts
@@ -10,6 +10,8 @@ import {
import { DateTime } from 'luxon'
import { Message } from 'node-rdkafka'
+import { compileHog } from '~/cdp/templates/compiler'
+import { HogFunctionType } from '~/cdp/types'
import { KAFKA_APP_METRICS_2, KAFKA_LOGS_CLICKHOUSE, KAFKA_LOGS_INGESTION_DLQ } from '~/common/config/kafka-topics'
import { APP_METRICS_OUTPUT, AppMetricsOutput } from '~/common/outputs'
import { IngestionOutputs } from '~/common/outputs/ingestion-outputs'
@@ -23,8 +25,9 @@ import { createTeam, getFirstTeam, getTeam, resetTestDatabase } from '~/tests/he
import { Hub, Team } from '~/types'
import { getDefaultTracesIngestionConsumerConfig } from './config'
+import * as otelMetrics from './ingestion-otel-metrics'
import { resetLogsIngestionInstrumentsForTests } from './ingestion-otel-metrics'
-import { LogRecord, encodeLogRecords } from './log-record-avro'
+import { LogRecord, decodeLogRecords, encodeLogRecords } from './log-record-avro'
import {
DEFAULT_LOGS_RETENTION_DAYS,
LogsIngestionConsumer,
@@ -48,6 +51,7 @@ import { compileRuleSet } from './sampling/compile-rules'
import type { SamplingRulesCache } from './sampling/sampling-rules-cache'
import { BASE_REDIS_KEY } from './services/logs-rate-limiter.service'
import { TracesIngestionConsumer } from './traces-ingestion-consumer'
+import { LogsTransformerService } from './transformations/logs-transformer.service'
const DEFAULT_TEST_TIMEOUT = 5000
jest.setTimeout(DEFAULT_TEST_TIMEOUT)
@@ -192,12 +196,16 @@ describe('LogsIngestionConsumer', () => {
let team2: Team
let fixedTime: DateTime
let logMessageDroppedCounterSpy: jest.SpyInstance
+ let recordLogMessageDroppedSpy: jest.SpyInstance
const createLogsIngestionConsumer = async (
hub: Hub,
overrides: any = {},
depsPartial: Partial<
- Pick<LogsIngestionConsumerDeps, 'samplingRulesCache' | 'metricRulesCache' | 'metricsEmitter'>
+ Pick<
+ LogsIngestionConsumerDeps,
+ 'samplingRulesCache' | 'metricRulesCache' | 'metricsEmitter' | 'logsTransformer'
+ >
> = {}
) => {
const consumer = new LogsIngestionConsumer(
@@ -258,6 +266,7 @@ describe('LogsIngestionConsumer', () => {
await deleteKeysWithPrefix(consumer['redis'], BASE_REDIS_KEY)
logMessageDroppedCounterSpy = jest.spyOn(logMessageDroppedCounter, 'inc')
+ recordLogMessageDroppedSpy = jest.spyOn(otelMetrics, 'recordLogMessageDropped')
// Default to not quota limited - tests can override this
jest.spyOn(hub.quotaLimiting, 'isTeamTokenQuotaLimited').mockResolvedValue(false)
@@ -2153,4 +2162,155 @@ describe('LogsIngestionConsumer', () => {
expect(limiterConfig.LOGS_LIMITER_REFILL_RATE_KB_PER_SECOND).toBe(7)
})
})
+
+ describe('hog log transformations', () => {
+ let transformerConsumer: LogsIngestionConsumer
+
+ const buildTransformer = async (hog: string): Promise<LogsTransformerService> => {
+ const fn = {
+ id: '00000000-0000-0000-0000-000000000001',
+ team_id: team.id,
+ name: 'Test log transformation',
+ type: 'transformation_log',
+ enabled: true,
+ bytecode: await compileHog(hog),
+ inputs: {},
+ encrypted_inputs: null,
+ execution_order: 1,
+ created_at: new Date().toISOString(),
+ } as unknown as HogFunctionType
+ const manager = {
+ getHogFunctionsForTeams: jest.fn().mockResolvedValue({ [team.id]: [fn] }),
+ getHogFunctionIdsForTeams: jest.fn().mockResolvedValue({ [team.id]: [fn.id] }),
+ }
+ const monitoring = { queueAppMetric: jest.fn(), queueLogs: jest.fn(), flush: jest.fn() }
+ return new LogsTransformerService(manager as any, monitoring as any, {
+ siteUrl: 'http://localhost:8010',
+ hogTimeoutMs: 10,
+ messageBudgetMs: 100,
+ batchBudgetMs: 2000,
+ maxErrorLogsPerFunctionPerMessage: 3,
+ hogWatcherSampleRate: 0,
+ })
+ }
+
+ afterEach(async () => {
+ await transformerConsumer?.stop()
+ })
+
+ it('applies an enabled transformation to produced records', async () => {
+ const logsTransformer = await buildTransformer(`
+ let rec := record
+ rec.body := replaceAll(rec.body, 'sensitive', '[REDACTED]')
+ return rec
+ `)
+ transformerConsumer = await createLogsIngestionConsumer(
+ hub,
+ { LOGS_TRANSFORMATIONS_ENABLED_TEAMS: '*' },
+ { logsTransformer }
+ )
+
+ const messages = await createKafkaMessages([createLogMessage({ message: 'something sensitive here' })], {
+ token: team.api_token,
+ })
+ await waitForBackgroundTasks(transformerConsumer.processKafkaBatch(messages))
+
+ const logsMessages = getProducedKafkaMessages().filter((m) => m.topic === 'clickhouse_logs_test')
+ expect(logsMessages).toHaveLength(1)
+ const [, , records] = await decodeLogRecords(logsMessages[0].value as Buffer)
+ expect(records).toHaveLength(1)
+ expect(records[0].body).toContain('[REDACTED]')
+ expect(records[0].body).not.toContain('sensitive')
+ })
+
+ it('does not produce a message when transformations drop every record', async () => {
+ const logsTransformer = await buildTransformer(`return null`)
+ transformerConsumer = await createLogsIngestionConsumer(
+ hub,
+ { LOGS_TRANSFORMATIONS_ENABLED_TEAMS: '*' },
+ { logsTransformer }
+ )
+
+ const messages = await createKafkaMessages([createLogMessage()], { token: team.api_token })
+ await waitForBackgroundTasks(transformerConsumer.processKafkaBatch(messages))
+
+ const logsMessages = getProducedKafkaMessages().filter((m) => m.topic === 'clickhouse_logs_test')
+ expect(logsMessages).toHaveLength(0)
+ expect(logMessageDroppedCounterSpy).toHaveBeenCalledWith(
+ { reason: 'transformations_all_dropped', team_id: team.id.toString() },
+ 1
+ )
+ // The OTel counter has to carry the same reason as the Prometheus one above —
+ // they were allowed to disagree, so a transformations drop read as sampling.
+ expect(recordLogMessageDroppedSpy).toHaveBeenCalledWith('transformations_all_dropped', team.id.toString())
+ })
+
+ it('attributes the full-message drop to transformations when sampling kept survivors', async () => {
+ const logsTransformer = await buildTransformer(`return null`)
+ // Drop rule that does not match the record, so sampling keeps it and the
+ // transformation is what removes the last survivor.
+ const mockSamplingCache: Pick<SamplingRulesCache, 'getCompiledRuleSet'> = {
+ getCompiledRuleSet: () =>
+ Promise.resolve(
+ compileRuleSet([
+ {
+ id: '00000000-0000-0000-0000-0000000000ab',
+ rule_type: 'severity_sampling',
+ scope_service: 'test-service',
+ scope_path_pattern: null,
+ scope_attribute_filters: [],
+ config: { actions: { INFO: { type: 'drop' } } },
+ },
+ ])
+ ),
+ }
+ transformerConsumer = await createLogsIngestionConsumer(
+ hub,
+ { LOGS_TRANSFORMATIONS_ENABLED_TEAMS: '*' },
+ { logsTransformer, samplingRulesCache: mockSamplingCache as SamplingRulesCache }
+ )
+
+ const messages = await createKafkaMessages([createLogMessage({ level: 'error' })], {
+ token: team.api_token,
+ })
+ await waitForBackgroundTasks(transformerConsumer.processKafkaBatch(messages))
+
+ const logsMessages = getProducedKafkaMessages().filter((m) => m.topic === 'clickhouse_logs_test')
+ expect(logsMessages).toHaveLength(0)
+ expect(logMessageDroppedCounterSpy).toHaveBeenCalledWith(
+ { reason: 'transformations_all_dropped', team_id: team.id.toString() },
+ 1
+ )
+ })
+
+ it('does not run transformations when the team is not in the allowlist', async () => {
+ const logsTransformer = await buildTransformer(`return null`)
+ transformerConsumer = await createLogsIngestionConsumer(
+ hub,
+ { LOGS_TRANSFORMATIONS_ENABLED_TEAMS: '' },
+ { logsTransformer }
+ )
+
+ const messages = await createKafkaMessages([createLogMessage()], { token: team.api_token })
+ await waitForBackgroundTasks(transformerConsumer.processKafkaBatch(messages))
+
+ const logsMessages = getProducedKafkaMessages().filter((m) => m.topic === 'clickhouse_logs_test')
+ expect(logsMessages).toHaveLength(1)
+ })
+
+ it('does not run transformations when the killswitch is on', async () => {
+ const logsTransformer = await buildTransformer(`return null`)
+ transformerConsumer = await createLogsIngestionConsumer(
+ hub,
+ { LOGS_TRANSFORMATIONS_ENABLED_TEAMS: '*', LOGS_TRANSFORMATIONS_KILLSWITCH: true },
+ { logsTransformer }
+ )
+
+ const messages = await createKafkaMessages([createLogMessage()], { token: team.api_token })
+ await waitForBackgroundTasks(transformerConsumer.processKafkaBatch(messages))
+
+ const logsMessages = getProducedKafkaMessages().filter((m) => m.topic === 'clickhouse_logs_test')
+ expect(logsMessages).toHaveLength(1)
+ })
+ })
})
diff --git a/nodejs/src/logs/logs-ingestion-consumer.ts b/nodejs/src/logs/logs-ingestion-consumer.ts
index df1fba491127..49220e413541 100644
--- a/nodejs/src/logs/logs-ingestion-consumer.ts
+++ b/nodejs/src/logs/logs-ingestion-consumer.ts
@@ -26,7 +26,7 @@ import {
recordLogsReceived,
} from './ingestion-otel-metrics'
import { type PiiScrubStats } from './log-pii-scrub'
-import { type LogRecord, processLogMessageBuffer } from './log-record-avro'
+import { type LogRecord, type LogRecordsTransform, 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'
@@ -37,6 +37,7 @@ import type { CompiledRuleSet } from './sampling/evaluate'
import { LogsSamplingService } from './sampling/logs-sampling.service'
import { SamplingRulesCache } from './sampling/sampling-rules-cache'
import { LogsRateLimiterService } from './services/logs-rate-limiter.service'
+import { LogsTransformerService, TransformationBatchBudget } from './transformations/logs-transformer.service'
import { LogsIngestionMessage } from './types'
export interface LogsIngestionConsumerDeps {
@@ -48,6 +49,8 @@ export interface LogsIngestionConsumerDeps {
metricRulesCache?: MetricRulesCache
/** OTLP sender for log-generated metrics; required alongside `metricRulesCache` to activate the feature. */
metricsEmitter?: LogsMetricsEmitter
+ /** When set, enabled teams run hog log transformations after the built-in processing. */
+ logsTransformer?: LogsTransformerService
/**
* Resolved outputs registry — must include `LOGS_OUTPUT`, `LOGS_DLQ_OUTPUT`,
* and `APP_METRICS_OUTPUT`. The producer + topic for each is wired by the
@@ -274,6 +277,8 @@ export class LogsIngestionConsumer {
private readonly billingProrateEnabled: boolean
private readonly metricRulesEnabledTeamsRaw: string
private readonly metricRulesKillswitch: boolean
+ private readonly transformationsEnabledTeamsRaw: string
+ private readonly transformationsKillswitch: boolean
protected groupId: string
protected topic: string
@@ -319,6 +324,8 @@ export class LogsIngestionConsumer {
this.billingProrateEnabled = mergedConfig.LOGS_BILLING_PRORATE_ENABLED
this.metricRulesEnabledTeamsRaw = mergedConfig.LOGS_METRICS_RULES_ENABLED_TEAMS
this.metricRulesKillswitch = mergedConfig.LOGS_METRICS_RULES_KILLSWITCH
+ this.transformationsEnabledTeamsRaw = mergedConfig.LOGS_TRANSFORMATIONS_ENABLED_TEAMS
+ this.transformationsKillswitch = mergedConfig.LOGS_TRANSFORMATIONS_KILLSWITCH
}
private isSamplingEvalEnabledForTeam(teamId: number): boolean {
@@ -335,14 +342,42 @@ export class LogsIngestionConsumer {
return teamIdMatchesCsv(this.metricRulesEnabledTeamsRaw, teamId)
}
+ private isTransformationsEnabledForTeam(teamId: number): boolean {
+ if (this.transformationsKillswitch || !this.deps.logsTransformer) {
+ return false
+ }
+ return teamIdMatchesCsv(this.transformationsEnabledTeamsRaw, teamId)
+ }
+
+ /**
+ * Builds the hog log transformation hook for a message, or undefined when the team
+ * is not gated in or has no enabled transformation_log functions (the existence
+ * check is an in-process cache hit, preserving the no-decode passthrough).
+ */
+ private async buildRecordsTransform(
+ message: LogsIngestionMessage,
+ batchBudget?: TransformationBatchBudget
+ ): Promise<LogRecordsTransform | undefined> {
+ const transformer = this.deps.logsTransformer
+ if (!transformer || !this.isTransformationsEnabledForTeam(message.teamId)) {
+ return undefined
+ }
+ if (!(await transformer.teamHasTransformations(message.teamId))) {
+ return undefined
+ }
+ return (records) => transformer.transformRecords(message.teamId, records, batchBudget)
+ }
+
/**
* Decode + optional head sampling, or passthrough `processLogMessageBuffer`.
- * `sampling_all_dropped` means do not enqueue to logs output (message fully sampled out).
+ * `all_dropped` means do not enqueue to logs output (every record was sampled out
+ * or dropped by transformations); `reason` distinguishes the source.
*/
private async resolveLogMessageBufferWithOptionalSampling(
message: LogsIngestionMessage,
logsSettings: LogsSettings,
- onRecordsDecoded?: (records: LogRecord[]) => void
+ onRecordsDecoded?: (records: LogRecord[]) => void,
+ batchBudget?: TransformationBatchBudget
): Promise<
| {
outcome: 'produce'
@@ -355,7 +390,8 @@ export class LogsIngestionConsumer {
contentBytesTotal: number
}
| {
- outcome: 'sampling_all_dropped'
+ outcome: 'all_dropped'
+ reason: 'sampling_all_dropped' | 'transformations_all_dropped'
pii: PiiScrubStats
recordsDropped: number
recordsDroppedByRuleId: Map<string, number>
@@ -371,6 +407,7 @@ export class LogsIngestionConsumer {
ruleSet = await samplingCache.getCompiledRuleSet(message.teamId)
}
const useSamplingPipeline = Boolean(ruleSet && ruleSet.rules.length > 0)
+ const recordsTransform = await this.buildRecordsTransform(message, batchBudget)
trace.getActiveSpan()?.setAttributes({
'logs.sampling.killswitch': this.samplingKillswitch,
@@ -379,6 +416,7 @@ export class LogsIngestionConsumer {
'logs.sampling.cache_present': Boolean(samplingCache),
'logs.sampling.eval_enabled_for_team': samplingEvalEnabled,
'logs.sampling.compiled_rule_count': ruleSet?.rules.length ?? 0,
+ 'logs.transformations.enabled_for_team': Boolean(recordsTransform),
'logs.sampling.pipeline': useSamplingPipeline
? 'decode_sample_encode'
: 'passthrough_processLogMessageBuffer',
@@ -391,7 +429,8 @@ export class LogsIngestionConsumer {
ruleSet,
message.teamId,
message.bytesUncompressed,
- onRecordsDecoded
+ onRecordsDecoded,
+ recordsTransform
)
if (sampled.recordsDropped > 0) {
logsSamplingRecordsDroppedCounter.inc({ team_id: message.teamId.toString() }, sampled.recordsDropped)
@@ -401,7 +440,11 @@ export class LogsIngestionConsumer {
}
if (sampled.allDropped) {
return {
- outcome: 'sampling_all_dropped',
+ outcome: 'all_dropped',
+ reason:
+ sampled.allDroppedBy === 'transformations'
+ ? 'transformations_all_dropped'
+ : 'sampling_all_dropped',
pii: sampled.pii,
recordsDropped: sampled.recordsDropped,
recordsDroppedByRuleId: sampled.recordsDroppedByRuleId,
@@ -422,8 +465,25 @@ export class LogsIngestionConsumer {
}
}
- // Passthrough (sampling disabled / no rules): nothing dropped, so nothing to credit.
- const res = await processLogMessageBuffer(message.message.value!, logsSettings, onRecordsDecoded)
+ // Passthrough (sampling disabled / no rules): drop rules removed nothing, so nothing to credit.
+ const res = await processLogMessageBuffer(
+ message.message.value!,
+ logsSettings,
+ onRecordsDecoded,
+ recordsTransform
+ )
+ if (res.value === null) {
+ return {
+ outcome: 'all_dropped',
+ reason: 'transformations_all_dropped',
+ pii: res.pii,
+ recordsDropped: 0,
+ recordsDroppedByRuleId: new Map(),
+ bytesDroppedByRuleId: new Map(),
+ contentBytesDropped: 0,
+ contentBytesTotal: 0,
+ }
+ }
return {
outcome: 'produce',
processedValue: res.value,
@@ -462,11 +522,24 @@ export class LogsIngestionConsumer {
...rateLimiterDroppedMessages,
])
+ // One transformation time budget shared by all messages of this batch
+ const transformationBatchBudget = this.deps.logsTransformer?.startBatch()
+
return {
// Produce first so PII replacement counts are folded into `usageStats` before MSK usage emit
backgroundTask: (async () => {
- await this.processAndProduceLogMessages(rateLimiterAllowedMessages, usageStats)
+ await this.processAndProduceLogMessages(
+ rateLimiterAllowedMessages,
+ usageStats,
+ transformationBatchBudget
+ )
await this.emitUsageMetrics(usageStats)
+ // Best-effort flush of transformation app metrics + function logs; never block the data path
+ if (this.deps.logsTransformer) {
+ await this.deps.logsTransformer.flush().catch((error) => {
+ logger.error('Failed to flush logs transformer monitoring', { error: String(error) })
+ })
+ }
})(),
messages: rateLimiterAllowedMessages,
}
@@ -683,7 +756,8 @@ export class LogsIngestionConsumer {
private async processAndProduceLogMessages(
messages: LogsIngestionMessage[],
- usageStats: UsageStatsByTeam
+ usageStats: UsageStatsByTeam,
+ transformationBatchBudget?: TransformationBatchBudget
): Promise<void> {
const metricTalliesByTeam = new Map<
number,
@@ -733,7 +807,8 @@ export class LogsIngestionConsumer {
this.resolveLogMessageBufferWithOptionalSampling(
message,
logsSettings,
- onRecordsDecoded
+ onRecordsDecoded,
+ transformationBatchBudget
)
)
@@ -805,12 +880,12 @@ export class LogsIngestionConsumer {
}
}
- if (resolved.outcome === 'sampling_all_dropped') {
+ if (resolved.outcome === 'all_dropped') {
logMessageDroppedCounter.inc(
- { reason: 'sampling_all_dropped', team_id: message.teamId.toString() },
+ { reason: resolved.reason, team_id: message.teamId.toString() },
1
)
- recordLogMessageDropped('sampling_all_dropped', message.teamId.toString())
+ recordLogMessageDropped(resolved.reason, message.teamId.toString())
this.addPiiStatsIntoUsage(usageStats, message.teamId, resolved.pii)
this.queueSamplingRecordsDroppedByRule(message.teamId, resolved.recordsDroppedByRuleId)
this.queueBytesDroppedByRule(message.teamId, resolved.bytesDroppedByRuleId)
diff --git a/nodejs/src/logs/outputs/registry.ts b/nodejs/src/logs/outputs/registry.ts
index a6075b4921fb..821907266ff3 100644
--- a/nodejs/src/logs/outputs/registry.ts
+++ b/nodejs/src/logs/outputs/registry.ts
@@ -1,4 +1,4 @@
-import { APP_METRICS_OUTPUT } from '~/common/outputs'
+import { APP_METRICS_OUTPUT, LOG_ENTRIES_OUTPUT } from '~/common/outputs'
import { IngestionOutputsBuilder } from '~/common/outputs/ingestion-outputs-builder'
import { LOGS_DLQ_OUTPUT, LOGS_OUTPUT } from './outputs'
@@ -9,6 +9,7 @@ import { LOGS_DLQ_OUTPUT, LOGS_OUTPUT } from './outputs'
* - `LOGS_OUTPUT` — main log data path → topic from `LOGS_INGESTION_CONSUMER_CLICKHOUSE_TOPIC`.
* - `LOGS_DLQ_OUTPUT` — DLQ for failed messages → topic from `LOGS_INGESTION_CONSUMER_DLQ_TOPIC`.
* - `APP_METRICS_OUTPUT` — usage metrics → topic from `LOGS_INGESTION_OUTPUT_APP_METRICS_TOPIC`.
+ * - `LOG_ENTRIES_OUTPUT` — hog function logs (UI log viewer) → topic from `LOGS_INGESTION_OUTPUT_LOG_ENTRIES_TOPIC`.
*
* Per-output producer is env-controlled (`*_PRODUCER` keys) so the route can be
* flipped between MSK / Warpstream-logs / Warpstream-ingestion without code changes.
@@ -19,6 +20,10 @@ export function createLogsOutputsRegistry() {
topicKey: 'LOGS_INGESTION_OUTPUT_APP_METRICS_TOPIC',
producerKey: 'LOGS_INGESTION_OUTPUT_APP_METRICS_PRODUCER',
})
+ .register(LOG_ENTRIES_OUTPUT, {
+ topicKey: 'LOGS_INGESTION_OUTPUT_LOG_ENTRIES_TOPIC',
+ producerKey: 'LOGS_INGESTION_OUTPUT_LOG_ENTRIES_PRODUCER',
+ })
.register(LOGS_OUTPUT, {
topicKey: 'LOGS_INGESTION_CONSUMER_CLICKHOUSE_TOPIC',
producerKey: 'LOGS_INGESTION_OUTPUT_LOGS_PRODUCER',
@@ -40,6 +45,10 @@ export function createTracesOutputsRegistry() {
topicKey: 'LOGS_INGESTION_OUTPUT_APP_METRICS_TOPIC',
producerKey: 'LOGS_INGESTION_OUTPUT_APP_METRICS_PRODUCER',
})
+ .register(LOG_ENTRIES_OUTPUT, {
+ topicKey: 'LOGS_INGESTION_OUTPUT_LOG_ENTRIES_TOPIC',
+ producerKey: 'LOGS_INGESTION_OUTPUT_LOG_ENTRIES_PRODUCER',
+ })
.register(LOGS_OUTPUT, {
topicKey: 'TRACES_INGESTION_CONSUMER_CLICKHOUSE_TOPIC',
producerKey: 'LOGS_INGESTION_OUTPUT_LOGS_PRODUCER',
diff --git a/nodejs/src/logs/sampling/logs-sampling.service.ts b/nodejs/src/logs/sampling/logs-sampling.service.ts
index 6494061215f6..5ad55983ad50 100644
--- a/nodejs/src/logs/sampling/logs-sampling.service.ts
+++ b/nodejs/src/logs/sampling/logs-sampling.service.ts
@@ -8,6 +8,7 @@ import { logger } from '~/common/utils/logger'
import { type PiiScrubStats } from '~/logs/log-pii-scrub'
import {
type LogRecord,
+ type LogRecordsTransform,
decodeLogRecords,
encodeLogRecords,
transformDecodedLogRecordsInPlace,
@@ -72,8 +73,10 @@ export type ProcessBufferWithSamplingResult = {
contentBytesDropped: number
/** Sum of customer-content bytes across ALL decoded rows (kept + dropped). Billing pro-rate denominator. */
contentBytesTotal: number
- /** When true, the caller must not produce this message to downstream Kafka (all lines sampled out). */
+ /** When true, the caller must not produce this message to downstream Kafka (all lines removed). */
allDropped: boolean
+ /** What removed the final surviving lines when `allDropped` is true. */
+ allDroppedBy?: 'sampling' | 'transformations'
}
const recordBytes = (r: LogRecord): number => r.bytes_uncompressed ?? 0
@@ -115,7 +118,8 @@ export class LogsSamplingService {
ruleSet: CompiledRuleSet,
teamId?: number,
headerBytesUncompressed: number = 0,
- onRecordsDecoded?: (records: LogRecord[]) => void
+ onRecordsDecoded?: (records: LogRecord[]) => void,
+ recordsTransform?: LogRecordsTransform
): Promise<ProcessBufferWithSamplingResult> {
const [logRecordType, compressionCodec, records] = await decodeLogRecords(buffer)
if (!logRecordType) {
@@ -202,6 +206,13 @@ export class LogsSamplingService {
}
}
+ // Hog log transformations run last, on the records that survived the drop rules
+ let keptBeforeTransform = 0
+ if (recordsTransform && kept.length > 0) {
+ keptBeforeTransform = kept.length
+ await recordsTransform(kept)
+ }
+
trace.getActiveSpan()?.setAttributes({
'logs.sampling.input_record_count': records.length,
'logs.sampling.kept_record_count': kept.length,
@@ -222,6 +233,9 @@ export class LogsSamplingService {
contentBytesDropped,
contentBytesTotal,
allDropped: true,
+ // Sampling left survivors and the transform removed the rest — attribute
+ // the full-message drop to transformations, not the drop rules.
+ allDroppedBy: keptBeforeTransform > 0 ? 'transformations' : 'sampling',
}
}
const value = await encodeLogRecords(logRecordType, compressionCodec, kept)
diff --git a/nodejs/src/servers/ingestion-logs-server.ts b/nodejs/src/servers/ingestion-logs-server.ts
index bb99b81bd7ef..d512b81f6ee5 100644
--- a/nodejs/src/servers/ingestion-logs-server.ts
+++ b/nodejs/src/servers/ingestion-logs-server.ts
@@ -1,10 +1,12 @@
import { defaultConfig, overrideConfigWithEnv } from '~/common/config/config'
import { createPosthogRedisConnectionConfig } from '~/common/config/redis-pools'
import { KafkaProducerRegistry } from '~/common/outputs/kafka-producer-registry'
+import { createRedisV2PoolFromConfig } from '~/common/redis/redis-v2'
import { QuotaLimiting } from '~/common/services/quota-limiting.service'
import { PostgresRouter } from '~/common/utils/db/postgres'
import { createRedisPoolFromConfig } from '~/common/utils/db/redis'
import { logger } from '~/common/utils/logger'
+import { PubSub } from '~/common/utils/pubsub'
import { TeamManager } from '~/common/utils/team-manager'
import {
LogsIngestionConsumerConfig,
@@ -24,7 +26,13 @@ import {
} from '~/logs/outputs/producers'
import { createLogsOutputsRegistry } from '~/logs/outputs/registry'
import { SamplingRulesCache } from '~/logs/sampling/sampling-rules-cache'
+import { LogsTransformerService } from '~/logs/transformations/logs-transformer.service'
+import type { CdpConfig } from '../cdp/config'
+import { HogFunctionManagerService } from '../cdp/services/managers/hog-function-manager.service'
+import { HogFunctionMonitoringService } from '../cdp/services/monitoring/hog-function-monitoring.service'
+import { HogWatcherService } from '../cdp/services/monitoring/hog-watcher.service'
+import { EncryptedFields } from '../cdp/utils/encryption-utils'
import { CommonConfig } from '../common/config'
import { DatabaseConnectionConfig, KafkaBrokerConfig, RedisConnectionsConfig } from '../ingestion/config'
import { PluginServerService, RedisPool } from '../types'
@@ -49,7 +57,38 @@ export type IngestionLogsServerConfig = BaseServerConfig &
KafkaBrokerConfig &
DatabaseConnectionConfig &
RedisConnectionsConfig &
- Pick<CommonConfig, 'LOG_LEVEL' | 'PLUGIN_SERVER_MODE' | 'CLOUD_DEPLOYMENT' | 'HEALTHCHECK_MAX_STALE_SECONDS'>
+ Pick<
+ CommonConfig,
+ | 'LOG_LEVEL'
+ | 'PLUGIN_SERVER_MODE'
+ | 'CLOUD_DEPLOYMENT'
+ | 'HEALTHCHECK_MAX_STALE_SECONDS'
+ | 'ENCRYPTION_SALT_KEYS'
+ | 'SITE_URL'
+ > &
+ // HogWatcher for log transformations shares CDP's redis + tuning so function
+ // health state is read and written where the API and CDP consumers expect it.
+ Pick<
+ CdpConfig,
+ | 'CDP_REDIS_HOST'
+ | 'CDP_REDIS_PORT'
+ | 'CDP_REDIS_PASSWORD'
+ | 'CDP_WATCHER_HOG_COST_TIMING_LOWER_MS'
+ | 'CDP_WATCHER_HOG_COST_TIMING_UPPER_MS'
+ | 'CDP_WATCHER_HOG_COST_TIMING'
+ | 'CDP_WATCHER_ASYNC_COST_TIMING_LOWER_MS'
+ | 'CDP_WATCHER_ASYNC_COST_TIMING_UPPER_MS'
+ | 'CDP_WATCHER_ASYNC_COST_TIMING'
+ | 'CDP_WATCHER_SEND_EVENTS'
+ | 'CDP_WATCHER_BUCKET_SIZE'
+ | 'CDP_WATCHER_REFILL_RATE'
+ | 'CDP_WATCHER_TTL'
+ | 'CDP_WATCHER_AUTOMATICALLY_DISABLE_FUNCTIONS'
+ | 'CDP_WATCHER_THRESHOLD_DEGRADED'
+ | 'CDP_WATCHER_STATE_LOCK_TTL'
+ | 'CDP_WATCHER_OBSERVE_RESULTS_BUFFER_TIME_MS'
+ | 'CDP_WATCHER_OBSERVE_RESULTS_BUFFER_MAX_RESULTS'
+ >
export class IngestionLogsServer implements NodeServer {
readonly lifecycle: ServerLifecycle
@@ -58,6 +97,7 @@ export class IngestionLogsServer implements NodeServer {
private postgres?: PostgresRouter
private posthogRedisPool?: RedisPool
private producerRegistry?: KafkaProducerRegistry<LogsProducerName>
+ private pubsub?: PubSub
constructor(config: Partial<IngestionLogsServerConfig> = {}) {
this.config = {
@@ -115,7 +155,67 @@ export class IngestionLogsServer implements NodeServer {
// 2. Resolve outputs (topic + producer per logical name, env-controlled)
const outputs = createLogsOutputsRegistry().build(this.producerRegistry, this.config)
- // 3. Logs ingestion consumer
+ // 3. Hog log transformations (per-team execution is gated by
+ // LOGS_TRANSFORMATIONS_ENABLED_TEAMS; the services themselves are cheap)
+ this.pubsub = new PubSub(this.posthogRedisPool)
+ await this.pubsub.start()
+ const hogFunctionManager = new HogFunctionManagerService(
+ this.postgres,
+ this.pubsub,
+ new EncryptedFields(this.config.ENCRYPTION_SALT_KEYS)
+ )
+ const hogFunctionMonitoring = new HogFunctionMonitoringService(outputs)
+
+ // HogWatcher on CDP's redis so function health state lands where the API reads it.
+ // A sample rate of 0 (default) keeps it fully dormant — no Redis traffic.
+ const cdpRedis = createRedisV2PoolFromConfig({
+ connection: this.config.CDP_REDIS_HOST
+ ? {
+ url: this.config.CDP_REDIS_HOST,
+ options: { port: this.config.CDP_REDIS_PORT, password: this.config.CDP_REDIS_PASSWORD },
+ name: 'logs-cdp-redis',
+ }
+ : { url: this.config.REDIS_URL, name: 'logs-cdp-redis-fallback' },
+ poolMinSize: this.config.REDIS_POOL_MIN_SIZE,
+ poolMaxSize: this.config.REDIS_POOL_MAX_SIZE,
+ })
+ const hogWatcher = new HogWatcherService(
+ teamManager,
+ {
+ hogCostTimingLowerMs: this.config.CDP_WATCHER_HOG_COST_TIMING_LOWER_MS,
+ hogCostTimingUpperMs: this.config.CDP_WATCHER_HOG_COST_TIMING_UPPER_MS,
+ hogCostTiming: this.config.CDP_WATCHER_HOG_COST_TIMING,
+ asyncCostTimingLowerMs: this.config.CDP_WATCHER_ASYNC_COST_TIMING_LOWER_MS,
+ asyncCostTimingUpperMs: this.config.CDP_WATCHER_ASYNC_COST_TIMING_UPPER_MS,
+ asyncCostTiming: this.config.CDP_WATCHER_ASYNC_COST_TIMING,
+ sendEvents: this.config.CDP_WATCHER_SEND_EVENTS,
+ bucketSize: this.config.CDP_WATCHER_BUCKET_SIZE,
+ refillRate: this.config.CDP_WATCHER_REFILL_RATE,
+ ttl: this.config.CDP_WATCHER_TTL,
+ automaticallyDisableFunctions: this.config.CDP_WATCHER_AUTOMATICALLY_DISABLE_FUNCTIONS,
+ thresholdDegraded: this.config.CDP_WATCHER_THRESHOLD_DEGRADED,
+ stateLockTtl: this.config.CDP_WATCHER_STATE_LOCK_TTL,
+ observeResultsBufferTimeMs: this.config.CDP_WATCHER_OBSERVE_RESULTS_BUFFER_TIME_MS,
+ observeResultsBufferMaxResults: this.config.CDP_WATCHER_OBSERVE_RESULTS_BUFFER_MAX_RESULTS,
+ },
+ cdpRedis
+ )
+
+ const logsTransformer = new LogsTransformerService(
+ hogFunctionManager,
+ hogFunctionMonitoring,
+ {
+ siteUrl: this.config.SITE_URL,
+ hogTimeoutMs: this.config.LOGS_TRANSFORMATIONS_HOG_TIMEOUT_MS,
+ messageBudgetMs: this.config.LOGS_TRANSFORMATIONS_MESSAGE_BUDGET_MS,
+ batchBudgetMs: this.config.LOGS_TRANSFORMATIONS_BATCH_BUDGET_MS,
+ maxErrorLogsPerFunctionPerMessage: this.config.LOGS_TRANSFORMATIONS_MAX_ERROR_LOGS_PER_FUNCTION,
+ hogWatcherSampleRate: this.config.LOGS_TRANSFORMATIONS_HOG_WATCHER_SAMPLE_RATE,
+ },
+ hogWatcher
+ )
+
+ // 4. Logs ingestion consumer
const serviceLoaders: (() => Promise<PluginServerService>)[] = []
serviceLoaders.push(async () => {
@@ -126,6 +226,7 @@ export class IngestionLogsServer implements NodeServer {
samplingRulesCache,
metricRulesCache,
metricsEmitter,
+ logsTransformer,
})
await consumer.start()
return consumer.service
@@ -140,6 +241,9 @@ export class IngestionLogsServer implements NodeServer {
kafkaProducers: [],
redisPools: [this.posthogRedisPool].filter(Boolean) as RedisPool[],
postgres: this.postgres,
+ // PubSub holds a client from posthogRedisPool — it must stop in the services
+ // phase, before the base server drains the pool, or stop() hangs.
+ pubsub: this.pubsub,
additionalCleanup: async () => {
await this.producerRegistry?.disconnectAll()
},