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): pro-rate size headers when drop rules remove rows (#63944)

Frank Hamand3fe3160fad3b
diff --git a/nodejs/src/logs-ingestion/logs-ingestion-consumer.test.ts b/nodejs/src/logs-ingestion/logs-ingestion-consumer.test.ts
index c6e57c5a8863..d43d5935b573 100644
--- a/nodejs/src/logs-ingestion/logs-ingestion-consumer.test.ts
+++ b/nodejs/src/logs-ingestion/logs-ingestion-consumer.test.ts
@@ -113,6 +113,67 @@ const createKafkaMessages = async (logData: any[], headers: Record<string, strin
return Promise.all(logData.map((data) => createKafkaMessage(data, headers)))
}
+// Single Kafka message carrying several log records, so a drop rule can remove some rows while
+// others survive (partial drop) — the path that re-encodes and re-forwards to the output topic.
+const createMultiRecordKafkaMessage = async (
+ logDataList: any[],
+ headers: Record<string, string> = {}
+): Promise<Message> => {
+ const avro = require('avsc')
+ const logRecordType = avro.Type.forSchema({
+ type: 'record',
+ name: 'LogRecord',
+ fields: [
+ { name: 'uuid', type: ['null', 'string'] },
+ { name: 'trace_id', type: ['null', 'bytes'] },
+ { name: 'span_id', type: ['null', 'bytes'] },
+ { name: 'trace_flags', type: ['null', 'int'] },
+ { name: 'timestamp', type: ['null', 'long'] },
+ { name: 'observed_timestamp', type: ['null', 'long'] },
+ { name: 'body', type: ['null', 'string'] },
+ { name: 'severity_text', type: ['null', 'string'] },
+ { name: 'severity_number', type: ['null', 'int'] },
+ { name: 'service_name', type: ['null', 'string'] },
+ { name: 'resource_attributes', type: ['null', { type: 'map', values: 'string' }] },
+ { name: 'instrumentation_scope', type: ['null', 'string'] },
+ { name: 'event_name', type: ['null', 'string'] },
+ { name: 'attributes', type: ['null', { type: 'map', values: 'string' }] },
+ ],
+ })
+
+ const records: LogRecord[] = logDataList.map((logData, i) => ({
+ uuid: `test-uuid-${offsetIncrementer}-${i}`,
+ trace_id: null,
+ span_id: null,
+ trace_flags: null,
+ timestamp: DateTime.now().toMillis() * 1000,
+ observed_timestamp: DateTime.now().toMillis() * 1000,
+ body: JSON.stringify(logData),
+ severity_text: logData.level || 'info',
+ severity_number: 9,
+ service_name: logData.service || 'test-service',
+ resource_attributes: null,
+ instrumentation_scope: null,
+ event_name: null,
+ attributes: null,
+ }))
+
+ const value = await encodeLogRecords(logRecordType, 'zstandard', records)
+
+ return {
+ key: null,
+ value,
+ size: value.length,
+ topic: 'test',
+ offset: offsetIncrementer++,
+ timestamp: DateTime.now().toMillis(),
+ partition: 1,
+ headers: Object.entries(headers).map(([key, value]) => ({
+ [key]: Buffer.from(value),
+ })),
+ }
+}
+
describe('LogsIngestionConsumer', () => {
let consumer: LogsIngestionConsumer
let hub: Hub
@@ -1683,6 +1744,48 @@ describe('LogsIngestionConsumer', () => {
// The fully-dropped message's 400-byte header is credited; only the kept one bills.
expect(teamBytesIngested()).toBe(600)
})
+
+ const outputHeaders = (): Record<string, string> | undefined =>
+ getProducedKafkaMessages().find((m) => m.topic === KAFKA_LOGS_CLICKHOUSE)?.headers as
+ | Record<string, string>
+ | undefined
+
+ // One message, two equal-content records: the info row is dropped, the error row survives.
+ // Shadow mode forwards the original gross headers; enabled mode scales both by the same
+ // dropped content fraction (~0.5), so the 500/1000 ratio is preserved.
+ it.each([
+ { label: 'shadow mode (default) forwards the original gross size headers', enabled: false },
+ { label: 'enabled mode pro-rates the forwarded size headers by the dropped fraction', enabled: true },
+ ])('$label', async ({ enabled }) => {
+ if (enabled) {
+ await consumer.stop()
+ consumer = await createLogsIngestionConsumer(
+ hub,
+ { LOGS_BILLING_PRORATE_ENABLED: true },
+ { samplingRulesCache: mockSamplingCache as SamplingRulesCache }
+ )
+ await deleteKeysWithPrefix(consumer['redis'], BASE_REDIS_KEY)
+ }
+
+ const message = await createMultiRecordKafkaMessage(
+ [createLogMessage({ level: 'info' }), createLogMessage({ level: 'error' })],
+ { token: team.api_token, bytes_uncompressed: '1000', bytes_compressed: '500', record_count: '2' }
+ )
+ await waitForBackgroundTasks(consumer.processKafkaBatch([message]))
+
+ const uncompressed = parseInt(outputHeaders()!.bytes_uncompressed, 10)
+ const compressed = parseInt(outputHeaders()!.bytes_compressed, 10)
+ if (!enabled) {
+ expect(uncompressed).toBe(1000)
+ expect(compressed).toBe(500)
+ return
+ }
+ expect(uncompressed).toBeGreaterThan(0)
+ expect(uncompressed).toBeLessThan(1000)
+ expect(compressed).toBeGreaterThan(0)
+ expect(compressed).toBeLessThan(500)
+ expect(compressed / uncompressed).toBeCloseTo(0.5, 5)
+ })
})
})
diff --git a/nodejs/src/logs-ingestion/logs-ingestion-consumer.ts b/nodejs/src/logs-ingestion/logs-ingestion-consumer.ts
index fd21c756ccd7..4e5f2444b976 100644
--- a/nodejs/src/logs-ingestion/logs-ingestion-consumer.ts
+++ b/nodejs/src/logs-ingestion/logs-ingestion-consumer.ts
@@ -575,6 +575,9 @@ export class LogsIngestionConsumer {
async () => this.resolveLogMessageBufferWithOptionalSampling(message, logsSettings)
)
+ let bytesUncompressedHeaderOverride: number | undefined
+ let bytesCompressedHeaderOverride: number | undefined
+
// Drop rules removed rows from this message — credit billing by the dropped
// content fraction. `bytesReceived` stays gross (what was sent); `bytesAllowed`
// (→ bytes_ingested) and `recordsAllowed` reflect only what survived the drops.
@@ -624,6 +627,16 @@ export class LogsIngestionConsumer {
billingRow.recordsAllowed - resolved.recordsDropped
)
}
+
+ // Scale both size headers down by the same dropped content fraction so
+ // downstream accounting sees only the surviving bytes.
+ const compressedCredit = billingByteReductionForDrops(
+ message.bytesCompressed,
+ resolved.contentBytesDropped,
+ resolved.contentBytesTotal
+ )
+ bytesUncompressedHeaderOverride = Math.max(0, header - contentCredit)
+ bytesCompressedHeaderOverride = Math.max(0, message.bytesCompressed - compressedCredit)
}
}
@@ -653,6 +666,12 @@ export class LogsIngestionConsumer {
team_id: message.teamId.toString(),
'json-parse': jsonParse.toString(),
'retention-days': retentionDays.toString(),
+ ...(bytesUncompressedHeaderOverride !== undefined
+ ? { bytes_uncompressed: bytesUncompressedHeaderOverride.toString() }
+ : {}),
+ ...(bytesCompressedHeaderOverride !== undefined
+ ? { bytes_compressed: bytesCompressedHeaderOverride.toString() }
+ : {}),
},
},
])