: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
fix(logs): fail open on infra errors and harden transformation globals (#76026)
Daniel Viscafab696b6555a
diff --git a/nodejs/src/cdp/templates/_transformations_log/drop-by-severity/drop-by-severity.template.ts b/nodejs/src/cdp/templates/_transformations_log/drop-by-severity/drop-by-severity.template.tsindex bf5de974fd0e..7b4f3a421f50 100644--- a/nodejs/src/cdp/templates/_transformations_log/drop-by-severity/drop-by-severity.template.ts+++ b/nodejs/src/cdp/templates/_transformations_log/drop-by-severity/drop-by-severity.template.ts@@ -6,7 +6,8 @@ export const template: HogFunctionTemplate = {type: 'transformation_log',id: 'template-log-transformation-drop-by-severity',name: 'Drop logs by severity',- description: 'Drop noisy log records at the configured severity levels (for example debug and trace).',+ description:+ 'Drop noisy log records at the configured severity levels (for example debug and trace). Dropped records still count toward ingestion billing.',icon_url: '/static/hedgehog/builder-hog-01.png',category: ['Custom'],code_language: 'hog',diff --git a/nodejs/src/logs/metrics-rules/tally.ts b/nodejs/src/logs/metrics-rules/tally.tsindex 7a7c333c072e..9c874f58824d 100644--- a/nodejs/src/logs/metrics-rules/tally.ts+++ b/nodejs/src/logs/metrics-rules/tally.ts@@ -79,7 +79,7 @@ function resolveNumericValue(key: string, record: LogRecord): number | null {* 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 {+export function idToHex(buffer: Buffer | null, expectedBytes: number): string | null {if (!buffer || buffer.length === 0) {return null}diff --git a/nodejs/src/logs/transformations/hog-log-exec.test.ts b/nodejs/src/logs/transformations/hog-log-exec.test.tsindex 8a418b3f6f35..69d86d20d758 100644--- a/nodejs/src/logs/transformations/hog-log-exec.test.ts+++ b/nodejs/src/logs/transformations/hog-log-exec.test.ts@@ -52,6 +52,36 @@ describe('hog-log-exec', () => {expect(globals.inputs).toEqual({ foo: 'bar' })expect(globals.project).toBe(PROJECT)})++ // capture-logs writes trace/span ids as base64 TEXT of the raw bytes, and zeroed+ // ids mean "absent" — customer code must see the same hex/null the rest of the+ // logs product (metric rules, ClickHouse sink) derives from these buffers.+ it.each([+ [+ 'base64-text trace_id from capture decodes to hex',+ { trace_id: Buffer.from(Buffer.from('0123456789abcdef0123456789abcdef', 'hex').toString('base64')) },+ (r: ReturnType<typeof buildLogRecordGlobals>['record']) =>+ expect(r.trace_id).toBe('0123456789abcdef0123456789abcdef'),+ ],+ [+ 'base64-text span_id from capture decodes to hex',+ { span_id: Buffer.from(Buffer.from('0123456789abcdef', 'hex').toString('base64')) },+ (r: ReturnType<typeof buildLogRecordGlobals>['record']) => expect(r.span_id).toBe('0123456789abcdef'),+ ],+ [+ 'zeroed trace_id is null, not a hex string of zeros',+ { trace_id: Buffer.alloc(16) },+ (r: ReturnType<typeof buildLogRecordGlobals>['record']) => expect(r.trace_id).toBeNull(),+ ],+ [+ 'unparseable trace_id is null, not garbage hex',+ { trace_id: Buffer.from('nope!') },+ (r: ReturnType<typeof buildLogRecordGlobals>['record']) => expect(r.trace_id).toBeNull(),+ ],+ ])('%s', (_name, overrides, assert) => {+ const globals = buildLogRecordGlobals(createRecord(overrides), PROJECT, {})+ assert(globals.record)+ })})describe('resolveLogTransformationInputs', () => {diff --git a/nodejs/src/logs/transformations/hog-log-exec.ts b/nodejs/src/logs/transformations/hog-log-exec.tsindex 40e855aa2bf8..ccf80303c83f 100644--- a/nodejs/src/logs/transformations/hog-log-exec.ts+++ b/nodejs/src/logs/transformations/hog-log-exec.ts@@ -6,6 +6,7 @@ import { execHogImmediate } from '~/cdp/utils/hog-exec'import { parseJSON } from '~/common/utils/json-parse'import type { LogRecord } from '../log-record-avro'+import { idToHex } from '../metrics-rules/tally'// Per-record execution primitives for log transformations. Pure functions, no I/O:// orchestration (function fetching, budgets, monitoring) lives in the transformer service.@@ -67,8 +68,8 @@ export function buildLogRecordGlobals(event_name: record.event_name ?? null,timestamp: record.timestamp ?? null,observed_timestamp: record.observed_timestamp ?? null,- trace_id: record.trace_id ? record.trace_id.toString('hex') : null,- span_id: record.span_id ? record.span_id.toString('hex') : null,+ trace_id: idToHex(record.trace_id, 16),+ span_id: idToHex(record.span_id, 8),},inputs,}diff --git a/nodejs/src/logs/transformations/logs-transformer.service.test.ts b/nodejs/src/logs/transformations/logs-transformer.service.test.tsindex 8047bbf4dc75..71f0c681e79b 100644--- a/nodejs/src/logs/transformations/logs-transformer.service.test.ts+++ b/nodejs/src/logs/transformations/logs-transformer.service.test.ts@@ -556,5 +556,54 @@ describe('LogsTransformerService', () => {expect.objectContaining({ metric_name: 'disabled_permanently', app_source_id: fn.id, count: 2 }))})++ it('runs all functions untouched by the watcher when the state read throws', async () => {+ const watcher = createMockWatcher()+ watcher.getEffectiveStates.mockRejectedValue(new Error('redis down'))+ service = withWatcher(watcher, 1)+ setFunctions([+ await createFunction(`+ let rec := record+ rec.body := 'transformed'+ return rec+ `),+ ])++ const records = [createRecord()]+ const { recordsDropped } = await service.transformRecords(TEAM_ID, records)++ expect(recordsDropped).toBe(0)+ expect(records[0].body).toBe('transformed')+ })+ })++ describe('fail-open on infrastructure errors', () => {+ it('passes records through untouched when the function fetch throws', async () => {+ manager.getHogFunctionsForTeams.mockRejectedValue(new Error('pg down'))++ const records = [createRecord(), createRecord()]+ const result = await service.transformRecords(TEAM_ID, records)++ expect(result.recordsDropped).toBe(0)+ expect(records).toHaveLength(2)+ expect(records[0].body).toBe('user [email protected] logged in')+ })++ it('reports no transformations when the id fetch throws', async () => {+ manager.getHogFunctionIdsForTeams.mockRejectedValue(new Error('pg down'))++ await expect(service.teamHasTransformations(TEAM_ID)).resolves.toBe(false)+ })+ })++ it('survives messages with more records than the V8 spread argument limit', async () => {+ setFunctions([await createFunction('return record')])+ service = new LogsTransformerService(manager as any, monitoring as any, { ...config, messageBudgetMs: 0 })++ const records = Array.from({ length: 130_000 }, () => createRecord())+ const result = await service.transformRecords(TEAM_ID, records)++ expect(result.recordsDropped).toBe(0)+ expect(records).toHaveLength(130_000)})})diff --git a/nodejs/src/logs/transformations/logs-transformer.service.ts b/nodejs/src/logs/transformations/logs-transformer.service.tsindex 3412ce79aaa3..56e49c9941a1 100644--- a/nodejs/src/logs/transformations/logs-transformer.service.ts+++ b/nodejs/src/logs/transformations/logs-transformer.service.ts@@ -70,6 +70,12 @@ export const transformationUnexpectedErrorsCounter = new Counter({help: 'Unexpected (non-customer-code) errors in the logs transformer. Any occurrence should alert.',})+export const transformationInfraErrorsCounter = new Counter({+ name: 'logs_ingestion_transformations_infra_errors_total',+ help: 'Infrastructure errors while fetching functions or reading watcher state; function fetch errors pass records through untransformed.',+ labelNames: ['source'], // functions_fetch | watcher_state+})+export interface LogsTransformerConfig {siteUrl: string/** Hard per-record VM kill */@@ -140,8 +146,19 @@ export class LogsTransformerService {/** Cheap existence check (in-process LazyLoader cache) used to preserve the* no-decode passthrough for teams without transformations. */public async teamHasTransformations(teamId: number): Promise<boolean> {- const idsByTeam = await this.hogFunctionManager.getHogFunctionIdsForTeams([teamId], ['transformation_log'])- return (idsByTeam[teamId] ?? []).length > 0+ // Fail open: a fetch failure (cold cache + Postgres blip) must skip transformations+ // for the message, never bubble into the consumer's catch and DLQ valid records.+ try {+ const idsByTeam = await this.hogFunctionManager.getHogFunctionIdsForTeams([teamId], ['transformation_log'])+ return (idsByTeam[teamId] ?? []).length > 0+ } catch (error) {+ transformationInfraErrorsCounter.inc({ source: 'functions_fetch' })+ logger.warn('[logs-transformer] function id fetch failed — skipping transformations', {+ teamId,+ error: String(error),+ })+ return false+ }}public async flush(): Promise<void> {@@ -156,8 +173,23 @@ export class LogsTransformerService {const recordsDroppedByFunctionId = new Map<string, number>()let recordsDropped = 0- const functionsByTeam = await this.hogFunctionManager.getHogFunctionsForTeams([teamId], ['transformation_log'])- const allFunctions = functionsByTeam[teamId] ?? []+ let allFunctions: HogFunctionType[]+ try {+ const functionsByTeam = await this.hogFunctionManager.getHogFunctionsForTeams(+ [teamId],+ ['transformation_log']+ )+ allFunctions = functionsByTeam[teamId] ?? []+ } catch (error) {+ // Fail open like the fetch in teamHasTransformations: pass records through+ // untransformed rather than DLQ the message.+ transformationInfraErrorsCounter.inc({ source: 'functions_fetch' })+ logger.warn('[logs-transformer] function fetch failed — records passed through untransformed', {+ teamId,+ error: String(error),+ })+ return { recordsDropped, recordsDroppedByFunctionId }+ }if (allFunctions.length === 0 || records.length === 0) {return { recordsDropped, recordsDroppedByFunctionId }}@@ -237,9 +269,13 @@ export class LogsTransformerService {}}- // Replace contents in place so callers holding the array reference see the result+ // Replace contents in place so callers holding the array reference see the result.+ // One-by-one push: spreading an unbounded record array would exceed V8's argument+ // limit and throw RangeError, escaping the per-record fail-open handling.records.length = 0- records.push(...kept)+ for (const record of kept) {+ records.push(record)+ }transformationVmDurationHistogram.observe(messageVmMs / 1000)this.queueAggregates(teamId, aggregates)@@ -259,7 +295,19 @@ export class LogsTransformerService {if (!this.hogWatcher) {return functions}- const states = await this.hogWatcher.getEffectiveStates(functions.map((fn) => fn.id))+ let states: Awaited<ReturnType<HogWatcherService['getEffectiveStates']>>+ try {+ states = await this.hogWatcher.getEffectiveStates(functions.map((fn) => fn.id))+ } catch (error) {+ // Fail open: a Redis blip on a sampled message must not DLQ it — run every+ // function as if unsampled rather than propagate.+ transformationInfraErrorsCounter.inc({ source: 'watcher_state' })+ logger.warn('[logs-transformer] watcher state read failed — running all functions', {+ teamId,+ error: String(error),+ })+ return functions+ }const active: HogFunctionType[] = []for (const fn of functions) {if (states[fn.id]?.state === HogWatcherState.disabled) {