: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
feat(logs): hog log transformation engine (#75141)
Daniel Viscaa0e4bca5ed62
diff --git a/nodejs/src/cdp/services/monitoring/hog-watcher.service.test.ts b/nodejs/src/cdp/services/monitoring/hog-watcher.service.test.tsindex c5d854f1c30e..2642e8084140 100644--- a/nodejs/src/cdp/services/monitoring/hog-watcher.service.test.ts+++ b/nodejs/src/cdp/services/monitoring/hog-watcher.service.test.ts@@ -632,4 +632,53 @@ describe('HogWatcher', () => {)})})++ describe('observeAggregatedResults', () => {+ // Cost curve with the default config: lower=50ms, upper=550ms, cost=100.+ it('charges no cost when the aggregate duration is below the lower bound', async () => {+ await watcher.observeAggregatedResults([{ hogFunction, totalDurationMs: 50 }])+ const state = await watcher.getPersistedState(hogFunctionId)+ expect(watcherConfig.bucketSize - state.tokens).toEqual(0)+ })++ it('charges the full cost at the upper bound', async () => {+ await watcher.observeAggregatedResults([{ hogFunction, totalDurationMs: 550 }])+ const state = await watcher.getPersistedState(hogFunctionId)+ expect(watcherConfig.bucketSize - state.tokens).toEqual(100)+ })++ it('scales cost with total VM time past the upper bound', async () => {+ // (1050 - 50) / (550 - 50) = 2 → twice the max single-message cost+ await watcher.observeAggregatedResults([{ hogFunction, totalDurationMs: 1050 }])+ const state = await watcher.getPersistedState(hogFunctionId)+ expect(watcherConfig.bucketSize - state.tokens).toEqual(200)+ })++ it('accumulates cost across observations for the same function', async () => {+ await watcher.observeAggregatedResults([+ { hogFunction, totalDurationMs: 300 },+ { hogFunction, totalDurationMs: 300 },+ ])+ const state = await watcher.getPersistedState(hogFunctionId)+ expect(watcherConfig.bucketSize - state.tokens).toEqual(100) // 50 + 50+ })++ it('marks a function degraded once its bucket drops to the threshold', async () => {+ // cost 2000 leaves tokens at 8000 = 80% of the bucket → degraded+ await watcher.observeAggregatedResults([{ hogFunction, totalDurationMs: 10050 }])+ const state = await watcher.getPersistedState(hogFunctionId)+ expect(state.tokens).toEqual(8000)+ expect(state.state).toEqual(HogWatcherState.degraded)+ })++ it('charges each function independently', async () => {+ const other = createHogFunction({ id: 'other-fn', team_id: 2 })+ await watcher.observeAggregatedResults([+ { hogFunction, totalDurationMs: 550 },+ { hogFunction: other, totalDurationMs: 50 },+ ])+ expect(watcherConfig.bucketSize - (await watcher.getPersistedState(hogFunctionId)).tokens).toEqual(100)+ expect(watcherConfig.bucketSize - (await watcher.getPersistedState('other-fn')).tokens).toEqual(0)+ })+ })})diff --git a/nodejs/src/cdp/services/monitoring/hog-watcher.service.ts b/nodejs/src/cdp/services/monitoring/hog-watcher.service.tsindex 9b7621659d66..81cc3e896a40 100644--- a/nodejs/src/cdp/services/monitoring/hog-watcher.service.ts+++ b/nodejs/src/cdp/services/monitoring/hog-watcher.service.ts@@ -53,6 +53,12 @@ export type HogWatcherFunctionState = {state: HogWatcherState}+type FunctionCostEntry = {+ hogFunction?: HogFunctionType+ functionId: string+ cost: number+}+const hogFunctionStateChange = new Counter({name: 'cdp_hog_function_state_change',help: 'Number of times a transformation state changed',@@ -387,14 +393,7 @@ export class HogWatcherService {}public async observeResults(results: CyclotronJobInvocationResult[]): Promise<void> {- const functionCosts: Record<- CyclotronJobInvocation['functionId'],- {- hogFunction?: HogFunctionType- functionId: CyclotronJobInvocation['functionId']- cost: number- }- > = {}+ const functionCosts: Record<CyclotronJobInvocation['functionId'], FunctionCostEntry> = {}results.forEach((result) => {if (!isHogFunctionResult(result)) {@@ -423,8 +422,44 @@ export class HogWatcherService {functionCosts[result.invocation.functionId] = functionCost})- const functionCostEntries = Object.values(functionCosts)+ await this.applyCostsAndTransitionStates(Object.values(functionCosts))+ }++ /**+ * Per-(function, Kafka message) cost reporting for log transformations.+ *+ * The events path allocates one CyclotronJobInvocationResult per event; at log-record+ * volumes that is prohibitive, so the logs transformer reports a single aggregated VM+ * duration per function per message instead. Cost is derived from that aggregate via the+ * same piecewise-linear curve (bounds come from this instance's config, so a logs-tuned+ * HogWatcher charges on a logs-appropriate scale). Everything downstream — token bucket,+ * state reads, transition rules — is shared with observeResults.+ */+ public async observeAggregatedResults(+ observations: { hogFunction: HogFunctionType; totalDurationMs: number }[]+ ): Promise<void> {+ const functionCosts: Record<string, FunctionCostEntry> = {}+ const costConfig = this.costsMapping.hog+ if (!costConfig) {+ return+ }++ for (const { hogFunction, totalDurationMs } of observations) {+ const functionCost = functionCosts[hogFunction.id] ?? {+ functionId: hogFunction.id,+ cost: 0,+ hogFunction,+ }+ const ratio =+ Math.max(totalDurationMs - costConfig.lowerBound, 0) / (costConfig.upperBound - costConfig.lowerBound)+ functionCost.cost += Math.round(costConfig.cost * ratio)+ functionCosts[hogFunction.id] = functionCost+ }++ await this.applyCostsAndTransitionStates(Object.values(functionCosts))+ }+ private async applyCostsAndTransitionStates(functionCostEntries: FunctionCostEntry[]): Promise<void> {if (functionCostEntries.length === 0) {return}diff --git a/nodejs/src/cdp/utils/hog-exec.ts b/nodejs/src/cdp/utils/hog-exec.tsindex 30b18979dd5f..210770f8da46 100644--- a/nodejs/src/cdp/utils/hog-exec.ts+++ b/nodejs/src/cdp/utils/hog-exec.ts@@ -25,7 +25,7 @@ export async function execHog(})}-function execHogImmediate(+export function execHogImmediate(bytecode: any,options?: ExecOptions): {diff --git a/nodejs/src/logs/transformations/benchmarks/fixtures.ts b/nodejs/src/logs/transformations/benchmarks/fixtures.tsnew file mode 100644index 000000000000..36212e730955--- /dev/null+++ b/nodejs/src/logs/transformations/benchmarks/fixtures.ts@@ -0,0 +1,200 @@+import type { LogRecord } from '../../log-record-avro'++// Fixtures for benchmarking Hog programs against realistic log records.+// Record sizes are calibrated to the production average of ~0.9KB uncompressed per record.++export interface BenchProgram {+ id: string+ name: string+ hog: string+ inputs: Record<string, unknown>+}++export interface BenchGlobals {+ project: { id: number; name: string; url: string }+ record: Record<string, unknown>+ inputs: Record<string, unknown>+}++const NOW_NS = 1_780_000_000_000_000_000++export const BENCH_LOG_RECORDS: { id: string; record: LogRecord }[] = [+ {+ id: 'plain-body',+ record: {+ uuid: '0197a3f2-1111-7000-8000-000000000001',+ trace_id: null,+ span_id: null,+ trace_flags: 0,+ timestamp: NOW_NS,+ observed_timestamp: NOW_NS,+ // sk_fake_ prefix: shaped like a payment-provider secret for the scrub benchmark+ // without tripping GitHub push protection on a real-looking key.+ body: 'Failed to authorize request for user [email protected] with token Bearer sk_fake_abcdef1234567890abcdef1234567890 — retrying with backoff. Previous attempt failed after 1523ms due to upstream timeout from payments-gateway. Contact [email protected] if this persists across more than three consecutive attempts.',+ severity_text: 'error',+ severity_number: 17,+ service_name: 'payments-api',+ resource_attributes: {+ 'k8s.namespace.name': 'payments',+ 'k8s.pod.name': 'payments-api-6d8f9c7b4-x2j9q',+ 'deployment.environment': 'production',+ 'cloud.region': 'us-east-1',+ },+ instrumentation_scope: 'payments.auth',+ event_name: null,+ attributes: {+ 'http.method': 'POST',+ 'http.status_code': '401',+ 'http.route': '/api/v1/charges',+ 'user.email': '[email protected]',+ retry_count: '3',+ duration_ms: '1523',+ distinct_id: 'user_8f3k2j1h',+ },+ bytes_uncompressed: 880,+ },+ },+ {+ id: 'json-body',+ record: {+ uuid: '0197a3f2-1111-7000-8000-000000000002',+ trace_id: null,+ span_id: null,+ trace_flags: 0,+ timestamp: NOW_NS,+ observed_timestamp: NOW_NS,+ body: JSON.stringify({+ level: 'info',+ msg: 'order processed',+ order_id: 'ord_29f8a3kd02',+ customer: { id: 'cus_8d3f2', email: '[email protected]', country: 'DE' },+ items: [+ { sku: 'SKU-1001', qty: 2, price_cents: 1999 },+ { sku: 'SKU-2044', qty: 1, price_cents: 5499 },+ ],+ payment: { provider: 'stripe', token: 'sk_fake_51JxYzabcdef1234567890abcdef12', status: 'captured' },+ latency_ms: 187,+ attempt: 1,+ }),+ severity_text: 'info',+ severity_number: 9,+ service_name: 'orders-worker',+ resource_attributes: {+ 'k8s.namespace.name': 'commerce',+ 'k8s.pod.name': 'orders-worker-7f6d5c4b3-a1b2c',+ 'deployment.environment': 'production',+ },+ instrumentation_scope: 'orders.processor',+ event_name: null,+ attributes: {+ 'queue.name': 'orders-high',+ 'messaging.operation': 'process',+ distinct_id: 'user_2k4j5h6g',+ },+ bytes_uncompressed: 920,+ },+ },+ {+ id: 'fat-attributes',+ record: {+ uuid: '0197a3f2-1111-7000-8000-000000000003',+ trace_id: null,+ span_id: null,+ trace_flags: 0,+ timestamp: NOW_NS,+ observed_timestamp: NOW_NS,+ body: 'request completed',+ severity_text: 'debug',+ severity_number: 5,+ service_name: 'edge-router',+ resource_attributes: {+ 'k8s.namespace.name': 'edge',+ 'k8s.pod.name': 'edge-router-5c4b3a2d1-q9w8e',+ 'deployment.environment': 'production',+ 'cloud.region': 'eu-west-1',+ 'host.name': 'ip-10-0-12-34',+ },+ instrumentation_scope: 'edge.http',+ event_name: null,+ attributes: Object.fromEntries(+ Array.from({ length: 30 }, (_, i) => [`dim.field_${i}`, `value-${i}-${'x'.repeat(16)}`])+ ),+ bytes_uncompressed: 950,+ },+ },+]++export const BENCH_PROGRAMS: BenchProgram[] = [+ {+ id: 'noop',+ name: 'No-op passthrough (pure invocation overhead)',+ hog: `return record`,+ inputs: {},+ },+ {+ id: 'redact-attributes',+ name: 'Hash selected attribute keys with SHA256',+ hog: `+let rec := record+let keysToRedact := splitByString(',', inputs.redactKeys)+for (let key in keysToRedact) {+ let k := trim(key)+ if (not empty(rec.attributes?.[k])) {+ rec.attributes[k] := sha256Hex(concat(rec.attributes[k], inputs.salt))+ }+}+return rec+`,+ inputs: { redactKeys: 'user.email,distinct_id,card_number', salt: 'bench-salt' },+ },+ {+ id: 'body-regex-scrub',+ name: 'Regex scrub of emails and secret keys in body',+ hog: `+let rec := record+let body := rec.body+if (not empty(body)) {+ for (let pattern in [inputs.emailPattern, inputs.tokenPattern]) {+ let i := 0+ let found := extractRegex(body, pattern)+ while (i < 10 and notEmpty(found)) {+ body := replaceAll(body, found, '[REDACTED]')+ found := extractRegex(body, pattern)+ i := i + 1+ }+ }+ rec.body := body+}+return rec+`,+ inputs: {+ emailPattern: '[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,}',+ // Non-capturing group: extractRegex returns the first capture group when one+ // exists, and the scrub needs the whole token match.+ tokenPattern: 'sk_(?:fake|live|test)_[A-Za-z0-9]{10,}',+ },+ },+ {+ id: 'conditional-drop',+ name: 'Drop debug logs from a noisy service',+ hog: `+if (record.severity_text == 'debug' and record.service_name == inputs.noisyService) {+ return null+}+return record+`,+ inputs: { noisyService: 'edge-router' },+ },+]++// Preview of the globals shape planned for log transformations: the log record fields+// plus project context and resolved inputs. Buffers (trace/span ids) are excluded —+// the production globals builder will hex-encode them.+export function buildBenchGlobals(record: LogRecord, inputs: Record<string, unknown>): BenchGlobals {+ const { trace_id: _t, span_id: _s, ...rest } = record+ return {+ project: { id: 1, name: 'bench', url: 'http://localhost:8010/project/1' },+ record: { ...rest },+ inputs,+ }+}diff --git a/nodejs/src/logs/transformations/benchmarks/hogvm-exec.ts b/nodejs/src/logs/transformations/benchmarks/hogvm-exec.tsnew file mode 100644index 000000000000..7e60bafbf569--- /dev/null+++ b/nodejs/src/logs/transformations/benchmarks/hogvm-exec.ts@@ -0,0 +1,28 @@+import { ExecResult, convertHogToJS } from '@posthog/hogvm'++import { execHogImmediate } from '~/cdp/utils/hog-exec'++import type { BenchGlobals } from './fixtures'++// Thin wrapper over the production exec primitive so the benchmark measures the same+// VM + RE2 + crypto stack the per-record executor uses, including result conversion.+export function execBenchProgram(+ bytecode: unknown,+ globals: BenchGlobals,+ timeoutMs: number+): { execResult?: ExecResult; error?: unknown; durationMs: number } {+ const { execResult, error, durationMs } = execHogImmediate(bytecode, {+ globals,+ timeout: timeoutMs,+ maxAsyncSteps: 0,+ functions: {+ print: () => {},+ },+ })++ if (execResult?.finished) {+ execResult.result = convertHogToJS(execResult.result)+ }++ return { execResult, error, durationMs }+}diff --git a/nodejs/src/logs/transformations/benchmarks/hogvm-log-bench.test.ts b/nodejs/src/logs/transformations/benchmarks/hogvm-log-bench.test.tsnew file mode 100644index 000000000000..20b9065d80a9--- /dev/null+++ b/nodejs/src/logs/transformations/benchmarks/hogvm-log-bench.test.ts@@ -0,0 +1,86 @@+import { compileHog } from '~/cdp/templates/compiler'++import { BENCH_LOG_RECORDS, BENCH_PROGRAMS, buildBenchGlobals } from './fixtures'+import { execBenchProgram } from './hogvm-exec'++jest.setTimeout(30_000)++describe('hogvm log transformation benchmark programs', () => {+ // Ceiling is ~40x the expected mean (~25µs/record): generous enough to never flake on a+ // loaded CI worker, tight enough to catch an order-of-magnitude VM regression.+ const CEILING_US_PER_RECORD = 1000+ const ITERATIONS = 200+ const TIMEOUT_MS = 10++ it.each(BENCH_PROGRAMS.map((p) => [p.id, p] as const))(+ 'program %s executes correctly and under the per-record ceiling',+ async (_id, program) => {+ expect.hasAssertions()+ const bytecode = await compileHog(program.hog)++ for (const { id: recordId, record } of BENCH_LOG_RECORDS) {+ // Warmup (JIT, RE2 compile)+ for (let i = 0; i < 50; i++) {+ execBenchProgram(bytecode, buildBenchGlobals(record, program.inputs), TIMEOUT_MS)+ }++ let totalMs = 0+ for (let i = 0; i < ITERATIONS; i++) {+ const globals = buildBenchGlobals(record, program.inputs)+ const { error, execResult, durationMs } = execBenchProgram(bytecode, globals, TIMEOUT_MS)+ expect(error).toBeUndefined()+ expect(execResult?.error).toBeUndefined()+ expect(execResult?.finished).toBe(true)+ totalMs += durationMs+ }++ const meanUs = (totalMs / ITERATIONS) * 1000+ expect(meanUs).toBeLessThan(CEILING_US_PER_RECORD)++ if (process.env.BENCH_DEBUG) {+ console.info(`${program.id} × ${recordId}: ${meanUs.toFixed(1)}µs/record`)+ }+ }+ }+ )++ it('body-regex-scrub redacts emails and secret keys', async () => {+ const program = BENCH_PROGRAMS.find((p) => p.id === 'body-regex-scrub')!+ const bytecode = await compileHog(program.hog)+ const record = BENCH_LOG_RECORDS.find((r) => r.id === 'plain-body')!.record++ const { execResult } = execBenchProgram(bytecode, buildBenchGlobals(record, program.inputs), TIMEOUT_MS)++ const body = (execResult!.result as { body: string }).body+ expect(body).not.toContain('[email protected]')+ expect(body).not.toContain('[email protected]')+ expect(body).not.toContain('sk_fake_')+ expect(body).toContain('[REDACTED]')+ })++ it('redact-attributes hashes only the configured keys', async () => {+ const program = BENCH_PROGRAMS.find((p) => p.id === 'redact-attributes')!+ const bytecode = await compileHog(program.hog)+ const record = BENCH_LOG_RECORDS.find((r) => r.id === 'plain-body')!.record++ const { execResult } = execBenchProgram(bytecode, buildBenchGlobals(record, program.inputs), TIMEOUT_MS)++ const attributes = (execResult!.result as { attributes: Record<string, string> }).attributes+ expect(attributes['user.email']).toMatch(/^[a-f0-9]{64}$/)+ expect(attributes['distinct_id']).toMatch(/^[a-f0-9]{64}$/)+ expect(attributes['http.method']).toBe('POST')+ })++ it('conditional-drop returns null for matching records and passes others', async () => {+ const program = BENCH_PROGRAMS.find((p) => p.id === 'conditional-drop')!+ const bytecode = await compileHog(program.hog)++ const noisy = BENCH_LOG_RECORDS.find((r) => r.id === 'fat-attributes')!.record+ const dropped = execBenchProgram(bytecode, buildBenchGlobals(noisy, program.inputs), TIMEOUT_MS)+ expect(dropped.execResult?.result).toBeNull()++ const kept = BENCH_LOG_RECORDS.find((r) => r.id === 'plain-body')!.record+ const keptResult = execBenchProgram(bytecode, buildBenchGlobals(kept, program.inputs), TIMEOUT_MS)+ expect(keptResult.execResult?.result).not.toBeNull()+ })+})diff --git a/nodejs/src/logs/transformations/benchmarks/hogvm-log-bench.ts b/nodejs/src/logs/transformations/benchmarks/hogvm-log-bench.tsnew file mode 100644index 000000000000..527faaa276ad--- /dev/null+++ b/nodejs/src/logs/transformations/benchmarks/hogvm-log-bench.ts@@ -0,0 +1,100 @@+import { compileHog } from '~/cdp/templates/compiler'++import { BENCH_LOG_RECORDS, BENCH_PROGRAMS, buildBenchGlobals } from './fixtures'+import { execBenchProgram } from './hogvm-exec'++// Micro-benchmark: TS HogVM cost per log record per transformation program.+//+// Run with:+// cd nodejs && pnpm exec tsx src/logs/transformations/benchmarks/hogvm-log-bench.ts+//+// The numbers from this harness parameterize the log transformation budgets+// (per-record timeout, per-message budget, watcher cost curve). Re-run after+// hogvm upgrades or when changing the globals shape.++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[] = []++ for (const { program, bytecode } of compiled) {+ for (const { id: recordId, record } of BENCH_LOG_RECORDS) {+ // Fresh globals each iteration: transformations mutate the record, and reusing+ // a scrubbed record would let later iterations skip the regex-replace work.+ for (let i = 0; i < WARMUP_ITERATIONS; i++) {+ const result = execBenchProgram(bytecode, buildBenchGlobals(record, program.inputs), TIMEOUT_MS)+ if (result.error || result.execResult?.error) {+ throw new Error(+ `Program ${program.id} failed on record ${recordId}: ${result.error ?? result.execResult?.error}`+ )+ }+ }++ const durationsUs: number[] = []+ for (let i = 0; i < ITERATIONS; i++) {+ const globals = buildBenchGlobals(record, program.inputs)+ const { durationMs } = execBenchProgram(bytecode, globals, TIMEOUT_MS)+ 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],+ })+ }+ }++ 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(' '))+ }++ const overallMean = allStats.reduce((a, s) => a + s.meanUs, 0) / allStats.length+ console.info(`\nOverall mean across programs/records: ${overallMean.toFixed(1)}µs/record`)+ console.info('Capacity reference: top org sustains ~250k records/s; 25µs/record ≈ 6 dedicated cores/function.')+}++main().catch((error) => {+ console.error(error)+ process.exit(1)+})diff --git a/nodejs/src/logs/transformations/hog-log-exec.test.ts b/nodejs/src/logs/transformations/hog-log-exec.test.tsnew file mode 100644index 000000000000..8a418b3f6f35--- /dev/null+++ b/nodejs/src/logs/transformations/hog-log-exec.test.ts@@ -0,0 +1,460 @@+import { compileHog } from '~/cdp/templates/compiler'+import { parseJSON } from '~/common/utils/json-parse'++import type { LogRecord } from '../log-record-avro'+import {+ MAX_LOG_TRANSFORMATION_PRINT_LOGS,+ applyTransformResult,+ buildLogRecordGlobals,+ executeLogTransformation,+ resolveLogTransformationInputs,+} from './hog-log-exec'++jest.setTimeout(30_000)++const PROJECT = { id: 1, name: 'test', url: 'http://localhost:8010/project/1' }++const createRecord = (overrides: Partial<LogRecord> = {}): LogRecord => ({+ uuid: '0197a3f2-1111-7000-8000-000000000001',+ trace_id: Buffer.from('0123456789abcdef0123456789abcdef', 'hex'),+ span_id: Buffer.from('0123456789abcdef', 'hex'),+ trace_flags: 0,+ timestamp: 1_780_000_000_000_000_000,+ observed_timestamp: 1_780_000_000_000_000_000,+ body: 'user [email protected] logged in',+ severity_text: 'info',+ severity_number: 9,+ service_name: 'auth-api',+ // Attribute values are JSON-encoded on the wire, like capture produces them+ resource_attributes: { 'k8s.namespace.name': '"auth"' },+ instrumentation_scope: 'auth.sessions',+ event_name: null,+ attributes: { 'http.method': '"POST"', user_email: '"[email protected]"' },+ bytes_uncompressed: 120,+ ...overrides,+})++const run = async (hog: string, record: LogRecord, inputs: Record<string, unknown> = {}, options = {}) => {+ const bytecode = await compileHog(hog)+ const globals = buildLogRecordGlobals(record, PROJECT, inputs)+ return executeLogTransformation(bytecode, record, globals, options)+}++describe('hog-log-exec', () => {+ describe('buildLogRecordGlobals', () => {+ it('exposes record fields with buffers hex-encoded and nulls normalized', () => {+ const globals = buildLogRecordGlobals(createRecord({ attributes: null }), PROJECT, { foo: 'bar' })++ expect(globals.record.trace_id).toBe('0123456789abcdef0123456789abcdef')+ expect(globals.record.span_id).toBe('0123456789abcdef')+ expect(globals.record.attributes).toEqual({})+ expect(globals.record.body).toBe('user [email protected] logged in')+ expect(globals.inputs).toEqual({ foo: 'bar' })+ expect(globals.project).toBe(PROJECT)+ })+ })++ describe('resolveLogTransformationInputs', () => {+ it('reports the VM time spent on hog-templated inputs so callers can charge budgets', async () => {+ const record = createRecord()+ const { inputs, durationMs } = resolveLogTransformationInputs(+ {+ inputs: {+ svc: {+ value: 'service = {record.service_name}',+ bytecode: await compileHog(`return f'service = {record.service_name}'`),+ order: 0,+ },+ },+ encrypted_inputs: null,+ } as any,+ buildLogRecordGlobals(record, PROJECT, {}),+ 10+ )+ expect(inputs.svc).toBe('service = auth-api')+ expect(durationMs).toBeGreaterThan(0)+ })++ it('converts complex template results to plain JS values', async () => {+ // Hog objects come back as Maps; consumers of inputs (globals, encoders)+ // expect plain JS, like the transformation body's converted result.+ const record = createRecord()+ const { inputs } = resolveLogTransformationInputs(+ {+ inputs: {+ obj: { value: '', bytecode: await compileHog(`return {'k': 'v', 'list': [1, 2]}`), order: 0 },+ },+ encrypted_inputs: null,+ } as any,+ buildLogRecordGlobals(record, PROJECT, {}),+ 1000+ )+ expect(inputs.obj).toEqual({ k: 'v', list: [1, 2] })+ })++ it('kills memory-hungry input templates via the memory limit', async () => {+ // Input templates are customer bytecode running once per record; they must+ // get the same 8MB cap as the body, not the VM's larger default. The+ // allocation lands between the two so this fails if the cap is lost.+ const record = createRecord()+ const bytecode = await compileHog(`+ let s := 'xxxxxxxxxxxxxxxx'+ for (let i := 0; i < 19; i := i + 1) {+ s := concat(s, s)+ }+ return s+ `)+ expect(() =>+ resolveLogTransformationInputs(+ { inputs: { big: { value: '', bytecode, order: 0 } }, encrypted_inputs: null } as any,+ buildLogRecordGlobals(record, PROJECT, {}),+ 1000+ )+ ).toThrow(/memory/i)+ })+ })++ describe('executeLogTransformation', () => {+ it('mutates body and attributes in place', async () => {+ const record = createRecord()+ const outcome = await run(+ `+ let rec := record+ rec.body := replaceAll(rec.body, '[email protected]', '[REDACTED]')+ rec.attributes.user_email := sha256Hex(rec.attributes.user_email)+ return rec+ `,+ record+ )++ expect(outcome.status).toBe('mutated')+ expect(record.body).toBe('user [REDACTED] logged in')+ expect(parseJSON(record.attributes!.user_email)).toMatch(/^[a-f0-9]{64}$/)+ expect(record.attributes!['http.method']).toBe('"POST"')+ })++ it('passes resolved inputs through globals', async () => {+ const record = createRecord()+ const outcome = await run(+ `+ let rec := record+ rec.attributes.tagged := inputs.tag+ return rec+ `,+ record,+ { tag: 'from-input' }+ )++ expect(outcome.status).toBe('mutated')+ expect(record.attributes!.tagged).toBe('"from-input"')+ })++ it('matches conditions against decoded attribute values, as shown in the UI', async () => {+ // Wire values are JSON-encoded ('"POST"'); customer code must be able to+ // compare against the plain value the Logs UI displays.+ const record = createRecord()+ const outcome = await run(+ `+ if (record.attributes['http.method'] == 'POST') {+ return null+ }+ return record+ `,+ record+ )+ expect(outcome.status).toBe('dropped')+ })++ it('drops the record when the transformation returns null', async () => {+ const outcome = await run(`return null`, createRecord())+ expect(outcome.status).toBe('dropped')+ })++ it('ignores read-only fields in the returned record', async () => {+ const record = createRecord()+ const outcome = await run(+ `+ let rec := record+ rec.service_name := 'spoofed-service'+ rec.timestamp := 1+ rec.body := 'changed'+ return rec+ `,+ record+ )++ expect(outcome.status).toBe('mutated')+ expect(record.body).toBe('changed')+ expect(record.service_name).toBe('auth-api')+ expect(record.timestamp).toBe(1_780_000_000_000_000_000)+ expect(record.bytes_uncompressed).toBe(120)+ })++ it.each([+ ['a string', `return 'nope'`],+ ['a number', `return 42`],+ ['a list', `return [1, 2]`],+ ['a non-string body', `let rec := record\nrec.body := 42\nreturn rec`],+ ])('fails open without mutating when the result is %s', async (_desc, hog) => {+ const record = createRecord()+ const originalBody = record.body+ const outcome = await run(hog, record)++ expect(outcome.status).toBe('failed')+ expect(record.body).toBe(originalBody)+ expect(record.attributes).toEqual(createRecord().attributes)+ })++ it('stringifies non-string attribute values', async () => {+ const record = createRecord()+ const outcome = await run(+ `+ let rec := record+ rec.attributes.retry_count := 3+ return rec+ `,+ record+ )++ expect(outcome.status).toBe('mutated')+ expect(record.attributes!.retry_count).toBe('3')+ })++ it('kills runaway programs via the timeout', async () => {+ const record = createRecord()+ const outcome = await run(+ `+ let i := 0+ while (true) {+ i := i + 1+ }+ return record+ `,+ record,+ {},+ { timeoutMs: 5 }+ )++ expect(outcome.status).toBe('failed')+ if (outcome.status === 'failed') {+ expect(outcome.error).toContain('timed out')+ }+ expect(outcome.durationMs).toBeGreaterThanOrEqual(4)+ })++ it('kills memory-hungry programs via the memory limit', async () => {+ const record = createRecord()+ const outcome = await run(+ `+ let s := 'xxxxxxxxxxxxxxxx'+ for (let i := 0; i < 30; i := i + 1) {+ s := concat(s, s)+ }+ return record+ `,+ record,+ {},+ { timeoutMs: 1000 }+ )++ expect(outcome.status).toBe('failed')+ if (outcome.status === 'failed') {+ expect(outcome.error.toLowerCase()).toContain('memory')+ }+ })++ it('redacts sensitive values written into output fields', async () => {+ // A transformation can copy a decrypted input into the record; without+ // output redaction the secret becomes readable by anyone with Logs access.+ const record = createRecord()+ const outcome = await run(+ `+ let rec := record+ rec.body := f'key: {inputs.apiKey}'+ return rec+ `,+ record,+ { apiKey: 'super-secret-key' },+ { sensitiveValues: ['super-secret-key'] }+ )++ expect(outcome.status).toBe('mutated')+ expect(record.body).not.toContain('super-secret-key')+ expect(record.body).toContain('***REDACTED***')+ })++ it('redacts sensitive values written into attribute keys, not just values', async () => {+ // Hog can assign a dynamic key, so redacting only values leaves the same+ // exfiltration path open one level up: the secret becomes the key itself.+ const record = createRecord()+ const outcome = await run(+ `+ let rec := record+ rec.attributes[inputs.apiKey] := 'anything'+ return rec+ `,+ record,+ { apiKey: 'super-secret-key' },+ { sensitiveValues: ['super-secret-key'] }+ )++ expect(outcome.status).toBe('mutated')+ const serialized = JSON.stringify(record.attributes)+ expect(serialized).not.toContain('super-secret-key')+ expect(serialized).toContain('***REDACTED***')+ })++ it('rejects transformed fields that exceed the size cap without mutating', async () => {+ // Capture bounds ingest at 2MB per request; a transformation must not be+ // able to inflate a stored record past that boundary.+ const record = createRecord()+ const originalBody = record.body+ const outcome = await run(+ `+ let rec := record+ let s := 'xxxxxxxxxxxxxxxx'+ for (let i := 0; i < 17; i := i + 1) {+ s := concat(s, s)+ }+ rec.body := s+ return rec+ `,+ record,+ {},+ { timeoutMs: 1000 }+ )++ expect(outcome.status).toBe('failed')+ expect(record.body).toBe(originalBody)+ })++ it('caps the complete record: under-cap fields must not combine past the cap', async () => {+ // body alone is under the cap here, but severity_text and the attribute+ // map push the combined record over — the cap must be on the whole record.+ const record = createRecord()+ const originalSeverity = record.severity_text+ const outcome = await run(+ `+ let rec := record+ let s := 'xxxxxxxxxxxxxxxx'+ for (let i := 0; i < 15; i := i + 1) {+ s := concat(s, s)+ }+ rec.body := s+ rec.severity_text := s+ rec.attributes.padding := s+ return rec+ `,+ record,+ {},+ { timeoutMs: 1000 }+ )++ expect(outcome.status).toBe('failed')+ expect(record.severity_text).toBe(originalSeverity)+ })++ it('counts retained fields toward the record size cap', async () => {+ // A transformation that touches only body must not slip the record past+ // the cap by riding on large fields it left untouched.+ const bigAttr = JSON.stringify('y'.repeat(600 * 1024))+ const record = createRecord({ attributes: { big: bigAttr } })+ const originalBody = record.body+ const outcome = await run(+ `+ let rec := record+ let s := 'xxxxxxxxxxxxxxxx'+ for (let i := 0; i < 15; i := i + 1) {+ s := concat(s, s)+ }+ return {'body': s}+ `,+ record,+ {},+ { timeoutMs: 1000 }+ )++ expect(outcome.status).toBe('failed')+ expect(record.body).toBe(originalBody)+ })++ it('contains a cyclic returned record instead of throwing out of the executor', async () => {+ // A transformation can build a cycle; the redaction traversal must not+ // recurse forever — an uncaught throw here escapes the per-function+ // failure accounting in the caller.+ const record = createRecord()+ const outcome = await run(+ `+ let rec := record+ rec.attributes.self := rec.attributes+ return rec+ `,+ record,+ {},+ { sensitiveValues: ['some-secret'] }+ )++ expect(outcome.status).toBe('failed')+ expect(outcome.durationMs).toBeGreaterThanOrEqual(0)+ })++ it('captures print output up to the cap and redacts sensitive values', async () => {+ const record = createRecord()+ const outcome = await run(+ `+ for (let i := 0; i < 10; i := i + 1) {+ print('iteration', i, 'secret-value')+ }+ return record+ `,+ record,+ {},+ { sensitiveValues: ['secret-value'] }+ )++ expect(outcome.status).toBe('mutated')+ expect(outcome.logs).toHaveLength(MAX_LOG_TRANSFORMATION_PRINT_LOGS)+ expect(outcome.logs[0]).toBe('iteration, 0, ***REDACTED***')+ })+ })++ describe('applyTransformResult', () => {+ it('treats undefined and false like null (drop)', () => {+ const record = createRecord()+ expect(applyTransformResult(record, undefined)).toBe('dropped')+ expect(applyTransformResult(record, false)).toBe('dropped')+ expect(applyTransformResult(record, null)).toBe('dropped')+ })++ it('rejects invalid severity_text without mutating', () => {+ const record = createRecord()+ expect(applyTransformResult(record, { body: 'new', severity_text: 7 })).toBe('invalid')+ expect(record.body).toBe('user [email protected] logged in')+ expect(record.severity_text).toBe('info')+ })++ it('allows clearing body to null', () => {+ const record = createRecord()+ expect(applyTransformResult(record, { body: null })).toBe('mutated')+ expect(record.body).toBeNull()+ })++ it('allows clearing attribute maps to null, like body', () => {+ const record = createRecord()+ expect(applyTransformResult(record, { attributes: null, resource_attributes: null })).toBe('mutated')+ expect(record.attributes).toBeNull()+ expect(record.resource_attributes).toBeNull()+ })++ it('preserves the exact wire encoding of attribute values the transformation left untouched', async () => {+ // '"3"' (string) and '3' (number) both decode to '3'; only the original wire+ // form can restore the type, so untouched values must round-trip byte-identically.+ const record = createRecord({+ attributes: { str_num: '"3"', real_num: '3', flag: 'true', keep: '"plain"' },+ })+ const outcome = await run(`return record`, record)+ expect(outcome.status).toBe('mutated')+ expect(record.attributes).toEqual({ str_num: '"3"', real_num: '3', flag: 'true', keep: '"plain"' })+ })+ })+})diff --git a/nodejs/src/logs/transformations/hog-log-exec.ts b/nodejs/src/logs/transformations/hog-log-exec.tsnew file mode 100644index 000000000000..40e855aa2bf8--- /dev/null+++ b/nodejs/src/logs/transformations/hog-log-exec.ts@@ -0,0 +1,442 @@+import { convertHogToJS } from '@posthog/hogvm'++import type { HogFunctionType } from '~/cdp/types'+import { sanitizeLogMessage } from '~/cdp/utils'+import { execHogImmediate } from '~/cdp/utils/hog-exec'+import { parseJSON } from '~/common/utils/json-parse'++import type { LogRecord } from '../log-record-avro'++// Per-record execution primitives for log transformations. Pure functions, no I/O:+// orchestration (function fetching, budgets, monitoring) lives in the transformer service.++/** Hard per-record VM kill. ~100x the p99 of realistic scrub programs (see benchmarks/). */+export const DEFAULT_LOG_TRANSFORMATION_TIMEOUT_MS = 10++/** Log records are ~1KB; transformations have no business allocating anywhere near this. */+export const LOG_TRANSFORMATION_MEMORY_LIMIT_BYTES = 8 * 1024 * 1024++/** Max captured print() entries per invocation — far lower than destinations' 25,+ * since a transformation can run hundreds of thousands of times per second. */+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 interface LogTransformationGlobals {+ project: { id: number; name: string; url: string }+ record: {+ body: string | null+ attributes: Record<string, string>+ resource_attributes: Record<string, string>+ severity_text: string | null+ severity_number: number | null+ service_name: string | null+ instrumentation_scope: string | null+ event_name: string | null+ timestamp: number | null+ observed_timestamp: number | null+ trace_id: string | null+ span_id: string | null+ }+ inputs: Record<string, unknown>+}++export type LogTransformationOutcome =+ | { status: 'mutated'; durationMs: number; logs: string[] }+ | { status: 'dropped'; durationMs: number; logs: string[] }+ | { status: 'failed'; durationMs: number; logs: string[]; error: string }++export function buildLogRecordGlobals(+ record: LogRecord,+ project: LogTransformationGlobals['project'],+ inputs: Record<string, unknown>+): 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: record.trace_id ? record.trace_id.toString('hex') : null,+ span_id: record.span_id ? record.span_id.toString('hex') : null,+ },+ inputs,+ }+}++/**+ * 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+ * sink decodes string values with `JSONExtractString`, so that is what users see in+ * the Logs UI. Transformations must see the same decoded values — otherwise+ * `record.attributes['level'] == 'error'` silently never matches.+ */+export function decodeLogAttributeValue(value: string): string {+ if (value.length >= 2 && value.startsWith('"') && value.endsWith('"')) {+ try {+ const parsed = parseJSON(value)+ if (typeof parsed === 'string') {+ return parsed+ }+ } catch {+ // Not valid JSON — treat as a plain string+ }+ }+ return value+}++/**+ * Inverse of `decodeLogAttributeValue` for values written back onto the record:+ * plain strings are JSON-encoded so the ClickHouse sink's `JSONExtractString`+ * surfaces them; values that are already valid JSON (numbers, booleans, objects,+ * pre-encoded strings) pass through unchanged.+ */+export function encodeLogAttributeValue(value: string): string {+ try {+ parseJSON(value)+ return value+ } catch {+ return JSON.stringify(value)+ }+}++function decodeAttributeMap(map: Record<string, string> | null | undefined): Record<string, string> {+ const out: Record<string, string> = {}+ for (const [key, value] of Object.entries(map ?? {})) {+ out[key] = decodeLogAttributeValue(value)+ }+ return out+}++/**+ * Encodes a decoded attribute map back to the wire form. Values the transformation left+ * untouched keep their exact original wire encoding — the decode/encode pair is lossy for+ * string values that look like JSON scalars ('"3"' decodes to '3', which re-encodes as the+ * number 3), so round-tripping through the original is the only faithful option.+ */+function encodeAttributeMap(+ map: Record<string, string>,+ original: Record<string, string> | null | undefined+): 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)+ }+ }+ return out+}++function coerceStringMap(value: unknown): Record<string, string> | null {+ if (!value || typeof value !== 'object' || Array.isArray(value)) {+ return null+ }+ const result: Record<string, string> = {}+ for (const [key, entry] of Object.entries(value as Record<string, unknown>)) {+ if (entry === null || entry === undefined) {+ continue+ }+ if (typeof entry === 'string') {+ result[key] = entry+ } else {+ try {+ result[key] = JSON.stringify(entry)+ } catch {+ // Cyclic values can't be encoded; treat the whole result as invalid so+ // the failure stays inside the executor's normal accounting.+ return null+ }+ }+ if (Buffer.byteLength(result[key]) > MAX_TRANSFORMED_FIELD_BYTES) {+ return null+ }+ }+ return result+}++/**+ * Merges a transformation's return value back into the record, in place.+ *+ * Only `body`, `attributes`, `severity_text`, and `resource_attributes` are writable.+ * Timestamps, trace/span ids, service identity, and `bytes_uncompressed` are read-only:+ * billing bytes are computed at capture time, and scrubbing must never change what a+ * customer is billed.+ *+ * Returns 'invalid' (record untouched) when the result is not record-shaped — the+ * caller treats that as a failure and fails open.+ */+function redactString(value: string, sensitiveValues: string[]): string {+ let out = value+ for (const sensitive of sensitiveValues) {+ out = out.replaceAll(sensitive, '***REDACTED***')+ }+ return out+}++function redactSensitiveStrings(+ value: unknown,+ sensitiveValues: string[] | undefined,+ // Memo doubles as cycle guard: a transformation can return a cyclic record, and+ // an unbounded recursion here would throw past the caller's failure accounting.+ seen: WeakMap<object, unknown> = new WeakMap()+): unknown {+ if (!sensitiveValues?.length) {+ return value+ }+ if (typeof value === 'string') {+ return redactString(value, sensitiveValues)+ }+ if (Array.isArray(value)) {+ const existing = seen.get(value)+ if (existing) {+ return existing+ }+ const out: unknown[] = []+ seen.set(value, out)+ for (const item of value) {+ out.push(redactSensitiveStrings(item, sensitiveValues, seen))+ }+ return out+ }+ if (value && typeof value === 'object') {+ const existing = seen.get(value)+ if (existing) {+ return existing+ }+ const out: Record<string, unknown> = {}+ seen.set(value, out)+ for (const [key, item] of Object.entries(value)) {+ // Keys need redacting as much as values do: Hog can assign a dynamic key+ // (`rec.attributes[inputs.apiKey] := …`), so redacting only values leaves the+ // same exfiltration path open one level up. Two keys collapsing onto the same+ // redacted name is fine — both sides of that collision hold the secret.+ out[redactString(key, sensitiveValues)] = redactSensitiveStrings(item, sensitiveValues, seen)+ }+ return out+ }+ return value+}++export function applyTransformResult(record: LogRecord, execResult: unknown): 'mutated' | 'dropped' | 'invalid' {+ if (execResult === null || execResult === undefined || execResult === false) {+ return 'dropped'+ }++ if (typeof execResult !== 'object' || Array.isArray(execResult)) {+ return 'invalid'+ }++ const result = execResult as Record<string, unknown>++ // Validate everything before mutating anything, so an invalid result leaves the+ // record fully untouched rather than half-applied.+ let body: string | null | undefined = undefined+ if ('body' in result) {+ if (result.body !== null && typeof result.body !== 'string') {+ return 'invalid'+ }+ body = result.body+ }++ let severityText: string | null | undefined = undefined+ if ('severity_text' in result) {+ if (result.severity_text !== null && typeof result.severity_text !== 'string') {+ return 'invalid'+ }+ severityText = result.severity_text+ }++ // Like `body`, an explicit null clears the field; an absent key leaves it untouched.+ let attributes: Record<string, string> | null | undefined = undefined+ if ('attributes' in result) {+ if (result.attributes === null) {+ attributes = null+ } else {+ attributes = coerceStringMap(result.attributes)+ if (attributes === null) {+ return 'invalid'+ }+ }+ }++ let resourceAttributes: Record<string, string> | null | undefined = undefined+ if ('resource_attributes' in result) {+ if (result.resource_attributes === null) {+ resourceAttributes = null+ } else {+ resourceAttributes = coerceStringMap(result.resource_attributes)+ if (resourceAttributes === null) {+ return 'invalid'+ }+ }+ }++ // Cap the complete transformed output — body, severity, and attribute map+ // totals together — so no combination of writable fields can inflate a+ // 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)+ }+ }+ }+ if (totalBytes > MAX_TRANSFORMED_FIELD_BYTES) {+ return 'invalid'+ }++ if (body !== undefined) {+ record.body = body+ }+ if (severityText !== undefined) {+ record.severity_text = severityText+ }+ if (attributes !== undefined) {+ record.attributes = attributes === null ? null : encodeAttributeMap(attributes, record.attributes)+ }+ if (resourceAttributes !== undefined) {+ record.resource_attributes =+ resourceAttributes === null ? null : encodeAttributeMap(resourceAttributes, record.resource_attributes)+ }++ return 'mutated'+}++/**+ * Resolves a function's input values against log globals. Inputs may reference earlier+ * inputs, so resolution happens in declared order; hog-templated inputs execute their+ * compiled bytecode with the accumulated `inputs` visible.+ *+ * Throws on the first unresolvable input — callers decide the failure policy+ * (the pipeline fails open per record; the test-invocation API surfaces the error).+ */+export function resolveLogTransformationInputs(+ fn: Pick<HogFunctionType, 'inputs' | 'encrypted_inputs'>,+ globals: Omit<LogTransformationGlobals, 'inputs'>,+ timeoutMs: number+): { inputs: Record<string, unknown>; durationMs: number } {+ const inputs: Record<string, unknown> = {}+ const allInputs = { ...fn.inputs, ...fn.encrypted_inputs }+ // VM time spent on templates counts toward the same budgets as the code body —+ // record-referencing templates run per record and would otherwise bypass them.+ let durationMs = 0++ const entries = Object.entries(allInputs).sort(([, a], [, b]) => (a?.order ?? -1) - (b?.order ?? -1))++ for (const [key, input] of entries) {+ if (input?.bytecode && (input.templating ?? 'hog') === 'hog') {+ const {+ execResult,+ error,+ durationMs: execMs,+ } = execHogImmediate(input.bytecode, {+ globals: { ...globals, inputs },+ timeout: timeoutMs,+ maxAsyncSteps: 0,+ memoryLimit: LOG_TRANSFORMATION_MEMORY_LIMIT_BYTES,+ })+ durationMs += execMs+ if (error || execResult?.error || !execResult?.finished) {+ throw new Error(`Could not resolve input '${key}': ${error ?? execResult?.error}`)+ }+ // Hog objects surface as Maps; convert like the body's result so inputs+ // hold plain JS values for globals, encoders, and redaction.+ inputs[key] = convertHogToJS(execResult.result)+ } else {+ inputs[key] = input?.value+ }+ }++ return { inputs, durationMs }+}++export interface ExecuteLogTransformationOptions {+ timeoutMs?: number+ /** Values redacted from captured print() output (e.g. secret input values). */+ sensitiveValues?: string[]+}++/**+ * Runs one compiled transformation against one record's globals and merges the result+ * into the record in place. Synchronous and CPU-only: no async functions are registered,+ * so customer code cannot perform I/O.+ */+export function executeLogTransformation(+ bytecode: unknown,+ record: LogRecord,+ globals: LogTransformationGlobals,+ options: ExecuteLogTransformationOptions = {}+): LogTransformationOutcome {+ const timeoutMs = options.timeoutMs ?? DEFAULT_LOG_TRANSFORMATION_TIMEOUT_MS+ const logs: string[] = []++ const { execResult, error, durationMs } = execHogImmediate(bytecode, {+ globals,+ timeout: timeoutMs,+ maxAsyncSteps: 0,+ memoryLimit: LOG_TRANSFORMATION_MEMORY_LIMIT_BYTES,+ functions: {+ print: (...args: unknown[]) => {+ if (logs.length < MAX_LOG_TRANSFORMATION_PRINT_LOGS) {+ logs.push(sanitizeLogMessage(args, options.sensitiveValues))+ }+ },+ },+ })++ if (error || execResult?.error) {+ return { status: 'failed', durationMs, logs, error: String(error ?? execResult?.error) }+ }++ if (!execResult?.finished) {+ // With no async functions registered the VM always runs to completion or throws;+ // a paused VM here means a bug, not customer error. Treat as failure (fail-open).+ return { status: 'failed', durationMs, logs, error: 'VM did not finish execution' }+ }++ // Redact secrets from the returned record before it's applied: a transformation+ // 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)++ if (applied === 'invalid') {+ return {+ status: 'failed',+ durationMs,+ logs,+ error: 'Transformation must return the record (optionally mutated) or null to drop it',+ }+ }++ if (applied === 'dropped') {+ return { status: 'dropped', durationMs, logs }+ }++ return { status: 'mutated', durationMs, logs }+}diff --git a/nodejs/src/logs/transformations/logs-transformer.service.test.ts b/nodejs/src/logs/transformations/logs-transformer.service.test.tsnew file mode 100644index 000000000000..8047bbf4dc75--- /dev/null+++ b/nodejs/src/logs/transformations/logs-transformer.service.test.ts@@ -0,0 +1,560 @@+import { HogFunctionManagerService } from '~/cdp/services/managers/hog-function-manager.service'+import { HogFunctionMonitoringService } from '~/cdp/services/monitoring/hog-function-monitoring.service'+import { HogWatcherService, HogWatcherState } from '~/cdp/services/monitoring/hog-watcher.service'+import { compileHog } from '~/cdp/templates/compiler'+import { HogFunctionType } from '~/cdp/types'++import type { LogRecord } from '../log-record-avro'+import { LogsTransformerConfig, LogsTransformerService, TransformationBatchBudget } from './logs-transformer.service'++jest.setTimeout(30_000)++const TEAM_ID = 7++const createRecord = (overrides: Partial<LogRecord> = {}): LogRecord => ({+ uuid: '0197a3f2-1111-7000-8000-000000000001',+ trace_id: null,+ span_id: null,+ trace_flags: 0,+ timestamp: 1_780_000_000_000_000_000,+ observed_timestamp: 1_780_000_000_000_000_000,+ body: 'user [email protected] logged in',+ severity_text: 'info',+ severity_number: 9,+ service_name: 'auth-api',+ resource_attributes: {},+ instrumentation_scope: null,+ event_name: null,+ attributes: { user_email: '[email protected]' },+ bytes_uncompressed: 120,+ ...overrides,+})++let functionCounter = 0+const createFunction = async (hog: string, overrides: Partial<HogFunctionType> = {}): Promise<HogFunctionType> => {+ functionCounter+++ return {+ id: `00000000-0000-0000-0000-00000000000${functionCounter}`,+ team_id: TEAM_ID,+ name: `Test fn ${functionCounter}`,+ type: 'transformation_log',+ enabled: true,+ deleted: false,+ bytecode: await compileHog(hog),+ inputs: {},+ inputs_schema: [],+ encrypted_inputs: null,+ filters: null,+ mappings: null,+ masking: null,+ template_id: null,+ execution_order: functionCounter,+ created_at: new Date().toISOString(),+ updated_at: new Date().toISOString(),+ ...overrides,+ } as unknown as HogFunctionType+}++describe('LogsTransformerService', () => {+ let service: LogsTransformerService+ let manager: jest.Mocked<Pick<HogFunctionManagerService, 'getHogFunctionsForTeams' | 'getHogFunctionIdsForTeams'>>+ let monitoring: jest.Mocked<Pick<HogFunctionMonitoringService, 'queueAppMetric' | 'queueLogs' | 'flush'>>+ let config: LogsTransformerConfig++ const setFunctions = (functions: HogFunctionType[]) => {+ manager.getHogFunctionsForTeams.mockResolvedValue({ [TEAM_ID]: functions })+ manager.getHogFunctionIdsForTeams.mockResolvedValue({ [TEAM_ID]: functions.map((f) => f.id) })+ }++ const queuedMetrics = () => monitoring.queueAppMetric.mock.calls.map(([metric]) => metric)++ beforeEach(() => {+ functionCounter = 0+ manager = {+ getHogFunctionsForTeams: jest.fn(),+ getHogFunctionIdsForTeams: jest.fn(),+ } as any+ monitoring = {+ queueAppMetric: jest.fn(),+ queueLogs: jest.fn(),+ flush: jest.fn(),+ } as any+ config = {+ siteUrl: 'http://localhost:8010',+ hogTimeoutMs: 10,+ messageBudgetMs: 50,+ batchBudgetMs: 2000,+ maxErrorLogsPerFunctionPerMessage: 3,+ hogWatcherSampleRate: 0,+ }+ service = new LogsTransformerService(manager as any, monitoring as any, config)+ })++ it('does nothing when the team has no transformations', async () => {+ setFunctions([])+ const records = [createRecord()]++ const result = await service.transformRecords(TEAM_ID, records)++ expect(result.recordsDropped).toBe(0)+ expect(records[0].body).toBe('user [email protected] logged in')+ expect(monitoring.queueAppMetric).not.toHaveBeenCalled()+ })++ it('mutates all records and queues one aggregated success metric', async () => {+ setFunctions([+ await createFunction(`+ let rec := record+ rec.body := replaceAll(rec.body, '[email protected]', '[REDACTED]')+ return rec+ `),+ ])+ const records = [createRecord(), createRecord(), createRecord()]++ const result = await service.transformRecords(TEAM_ID, records)++ expect(result.recordsDropped).toBe(0)+ expect(records).toHaveLength(3)+ for (const record of records) {+ expect(record.body).toBe('user [REDACTED] logged in')+ }+ expect(queuedMetrics()).toEqual([+ expect.objectContaining({ metric_name: 'succeeded', count: 3, team_id: TEAM_ID }),+ ])+ expect(monitoring.queueLogs).not.toHaveBeenCalled()+ })++ it('removes dropped records from the array in place', async () => {+ setFunctions([+ await createFunction(`+ if (record.severity_text == 'debug') {+ return null+ }+ return record+ `),+ ])+ const records = [+ createRecord({ severity_text: 'debug' }),+ createRecord({ severity_text: 'info' }),+ createRecord({ severity_text: 'debug' }),+ ]+ const reference = records++ const result = await service.transformRecords(TEAM_ID, records)++ expect(result.recordsDropped).toBe(2)+ expect(reference).toHaveLength(1)+ expect(reference[0].severity_text).toBe('info')+ expect(result.recordsDroppedByFunctionId.get('00000000-0000-0000-0000-000000000001')).toBe(2)+ expect(queuedMetrics()).toEqual(+ expect.arrayContaining([+ expect.objectContaining({ metric_name: 'dropped', count: 2 }),+ expect.objectContaining({ metric_name: 'succeeded', count: 1 }),+ ])+ )+ })++ it('chains transformations in order, each seeing the previous mutation', async () => {+ setFunctions([+ await createFunction(`+ let rec := record+ rec.attributes.step := 'one'+ return rec+ `),+ await createFunction(`+ let rec := record+ rec.attributes.step := concat(rec.attributes.step, '-two')+ return rec+ `),+ ])+ const records = [createRecord()]++ await service.transformRecords(TEAM_ID, records)++ expect(records[0].attributes!.step).toBe('"one-two"')+ })++ it('fails open: annotates the record, keeps it, queues error logs, and continues', async () => {+ setFunctions([+ await createFunction(`+ print('about to explode')+ throw Error('boom')+ `),+ await createFunction(`+ let rec := record+ rec.attributes.after := 'ran'+ return rec+ `),+ ])+ const records = [createRecord()]++ const result = await service.transformRecords(TEAM_ID, records)++ expect(result.recordsDropped).toBe(0)+ expect(records).toHaveLength(1)+ expect(records[0].attributes!['$transformations_failed']).toContain('Test fn 1')+ expect(records[0].attributes!.after).toBe('"ran"')+ expect(queuedMetrics()).toEqual(+ expect.arrayContaining([+ expect.objectContaining({ metric_name: 'failed', count: 1 }),+ expect.objectContaining({ metric_name: 'succeeded', count: 1 }),+ ])+ )+ const [logEntries] = monitoring.queueLogs.mock.calls[0]+ expect(logEntries.some((entry) => entry.message.includes('about to explode'))).toBe(true)+ expect(logEntries.some((entry) => entry.level === 'error')).toBe(true)+ })++ it('caps captured error logs per function per message', async () => {+ setFunctions([await createFunction(`throw Error('boom')`)])+ const records = Array.from({ length: 10 }, () => createRecord())++ await service.transformRecords(TEAM_ID, records)++ const [logEntries] = monitoring.queueLogs.mock.calls[0]+ const errorEntries = logEntries.filter((entry) => entry.level === 'error')+ expect(errorEntries).toHaveLength(config.maxErrorLogsPerFunctionPerMessage)+ expect(queuedMetrics()).toEqual(+ expect.arrayContaining([expect.objectContaining({ metric_name: 'failed', count: 10 })])+ )+ })++ it('skips all records and annotates them when the message budget is already exhausted', async () => {+ config.messageBudgetMs = 0+ service = new LogsTransformerService(manager as any, monitoring as any, config)+ setFunctions([await createFunction(`return record`)])+ const records = [createRecord(), createRecord()]++ const result = await service.transformRecords(TEAM_ID, records)++ expect(result.recordsDropped).toBe(0)+ expect(records).toHaveLength(2)+ for (const record of records) {+ expect(record.attributes!['$transformations_skipped']).toBe('"budget"')+ }+ expect(queuedMetrics()).toEqual([expect.objectContaining({ metric_name: 'budget_skipped', count: 2 })])+ })++ it('stops transforming once a shared batch budget is exhausted', async () => {+ setFunctions([await createFunction(`return record`)])+ const budget = new TransformationBatchBudget(0)+ const records = [createRecord()]++ await service.transformRecords(TEAM_ID, records, budget)++ expect(records[0].attributes!['$transformations_skipped']).toBe('"budget"')+ expect(queuedMetrics()).toEqual([expect.objectContaining({ metric_name: 'budget_skipped', count: 1 })])+ })++ it('consumes the batch budget across messages', async () => {+ setFunctions([+ await createFunction(`+ let i := 0+ while (i < 100000) {+ i := i + 1+ }+ return record+ `),+ ])+ const budget = new TransformationBatchBudget(0.0001)++ const firstMessage = [createRecord()]+ await service.transformRecords(TEAM_ID, firstMessage, budget)+ expect(firstMessage[0].attributes!['$transformations_skipped']).toBeUndefined()+ expect(budget.usedMs).toBeGreaterThan(0)++ const secondMessage = [createRecord()]+ await service.transformRecords(TEAM_ID, secondMessage, budget)+ expect(secondMessage[0].attributes!['$transformations_skipped']).toBe('"budget"')+ })++ it('resolves static input templates once and applies them', async () => {+ setFunctions([+ await createFunction(+ `+ let rec := record+ rec.attributes.tag := inputs.tag+ return rec+ `,+ {+ inputs: {+ tag: { value: 'static-tag', order: 0 },+ },+ } as any+ ),+ ])+ const records = [createRecord(), createRecord()]++ await service.transformRecords(TEAM_ID, records)++ expect(records[0].attributes!.tag).toBe('"static-tag"')+ expect(records[1].attributes!.tag).toBe('"static-tag"')+ })++ it('resolves record-referencing input templates per record', async () => {+ setFunctions([+ await createFunction(+ `+ let rec := record+ rec.attributes.svc := inputs.svc+ return rec+ `,+ {+ inputs: {+ svc: {+ value: 'service = {record.service_name}',+ bytecode: await compileHog(`return f'service = {record.service_name}'`),+ order: 0,+ },+ },+ } as any+ ),+ ])+ const records = [createRecord({ service_name: 'svc-a' }), createRecord({ service_name: 'svc-b' })]++ await service.transformRecords(TEAM_ID, records)++ expect(records[0].attributes!.svc).toBe('"service = svc-a"')+ expect(records[1].attributes!.svc).toBe('"service = svc-b"')+ })++ it('resolves record-referencing encrypted input templates per record, not from cache', async () => {+ setFunctions([+ await createFunction(+ `+ let rec := record+ rec.attributes.svc := inputs.svc+ return rec+ `,+ {+ inputs: {},+ encrypted_inputs: {+ svc: {+ value: 'service = {record.service_name}',+ bytecode: await compileHog(`return f'service = {record.service_name}'`),+ order: 0,+ },+ },+ } as any+ ),+ ])+ const records = [createRecord({ service_name: 'svc-a' }), createRecord({ service_name: 'svc-b' })]++ await service.transformRecords(TEAM_ID, records)++ expect(records[0].attributes!.svc).toBe('"service = svc-a"')+ expect(records[1].attributes!.svc).toBe('"service = svc-b"')+ })++ it('treats a failing input template as an invocation failure, not a transformer bug', async () => {+ setFunctions([+ await createFunction(+ `+ let rec := record+ rec.attributes.tag := inputs.tag+ return rec+ `,+ {+ inputs: {+ tag: {+ value: '{record.missing.deeply.nested}',+ bytecode: await compileHog(`throw Error('template boom')`),+ order: 0,+ },+ },+ } as any+ ),+ ])+ const records = [createRecord()]++ const result = await service.transformRecords(TEAM_ID, records)++ // Fails open: the record survives untransformed, annotated as failed+ expect(result.recordsDropped).toBe(0)+ expect(records).toHaveLength(1)+ expect(records[0].attributes!['$transformations_failed']).toContain('Test fn 1')+ expect(queuedMetrics()).toEqual([expect.objectContaining({ metric_name: 'failed', count: 1 })])+ const queuedLogs = monitoring.queueLogs.mock.calls.flatMap(([logs]) => logs)+ expect(queuedLogs.some((log) => log.level === 'error' && log.message.includes('template boom'))).toBe(true)+ })++ it('redacts encrypted input values from captured logs', async () => {+ setFunctions([+ await createFunction(+ `+ print('the secret is', inputs.apiKey)+ throw Error('boom')+ `,+ {+ encrypted_inputs: { apiKey: { value: 'super-secret-key', order: 0 } },+ } as any+ ),+ ])+ const records = [createRecord()]++ await service.transformRecords(TEAM_ID, records)++ const [logEntries] = monitoring.queueLogs.mock.calls[0]+ const printed = logEntries.find((entry) => entry.message.includes('the secret is'))+ expect(printed?.message).toContain('***REDACTED***')+ expect(printed?.message).not.toContain('super-secret-key')+ })++ it('handles very large secret arrays without failing the function', async () => {+ // Spreading an unbounded array onto the traversal stack throws RangeError+ // past V8's argument limit, turning a legitimate function into a failure.+ const big = Array.from({ length: 150_000 }, (_, i) => `secret-${i}`)+ setFunctions([+ await createFunction(`return record`, {+ encrypted_inputs: { many: { value: big, order: 0 } },+ } as any),+ ])+ const records = [createRecord()]++ await service.transformRecords(TEAM_ID, records)++ expect(records[0].attributes?.['$transformations_failed']).toBeUndefined()+ })++ it('redacts deeply nested encrypted input values with no depth limit', async () => {+ // AnyInputField accepts arbitrary JSON; a depth cap would let a secret below+ // the cap escape redaction entirely.+ const deep = { a: { b: { c: { d: { e: { f: { g: { token: 'very-deep-secret' } } } } } } } }+ setFunctions([+ await createFunction(+ `+ print('deep token is', inputs.secret.a.b.c.d.e.f.g.token)+ throw Error('boom')+ `,+ { encrypted_inputs: { secret: { value: deep, order: 0 } } } as any+ ),+ ])+ const records = [createRecord()]++ await service.transformRecords(TEAM_ID, records)++ const queuedLogs = monitoring.queueLogs.mock.calls.flatMap(([logs]) => logs)+ const printed = queuedLogs.find((entry) => entry.message.includes('deep token is'))+ expect(printed?.message).toContain('***REDACTED***')+ expect(printed?.message).not.toContain('very-deep-secret')+ })++ it('redacts nested encrypted input values, not just top-level strings', async () => {+ // Secret inputs are schema-validated as any JSON value; a string buried in a+ // dict must be redacted like a top-level string secret.+ setFunctions([+ await createFunction(+ `+ print('token is', inputs.credentials.token)+ throw Error('boom')+ `,+ {+ encrypted_inputs: { credentials: { value: { token: 'nested-secret-token' }, order: 0 } },+ } as any+ ),+ ])+ const records = [createRecord()]++ await service.transformRecords(TEAM_ID, records)++ const queuedLogs = monitoring.queueLogs.mock.calls.flatMap(([logs]) => logs)+ const printed = queuedLogs.find((entry) => entry.message.includes('token is'))+ expect(printed?.message).toContain('***REDACTED***')+ expect(printed?.message).not.toContain('nested-secret-token')+ })++ it('redacts encrypted input values from the thrown error message', async () => {+ // print() output is sanitized at capture, but the thrown error string is+ // queued as the error-level log entry — throwing a secret must not let it+ // be read back from persisted function logs.+ setFunctions([+ await createFunction(`throw Error(f'lookup failed for {inputs.apiKey}')`, {+ encrypted_inputs: { apiKey: { value: 'super-secret-key', order: 0 } },+ } as any),+ ])+ const records = [createRecord()]++ await service.transformRecords(TEAM_ID, records)++ const queuedLogs = monitoring.queueLogs.mock.calls.flatMap(([logs]) => logs)+ const errorEntry = queuedLogs.find((entry) => entry.level === 'error')+ expect(errorEntry?.message).toContain('***REDACTED***')+ expect(errorEntry?.message).not.toContain('super-secret-key')+ })++ it('teamHasTransformations uses the cheap id lookup', async () => {+ manager.getHogFunctionIdsForTeams.mockResolvedValue({ [TEAM_ID]: ['some-id'] })+ await expect(service.teamHasTransformations(TEAM_ID)).resolves.toBe(true)++ manager.getHogFunctionIdsForTeams.mockResolvedValue({ [TEAM_ID]: [] })+ await expect(service.teamHasTransformations(TEAM_ID)).resolves.toBe(false)+ expect(manager.getHogFunctionsForTeams).not.toHaveBeenCalled()+ })++ it('flush delegates to the monitoring service', async () => {+ await service.flush()+ expect(monitoring.flush).toHaveBeenCalled()+ })++ describe('HogWatcher integration', () => {+ const createMockWatcher = (): jest.Mocked<+ Pick<HogWatcherService, 'getEffectiveStates' | 'observeAggregatedResults'>+ > =>+ ({+ getEffectiveStates: jest.fn().mockResolvedValue({}),+ observeAggregatedResults: jest.fn().mockResolvedValue(undefined),+ }) as any++ const withWatcher = (watcher: any, sampleRate: number): LogsTransformerService =>+ new LogsTransformerService(+ manager as any,+ monitoring as any,+ { ...config, hogWatcherSampleRate: sampleRate },+ watcher+ )++ it('never touches the watcher when the sample rate is 0', async () => {+ const watcher = createMockWatcher()+ service = withWatcher(watcher, 0)+ setFunctions([await createFunction('return record')])++ await service.transformRecords(TEAM_ID, [createRecord()])++ expect(watcher.getEffectiveStates).not.toHaveBeenCalled()+ expect(watcher.observeAggregatedResults).not.toHaveBeenCalled()+ })++ it('reports one aggregated observation per function when sampled', async () => {+ const watcher = createMockWatcher()+ service = withWatcher(watcher, 1)+ const fn = await createFunction('return record')+ setFunctions([fn])++ await service.transformRecords(TEAM_ID, [createRecord(), createRecord()])++ expect(watcher.observeAggregatedResults).toHaveBeenCalledTimes(1)+ const observations = watcher.observeAggregatedResults.mock.calls[0][0]+ expect(observations).toHaveLength(1)+ expect(observations[0].hogFunction.id).toEqual(fn.id)+ expect(observations[0].totalDurationMs).toBeGreaterThanOrEqual(0)+ })++ it('skips functions the watcher has disabled and records a metric', async () => {+ const watcher = createMockWatcher()+ const fn = await createFunction('return null') // would drop every record if it ran+ watcher.getEffectiveStates.mockResolvedValue({ [fn.id]: { state: HogWatcherState.disabled, tokens: 0 } })+ service = withWatcher(watcher, 1)+ setFunctions([fn])++ const records = [createRecord(), createRecord()]+ const { recordsDropped } = await service.transformRecords(TEAM_ID, records)++ expect(recordsDropped).toEqual(0)+ expect(records).toHaveLength(2)+ expect(watcher.observeAggregatedResults).not.toHaveBeenCalled()+ expect(queuedMetrics()).toContainEqual(+ expect.objectContaining({ metric_name: 'disabled_permanently', app_source_id: fn.id, count: 2 })+ )+ })+ })+})diff --git a/nodejs/src/logs/transformations/logs-transformer.service.ts b/nodejs/src/logs/transformations/logs-transformer.service.tsnew file mode 100644index 000000000000..3412ce79aaa3--- /dev/null+++ b/nodejs/src/logs/transformations/logs-transformer.service.ts@@ -0,0 +1,565 @@+import { DateTime } from 'luxon'+import { Counter, Histogram } from 'prom-client'++import { HogFunctionManagerService } from '~/cdp/services/managers/hog-function-manager.service'+import { HogFunctionMonitoringService } from '~/cdp/services/monitoring/hog-function-monitoring.service'+import { HogWatcherService, HogWatcherState } from '~/cdp/services/monitoring/hog-watcher.service'+import { HogFunctionType, LogEntry } from '~/cdp/types'+import { sanitizeLogMessage } from '~/cdp/utils'+import { yieldEventLoopIfNeeded } from '~/common/utils/event-loop-yield'+import { logger } from '~/common/utils/logger'+import { UUIDT } from '~/common/utils/utils'++import type { LogRecord } from '../log-record-avro'+import {+ LogTransformationGlobals,+ buildLogRecordGlobals,+ decodeLogAttributeValue,+ encodeLogAttributeValue,+ executeLogTransformation,+ resolveLogTransformationInputs,+} from './hog-log-exec'++// Iterative with a visited set: no depth cap (a secret below any cap would escape+// redaction entirely) and safe against cyclic values.+function collectStringLeaves(root: unknown, out: string[]): void {+ const stack: unknown[] = [root]+ const seen = new WeakSet<object>()+ while (stack.length > 0) {+ const value = stack.pop()+ if (typeof value === 'string') {+ if (value.length > 0) {+ out.push(value)+ }+ continue+ }+ if (value && typeof value === 'object') {+ if (seen.has(value)) {+ continue+ }+ seen.add(value)+ // Push one-by-one: spreading an unbounded user-supplied array would+ // exceed V8's argument limit and throw RangeError.+ for (const item of Array.isArray(value) ? value : Object.values(value)) {+ stack.push(item)+ }+ }+ }+}++export const transformationRecordsCounter = new Counter({+ name: 'logs_ingestion_transformations_records_total',+ help: 'Per-record log transformation outcomes',+ labelNames: ['result'], // succeeded | failed | dropped | budget_skipped | watcher_disabled+})++export const transformationVmDurationHistogram = new Histogram({+ name: 'logs_ingestion_transformations_vm_duration_seconds',+ help: 'Total HogVM execution time spent on log transformations per Kafka message',+ buckets: [0.001, 0.005, 0.01, 0.025, 0.05, 0.1, 0.25, 0.5, 1, 2],+})++export const transformationBudgetExhaustedCounter = new Counter({+ name: 'logs_ingestion_transformations_budget_exhausted_total',+ help: 'Transformation time budget exhausted; remaining records passed through untransformed',+ labelNames: ['scope', 'team_id'], // scope: message | batch+})++export const transformationUnexpectedErrorsCounter = new Counter({+ name: 'logs_ingestion_transformations_unexpected_errors_total',+ help: 'Unexpected (non-customer-code) errors in the logs transformer. Any occurrence should alert.',+})++export interface LogsTransformerConfig {+ siteUrl: string+ /** Hard per-record VM kill */+ hogTimeoutMs: number+ /** Cumulative VM time budget per Kafka message */+ messageBudgetMs: number+ /** Cumulative VM time budget per consumer batch */+ batchBudgetMs: number+ /** Max failed invocations whose print/error logs are captured, per function per message */+ maxErrorLogsPerFunctionPerMessage: number+ /** Fraction of messages on which HogWatcher state is read and aggregate cost reported.+ * 0 disables the watcher entirely (no Redis reads, no observations). */+ hogWatcherSampleRate: number+}++/** Tracks cumulative VM time across all messages of one consumer batch. */+export class TransformationBatchBudget {+ usedMs = 0++ constructor(private readonly totalMs: number) {}++ get exhausted(): boolean {+ return this.usedMs >= this.totalMs+ }++ add(durationMs: number): void {+ this.usedMs += durationMs+ }+}++interface FunctionAggregates {+ succeeded: number+ failed: number+ dropped: number+ budgetSkipped: number+ totalDurationMs: number+ errorLogs: LogEntry[]+}++const ATTR_TRANSFORMATIONS_FAILED = '$transformations_failed'+const ATTR_TRANSFORMATIONS_SKIPPED = '$transformations_skipped'++/**+ * Runs a team's enabled log transformations over the records of one Kafka message,+ * mutating the array in place (dropped records are removed).+ *+ * Failure semantics are fail-open throughout, mirroring events ingestion and the+ * logs sampling pipeline: a failing transformation annotates the record and passes+ * it through unchanged. Budgets bound the worst-case added latency; when exhausted,+ * remaining records skip transformation and are annotated.+ *+ * Unlike the events HogTransformerService there are no per-invocation result objects:+ * at logs volume (100k+ records/s for large teams) metrics are aggregated per+ * (function, message) and print() output is only kept for failing invocations.+ */+export class LogsTransformerService {+ constructor(+ private hogFunctionManager: HogFunctionManagerService,+ private monitoring: HogFunctionMonitoringService,+ private config: LogsTransformerConfig,+ private hogWatcher?: HogWatcherService+ ) {}++ public startBatch(): TransformationBatchBudget {+ return new TransformationBatchBudget(this.config.batchBudgetMs)+ }++ /** Cheap existence check (in-process LazyLoader cache) used to preserve the+ * no-decode passthrough for teams without transformations. */+ public async teamHasTransformations(teamId: number): Promise<boolean> {+ const idsByTeam = await this.hogFunctionManager.getHogFunctionIdsForTeams([teamId], ['transformation_log'])+ return (idsByTeam[teamId] ?? []).length > 0+ }++ public async flush(): Promise<void> {+ await this.monitoring.flush()+ }++ public async transformRecords(+ teamId: number,+ records: LogRecord[],+ batchBudget?: TransformationBatchBudget+ ): Promise<{ recordsDropped: number; recordsDroppedByFunctionId: Map<string, number> }> {+ const recordsDroppedByFunctionId = new Map<string, number>()+ let recordsDropped = 0++ const functionsByTeam = await this.hogFunctionManager.getHogFunctionsForTeams([teamId], ['transformation_log'])+ const allFunctions = functionsByTeam[teamId] ?? []+ if (allFunctions.length === 0 || records.length === 0) {+ return { recordsDropped, recordsDroppedByFunctionId }+ }++ // On a sampled message the watcher reads state (to skip disabled functions) and, at the+ // end, receives the aggregate cost. A sample rate of 0 means no Redis traffic at all.+ const runWatcher = !!this.hogWatcher && Math.random() < this.config.hogWatcherSampleRate+ const functions = runWatcher+ ? await this.dropWatcherDisabled(teamId, allFunctions, records.length)+ : allFunctions+ if (functions.length === 0) {+ return { recordsDropped, recordsDroppedByFunctionId }+ }++ const project = {+ id: teamId,+ name: '',+ url: `${this.config.siteUrl}/project/${teamId}`,+ }+ const instanceId = new UUIDT().toString()+ const aggregates = new Map<string, FunctionAggregates>()+ const inputsCache = new Map<string, Record<string, unknown> | null>()+ const sensitiveValuesCache = new Map<string, string[]>()+ let messageVmMs = 0+ let budgetExhaustedScope: 'message' | 'batch' | null = null++ const kept: LogRecord[] = []++ for (let i = 0; i < records.length; i++) {+ const record = records[i]++ if (budgetExhaustedScope === null) {+ if (batchBudget?.exhausted) {+ budgetExhaustedScope = 'batch'+ } else if (messageVmMs >= this.config.messageBudgetMs) {+ budgetExhaustedScope = 'message'+ }+ if (budgetExhaustedScope !== null) {+ transformationBudgetExhaustedCounter.inc({+ scope: budgetExhaustedScope,+ team_id: String(teamId),+ })+ }+ }++ if (budgetExhaustedScope !== null) {+ record.attributes = record.attributes ?? {}+ // JSON-encoded like every attribute value, so the ClickHouse sink surfaces it+ record.attributes[ATTR_TRANSFORMATIONS_SKIPPED] = encodeLogAttributeValue('budget')+ transformationRecordsCounter.inc({ result: 'budget_skipped' })+ for (const fn of functions) {+ this.getAggregates(aggregates, fn.id).budgetSkipped+++ }+ kept.push(record)+ continue+ }++ const dropped = await yieldEventLoopIfNeeded('logs-transformer', () => {+ return this.transformSingleRecord(record, functions, project, {+ teamId,+ instanceId,+ aggregates,+ inputsCache,+ sensitiveValuesCache,+ recordsDroppedByFunctionId,+ addVmMs: (ms) => {+ messageVmMs += ms+ batchBudget?.add(ms)+ },+ })+ })++ if (dropped) {+ recordsDropped+++ } else {+ kept.push(record)+ }+ }++ // Replace contents in place so callers holding the array reference see the result+ records.length = 0+ records.push(...kept)++ transformationVmDurationHistogram.observe(messageVmMs / 1000)+ this.queueAggregates(teamId, aggregates)+ if (runWatcher) {+ this.reportToWatcher(functions, aggregates)+ }++ return { recordsDropped, recordsDroppedByFunctionId }+ }++ /** Reads watcher state once per message and removes functions it has disabled. */+ private async dropWatcherDisabled(+ teamId: number,+ functions: HogFunctionType[],+ recordCount: number+ ): Promise<HogFunctionType[]> {+ if (!this.hogWatcher) {+ return functions+ }+ const states = await this.hogWatcher.getEffectiveStates(functions.map((fn) => fn.id))+ const active: HogFunctionType[] = []+ for (const fn of functions) {+ if (states[fn.id]?.state === HogWatcherState.disabled) {+ transformationRecordsCounter.inc({ result: 'watcher_disabled' }, recordCount)+ this.monitoring.queueAppMetric(+ {+ team_id: teamId,+ app_source_id: fn.id,+ metric_kind: 'failure',+ metric_name: 'disabled_permanently',+ count: recordCount,+ },+ 'hog_function'+ )+ } else {+ active.push(fn)+ }+ }+ return active+ }++ /** Reports one aggregated VM-time observation per function for this message. Fire-and-forget. */+ private reportToWatcher(functions: HogFunctionType[], aggregates: Map<string, FunctionAggregates>): void {+ if (!this.hogWatcher) {+ return+ }+ const byId = new Map(functions.map((fn) => [fn.id, fn]))+ const observations: { hogFunction: HogFunctionType; totalDurationMs: number }[] = []+ for (const [functionId, agg] of aggregates) {+ const hogFunction = byId.get(functionId)+ // A 0ms aggregate still costs nothing, but reporting it keeps token refill honest.+ if (hogFunction) {+ observations.push({ hogFunction, totalDurationMs: agg.totalDurationMs })+ }+ }+ if (observations.length > 0) {+ this.hogWatcher.observeAggregatedResults(observations).catch((error) => {+ logger.warn('⚠️', '[logs-transformer] HogWatcher observeAggregatedResults failed', {+ error: String(error),+ })+ })+ }+ }++ /** Runs every function in execution order against one record. Returns true if dropped. */+ private transformSingleRecord(+ record: LogRecord,+ functions: HogFunctionType[],+ project: LogTransformationGlobals['project'],+ ctx: {+ teamId: number+ instanceId: string+ aggregates: Map<string, FunctionAggregates>+ inputsCache: Map<string, Record<string, unknown> | null>+ sensitiveValuesCache: Map<string, string[]>+ recordsDroppedByFunctionId: Map<string, number>+ addVmMs: (ms: number) => void+ }+ ): boolean {+ for (const fn of functions) {+ const agg = this.getAggregates(ctx.aggregates, fn.id)++ const globals = buildLogRecordGlobals(record, project, {})++ // Input templates are customer-owned bytecode — a failing template is an+ // invocation failure (fail open, annotate, surface in function logs), not a+ // transformer bug worth alerting on.+ try {+ const { inputs, vmMs } = this.resolveInputs(fn, globals, ctx.inputsCache)+ globals.inputs = inputs+ ctx.addVmMs(vmMs)+ agg.totalDurationMs += vmMs+ } catch (error) {+ agg.failed+++ transformationRecordsCounter.inc({ result: 'failed' })+ this.annotateFailure(record, fn)+ this.captureErrorLogs(+ fn,+ ctx.teamId,+ ctx.instanceId,+ agg,+ [],+ String(error),+ this.getSensitiveValues(fn, ctx.sensitiveValuesCache)+ )+ continue+ }++ let outcome+ try {+ outcome = executeLogTransformation(fn.bytecode, record, globals, {+ timeoutMs: this.config.hogTimeoutMs,+ sensitiveValues: this.getSensitiveValues(fn, ctx.sensitiveValuesCache),+ })+ } catch (error) {+ // Errors from customer code are contained inside executeLogTransformation;+ // reaching here means a transformer bug.+ transformationUnexpectedErrorsCounter.inc()+ logger.error('⚠️', '[logs-transformer] unexpected error', {+ teamId: ctx.teamId,+ functionId: fn.id,+ error: String(error),+ })+ this.annotateFailure(record, fn)+ agg.failed+++ transformationRecordsCounter.inc({ result: 'failed' })+ continue+ }++ ctx.addVmMs(outcome.durationMs)+ agg.totalDurationMs += outcome.durationMs++ if (outcome.status === 'failed') {+ agg.failed+++ transformationRecordsCounter.inc({ result: 'failed' })+ this.annotateFailure(record, fn)+ this.captureErrorLogs(+ fn,+ ctx.teamId,+ ctx.instanceId,+ agg,+ outcome.logs,+ outcome.error,+ this.getSensitiveValues(fn, ctx.sensitiveValuesCache)+ )+ continue+ }++ if (outcome.status === 'dropped') {+ agg.dropped+++ transformationRecordsCounter.inc({ result: 'dropped' })+ ctx.recordsDroppedByFunctionId.set(fn.id, (ctx.recordsDroppedByFunctionId.get(fn.id) ?? 0) + 1)+ return true+ }++ agg.succeeded+++ transformationRecordsCounter.inc({ result: 'succeeded' })+ }++ return false+ }++ /**+ * Resolves function inputs once per (function, message) and caches them — unless any+ * input template references the `record` global, in which case resolution happens per+ * record (cache stores null to remember that decision).+ */+ private resolveInputs(+ fn: HogFunctionType,+ globals: LogTransformationGlobals,+ cache: Map<string, Record<string, unknown> | null>+ ): { inputs: Record<string, unknown>; vmMs: number } {+ const cached = cache.get(fn.id)+ if (cached) {+ return { inputs: cached, vmMs: 0 }+ }++ if (cached === undefined) {+ // First sight of this function in this message: decide cacheability with a+ // cheap scan over all templates (encrypted included). False positives only+ // cost per-record resolution.+ const referencesRecord = JSON.stringify({ ...fn.inputs, ...fn.encrypted_inputs }).includes('record')+ if (!referencesRecord) {+ const resolved = this.resolveInputsUncached(fn, globals)+ cache.set(fn.id, resolved.inputs)+ return { inputs: resolved.inputs, vmMs: resolved.durationMs }+ }+ cache.set(fn.id, null)+ }++ const resolved = this.resolveInputsUncached(fn, globals)+ return { inputs: resolved.inputs, vmMs: resolved.durationMs }+ }++ private resolveInputsUncached(+ fn: HogFunctionType,+ globals: LogTransformationGlobals+ ): { inputs: Record<string, unknown>; durationMs: number } {+ return resolveLogTransformationInputs(fn, globals, this.config.hogTimeoutMs)+ }++ private getSensitiveValues(fn: HogFunctionType, cache: Map<string, string[]>): string[] {+ let values = cache.get(fn.id)+ if (!values) {+ // Secret inputs are schema-validated as any JSON value, so redaction must+ // cover string leaves nested in dicts/arrays, not just top-level strings.+ values = []+ for (const input of Object.values(fn.encrypted_inputs ?? {})) {+ collectStringLeaves(input?.value, values)+ }+ cache.set(fn.id, values)+ }+ return values+ }++ private annotateFailure(record: LogRecord, fn: HogFunctionType): void {+ record.attributes = record.attributes ?? {}+ const rawExisting = record.attributes[ATTR_TRANSFORMATIONS_FAILED]+ const existing = rawExisting ? decodeLogAttributeValue(rawExisting) : undefined+ const identifier = `${fn.name} (${fn.id})`+ record.attributes[ATTR_TRANSFORMATIONS_FAILED] = encodeLogAttributeValue(+ existing ? `${existing}, ${identifier}` : identifier+ )+ }++ private captureErrorLogs(+ fn: HogFunctionType,+ teamId: number,+ instanceId: string,+ agg: FunctionAggregates,+ printLogs: string[],+ error: string,+ sensitiveValues: string[]+ ): void {+ const capturedFailures = agg.errorLogs.filter((log) => log.level === 'error').length+ if (capturedFailures >= this.config.maxErrorLogsPerFunctionPerMessage) {+ return+ }++ const base = {+ team_id: teamId,+ log_source: 'hog_function' as const,+ log_source_id: fn.id,+ instance_id: instanceId,+ }+ for (const message of printLogs) {+ agg.errorLogs.push({ ...base, level: 'info', message, timestamp: DateTime.now() })+ }+ // The thrown error string is customer-influenced like print() output —+ // redact encrypted input values before it reaches persisted function logs.+ agg.errorLogs.push({+ ...base,+ level: 'error',+ message: sanitizeLogMessage([error], sensitiveValues),+ timestamp: DateTime.now(),+ })+ }++ private getAggregates(aggregates: Map<string, FunctionAggregates>, functionId: string): FunctionAggregates {+ let agg = aggregates.get(functionId)+ if (!agg) {+ agg = { succeeded: 0, failed: 0, dropped: 0, budgetSkipped: 0, totalDurationMs: 0, errorLogs: [] }+ aggregates.set(functionId, agg)+ }+ return agg+ }++ private queueAggregates(teamId: number, aggregates: Map<string, FunctionAggregates>): void {+ for (const [functionId, agg] of aggregates) {+ if (agg.succeeded > 0) {+ this.monitoring.queueAppMetric(+ {+ team_id: teamId,+ app_source_id: functionId,+ metric_kind: 'success',+ metric_name: 'succeeded',+ count: agg.succeeded,+ },+ 'hog_function'+ )+ }+ if (agg.failed > 0) {+ this.monitoring.queueAppMetric(+ {+ team_id: teamId,+ app_source_id: functionId,+ metric_kind: 'failure',+ metric_name: 'failed',+ count: agg.failed,+ },+ 'hog_function'+ )+ }+ if (agg.dropped > 0) {+ this.monitoring.queueAppMetric(+ {+ team_id: teamId,+ app_source_id: functionId,+ metric_kind: 'other',+ metric_name: 'dropped',+ count: agg.dropped,+ },+ 'hog_function'+ )+ }+ if (agg.budgetSkipped > 0) {+ this.monitoring.queueAppMetric(+ {+ team_id: teamId,+ app_source_id: functionId,+ metric_kind: 'other',+ metric_name: 'budget_skipped',+ count: agg.budgetSkipped,+ },+ 'hog_function'+ )+ }+ if (agg.errorLogs.length > 0) {+ this.monitoring.queueLogs(agg.errorLogs, 'hog_function')+ }+ }+ }+}