: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
chore(logs): split message-key selection out of the pattern masker (#92777)
Jon McCallum7cd0204fb4eb
diff --git a/nodejs/src/logs/log-pattern-mask.test.ts b/nodejs/src/logs/log-pattern-mask.test.tsindex 51b520835934..06e6bdbff5c4 100644--- a/nodejs/src/logs/log-pattern-mask.test.ts+++ b/nodejs/src/logs/log-pattern-mask.test.ts@@ -4,15 +4,18 @@ import RE2 from 're2'import {JSON_ARRAY,KEY_SET_MAX_KEYS,+ type LogPatternResult,MASK_RULES,MESSAGE_KEYS,PATTERN_CAPS,PATTERN_VERSION,- computeLogPattern,+ buildLogPattern,maskString,} from './log-pattern-mask'describe('log-pattern-mask', () => {+ const patternResult = (body: string | null | undefined): LogPatternResult => buildLogPattern(body, MESSAGE_KEYS)+describe('maskString', () => {it.each([['timestamp iso Z', 'started at 2026-08-24T10:20:45.123Z ok', 'started at <TIMESTAMP> ok'],@@ -120,7 +123,7 @@ describe('log-pattern-mask', () => {})})- describe('computeLogPattern', () => {+ describe('buildLogPattern', () => {it('masks before truncating, so a UUID straddling the cut point still yields its placeholder', () => {// Long enough that the raw UUID crosses the output cap, short enough that `<UUID>` does not.// Filled with a non-hex letter, or the run itself masks to `<HEX>`.@@ -128,19 +131,19 @@ describe('log-pattern-mask', () => {const body = `${head} 0f2d6faf-07e3-4cff-bf47-7efa1024aee2`expect(body.length).toBeGreaterThan(PATTERN_CAPS.maxOutputChars)- const result = computeLogPattern(body)+ const result = patternResult(body)expect(result.pattern).toEqual(`${head} <UUID>`)expect(result.maskedLength).toEqual(`${head} <UUID>`.length)})it('reports the pre-truncation masked length and truncates the pattern', () => {- const result = computeLogPattern('x'.repeat(PATTERN_CAPS.maxOutputChars * 2))+ const result = patternResult('x'.repeat(PATTERN_CAPS.maxOutputChars * 2))expect(result.pattern).toEqual('x'.repeat(PATTERN_CAPS.maxOutputChars))expect(result.maskedLength).toEqual(PATTERN_CAPS.maxOutputChars * 2)})it('caps the input before masking and reports it', () => {- const result = computeLogPattern(`${'z'.repeat(PATTERN_CAPS.maxInputChars)} 12345678`)+ const result = patternResult(`${'z'.repeat(PATTERN_CAPS.maxInputChars)} 12345678`)expect(result.inputCapped).toEqual(true)// The number sat past the input cap, so no rule ever saw it.expect(result.maskedLength).toEqual(PATTERN_CAPS.maxInputChars)@@ -149,7 +152,7 @@ describe('log-pattern-mask', () => {it('caps the raw body before the JSON parse, so an oversized JSON body is treated as truncated prose', () => {const body = JSON.stringify({ message: 'x'.repeat(PATTERN_CAPS.maxInputChars) })- const result = computeLogPattern(body)+ const result = patternResult(body)expect(result.inputCapped).toEqual(true)expect(result.bodyKind).toEqual('plaintext')expect(result.pattern).toEqual(body.slice(0, PATTERN_CAPS.maxOutputChars))@@ -175,13 +178,13 @@ describe('log-pattern-mask', () => {['json object behind leading whitespace', ' \n\t{"msg":"hi 9"}', 'json_object_or_array', 'hi <N>'],['prose body that opens like JSON', 'null pointer at line 4', 'plaintext', 'null pointer at line <N>'],])('body kind %s', (_name, body, expectedKind, expectedPattern) => {- const result = computeLogPattern(body)+ const result = patternResult(body)expect(result.bodyKind).toEqual(expectedKind)expect(result.pattern).toEqual(expectedPattern)})describe('key-set identity for message-less JSON objects', () => {- const patternOf = (body: string): string => computeLogPattern(body).pattern+ const patternOf = (body: string): string => patternResult(body).patternit('is independent of source key order', () => {expect(patternOf('{"b":1,"a":2}')).toEqual('<JSON:a,b>')@@ -195,13 +198,13 @@ describe('log-pattern-mask', () => {const expected = `<JSON:${keys.slice(0, 32).join(',')},+8>`expect(patternOf(forward)).toEqual(expected)expect(patternOf(reversed)).toEqual(expected)- expect(computeLogPattern(forward).jsonKeyCount).toEqual(40)+ expect(patternResult(forward).jsonKeyCount).toEqual(40)})it('reports the key count only for key-set patterns', () => {- expect(computeLogPattern('{"a":1}').jsonKeyCount).toEqual(1)- expect(computeLogPattern('[1,2]').jsonKeyCount).toBeUndefined()- expect(computeLogPattern('{"message":"hi"}').jsonKeyCount).toBeUndefined()+ expect(patternResult('{"a":1}').jsonKeyCount).toEqual(1)+ expect(patternResult('[1,2]').jsonKeyCount).toBeUndefined()+ expect(patternResult('{"message":"hi"}').jsonKeyCount).toBeUndefined()})it('renders an empty object as an empty key set', () => {@@ -290,7 +293,7 @@ describe('log-pattern-mask', () => {const shapeDigest = (): string =>createHash('sha256')- .update([SHAPE_INPUTS, ...CORPUS.map((body) => computeLogPattern(body).pattern)].join('\x01'))+ .update([SHAPE_INPUTS, ...CORPUS.map((body) => patternResult(body).pattern)].join('\x01')).digest('hex').slice(0, 16)@@ -301,7 +304,7 @@ describe('log-pattern-mask', () => {it('reaches every mask rule, so a new rule cannot land without moving the digest', () => {const fires = MASK_RULES.map(() => 0)for (const body of CORPUS) {- computeLogPattern(body).ruleFires.forEach((count, index) => (fires[index] += count))+ patternResult(body).ruleFires.forEach((count, index) => (fires[index] += count))}// Reported by pattern, not name: klogtime is four rules under one name, so a name would// not say which of them the corpus misses.@@ -312,7 +315,7 @@ describe('log-pattern-mask', () => {// `parseLogBodyForIngestion` picks which branch of `computeLogPattern` runs, and it lives in// another module that neither half of the digest hashes. Reaching every kind is what makes a// change over there surface as a moved digest instead of as silence.- const kinds = [...new Set(CORPUS.map((body) => computeLogPattern(body).bodyKind))].sort()+ const kinds = [...new Set(CORPUS.map((body) => patternResult(body).bodyKind))].sort()expect(kinds).toEqual(['empty', 'json_object_or_array', 'json_string', 'plaintext', 'primitive'])})diff --git a/nodejs/src/logs/log-pattern-mask.ts b/nodejs/src/logs/log-pattern-mask.tsindex 175ab5febfcd..5dbca5b393d0 100644--- a/nodejs/src/logs/log-pattern-mask.ts+++ b/nodejs/src/logs/log-pattern-mask.ts@@ -128,11 +128,11 @@ export type LogPatternResult = {export const MESSAGE_KEYS = ['message', 'msg', 'event'] as const-function extractJsonMessage(value: object): string | null {+function extractJsonMessage(value: object, messageKeys: readonly string[]): string | null {if (Array.isArray(value)) {return null}- for (const key of MESSAGE_KEYS) {+ for (const key of messageKeys) {const candidate = (value as Record<string, unknown>)[key]if (typeof candidate === 'string') {return candidate@@ -151,9 +151,17 @@ function jsonKeySetPattern(value: object): string {return `<JSON:${kept.join(',')}${overflow > 0 ? `,+${overflow}` : ''}>`}-export function computeLogPattern(body: string | null | undefined): LogPatternResult {+export type PatternInputSelection =+ | { kind: 'empty'; bodyKind: PatternBodyKind; inputCapped: boolean }+ | { kind: 'mask'; input: string; bodyKind: PatternBodyKind; inputCapped: boolean }+ | { kind: 'pattern'; pattern: string; bodyKind: PatternBodyKind; inputCapped: boolean; jsonKeyCount?: number }++export function selectPatternInput(+ body: string | null | undefined,+ messageKeys: readonly string[]+): PatternInputSelection {if (body === null || body === undefined || body === '') {- return { pattern: '', bodyKind: 'empty', inputCapped: false, maskedLength: 0, ruleFires: [] }+ return { kind: 'empty', bodyKind: 'empty', inputCapped: false }}const inputCapped = body.length > PATTERN_CAPS.maxInputChars@@ -162,45 +170,61 @@ export function computeLogPattern(body: string | null | undefined): LogPatternReconst bodyKind: PatternBodyKind =parsed.kind === 'json_primitive' ? 'primitive' : parsed.kind === 'invalid_json' ? 'plaintext' : parsed.kind- let maskInput: stringswitch (parsed.kind) {case 'empty':- maskInput = ''- break+ return { kind: 'mask', input: '', bodyKind, inputCapped }case 'json_object_or_array': {- const message = extractJsonMessage(parsed.value)+ const message = extractJsonMessage(parsed.value, messageKeys)if (message === null) {const isArray = Array.isArray(parsed.value)- const pattern = isArray ? JSON_ARRAY : jsonKeySetPattern(parsed.value)return {- pattern: capOutput(pattern),+ kind: 'pattern',+ pattern: isArray ? JSON_ARRAY : jsonKeySetPattern(parsed.value),bodyKind,inputCapped,- maskedLength: pattern.length,...(isArray ? {} : { jsonKeyCount: Object.keys(parsed.value).length }),- ruleFires: [],}}- maskInput = message- break+ return { kind: 'mask', input: message, bodyKind, inputCapped }}case 'json_string':- maskInput = parsed.value- break+ return { kind: 'mask', input: parsed.value, bodyKind, inputCapped }case 'json_primitive':- maskInput = cappedBody- break+ return { kind: 'mask', input: cappedBody, bodyKind, inputCapped }case 'invalid_json':- maskInput = parsed.raw- break+ return { kind: 'mask', input: parsed.raw, bodyKind, inputCapped }+ }+}++export type MaskedPattern = {+ pattern: string+ maskedLength: number+ ruleFires: number[]+}++export function computeLogPattern(input: string): MaskedPattern {+ const { masked, ruleFires } = maskString(input)+ return { pattern: capOutput(masked), maskedLength: masked.length, ruleFires }+}++export function buildLogPattern(body: string | null | undefined, messageKeys: readonly string[]): LogPatternResult {+ const selection = selectPatternInput(body, messageKeys)+ const { bodyKind, inputCapped } = selection++ if (selection.kind === 'empty') {+ return { pattern: '', bodyKind, inputCapped, maskedLength: 0, ruleFires: [] }}- const { masked, ruleFires } = maskString(maskInput)- return {- pattern: capOutput(masked),- bodyKind,- inputCapped,- maskedLength: masked.length,- ruleFires,+ if (selection.kind === 'pattern') {+ return {+ pattern: capOutput(selection.pattern),+ bodyKind,+ inputCapped,+ maskedLength: selection.pattern.length,+ ...(selection.jsonKeyCount === undefined ? {} : { jsonKeyCount: selection.jsonKeyCount }),+ ruleFires: [],+ }}++ return { ...computeLogPattern(selection.input), bodyKind, inputCapped }}diff --git a/nodejs/src/logs/log-pattern-stage.ts b/nodejs/src/logs/log-pattern-stage.tsindex 4a75e28b0d54..cc07894b0356 100644--- a/nodejs/src/logs/log-pattern-stage.ts+++ b/nodejs/src/logs/log-pattern-stage.ts@@ -1,7 +1,7 @@import { performance } from 'node:perf_hooks'import { Counter, Histogram } from 'prom-client'-import { MASK_RULES, PATTERN_VERSION, computeLogPattern } from './log-pattern-mask'+import { MASK_RULES, MESSAGE_KEYS, PATTERN_VERSION, buildLogPattern } from './log-pattern-mask'import type { LogRecord } from './log-record-avro'import type { PipelineStage } from './pipeline/log-processing-pipeline'@@ -72,7 +72,7 @@ function stampBatch(records: LogRecord[]): void {for (const record of records) {const start = performance.now()- const result = computeLogPattern(record.body)+ const result = buildLogPattern(record.body, MESSAGE_KEYS)record.pattern = result.patternrecord.pattern_version = PATTERN_VERSIONlogsPatternMaskingDurationHistogram.observe((performance.now() - start) / 1000)