: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): quarantine unprocessable messages and log fatal crashes (#91829)
Frank Hamand455990c4d178
diff --git a/nodejs/src/logs/logs-ingestion-consumer.test.ts b/nodejs/src/logs/logs-ingestion-consumer.test.tsindex 73b0394a1b4c..9abfbbf06f11 100644--- a/nodejs/src/logs/logs-ingestion-consumer.test.ts+++ b/nodejs/src/logs/logs-ingestion-consumer.test.ts@@ -33,6 +33,7 @@ import {DEFAULT_LOGS_RETENTION_DAYS,LogsIngestionConsumer,type LogsIngestionConsumerDeps,+ describeBatchPosition,logMessageDlqCounter,logMessageDroppedCounter,logsBillingBytesCreditedCounter,@@ -43,6 +44,7 @@ import {logsRecordsBytesExceedPayloadCounter,logsRecordsDroppedCounter,logsRecordsReceivedCounter,+ parseSizeHeader,} from './logs-ingestion-consumer'import { compileMetricRules } from './metrics-rules/compile-metric-rules'import type { MetricRulesCache } from './metrics-rules/metric-rules-cache'@@ -632,10 +634,74 @@ describe('LogsIngestionConsumer', () => {expect(dlqMessage.headers).toHaveProperty('error_message')expect(dlqMessage.headers).toHaveProperty('error_name')expect(dlqMessage.headers).toHaveProperty('failed_at')+ // Position of the source record, so it can be read back and replayed+ expect(dlqMessage.headers.source_topic).toEqual(messages[0].topic)+ expect(dlqMessage.headers.source_partition).toEqual(messages[0].partition.toString())+ expect(dlqMessage.headers.source_offset).toEqual(messages[0].offset.toString())} finally {mockProducer.queueMessages = originalQueueMessages}})++ it('should send a message with an unparseable size header to DLQ instead of ingesting it', async () => {+ const logData = createLogMessage()+ const messages = await createKafkaMessages([logData], {+ token: team.api_token,+ // NaN here would otherwise flow into the usage counters and per-team billing stats+ bytes_uncompressed: 'not-a-number',+ })++ await waitForBackgroundTasks(consumer.processKafkaBatch(messages))++ const produced = getProducedKafkaMessages()+ expect(produced.filter((m) => m.topic === KAFKA_LOGS_CLICKHOUSE)).toHaveLength(0)++ const dlq = produced.filter((m) => m.topic === KAFKA_LOGS_INGESTION_DLQ)+ expect(dlq).toHaveLength(1)+ expect(dlq[0]?.headers?.error_message).toEqual('invalid_size_headers')+ expect(dlq[0]?.headers?.team_id).toEqual(team.id.toString())+ })++ it('should fail the batch when the message cannot be written to the DLQ', async () => {+ const logData = createLogMessage()+ const messages = await createKafkaMessages([logData], {+ token: team.api_token,+ bytes_uncompressed: 'not-a-number',+ })++ const originalQueueMessages = mockProducer.queueMessages+ mockProducer.queueMessages = jest.fn().mockRejectedValue(new Error('DLQ unavailable'))++ try {+ // Resolving here would commit the source offset with no copy anywhere, so the+ // only record of the payload would be gone.+ await expect(consumer.processKafkaBatch(messages)).rejects.toThrow('DLQ unavailable')+ } finally {+ mockProducer.queueMessages = originalQueueMessages+ }+ })+ })++ describe('describeBatchPosition', () => {+ it('collapses each partition to its offset span', () => {+ const at = (partition: number, offset: number): Message => ({ partition, offset }) as Message++ expect(describeBatchPosition([at(3, 1000), at(3, 1099), at(7, 42)])).toEqual({+ '3': '1000-1099',+ '7': '42',+ })+ })+ })++ describe('parseSizeHeader', () => {+ it.each([+ ['1234', 1234],+ [undefined, 0],+ ['not-a-number', null],+ ['-5', null],+ ])('parses %p as %p', (raw, expected) => {+ expect(parseSizeHeader(raw)).toEqual(expected)+ })})describe('message routing', () => {diff --git a/nodejs/src/logs/logs-ingestion-consumer.ts b/nodejs/src/logs/logs-ingestion-consumer.tsindex 03d0c9e0ee79..0038bf5d3b45 100644--- a/nodejs/src/logs/logs-ingestion-consumer.ts+++ b/nodejs/src/logs/logs-ingestion-consumer.ts@@ -114,6 +114,41 @@ function teamIdMatchesCsv(raw: string, teamId: number): boolean {.includes(teamId)}+/**+ * Per-partition offset span of a batch, for the batch log line. A consumer that dies mid-batch+ * writes nothing after it, so this is what names the records it was holding.+ */+export function describeBatchPosition(messages: Message[]): Record<string, string> {+ const spans = new Map<number, { min: number; max: number }>()+ for (const message of messages) {+ const span = spans.get(message.partition)+ if (span) {+ span.min = Math.min(span.min, message.offset)+ span.max = Math.max(span.max, message.offset)+ } else {+ spans.set(message.partition, { min: message.offset, max: message.offset })+ }+ }++ const spanByPartition: Record<string, string> = {}+ for (const [partition, { min, max }] of spans) {+ spanByPartition[partition.toString()] = min === max ? min.toString() : `${min}-${max}`+ }+ return spanByPartition+}++/**+ * Parse a batch size header, or `null` when the value is unusable. These feed usage counters and+ * billing stats, so a malformed one must not reach them: `parseInt` returns NaN for junk, and+ * prom-client's own guard treats NaN as falsy and lets it through, which leaves the counter NaN+ * for the life of the process. Parsing stays as lenient as before — only NaN and negatives, which+ * no caller can use, are rejected.+ */+export function parseSizeHeader(raw: string | undefined): number | null {+ const parsed = parseInt(raw ?? '0', 10)+ return Number.isFinite(parsed) && parsed >= 0 ? parsed : null+}+const DEFAULT_USAGE_STATS: UsageStats = {bytesReceived: 0,recordsReceived: 0,@@ -1017,24 +1052,43 @@ export class LogsIngestionConsumer {}private async produceToDlq(message: LogsIngestionMessage, error: unknown): Promise<void> {+ await this.produceRawToDlq(message.message, error, { token: message.token, teamId: message.teamId })+ }++ /**+ * Quarantine a raw Kafka message. Takes the message rather than a `LogsIngestionMessage` so+ * failures from before the team is resolved can reach the DLQ too — those used to be counted+ * and discarded, which lost the only copy of the payload.+ */+ private async produceRawToDlq(+ message: Message,+ error: unknown,+ context: { token?: string; teamId?: number }+ ): Promise<void> {const errorMessage = error instanceof Error ? error.message : String(error)const errorName = error instanceof Error ? error.name : 'UnknownError'+ const teamIdLabel = context.teamId?.toString() ?? 'unknown'- logMessageDlqCounter.inc({ reason: errorName, team_id: message.teamId.toString() })- recordLogMessageDlq(errorName, message.teamId.toString())+ logMessageDlqCounter.inc({ reason: errorName, team_id: teamIdLabel })+ recordLogMessageDlq(errorName, teamIdLabel)try {await this.deps.outputs.queueMessages(LOGS_DLQ_OUTPUT, [{- value: message.message.value,+ value: message.value,key: null,headers: {- ...parseKafkaHeaders(message.message.headers),- token: message.token,- team_id: message.teamId.toString(),+ ...parseKafkaHeaders(message.headers),+ ...(context.token !== undefined ? { token: context.token } : {}),+ team_id: teamIdLabel,error_message: errorMessage,error_name: errorName,failed_at: new Date().toISOString(),+ // Where the message came from, so a quarantined record can be read back+ // from the source partition and replayed against the consumer.+ source_topic: message.topic,+ source_partition: message.partition.toString(),+ source_offset: message.offset.toString(),},},])@@ -1042,7 +1096,13 @@ export class LogsIngestionConsumer {logger.error('Failed to produce message to DLQ', {error: dlqError,originalError: errorMessage,+ partition: message.partition,+ offset: message.offset,})+ // Rethrow: quarantine is what lets the caller move past the record. Swallowing this+ // would commit the source offset with no copy anywhere, which loses the payload for+ // good. Failing the batch keeps the record on the source topic until the DLQ is back.+ throw dlqError}}@@ -1191,10 +1251,28 @@ export class LogsIngestionConsumer {return}- const bytesUncompressed = parseInt(headers.bytes_uncompressed ?? '0', 10)- const bytesUncompressedRecords = parseInt(headers.bytes_uncompressed_records ?? '0', 10)- const bytesCompressed = parseInt(headers.bytes_compressed ?? '0', 10)- const recordCount = parseInt(headers.record_count ?? '0', 10)+ const bytesUncompressed = parseSizeHeader(headers.bytes_uncompressed)+ const bytesUncompressedRecords = parseSizeHeader(headers.bytes_uncompressed_records)+ const bytesCompressed = parseSizeHeader(headers.bytes_compressed)+ const recordCount = parseSizeHeader(headers.record_count)++ if (+ bytesUncompressed === null ||+ bytesUncompressedRecords === null ||+ bytesCompressed === null ||+ recordCount === null+ ) {+ logger.error('🔴', 'logs_ingestion_invalid_size_headers', {+ teamId: team.id,+ partition: message.partition,+ offset: message.offset,+ })+ await this.produceRawToDlq(message, new Error('invalid_size_headers'), {+ token,+ teamId: team.id,+ })+ return+ }if (bytesUncompressedRecords > bytesUncompressed) {// Billing can only switch from payload-based to records-based bytes if the@@ -1212,9 +1290,16 @@ export class LogsIngestionConsumer {recordCount,})} catch (e) {- logger.error('Error parsing message', e)+ // A message we cannot parse is message-scoped and will fail the same way on+ // every redelivery, so quarantine it instead of discarding the payload.+ logger.error('🔴', 'logs_ingestion_parse_error', {+ error: String(e),+ partition: message.partition,+ offset: message.offset,+ })logMessageDroppedCounter.inc({ reason: 'parse_error', team_id: 'unknown' })recordLogMessageDropped('parse_error', 'unknown')+ await this.produceRawToDlq(message, e, {})return}})@@ -1226,8 +1311,23 @@ export class LogsIngestionConsumer {public async processKafkaBatch(messages: Message[]): Promise<{ backgroundTask?: Promise<any>; messages: LogsIngestionMessage[] }> {- const events = await this._parseKafkaBatch(messages)- return await this.processBatch(events)+ try {+ const events = await this._parseKafkaBatch(messages)+ return await this.processBatch(events)+ } catch (error) {+ // Rethrow: the consumer deliberately lets a batch failure crash the process, which is+ // what preserves at-least-once. We do not DLQ here — everything on this path (quota+ // lookups, the rate limiter) is infrastructure-scoped, and quarantining a whole batch+ // over a Redis blip would drop good data. Name the records first so the restart loop+ // that follows points somewhere.+ logger.error('🔴', `${this.name} - batch failed`, {+ error: String(error),+ stack: error instanceof Error ? error.stack : undefined,+ size: messages.length,+ offsets: describeBatchPosition(messages),+ })+ throw error+ }}public async start(): Promise<void> {@@ -1235,6 +1335,7 @@ export class LogsIngestionConsumer {await this.kafkaConsumer.connect(async (messages) => {logger.info('🔁', `${this.name} - handling batch`, {size: messages.length,+ offsets: describeBatchPosition(messages),})return await instrumentFn('logsIngestionConsumer.handleEachBatch', async () => {diff --git a/nodejs/src/servers/base-server.ts b/nodejs/src/servers/base-server.tsindex df45489e9d6b..46d7b20b1756 100644--- a/nodejs/src/servers/base-server.ts+++ b/nodejs/src/servers/base-server.ts@@ -210,6 +210,14 @@ export class ServerLifecycle {process.on('unhandledRejection', rejectionHandler)const exceptionHandler = async (error: Error) => {+ // Log before stopping. Without this the process exits silently, so a crash loop+ // shows only a rising restart count and whatever the service logged last.+ logger.error('🤮', `Uncaught Exception`, { error: String(error), stack: error?.stack })++ captureException(error, {+ extra: { detected_at: `ServerLifecycle on uncaughtException` },+ })+await this.stop(getCleanupResources, error)}this.processListeners.set('uncaughtException', exceptionHandler)