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(autoresearch): reduce logs transformation per-record latency (#100280)

Daniel Visca61e44d400325
diff --git a/nodejs/src/common/utils/tracked-re2.test.ts b/nodejs/src/common/utils/tracked-re2.test.ts
new file mode 100644
index 000000000000..e14835721492
--- /dev/null
+++ b/nodejs/src/common/utils/tracked-re2.test.ts
@@ -0,0 +1,60 @@
+import { createTrackedRE2 } from './tracked-re2'
+
+describe('createTrackedRE2', () => {
+ it('returns the same instance for the same pattern and flags within the cache', () => {
+ const a = createTrackedRE2('foo\\d+', undefined, 'test-cache')
+ const b = createTrackedRE2('foo\\d+', undefined, 'test-cache')
+ expect(a).toBe(b)
+ })
+
+ it('returns different instances for different patterns', () => {
+ const a = createTrackedRE2('foo', undefined, 'test-cache')
+ const b = createTrackedRE2('bar', undefined, 'test-cache')
+ expect(a).not.toBe(b)
+ })
+
+ it('distinguishes flags in the cache key', () => {
+ const a = createTrackedRE2('foo', undefined, 'test-cache')
+ const b = createTrackedRE2('foo', 'i', 'test-cache')
+ expect(a).not.toBe(b)
+ })
+
+ it.each([
+ ['foo', 'is', 'isfoo', undefined],
+ ['foo', 'i', 'ifoo', undefined],
+ ['bar', 'si', 'sibar', undefined],
+ ])('does not alias (%s, %p) with (%s, %p) in the cache key', (patternA, flagsA, patternB, flagsB) => {
+ const a = createTrackedRE2(patternA, flagsA, 'test-cache')
+ const b = createTrackedRE2(patternB, flagsB, 'test-cache')
+ expect(b).not.toBe(a)
+ expect(b.source).toBe(patternB)
+ expect(a.source).toBe(patternA)
+ })
+
+ it('cached instances remain usable across repeated exec/test calls', () => {
+ const re = createTrackedRE2('sk_(?:live|test)_([A-Za-z0-9]{10,})', undefined, 'test-cache')
+ expect(re.test('token sk_live_abcdefghijklmnop')).toBe(true)
+ expect(re.exec('token sk_live_abcdefghijklmnop')?.[1]).toBe('abcdefghijklmnop')
+ // Reuse after prior exec: no sticky lastIndex (no /g flag)
+ expect(re.exec('sk_test_zzzzzzzzzzzz')?.[1]).toBe('zzzzzzzzzzzz')
+ expect(re.test('no match here')).toBe(false)
+ })
+
+ it('does not cache patterns above the per-entry size limit', () => {
+ // A customer-controlled pattern can be arbitrarily large; caching even a handful
+ // of huge patterns would grow shared ingestion-worker memory without bound.
+ const hugePattern = 'a'.repeat(64 * 1024)
+ const a = createTrackedRE2(hugePattern, undefined, 'test-cache-huge')
+ const b = createTrackedRE2(hugePattern, undefined, 'test-cache-huge')
+ // Not cached: each call compiles a fresh instance.
+ expect(a).not.toBe(b)
+ })
+
+ it('still caches patterns at the boundary size', () => {
+ // Just under the limit must remain cached (we do not break the hot path).
+ const pattern = 'a'.repeat(1024)
+ const a = createTrackedRE2(pattern, undefined, 'test-cache-boundary')
+ const b = createTrackedRE2(pattern, undefined, 'test-cache-boundary')
+ expect(a).toBe(b)
+ })
+})
diff --git a/nodejs/src/common/utils/tracked-re2.ts b/nodejs/src/common/utils/tracked-re2.ts
index f5ea060b57b1..dd63321689b9 100644
--- a/nodejs/src/common/utils/tracked-re2.ts
+++ b/nodejs/src/common/utils/tracked-re2.ts
@@ -25,9 +25,65 @@ const re2CreationCounter = new Counter({
* @param flags Optional regex flags (e.g., 'g', 'i', 'm')
* @param source Label to identify where this allocation came from (for debugging)
* @returns RE2 instance
+ *
+ * Instances are cached by (pattern, flags) in a small LRU: RE2 compilation is the
+ * dominant cost of a regex evaluation, and hot paths (log transformations, sampling,
+ * PII scrub) recompile the same handful of patterns for every record at 100k+/s.
+ * Only string patterns without the `g` flag are cached: a `g`/`y` regex carries
+ * mutable `lastIndex` state across exec() calls, so sharing it would corrupt matches.
+ * The cache is bounded so adversarial or high-cardinality patterns cannot grow it
+ * without limit (each RE2 holds native memory).
+ *
+ * Two bounds guard the cache, not one:
+ * - entry count (RE2_CACHE_MAX_ENTRIES) caps how many patterns are held, and
+ * - per-entry size (RE2_CACHE_MAX_PATTERN_BYTES) caps how large any single
+ * cached pattern may be.
+ * The count bound alone is not sufficient: a customer-controlled transformation
+ * could feed a handful of multi-megabyte patterns into the cache, and each cached
+ * RE2 holds native memory proportional to its pattern, growing shared
+ * ingestion-worker memory without limit. Oversized patterns are compiled fresh on
+ * every call and never stored.
*/
+const RE2_CACHE_MAX_ENTRIES = 256
+// Patterns larger than this are compiled but never cached. 8 KB is far above any
+// legitimate transformation pattern yet small enough that the maximum native memory
+// the cache can hold stays bounded (~256 × 8 KB of pattern source, plus compiled
+// program size) regardless of attacker input.
+const RE2_CACHE_MAX_PATTERN_BYTES = 8 * 1024
+const re2Cache = new Map<string, RE2>()
+
export function createTrackedRE2(pattern: string | RegExp, flags?: string, source = 'unknown'): RE2 {
+ const cacheable =
+ typeof pattern === 'string' &&
+ pattern.length <= RE2_CACHE_MAX_PATTERN_BYTES &&
+ !flags?.includes('g') &&
+ !flags?.includes('y')
+ if (!cacheable) {
+ re2CreationCounter.inc({ source })
+ return (flags ? new RE2(pattern, flags) : new RE2(pattern)) as RE2
+ }
+
+ // Serialize the (flags, pattern) pair: concatenating without a separator lets
+ // distinct pairs alias each other (e.g. ('foo', 'is') and ('isfoo', undefined)),
+ // so the cache would hand back a regex compiled from the wrong pattern/flags.
+ const key = JSON.stringify([flags ?? '', pattern])
+ const cached = re2Cache.get(key)
+ if (cached) {
+ // Refresh recency: delete+set moves the entry to the LRU tail.
+ re2Cache.delete(key)
+ re2Cache.set(key, cached)
+ return cached
+ }
+
re2CreationCounter.inc({ source })
- const regex = flags ? new RE2(pattern, flags) : new RE2(pattern)
- return regex as RE2
+ const regex = (flags ? new RE2(pattern, flags) : new RE2(pattern)) as RE2
+ re2Cache.set(key, regex)
+ if (re2Cache.size > RE2_CACHE_MAX_ENTRIES) {
+ // Evict the least-recently-used entry (Map preserves insertion order).
+ const oldest = re2Cache.keys().next().value
+ if (oldest !== undefined) {
+ re2Cache.delete(oldest)
+ }
+ }
+ return regex
}
diff --git a/nodejs/src/logs/attribute-value.test.ts b/nodejs/src/logs/attribute-value.test.ts
new file mode 100644
index 000000000000..eada41ddcbd2
--- /dev/null
+++ b/nodejs/src/logs/attribute-value.test.ts
@@ -0,0 +1,44 @@
+import { decodeLogAttributeValue, encodeLogAttributeValue } from './attribute-value'
+
+describe('decodeLogAttributeValue', () => {
+ it.each([
+ ['plain quoted string', '"error"', 'error'],
+ ['empty quoted string', '""', ''],
+ ['quoted number-like string', '"3"', '3'],
+ ['unquoted value passes through', 'error', 'error'],
+ ['unquoted number passes through', '123', '123'],
+ ['single leading quote only', '"error', '"error'],
+ ['single trailing quote only', 'error"', 'error"'],
+ ['too short to be quoted', '"', '"'],
+ ['escaped quote inside', '"say \\"hi\\""', 'say "hi"'],
+ ['escaped backslash inside', '"a\\\\b"', 'a\\b'],
+ ['unicode escape', '"\\u0041BC"', 'ABC'],
+ ['newline escape', '"a\\nb"', 'a\nb'],
+ ['invalid JSON quoted value passes through', '"unterminated\\', '"unterminated\\'],
+ ['quoted-but-invalid JSON passes through as-is', '"a"b"', '"a"b"'],
+ ['multibyte content', '"héllo wörld"', 'héllo wörld'],
+ ['quoted JSON-looking string', '"{\\"a\\":1}"', '{"a":1}'],
+ ])('%s', (_name, input, expected) => {
+ expect(decodeLogAttributeValue(input)).toBe(expected)
+ })
+
+ it('matches JSON.parse semantics on quoted strings', () => {
+ const cases = ['"error"', '"3"', '"a\\nb"', '"\\u0041"', '"say \\"hi\\""', '"a\\\\b"', '""']
+ for (const input of cases) {
+ // oxlint-disable-next-line eslint-js/no-restricted-syntax
+ expect(decodeLogAttributeValue(input)).toBe(JSON.parse(input))
+ }
+ })
+})
+
+describe('encodeLogAttributeValue', () => {
+ it.each([
+ ['plain string is JSON-encoded', 'error', '"error"'],
+ ['already-encoded string passes through', '"error"', '"error"'],
+ ['number passes through', '123', '123'],
+ ['boolean passes through', 'true', 'true'],
+ ['object passes through', '{"a":1}', '{"a":1}'],
+ ])('%s', (_name, input, expected) => {
+ expect(encodeLogAttributeValue(input)).toBe(expected)
+ })
+})
diff --git a/nodejs/src/logs/attribute-value.ts b/nodejs/src/logs/attribute-value.ts
index 4e9c239eb97b..0766bd6c8ccc 100644
--- a/nodejs/src/logs/attribute-value.ts
+++ b/nodejs/src/logs/attribute-value.ts
@@ -1,5 +1,3 @@
-import { parseJSON } from '~/common/utils/json-parse'
-
/**
* Attribute values arrive JSON-encoded from capture (`any_value_to_json`): a string
* attribute is stored as `"error"` (with quotes), a number as `123`. The ClickHouse
@@ -7,11 +5,24 @@ import { parseJSON } from '~/common/utils/json-parse'
* the Logs UI. Every ingestion-time consumer of the attribute maps (transformations,
* drop-rule matching, metric-rule tallying) must see the same decoded values —
* otherwise `record.attributes['level'] == 'error'` silently never matches.
+ *
+ * Uses JSON.parse directly, not the instrumented parseJSON wrapper: this runs per
+ * attribute per record at 100k+ records/s, and the wrapper's two performance.now()
+ * calls plus a Prometheus Summary.observe per parse cost more than the parse itself.
*/
export function decodeLogAttributeValue(value: string): string {
if (value.length >= 2 && value.startsWith('"') && value.endsWith('"')) {
+ // A quoted string whose interior has no backslash and no quote is escape-free
+ // valid JSON, so the decode is a plain slice and JSON.parse would return the
+ // identical string. Anything else ('"a"b"', escapes) falls through to
+ // JSON.parse to preserve its exact accept/reject behavior.
+ const interior = value.slice(1, -1)
+ if (!interior.includes('\\') && !interior.includes('"')) {
+ return interior
+ }
try {
- const parsed = parseJSON(value)
+ // oxlint-disable-next-line eslint-js/no-restricted-syntax
+ const parsed = JSON.parse(value)
if (typeof parsed === 'string') {
return parsed
}
@@ -30,7 +41,8 @@ export function decodeLogAttributeValue(value: string): string {
*/
export function encodeLogAttributeValue(value: string): string {
try {
- parseJSON(value)
+ // oxlint-disable-next-line eslint-js/no-restricted-syntax
+ JSON.parse(value)
return value
} catch {
return JSON.stringify(value)
diff --git a/nodejs/src/logs/transformations/benchmarks/bench-stats.ts b/nodejs/src/logs/transformations/benchmarks/bench-stats.ts
new file mode 100644
index 000000000000..7484b65610f4
--- /dev/null
+++ b/nodejs/src/logs/transformations/benchmarks/bench-stats.ts
@@ -0,0 +1,42 @@
+export interface BenchStats {
+ programId: string
+ recordId: string
+ meanUs: number
+ p50Us: number
+ p95Us: number
+ p99Us: number
+ maxUs: number
+}
+
+export function computeBenchStats(programId: string, recordId: string, durationsUs: number[]): BenchStats {
+ const sorted = [...durationsUs].sort((a, b) => a - b)
+ const pick = (p: number): number => sorted[Math.min(sorted.length - 1, Math.floor((p / 100) * sorted.length))]
+ return {
+ programId,
+ recordId,
+ meanUs: sorted.reduce((a, b) => a + b, 0) / sorted.length,
+ p50Us: pick(50),
+ p95Us: pick(95),
+ p99Us: pick(99),
+ maxUs: sorted[sorted.length - 1],
+ }
+}
+
+export function printBenchStatsTable(title: string, iterations: number, allStats: BenchStats[]): void {
+ console.info(`\n${title} (${iterations} iterations each, µs):\n`)
+ const header = ['program', 'record', 'mean', 'p50', 'p95', 'p99', 'max']
+ const rows = allStats.map((s) => [
+ s.programId,
+ s.recordId,
+ s.meanUs.toFixed(1),
+ s.p50Us.toFixed(1),
+ s.p95Us.toFixed(1),
+ s.p99Us.toFixed(1),
+ s.maxUs.toFixed(1),
+ ])
+ const widths = header.map((h, i) => Math.max(h.length, ...rows.map((r) => r[i].length)))
+ console.info(header.map((h, i) => h.padEnd(widths[i])).join(' '))
+ for (const row of rows) {
+ console.info(row.map((c, i) => c.padEnd(widths[i])).join(' '))
+ }
+}
diff --git a/nodejs/src/logs/transformations/benchmarks/hogvm-log-bench.ts b/nodejs/src/logs/transformations/benchmarks/hogvm-log-bench.ts
index 527faaa276ad..107dc7713820 100644
--- a/nodejs/src/logs/transformations/benchmarks/hogvm-log-bench.ts
+++ b/nodejs/src/logs/transformations/benchmarks/hogvm-log-bench.ts
@@ -1,5 +1,6 @@
import { compileHog } from '~/cdp/templates/compiler'
+import { computeBenchStats, printBenchStatsTable } from './bench-stats'
import { BENCH_LOG_RECORDS, BENCH_PROGRAMS, buildBenchGlobals } from './fixtures'
import { execBenchProgram } from './hogvm-exec'
@@ -16,28 +17,13 @@ const WARMUP_ITERATIONS = 500
const ITERATIONS = 5_000
const TIMEOUT_MS = 10
-interface BenchStats {
- programId: string
- recordId: string
- meanUs: number
- p50Us: number
- p95Us: number
- p99Us: number
- maxUs: number
-}
-
-function percentile(sorted: number[], p: number): number {
- const idx = Math.min(sorted.length - 1, Math.floor((p / 100) * sorted.length))
- return sorted[idx]
-}
-
async function main(): Promise<void> {
console.info(`Compiling ${BENCH_PROGRAMS.length} Hog programs via bin/hog...`)
const compiled = await Promise.all(
BENCH_PROGRAMS.map(async (program) => ({ program, bytecode: await compileHog(program.hog) }))
)
- const allStats: BenchStats[] = []
+ const allStats = []
for (const { program, bytecode } of compiled) {
for (const { id: recordId, record } of BENCH_LOG_RECORDS) {
@@ -59,35 +45,11 @@ async function main(): Promise<void> {
durationsUs.push(durationMs * 1000)
}
- durationsUs.sort((a, b) => a - b)
- allStats.push({
- programId: program.id,
- recordId,
- meanUs: durationsUs.reduce((a, b) => a + b, 0) / durationsUs.length,
- p50Us: percentile(durationsUs, 50),
- p95Us: percentile(durationsUs, 95),
- p99Us: percentile(durationsUs, 99),
- maxUs: durationsUs[durationsUs.length - 1],
- })
+ allStats.push(computeBenchStats(program.id, recordId, durationsUs))
}
}
- console.info(`\nHogVM per-record execution cost (${ITERATIONS} iterations each, µs):\n`)
- const header = ['program', 'record', 'mean', 'p50', 'p95', 'p99', 'max']
- const rows = allStats.map((s) => [
- s.programId,
- s.recordId,
- s.meanUs.toFixed(1),
- s.p50Us.toFixed(1),
- s.p95Us.toFixed(1),
- s.p99Us.toFixed(1),
- s.maxUs.toFixed(1),
- ])
- const widths = header.map((h, i) => Math.max(h.length, ...rows.map((r) => r[i].length)))
- console.info(header.map((h, i) => h.padEnd(widths[i])).join(' '))
- for (const row of rows) {
- console.info(row.map((c, i) => c.padEnd(widths[i])).join(' '))
- }
+ printBenchStatsTable('HogVM per-record execution cost', ITERATIONS, allStats)
const overallMean = allStats.reduce((a, s) => a + s.meanUs, 0) / allStats.length
console.info(`\nOverall mean across programs/records: ${overallMean.toFixed(1)}µs/record`)
diff --git a/nodejs/src/logs/transformations/benchmarks/transformer-log-bench.serial.test.ts b/nodejs/src/logs/transformations/benchmarks/transformer-log-bench.serial.test.ts
new file mode 100644
index 000000000000..55b2b0a2bebd
--- /dev/null
+++ b/nodejs/src/logs/transformations/benchmarks/transformer-log-bench.serial.test.ts
@@ -0,0 +1,57 @@
+// Serial: concurrent workers invalidate this CPU-performance threshold.
+import { compileHog } from '~/cdp/templates/compiler'
+
+import type { LogRecord } from '../../log-record-avro'
+import { buildLogRecordGlobals, executeLogTransformation } from '../hog-log-exec'
+import { BENCH_LOG_RECORDS, BENCH_PROGRAMS } from './fixtures'
+
+jest.setTimeout(60_000)
+
+describe('logs transformation production-path benchmark', () => {
+ // Ceiling is ~14x the expected mean (~35µs/record): generous enough to never flake
+ // on a loaded CI worker, tight enough to catch an order-of-magnitude regression in
+ // the per-record production path (globals build + VM run + result apply).
+ const CEILING_US_PER_RECORD = 500
+ const ITERATIONS = 200
+ const TIMEOUT_MS = 10
+
+ it.each(BENCH_PROGRAMS.map((p) => [p.id, p] as const))(
+ 'program %s runs the full per-record path correctly and under the ceiling',
+ async (_id, program) => {
+ expect.hasAssertions()
+ const bytecode = await compileHog(program.hog)
+ const project = { id: 1, name: 'bench', url: 'http://localhost:8010/project/1' }
+
+ for (const { id: recordId, record } of BENCH_LOG_RECORDS) {
+ // Wire-form clone per iteration: execution mutates the record, and a
+ // pre-scrubbed record would let later iterations skip the regex work.
+ const runOnce = (): { durationUs: number; status: string } => {
+ // oxlint-disable-next-line eslint-js/no-restricted-syntax
+ const rec: LogRecord = JSON.parse(JSON.stringify(record))
+ const start = performance.now()
+ const globals = buildLogRecordGlobals(rec, project, { ...program.inputs })
+ const outcome = executeLogTransformation(bytecode, rec, globals, { timeoutMs: TIMEOUT_MS })
+ return { durationUs: (performance.now() - start) * 1000, status: outcome.status }
+ }
+
+ for (let i = 0; i < 50; i++) {
+ expect(runOnce().status).not.toBe('failed')
+ }
+
+ let totalUs = 0
+ for (let i = 0; i < ITERATIONS; i++) {
+ const { durationUs, status } = runOnce()
+ expect(status).not.toBe('failed')
+ totalUs += durationUs
+ }
+
+ const meanUs = totalUs / ITERATIONS
+ expect(meanUs).toBeLessThan(CEILING_US_PER_RECORD)
+
+ if (process.env.BENCH_DEBUG) {
+ console.info(`${program.id} × ${recordId}: ${meanUs.toFixed(1)}µs/record (production path)`)
+ }
+ }
+ }
+ )
+})
diff --git a/nodejs/src/logs/transformations/benchmarks/transformer-log-bench.ts b/nodejs/src/logs/transformations/benchmarks/transformer-log-bench.ts
new file mode 100644
index 000000000000..aa02caf8cfdc
--- /dev/null
+++ b/nodejs/src/logs/transformations/benchmarks/transformer-log-bench.ts
@@ -0,0 +1,108 @@
+import { performance } from 'perf_hooks'
+
+import { compileHog } from '~/cdp/templates/compiler'
+
+import { encodeLogAttributeValue } from '../../attribute-value'
+import type { LogRecord } from '../../log-record-avro'
+import { buildLogRecordGlobals, executeLogTransformation } from '../hog-log-exec'
+import { computeBenchStats, printBenchStatsTable } from './bench-stats'
+import { BENCH_LOG_RECORDS, BENCH_PROGRAMS } from './fixtures'
+
+// Micro-benchmark of the PRODUCTION per-record transformation path, unlike
+// hogvm-log-bench.ts which times raw HogVM execution only. The measured interval
+// covers everything transformSingleRecord does per record per function:
+// buildLogRecordGlobals (decode attribute maps, hex-encode ids) +
+// executeLogTransformation (VM run + convertHogToJS + applyTransformResult re-encode).
+// The gap between this number and hogvm-log-bench's is TS-side per-record overhead.
+//
+// Run with:
+// cd nodejs && pnpm exec tsx src/logs/transformations/benchmarks/transformer-log-bench.ts
+//
+// Pass/fail gate: exits 1 when the overall mean exceeds
+// REGRESSION_CEILING_US_PER_RECORD — ~10x the expected mean, generous enough to
+// never flake on a loaded machine, tight enough to catch an order-of-magnitude
+// regression in the per-record path.
+
+const WARMUP_ITERATIONS = 500
+const ITERATIONS = 5_000
+const TIMEOUT_MS = 10
+const REGRESSION_CEILING_US_PER_RECORD = 500
+
+// Wire-form encoding like the consumer's Avro decode produces: attribute values are
+// JSON-encoded strings.
+function toWireRecord(record: LogRecord): LogRecord {
+ return {
+ ...record,
+ attributes: record.attributes
+ ? Object.fromEntries(Object.entries(record.attributes).map(([k, v]) => [k, encodeLogAttributeValue(v)]))
+ : record.attributes,
+ resource_attributes: record.resource_attributes
+ ? Object.fromEntries(
+ Object.entries(record.resource_attributes).map(([k, v]) => [k, encodeLogAttributeValue(v)])
+ )
+ : record.resource_attributes,
+ }
+}
+
+async function main(): Promise<void> {
+ console.info(`Compiling ${BENCH_PROGRAMS.length} Hog programs via bin/hog...`)
+ const compiled = await Promise.all(
+ BENCH_PROGRAMS.map(async (program) => ({ program, bytecode: await compileHog(program.hog) }))
+ )
+
+ const project = { id: 1, name: 'bench', url: 'http://localhost:8010/project/1' }
+ const allStats = []
+
+ for (const { program, bytecode } of compiled) {
+ for (const { id: recordId, record } of BENCH_LOG_RECORDS) {
+ const wireRecord = toWireRecord(record)
+
+ // Fresh wire-record clone per iteration, kept outside the timer: execution
+ // mutates the record in place, and reusing a scrubbed record would let later
+ // iterations skip the regex-replace work.
+ const runOnce = (): { durationUs: number; status: string } => {
+ // oxlint-disable-next-line eslint-js/no-restricted-syntax
+ const rec: LogRecord = JSON.parse(JSON.stringify(wireRecord))
+ const start = performance.now()
+ const globals = buildLogRecordGlobals(rec, project, { ...program.inputs })
+ const outcome = executeLogTransformation(bytecode, rec, globals, { timeoutMs: TIMEOUT_MS })
+ const durationUs = (performance.now() - start) * 1000
+ return { durationUs, status: outcome.status }
+ }
+
+ for (let i = 0; i < WARMUP_ITERATIONS; i++) {
+ const { status } = runOnce()
+ if (status === 'failed') {
+ throw new Error(`Program ${program.id} failed on record ${recordId} during warmup`)
+ }
+ }
+
+ const durationsUs: number[] = []
+ for (let i = 0; i < ITERATIONS; i++) {
+ const { durationUs, status } = runOnce()
+ if (status === 'failed') {
+ throw new Error(`Program ${program.id} failed on record ${recordId}`)
+ }
+ durationsUs.push(durationUs)
+ }
+
+ allStats.push(computeBenchStats(program.id, recordId, durationsUs))
+ }
+ }
+
+ printBenchStatsTable('Production-path per-record cost', ITERATIONS, allStats)
+
+ const overallMeanUs = allStats.reduce((a, s) => a + s.meanUs, 0) / allStats.length
+ console.info(`\nMETRIC overall_mean_us_per_record: ${overallMeanUs.toFixed(1)}`)
+ if (overallMeanUs > REGRESSION_CEILING_US_PER_RECORD) {
+ console.error(
+ `FAIL: overall mean ${overallMeanUs.toFixed(1)}µs/record exceeds regression ceiling of ${REGRESSION_CEILING_US_PER_RECORD}µs/record`
+ )
+ process.exit(1)
+ }
+}
+
+main().catch((error) => {
+ console.error(error)
+ process.exit(1)
+})
diff --git a/nodejs/src/logs/transformations/hog-log-exec.ts b/nodejs/src/logs/transformations/hog-log-exec.ts
index f4b7a8c0fa54..6b27d86acb2f 100644
--- a/nodejs/src/logs/transformations/hog-log-exec.ts
+++ b/nodejs/src/logs/transformations/hog-log-exec.ts
@@ -57,24 +57,49 @@ export function buildLogRecordGlobals(
): LogTransformationGlobals {
return {
project,
- record: {
- body: record.body ?? null,
- attributes: decodeAttributeMap(record.attributes),
- resource_attributes: decodeAttributeMap(record.resource_attributes),
- severity_text: record.severity_text ?? null,
- severity_number: record.severity_number ?? null,
- service_name: record.service_name ?? null,
- instrumentation_scope: record.instrumentation_scope ?? null,
- event_name: record.event_name ?? null,
- timestamp: record.timestamp ?? null,
- observed_timestamp: record.observed_timestamp ?? null,
- trace_id: idToHex(record.trace_id, 16),
- span_id: idToHex(record.span_id, 8),
- },
+ record: buildLogRecordGlobalsRecord(record),
inputs,
}
}
+/** The `record` half of the globals, with attribute maps decoded once. */
+export function buildLogRecordGlobalsRecord(record: LogRecord): LogTransformationGlobals['record'] {
+ return {
+ body: record.body ?? null,
+ attributes: decodeAttributeMap(record.attributes),
+ resource_attributes: decodeAttributeMap(record.resource_attributes),
+ severity_text: record.severity_text ?? null,
+ severity_number: record.severity_number ?? null,
+ service_name: record.service_name ?? null,
+ instrumentation_scope: record.instrumentation_scope ?? null,
+ event_name: record.event_name ?? null,
+ timestamp: record.timestamp ?? null,
+ observed_timestamp: record.observed_timestamp ?? null,
+ trace_id: idToHex(record.trace_id, 16),
+ span_id: idToHex(record.span_id, 8),
+ }
+}
+
+/**
+ * Refreshes the mutable record fields of an already-built globals object from the
+ * (possibly transformed) record. Lets the per-function loop reuse one globals build
+ * per record instead of re-decoding every attribute map per function.
+ */
+export function refreshLogRecordGlobalsRecord(target: LogTransformationGlobals['record'], record: LogRecord): void {
+ target.body = record.body ?? null
+ target.attributes = decodeAttributeMap(record.attributes)
+ target.resource_attributes = decodeAttributeMap(record.resource_attributes)
+ target.severity_text = record.severity_text ?? null
+ target.severity_number = record.severity_number ?? null
+ target.service_name = record.service_name ?? null
+ target.instrumentation_scope = record.instrumentation_scope ?? null
+ target.event_name = record.event_name ?? null
+ target.timestamp = record.timestamp ?? null
+ target.observed_timestamp = record.observed_timestamp ?? null
+ target.trace_id = idToHex(record.trace_id, 16)
+ target.span_id = idToHex(record.span_id, 8)
+}
+
function decodeAttributeMap(map: Record<string, string> | null | undefined): Record<string, string> {
const out: Record<string, string> = {}
for (const [key, value] of Object.entries(map ?? {})) {
@@ -91,16 +116,22 @@ function decodeAttributeMap(map: Record<string, string> | null | undefined): Rec
*/
function encodeAttributeMap(
map: Record<string, string>,
- original: Record<string, string> | null | undefined
+ original: Record<string, string> | null | undefined,
+ // The map already decoded by the globals build: comparing against it decides
+ // "untouched" without decoding every original wire value a second time.
+ originalDecoded?: Record<string, string>
): Record<string, string> {
const out: Record<string, string> = {}
for (const [key, value] of Object.entries(map)) {
const originalValue = original?.[key]
- if (originalValue !== undefined && decodeLogAttributeValue(originalValue) === value) {
- out[key] = originalValue
- } else {
- out[key] = encodeLogAttributeValue(value)
+ if (originalValue !== undefined) {
+ const decoded = originalDecoded?.[key] ?? decodeLogAttributeValue(originalValue)
+ if (decoded === value) {
+ out[key] = originalValue
+ continue
+ }
}
+ out[key] = encodeLogAttributeValue(value)
}
return out
}
@@ -195,7 +226,14 @@ function redactSensitiveStrings(
return value
}
-export function applyTransformResult(record: LogRecord, execResult: unknown): 'mutated' | 'dropped' | 'invalid' {
+export function applyTransformResult(
+ record: LogRecord,
+ execResult: unknown,
+ decodedOriginals?: {
+ attributes?: Record<string, string>
+ resource_attributes?: Record<string, string>
+ }
+): 'mutated' | 'dropped' | 'invalid' {
if (execResult === null || execResult === undefined || execResult === false) {
return 'dropped'
}
@@ -282,11 +320,18 @@ export function applyTransformResult(record: LogRecord, execResult: unknown): 'm
record.severity_text = severityText
}
if (attributes !== undefined) {
- record.attributes = attributes === null ? null : encodeAttributeMap(attributes, record.attributes)
+ record.attributes =
+ attributes === null ? null : encodeAttributeMap(attributes, record.attributes, decodedOriginals?.attributes)
}
if (resourceAttributes !== undefined) {
record.resource_attributes =
- resourceAttributes === null ? null : encodeAttributeMap(resourceAttributes, record.resource_attributes)
+ resourceAttributes === null
+ ? null
+ : encodeAttributeMap(
+ resourceAttributes,
+ record.resource_attributes,
+ decodedOriginals?.resource_attributes
+ )
}
return 'mutated'
@@ -388,7 +433,10 @@ export function executeLogTransformation(
// can copy a decrypted input into a writable field, and Logs readers must not be
// able to recover encrypted input values that way.
const converted = redactSensitiveStrings(convertHogToJS(execResult.result), options.sensitiveValues)
- const applied = applyTransformResult(record, converted)
+ const applied = applyTransformResult(record, converted, {
+ attributes: globals.record.attributes,
+ resource_attributes: globals.record.resource_attributes,
+ })
if (applied === 'invalid') {
return {
diff --git a/nodejs/src/logs/transformations/logs-transformer.service.ts b/nodejs/src/logs/transformations/logs-transformer.service.ts
index 129ec911c04f..6e0073246e61 100644
--- a/nodejs/src/logs/transformations/logs-transformer.service.ts
+++ b/nodejs/src/logs/transformations/logs-transformer.service.ts
@@ -13,8 +13,9 @@ import { decodeLogAttributeValue, encodeLogAttributeValue } from '../attribute-v
import type { LogRecord } from '../log-record-avro'
import {
LogTransformationGlobals,
- buildLogRecordGlobals,
+ buildLogRecordGlobalsRecord,
executeLogTransformation,
+ refreshLogRecordGlobalsRecord,
resolveLogTransformationInputs,
} from './hog-log-exec'
@@ -288,10 +289,24 @@ export class LogsTransformerService {
addVmMs: (ms: number) => void
}
): boolean {
+ // Built once per record, not per function: the decoded maps change only when a
+ // function transforms the record, so globals are refreshed from the record
+ // between functions instead of rebuilt.
+ const globals: LogTransformationGlobals = {
+ project,
+ record: buildLogRecordGlobalsRecord(record),
+ inputs: {},
+ }
+ // Refreshed only after a function actually wrote to the record (a mutation or a
+ // failure annotation): most functions leave most records untouched.
+ let recordDirty = false
for (const fn of functions) {
const agg = this.getAggregates(ctx.aggregates, fn.id)
- const globals = buildLogRecordGlobals(record, project, {})
+ if (recordDirty) {
+ refreshLogRecordGlobalsRecord(globals.record, record)
+ recordDirty = false
+ }
// Input templates are customer-owned bytecode — a failing template is an
// invocation failure (fail open, annotate, surface in function logs), not a
@@ -305,6 +320,7 @@ export class LogsTransformerService {
agg.failed++
transformationRecordsCounter.inc({ result: 'failed' })
this.annotateFailure(record, fn)
+ recordDirty = true
this.captureErrorLogs(
fn,
ctx.teamId,
@@ -333,6 +349,7 @@ export class LogsTransformerService {
error: String(error),
})
this.annotateFailure(record, fn)
+ recordDirty = true
agg.failed++
transformationRecordsCounter.inc({ result: 'failed' })
continue
@@ -345,6 +362,7 @@ export class LogsTransformerService {
agg.failed++
transformationRecordsCounter.inc({ result: 'failed' })
this.annotateFailure(record, fn)
+ recordDirty = true
this.captureErrorLogs(
fn,
ctx.teamId,
@@ -366,6 +384,7 @@ export class LogsTransformerService {
agg.succeeded++
transformationRecordsCounter.inc({ result: 'succeeded' })
+ recordDirty = true
}
return false