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.

fix(logs): bound json body enrichment and share size accounting (#102850)

Jon McCallum98317ebeca74
diff --git a/docs/published/docs/logs/logs-config.mdx b/docs/published/docs/logs/logs-config.mdx
index 13228cf15db9..751c1c339688 100644
--- a/docs/published/docs/logs/logs-config.mdx
+++ b/docs/published/docs/logs/logs-config.mdx
@@ -58,6 +58,16 @@ This setting changes only how patterns are derived. The stored log body is never
A change reaches log ingestion within a few minutes. Records ingested in that window keep the patterns derived from the previous configuration.
+## JSON body parsing limits
+
+**JSON parse logs** flattens a JSON body into up to 50 attributes. Sender-supplied attributes win on key collisions. Nested objects use dotted paths; arrays in the body keep their existing indexed paths, such as `items.0.name`. The original body is retained.
+
+Body enrichment has a 1 MiB byte budget for the body, severity text, and the keys and values in both log and resource attributes combined. This is a logical content limit, not the size of the encoded Avro record. The same accounting applies to log transformations. A body can fit on its own but exceed this limit when its extracted fields are added.
+
+Flattening visits at most 10,000 JSON nodes, allows a depth of 128, and budgets at most 1 MiB for generated paths and separately for retained serialized attributes. It retains at most 50 fields but continues the bounded traversal to preserve later collisions with those fields. If a size or traversal budget is exceeded, enrichment adds no fields and leaves the input record unchanged. Other configured ingestion stages still apply.
+
+Operators can monitor `logs_ingestion_json_enrichment_skipped_total` with `reason` values `input_size`, `flatten_budget`, and `output_size`. These counts indicate skipped enrichment, not dropped logs.
+
## JSON attribute parsing configuration
In **Settings > Project > Logs > JSON parse log attribute**, enter one attribute key and select **Save**. Clear the key and save to turn it off. This setting is independent of **JSON parse logs**, which parses the log body. The control uses the same project-admin and Logs Editor restrictions as the other Logs settings.
diff --git a/nodejs/src/logs/ingestion-otel-metrics.test.ts b/nodejs/src/logs/ingestion-otel-metrics.test.ts
index 3e809fa5c66d..b24cc3867bc7 100644
--- a/nodejs/src/logs/ingestion-otel-metrics.test.ts
+++ b/nodejs/src/logs/ingestion-otel-metrics.test.ts
@@ -8,6 +8,7 @@ import {
} from '@opentelemetry/sdk-metrics'
import {
+ recordJsonEnrichmentSkipped,
recordLogMessageDlq,
recordLogMessageDropped,
recordLogProcessingDuration,
@@ -51,6 +52,13 @@ describe('ingestion-otel-metrics', () => {
.flatMap((m) => m.dataPoints as unknown as readonly DataPoint<T>[])
it.each([
+ [
+ 'recordJsonEnrichmentSkipped',
+ 'logs_ingestion_json_enrichment_skipped_total',
+ () => recordJsonEnrichmentSkipped('output_size'),
+ { reason: 'output_size' },
+ 1,
+ ],
[
'recordLogsReceived bytes',
'logs_ingestion_bytes_received_total',
diff --git a/nodejs/src/logs/ingestion-otel-metrics.ts b/nodejs/src/logs/ingestion-otel-metrics.ts
index 3195ff163331..c47d779b4879 100644
--- a/nodejs/src/logs/ingestion-otel-metrics.ts
+++ b/nodejs/src/logs/ingestion-otel-metrics.ts
@@ -25,6 +25,7 @@ interface LogsIngestionInstruments {
messagesDropped: Counter
messagesDlq: Counter
processingDuration: Histogram
+ jsonEnrichmentSkipped: Counter
}
/** Keep in lockstep with the logs_ingestion_processing_duration_seconds prom buckets. */
@@ -40,6 +41,9 @@ function getInstruments(): LogsIngestionInstruments {
description: 'Total uncompressed bytes received for logs ingestion',
unit: 'By',
}),
+ jsonEnrichmentSkipped: createCounterWithExemplars(meter, 'logs_ingestion_json_enrichment_skipped_total', {
+ description: 'Log body JSON enrichment skipped because a size or traversal budget was exceeded',
+ }),
recordsReceived: createCounterWithExemplars(meter, 'logs_ingestion_records_received_total', {
description: 'Total log records received',
}),
@@ -85,6 +89,10 @@ export const recordLogsReceived = swallowing((bytes: number, records: number): v
addPositive(recordsReceived, records)
})
+export const recordJsonEnrichmentSkipped = swallowing((reason: string): void => {
+ getInstruments().jsonEnrichmentSkipped.add(1, { reason })
+})
+
export const recordLogsAllowed = swallowing((bytes: number, records: number): void => {
const { bytesAllowed, recordsAllowed } = getInstruments()
addPositive(bytesAllowed, bytes)
diff --git a/nodejs/src/logs/log-record-avro.test.ts b/nodejs/src/logs/log-record-avro.test.ts
index c3b27f9dc799..c87bb63f177c 100644
--- a/nodejs/src/logs/log-record-avro.test.ts
+++ b/nodejs/src/logs/log-record-avro.test.ts
@@ -13,9 +13,12 @@ import {
extractJsonAttributesFromBody,
flattenJson,
logsJsonAttributeSniffCounter,
+ logsJsonEnrichmentSkippedCounter,
processLogMessageBuffer,
sniffJsonLogAttributes,
+ transformDecodedLogRecordsInPlace,
} from './log-record-avro'
+import { MAX_LOG_RECORD_BYTES, logRecordSizeBytes } from './log-record-size'
const LOG_RECORD_SCHEMA = avro.parse(`{
"type": "record",
@@ -112,6 +115,25 @@ const LOG_RECORD_SCHEMA = avro.parse(`{
]
}`)
+const createRecord = (overrides: Partial<LogRecord> = {}): LogRecord => ({
+ uuid: null,
+ trace_id: null,
+ span_id: null,
+ trace_flags: null,
+ timestamp: null,
+ observed_timestamp: null,
+ body: null,
+ severity_text: null,
+ severity_number: null,
+ service_name: null,
+ resource_attributes: null,
+ instrumentation_scope: null,
+ event_name: null,
+ attributes: null,
+ bytes_uncompressed: null,
+ ...overrides,
+})
+
describe('log-record-avro', () => {
describe('sniffJsonLogAttributes', () => {
it.each([
@@ -163,9 +185,78 @@ describe('log-record-avro', () => {
],
['handles empty object', {}, {}],
['handles empty array', { items: [] }, {}],
+ [
+ 'ignores inherited and non-enumerable properties',
+ Object.create({ inherited: true }, { kept: { value: 1, enumerable: true }, hidden: { value: 2 } }),
+ { kept: 1 },
+ ],
+ ['preserves later dotted-key overwrites', { path: { value: 1 }, 'path.value': 2 }, { 'path.value': 2 }],
+ ['preserves later nested overwrites', { 'path.value': 1, path: { value: 2 } }, { 'path.value': 2 }],
+ ['preserves top-level array indexing', ['a', null, { b: true }], { '0': 'a', '1': 'null', '2.b': true }],
])('%s', (_, input, expected) => {
expect(flattenJson(input)).toEqual(expected)
})
+
+ it.each([
+ [{ 'path.value': 1, filler: 2, path: { value: 3 } }, { 'path.value': 3 }],
+ [{ text: 1, '': { '2': 2 } }, { '2': 2 }],
+ [{ '-1': 1, '': { '0': 2 } }, { '0': 2 }],
+ [{ '2': 1, '': { '1': 2 } }, { '1': 2 }],
+ [{ '1': 1, '': { '2': 2 } }, { '1': 1 }],
+ ])('preserves ordering and collisions beyond the retained field limit for %j', (input, expected) => {
+ expect(flattenJson(input, '', 1)).toEqual(expected)
+ })
+
+ it.each([
+ ['unicode value at budget', { a: '😀' }, 7, { a: '😀' }],
+ ['unicode value over budget', { a: '😀' }, 6, null],
+ ['escaped value over budget', { a: '\n' }, 4, null],
+ ['cumulative paths over budget', { abc: { def: 1 } }, 9, null],
+ ['overwritten value releases budget', { 'a.b': 'long', a: { b: 1 } }, 20, { 'a.b': 1 }],
+ ] as const)('%s', (_name, input, maxBytes, expected) => {
+ expect(flattenJson(input, '', 50, maxBytes)).toEqual(expected)
+ })
+
+ it.each([128, 129, 10_000])('bounds deeply nested input at depth %i', (depth) => {
+ const input = parseJSON('{"nested":'.repeat(depth) + '1' + '}'.repeat(depth))
+ expect(flattenJson(input)).toEqual(depth <= 128 ? { [Array(depth).fill('nested').join('.')]: 1 } : null)
+ })
+
+ it.each([
+ Array.from({ length: 10_000 }, () => ({})),
+ Object.fromEntries(Array.from({ length: 10_000 }, (_, index) => [`key${index}`, {}])),
+ ])('bounds wide containers even when they contain no leaves', (input) => {
+ expect(flattenJson(input)).toBeNull()
+ })
+
+ it.each([
+ ['root', 9_999, false, false],
+ ['nested', 9_997, true, false],
+ ['nested', 9_998, true, true],
+ ] as const)(
+ 'honors the remaining node budget for %s objects with %i children',
+ (_name, count, nested, skipped) => {
+ const children = Object.fromEntries(Array.from({ length: count }, (_, index) => [`key${index}`, {}]))
+ const input = nested ? { first: true, children } : children
+
+ expect(flattenJson(input)).toEqual(skipped ? null : nested ? { first: true } : {})
+ }
+ )
+
+ it('stops key inspection when a sub-1 MiB object exceeds the node budget', () => {
+ const input = Object.fromEntries(Array.from({ length: 100_000 }, (_, index) => [String(index), 0]))
+ expect(Buffer.byteLength(JSON.stringify(input))).toBeLessThan(MAX_LOG_RECORD_BYTES)
+ const guardedInput = new Proxy(input, {
+ getOwnPropertyDescriptor(target, key) {
+ if (key === '10000') {
+ throw new Error('Inspected a key beyond the node budget')
+ }
+ return Reflect.getOwnPropertyDescriptor(target, key)
+ },
+ })
+
+ expect(flattenJson(guardedInput)).toBeNull()
+ })
})
describe('extractJsonAttributesFromBody', () => {
@@ -203,7 +294,7 @@ describe('log-record-avro', () => {
const body = JSON.stringify(largeObject)
const result = extractJsonAttributesFromBody(body)
- expect(Object.keys(result).length).toBe(50)
+ expect(Object.keys(result)).toEqual(Array.from({ length: 50 }, (_, index) => `key${index}`))
})
it('flattens nested JSON', () => {
@@ -335,6 +426,77 @@ describe('log-record-avro', () => {
})
describe('enrichLogRecordWithJsonAttributes', () => {
+ beforeEach(() => {
+ logsJsonEnrichmentSkippedCounter.reset()
+ })
+
+ it.each([-1, 0, 1])('checks merged UTF-8 content at the size boundary (%i bytes)', async (offset) => {
+ const record = createRecord({
+ body: '{"a":"é"}',
+ severity_text: 'info',
+ attributes: { existing: 'true' },
+ resource_attributes: { padding: '' },
+ })
+ const extractedBytes = 5
+ record.resource_attributes!.padding = 'x'.repeat(
+ MAX_LOG_RECORD_BYTES - logRecordSizeBytes(record) - extractedBytes + offset
+ )
+ const original = structuredClone(record)
+ const attributes = record.attributes
+
+ expect(enrichLogRecordWithJsonAttributes(record)).toBe(record)
+
+ if (offset > 0) {
+ expect(record).toEqual(original)
+ expect(record.attributes).toBe(attributes)
+ expect((await logsJsonEnrichmentSkippedCounter.get()).values).toEqual([
+ expect.objectContaining({ labels: { reason: 'output_size' }, value: 1 }),
+ ])
+ } else {
+ expect(record).toEqual({ ...original, attributes: { existing: 'true', a: '"é"' } })
+ expect(logRecordSizeBytes(record)).toBe(MAX_LOG_RECORD_BYTES + offset)
+ expect((await logsJsonEnrichmentSkippedCounter.get()).values).toEqual([])
+ }
+ })
+
+ it('counts only the winning sender value toward the merged budget', () => {
+ const record = createRecord({
+ body: JSON.stringify({ payload: 'x'.repeat(600 * 1024), added: true }),
+ attributes: { payload: '"sender"' },
+ })
+ enrichLogRecordWithJsonAttributes(record)
+ expect(record.attributes).toEqual({ payload: '"sender"', added: 'true' })
+ })
+
+ it.each([
+ ['input_size', JSON.stringify({ value: '😀'.repeat(MAX_LOG_RECORD_BYTES / 4) })],
+ ['output_size', JSON.stringify({ value: 'x'.repeat(600 * 1024), other: true })],
+ ['flatten_budget', '{"nested":'.repeat(129) + '1' + '}'.repeat(129)],
+ ])('preserves records and counts %s skips through the buffer processor', async (reason, body) => {
+ const record = createRecord({ body, attributes: { original: 'true' } })
+ const encoded = await encodeLogRecords(LOG_RECORD_SCHEMA, 'zstandard', [record])
+ const result = await processLogMessageBuffer(encoded, { json_parse_logs: true })
+ const [, , decoded] = await decodeLogRecords(result.value!)
+
+ expect(decoded).toEqual([{ ...record, bytes_uncompressed: null }])
+ expect((await logsJsonEnrichmentSkippedCounter.get()).values).toEqual([
+ expect.objectContaining({ labels: { reason }, value: 1 }),
+ ])
+ })
+
+ it('does not parse oversized bodies on direct or batch enrichment paths', async () => {
+ const body = JSON.stringify({ value: '😀'.repeat(MAX_LOG_RECORD_BYTES / 4) })
+ const parse = jest.spyOn(logBodyParse, 'parseLogBodyForIngestion')
+ try {
+ expect(extractJsonAttributesFromBody(body)).toEqual({})
+ enrichLogRecordWithJsonAttributes(createRecord({ body }))
+ await transformDecodedLogRecordsInPlace([createRecord({ body })], { json_parse_logs: true })
+ expect(parse.mock.calls.every(([input]) => input === null)).toBe(true)
+ } finally {
+ parse.mockRestore()
+ }
+ })
+
it('adds JSON attributes from body', () => {
const record: LogRecord = {
uuid: 'test-uuid',
diff --git a/nodejs/src/logs/log-record-avro.ts b/nodejs/src/logs/log-record-avro.ts
index d10f4dfd9e52..50d6d782fcb3 100644
--- a/nodejs/src/logs/log-record-avro.ts
+++ b/nodejs/src/logs/log-record-avro.ts
@@ -6,9 +6,10 @@ import { Readable } from 'stream'
import { instrumented } from '~/common/tracing/tracing-utils'
import type { LogsSettings } from '~/types'
-import { recordLogProcessingDuration } from './ingestion-otel-metrics'
+import { recordJsonEnrichmentSkipped, recordLogProcessingDuration } from './ingestion-otel-metrics'
import { type LogBodyParseResult, parseLogBodyForIngestion } from './log-body-parse'
import { EMPTY_PII, type PiiScrubStats, scrubLogRecord } from './log-pii-scrub'
+import { MAX_LOG_RECORD_BYTES, logRecordSizeBytes } from './log-record-size'
import {
type DropStats,
EMPTY_DROP_STATS,
@@ -17,6 +18,8 @@ import {
} from './pipeline/log-processing-pipeline'
const MAX_JSON_ATTRIBUTES = 50
+const MAX_JSON_NODES = 10_000
+const MAX_JSON_DEPTH = 128
const SPAN_LOGS_DECODE = 'logsIngestionConsumer.handleEachBatch.decodeLogRecords'
const SPAN_LOGS_PARSE_BODIES = 'logsIngestionConsumer.handleEachBatch.parseLogBodies'
@@ -40,6 +43,17 @@ export const logsJsonAttributeSniffCounter = new Counter({
labelNames: ['team_id', 'outcome'],
})
+export const logsJsonEnrichmentSkippedCounter = new Counter({
+ name: 'logs_ingestion_json_enrichment_skipped_total',
+ help: 'Log body JSON enrichment skipped because a size or traversal budget was exceeded',
+ labelNames: ['reason'],
+})
+
+function recordJsonEnrichmentSkip(reason: 'input_size' | 'flatten_budget' | 'output_size'): void {
+ logsJsonEnrichmentSkippedCounter.inc({ reason })
+ recordJsonEnrichmentSkipped(reason)
+}
+
export function sniffJsonLogAttributes(
records: readonly Pick<LogRecord, 'attributes'>[],
attributeKey: string,
@@ -184,7 +198,13 @@ const parseLogBodiesForIngestion = instrumented({
...logRecordProcessInstrumentOpts,
})(
(records: LogRecord[]): Promise<LogBodyParseResult[]> =>
- Promise.resolve(records.map((r) => parseLogBodyForIngestion(r.body)))
+ Promise.resolve(
+ records.map((record) =>
+ parseLogBodyForIngestion(
+ record.body && Buffer.byteLength(record.body) > MAX_LOG_RECORD_BYTES ? null : record.body
+ )
+ )
+ )
)
const encodeLogRecordsInstrumented = instrumented({
@@ -192,38 +212,109 @@ const encodeLogRecordsInstrumented = instrumented({
...logRecordProcessInstrumentOpts,
})(encodeLogRecords)
+function isArrayIndex(key: string): boolean {
+ const index = Number(key)
+ return Number.isInteger(index) && index >= 0 && index < 2 ** 32 - 1 && String(index) === key
+}
+
/**
* Flattens a JSON object into a flat key-value map with dot-notation keys.
* Arrays are indexed with numeric keys (e.g., "items.0.name").
*/
-export function flattenJson(obj: unknown, prefix = '', result: Record<string, any> = {}): Record<string, any> {
- if (obj === null || obj === undefined) {
- if (prefix) {
- result[prefix] = String(obj)
+function flattenJsonWithBudget(
+ obj: unknown,
+ prefix = '',
+ maxAttributes = MAX_JSON_ATTRIBUTES,
+ maxBytes = MAX_LOG_RECORD_BYTES
+): { values: Record<string, unknown>; attributes: Record<string, string> } | null {
+ const result: Record<string, unknown> = {}
+ const attributes: Record<string, string> = {}
+ const stack = [{ value: obj, prefix, depth: 0 }]
+ let nodes = 1
+ let pathBytes = Buffer.byteLength(prefix)
+ let attributeBytes = 0
+ let attributeCount = 0
+ let lastRetainedKey = ''
+
+ while (stack.length > 0) {
+ const entry = stack.pop()!
+ if (entry.depth > MAX_JSON_DEPTH || pathBytes > maxBytes) {
+ return null
}
- return result
- }
-
- if (typeof obj !== 'object') {
- if (prefix) {
- result[prefix] = obj
+ if (entry.value !== null && typeof entry.value === 'object') {
+ const value = entry.value as Record<string, unknown>
+ if (Array.isArray(value) && value.length + nodes > MAX_JSON_NODES) {
+ return null
+ }
+ const keys = Array.isArray(value) ? Array.from({ length: value.length }, (_, index) => String(index)) : []
+ if (!Array.isArray(value)) {
+ for (const key in value) {
+ if (!Object.hasOwn(value, key)) {
+ continue
+ }
+ if (nodes + keys.length >= MAX_JSON_NODES) {
+ return null
+ }
+ keys.push(key)
+ }
+ }
+ nodes += keys.length
+ for (let index = keys.length - 1; index >= 0; index--) {
+ const key = keys[index]
+ const childPrefix = entry.prefix ? `${entry.prefix}.${key}` : key
+ pathBytes += Buffer.byteLength(childPrefix)
+ if (pathBytes > maxBytes) {
+ return null
+ }
+ stack.push({ value: value[key], prefix: childPrefix, depth: entry.depth + 1 })
+ }
+ continue
}
- return result
- }
- if (Array.isArray(obj)) {
- for (let i = 0; i < obj.length; i++) {
- flattenJson(obj[i], prefix ? `${prefix}.${i}` : String(i), result)
+ const key = entry.prefix
+ if (!key || key === '__proto__' || maxAttributes <= 0) {
+ continue
+ }
+ const exists = Object.hasOwn(result, key)
+ if (!exists && attributeCount >= maxAttributes) {
+ if (!isArrayIndex(key)) {
+ continue
+ }
+ const lastKey = lastRetainedKey
+ if (isArrayIndex(lastKey) && Number(lastKey) <= Number(key)) {
+ continue
+ }
+ attributeBytes -= Buffer.byteLength(lastKey) + Buffer.byteLength(attributes[lastKey])
+ delete result[lastKey]
+ delete attributes[lastKey]
+ attributeCount--
+ }
+ const value = entry.value === null || entry.value === undefined ? String(entry.value) : entry.value
+ const serialized = JSON.stringify(value)
+ const valueBytes = Buffer.byteLength(serialized)
+ attributeBytes += exists ? valueBytes - Buffer.byteLength(attributes[key]) : Buffer.byteLength(key) + valueBytes
+ if (attributeBytes > maxBytes) {
+ return null
+ }
+ result[key] = value
+ attributes[key] = serialized
+ if (!exists) {
+ attributeCount++
+ if (attributeCount === maxAttributes) {
+ lastRetainedKey = Object.keys(result)[attributeCount - 1]
+ }
}
- return result
- }
-
- for (const [key, value] of Object.entries(obj)) {
- const newKey = prefix ? `${prefix}.${key}` : key
- flattenJson(value, newKey, result)
}
+ return { values: result, attributes }
+}
- return result
+export function flattenJson(
+ obj: unknown,
+ prefix = '',
+ maxAttributes = MAX_JSON_ATTRIBUTES,
+ maxBytes = MAX_LOG_RECORD_BYTES
+): Record<string, unknown> | null {
+ return flattenJsonWithBudget(obj, prefix, maxAttributes, maxBytes)?.values ?? null
}
function jsonAttributesFromBodyParse(bodyParse: LogBodyParseResult): Record<string, string> {
@@ -231,19 +322,12 @@ function jsonAttributesFromBodyParse(bodyParse: LogBodyParseResult): Record<stri
return {}
}
- const flattened = flattenJson(bodyParse.value)
- const newAttributes: Record<string, string> = {}
- let count = 0
-
- for (const [key, value] of Object.entries(flattened)) {
- if (count >= MAX_JSON_ATTRIBUTES) {
- break
- }
- count++
- newAttributes[key] = JSON.stringify(value)
+ const flattened = flattenJsonWithBudget(bodyParse.value)
+ if (flattened === null) {
+ recordJsonEnrichmentSkip('flatten_budget')
+ return {}
}
-
- return newAttributes
+ return flattened.attributes
}
/**
@@ -251,9 +335,32 @@ function jsonAttributesFromBodyParse(bodyParse: LogBodyParseResult): Record<stri
* Returns up to MAX_JSON_ATTRIBUTES attributes, without overwriting existing attributes.
*/
export function extractJsonAttributesFromBody(body: string | null): Record<string, string> {
+ if (body && Buffer.byteLength(body) > MAX_LOG_RECORD_BYTES) {
+ recordJsonEnrichmentSkip('input_size')
+ return {}
+ }
return jsonAttributesFromBodyParse(parseLogBodyForIngestion(body))
}
+function addJsonAttributes(record: LogRecord, jsonAttributes: Record<string, string>, recordBytes: number): void {
+ if (Object.keys(jsonAttributes).length === 0) {
+ return
+ }
+ for (const [key, value] of Object.entries(jsonAttributes)) {
+ if (!record.attributes || !Object.hasOwn(record.attributes, key)) {
+ recordBytes += Buffer.byteLength(key) + Buffer.byteLength(value)
+ if (recordBytes > MAX_LOG_RECORD_BYTES) {
+ recordJsonEnrichmentSkip('output_size')
+ return
+ }
+ }
+ }
+ record.attributes = {
+ ...jsonAttributes,
+ ...record.attributes, // existing attributes take precedence
+ }
+}
+
/**
* Processes a LogRecord by parsing its body as JSON and adding flattened attributes.
* Modifies the record in place and returns it.
@@ -266,16 +373,22 @@ export function enrichLogRecordWithJsonAttributes(record: LogRecord, bodyParse?:
return record
}
- const parse = bodyParse ?? parseLogBodyForIngestion(record.body)
- const existingAttributes = record.attributes || {}
- const jsonAttributes = jsonAttributesFromBodyParse(parse)
+ if (Buffer.byteLength(record.body) > MAX_LOG_RECORD_BYTES) {
+ recordJsonEnrichmentSkip('input_size')
+ return record
+ }
- if (Object.keys(jsonAttributes).length > 0) {
- record.attributes = {
- ...jsonAttributes,
- ...existingAttributes, // existing attributes take precedence
- }
+ const parse = bodyParse ?? parseLogBodyForIngestion(record.body)
+ if (parse.kind !== 'json_object_or_array') {
+ return record
}
+ const recordBytes = logRecordSizeBytes(record)
+ if (recordBytes > MAX_LOG_RECORD_BYTES) {
+ recordJsonEnrichmentSkip('input_size')
+ return record
+ }
+ const jsonAttributes = jsonAttributesFromBodyParse(parse)
+ addJsonAttributes(record, jsonAttributes, recordBytes)
return record
}
diff --git a/nodejs/src/logs/log-record-size.test.ts b/nodejs/src/logs/log-record-size.test.ts
new file mode 100644
index 000000000000..4150cf9b2af1
--- /dev/null
+++ b/nodejs/src/logs/log-record-size.test.ts
@@ -0,0 +1,11 @@
+import { logRecordSizeBytes } from './log-record-size'
+
+describe('logRecordSizeBytes', () => {
+ it.each([
+ [{ body: null, severity_text: null, attributes: null, resource_attributes: null }, 0],
+ [{ body: '', severity_text: '', attributes: {}, resource_attributes: {} }, 0],
+ [{ body: '😀', severity_text: 'é', attributes: { 漢: '"✓"' }, resource_attributes: { r: 'true' } }, 19],
+ ])('counts UTF-8 string and map content for %j', (record, expected) => {
+ expect(logRecordSizeBytes(record)).toBe(expected)
+ })
+})
diff --git a/nodejs/src/logs/log-record-size.ts b/nodejs/src/logs/log-record-size.ts
new file mode 100644
index 000000000000..299c36440793
--- /dev/null
+++ b/nodejs/src/logs/log-record-size.ts
@@ -0,0 +1,22 @@
+import type { LogRecord } from './log-record-avro'
+
+export const MAX_LOG_RECORD_BYTES = 1024 * 1024
+
+export function logRecordSizeBytes(
+ record: Pick<LogRecord, 'body' | 'severity_text' | 'attributes' | 'resource_attributes'>
+): number {
+ let bytes = 0
+ for (const value of [record.body, record.severity_text]) {
+ if (typeof value === 'string') {
+ bytes += Buffer.byteLength(value)
+ }
+ }
+ for (const attributes of [record.attributes, record.resource_attributes]) {
+ if (attributes) {
+ for (const [key, value] of Object.entries(attributes)) {
+ bytes += Buffer.byteLength(key) + Buffer.byteLength(value)
+ }
+ }
+ }
+ return bytes
+}
diff --git a/nodejs/src/logs/transformations/hog-log-exec.ts b/nodejs/src/logs/transformations/hog-log-exec.ts
index 6b27d86acb2f..2b670bb544e0 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 { decodeLogAttributeValue, encodeLogAttributeValue } from '../attribute-value'
import type { LogRecord } from '../log-record-avro'
+import { MAX_LOG_RECORD_BYTES, logRecordSizeBytes } from '../log-record-size'
import { idToHex } from '../metrics-rules/tally'
// Per-record execution primitives for log transformations. Pure functions, no I/O:
@@ -24,7 +25,7 @@ export const MAX_LOG_TRANSFORMATION_PRINT_LOGS = 5
/** Capture bounds whole ingest requests at 2MB; a transformation must not inflate a
* stored record past that boundary. The cap applies to the complete transformed
* output (body + severity + attribute map totals); oversize output is invalid. */
-export const MAX_TRANSFORMED_FIELD_BYTES = 1024 * 1024
+export const MAX_TRANSFORMED_FIELD_BYTES = MAX_LOG_RECORD_BYTES
export interface LogTransformationGlobals {
project: { id: number; name: string; url: string }
@@ -292,23 +293,16 @@ export function applyTransformResult(
// stored record past the boundary.
// Retained fields count too: a partial result (e.g. {body}) must not slip the
// record past the cap by riding on large fields it left untouched.
- let totalBytes = 0
const finalBody = body !== undefined ? body : record.body
const finalSeverity = severityText !== undefined ? severityText : record.severity_text
- for (const text of [finalBody, finalSeverity]) {
- if (typeof text === 'string') {
- totalBytes += Buffer.byteLength(text)
- }
- }
const finalAttributes = attributes !== undefined ? attributes : record.attributes
const finalResourceAttributes = resourceAttributes !== undefined ? resourceAttributes : record.resource_attributes
- for (const map of [finalAttributes, finalResourceAttributes]) {
- if (map) {
- for (const [key, value] of Object.entries(map)) {
- totalBytes += Buffer.byteLength(key) + Buffer.byteLength(value)
- }
- }
- }
+ const totalBytes = logRecordSizeBytes({
+ body: finalBody,
+ severity_text: finalSeverity,
+ attributes: finalAttributes,
+ resource_attributes: finalResourceAttributes,
+ })
if (totalBytes > MAX_TRANSFORMED_FIELD_BYTES) {
return 'invalid'
}