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.

chore(logs): unify log ingestion into one decode→stage→encode pipeline (#77328)

Frank Hamand2ccdaadf473b
diff --git a/nodejs/src/logs/log-record-avro.ts b/nodejs/src/logs/log-record-avro.ts
index 65d628fb266a..a63de2f73da9 100644
--- a/nodejs/src/logs/log-record-avro.ts
+++ b/nodejs/src/logs/log-record-avro.ts
@@ -9,6 +9,12 @@ import type { LogsSettings } from '~/types'
import { recordLogProcessingDuration } from './ingestion-otel-metrics'
import { type LogBodyParseResult, parseLogBodyForIngestion } from './log-body-parse'
import { EMPTY_PII, type PiiScrubStats, scrubLogRecord } from './log-pii-scrub'
+import {
+ type DropStats,
+ EMPTY_DROP_STATS,
+ type PipelineStage,
+ runPipelineStages,
+} from './pipeline/log-processing-pipeline'
const MAX_JSON_ATTRIBUTES = 50
@@ -294,18 +300,31 @@ export async function transformDecodedLogRecordsInPlace(
* (dropped records are removed). Used to run hog log transformations last. */
export type LogRecordsTransform = (records: LogRecord[]) => Promise<unknown>
+export type ProcessLogMessageBufferOptions = {
+ /** Runs after normalize and before the stages — sees every record post-scrub and pre-drop. */
+ onRecordsDecoded?: (records: LogRecord[]) => void
+ /** Ordered mutate/filter stages (sampling, hog transforms, per-row retention). */
+ stages?: PipelineStage[]
+}
+
+export type ProcessLogMessageBufferResult = {
+ value: Buffer | null
+ pii: PiiScrubStats
+ drops: DropStats
+}
+
/**
- * Processes an AVRO-encoded log message buffer containing multiple records.
- * Passthrough (no decode) when json_parse_logs and pii_scrub_logs are off and no
- * `recordsTransform` is given.
- * Otherwise: decode → optional PII scrub on `body` → optional parse bodies → optional JSON enrich
- * → optional `recordsTransform` (hog log transformations, always last) → encode.
+ * The single decode → transform → encode path for a log message buffer.
+ * Passthrough (no decode) when json_parse_logs and pii_scrub_logs are off, there are no `stages`, and
+ * no `onRecordsDecoded` visitor.
+ * Otherwise: decode → normalize (optional PII scrub on `body`, then optional JSON parse + enrich) →
+ * `onRecordsDecoded` visitor → run `stages` in order → encode.
*
* When both `json_parse_logs` and `pii_scrub_logs` are on, scrub runs **before** parse/enrich so flattened JSON
- * attributes are derived from the redacted body string. `parseLogBodiesForIngestion` runs only when JSON parse is on.
+ * attributes are derived from the redacted body string. A read-only message (no normalize, no stages)
+ * that only ran a visitor is returned untouched — no re-encode.
*
- * `value` is null when `recordsTransform` dropped every record — the caller must not
- * produce the message downstream.
+ * `value` is null when the stages dropped every record — the caller must not produce it downstream.
*/
export const processLogMessageBuffer = instrumented({
key: SPAN_LOGS_PROCESS_BUFFER,
@@ -313,20 +332,17 @@ export const processLogMessageBuffer = instrumented({
})(async function processLogMessageBufferImpl(
buffer: Buffer,
settings: LogsSettings,
- onRecordsDecoded?: (records: LogRecord[]) => void,
- recordsTransform?: LogRecordsTransform
-): Promise<{ value: Buffer | null; pii: PiiScrubStats }> {
+ options: ProcessLogMessageBufferOptions = {}
+): Promise<ProcessLogMessageBufferResult> {
+ const { onRecordsDecoded, stages = [] } = options
const jsonParse = settings.json_parse_logs ?? false
const piiScrub = settings.pii_scrub_logs ?? false
+ const normalizeActive = jsonParse || piiScrub
+ const mustReencode = normalizeActive || stages.length > 0
- if (!jsonParse && !piiScrub && !recordsTransform) {
- // Passthrough: the buffer is forwarded untouched. Decode only when a visitor
- // (metric-rule extraction) needs the records — skipping the re-encode either way.
- if (onRecordsDecoded) {
- const [, , records] = await decodeLogRecordsInstrumented(buffer)
- onRecordsDecoded(records)
- }
- return { value: buffer, pii: EMPTY_PII }
+ if (!mustReencode && !onRecordsDecoded) {
+ // Passthrough: nothing mutates or drops and no visitor needs the records — forward untouched.
+ return { value: buffer, pii: EMPTY_PII, drops: EMPTY_DROP_STATS() }
}
const startTime = Date.now()
@@ -343,15 +359,21 @@ export const processLogMessageBuffer = instrumented({
const pii = await transformDecodedLogRecordsInPlace(records, settings)
onRecordsDecoded?.(records)
- if (recordsTransform) {
- await recordsTransform(records)
- if (records.length === 0) {
- return { value: null, pii }
- }
+ const { kept, stats } = await runPipelineStages(records, stages)
+
+ if (!mustReencode) {
+ // Only a visitor ran — the buffer is unchanged, so forward it without re-encoding.
+ return { value: buffer, pii, drops: stats }
+ }
+ if (kept.length === 0 && stats.droppedBy) {
+ // A filter stage emptied the batch — signal the caller to suppress it. A batch that was
+ // *already* empty (nothing dropped) still re-encodes to a schema-only buffer, matching the
+ // pre-pipeline behavior; suppressing those is a separate change.
+ return { value: null, pii, drops: stats }
}
- const value = await encodeLogRecordsInstrumented(logRecordType, codec, records)
- return { value, pii }
+ const value = await encodeLogRecordsInstrumented(logRecordType, codec, kept)
+ return { value, pii, drops: stats }
} finally {
const durationSeconds = (Date.now() - startTime) / 1000
const durationLabels = {
@@ -365,6 +387,5 @@ export const processLogMessageBuffer = instrumented({
}) as (
buffer: Buffer,
settings: LogsSettings,
- onRecordsDecoded?: (records: LogRecord[]) => void,
- recordsTransform?: LogRecordsTransform
-) => Promise<{ value: Buffer | null; pii: PiiScrubStats }>
+ options?: ProcessLogMessageBufferOptions
+) => Promise<ProcessLogMessageBufferResult>
diff --git a/nodejs/src/logs/logs-ingestion-consumer.ts b/nodejs/src/logs/logs-ingestion-consumer.ts
index 49220e413541..5ac4738bab38 100644
--- a/nodejs/src/logs/logs-ingestion-consumer.ts
+++ b/nodejs/src/logs/logs-ingestion-consumer.ts
@@ -33,6 +33,7 @@ import { LogsMetricsEmitter } from './metrics-rules/metrics-emitter'
import { buildMetricRulesOtlpPayload } from './metrics-rules/otlp-payload'
import { type BatchTallies, createBatchTallies, tallyRecords } from './metrics-rules/tally'
import { LOGS_DLQ_OUTPUT, LOGS_OUTPUT, LogsDlqOutput, LogsOutput } from './outputs/outputs'
+import { EMPTY_DROP_STATS, type PipelineStage } from './pipeline/log-processing-pipeline'
import type { CompiledRuleSet } from './sampling/evaluate'
import { LogsSamplingService } from './sampling/logs-sampling.service'
import { SamplingRulesCache } from './sampling/sampling-rules-cache'
@@ -262,6 +263,28 @@ export function billingByteReductionForDrops(headerBytes: number, bytesDropped:
return Math.round(headerBytes * droppedFraction)
}
+/**
+ * Wraps a hog log transform (mutates the surviving records in place, may drop) as the last pipeline
+ * `filter` stage. Partial transform drops are not billed-credited — only the all-dropped case is
+ * attributed — so it reports no per-rule accounting, just the `transformations` tag when it removed
+ * any record.
+ */
+function makeTransformStage(transform: LogRecordsTransform): PipelineStage {
+ return {
+ kind: 'filter',
+ name: 'transformations',
+ run: async (records) => {
+ const before = records.length
+ await transform(records)
+ const stats = EMPTY_DROP_STATS()
+ if (records.length < before) {
+ stats.droppedBy = 'transformations'
+ }
+ return { kept: records, stats }
+ },
+ }
+}
+
export class LogsIngestionConsumer {
protected name = 'LogsIngestionConsumer'
// Billing identity for quota enforcement and usage metering; overridden by subclasses (e.g. traces).
@@ -409,6 +432,17 @@ export class LogsIngestionConsumer {
const useSamplingPipeline = Boolean(ruleSet && ruleSet.rules.length > 0)
const recordsTransform = await this.buildRecordsTransform(message, batchBudget)
+ // Assemble the ordered decode → transform → encode pipeline: sampling drop rules + rate
+ // limits first, hog transformations last. An empty list (with no metric visitor) leaves the
+ // buffer as a no-decode passthrough inside `processLogMessageBuffer`.
+ const stages: PipelineStage[] = []
+ if (useSamplingPipeline && ruleSet) {
+ stages.push(this.samplingService.makeSamplingStage(ruleSet, message.teamId, message.bytesUncompressed))
+ }
+ if (recordsTransform) {
+ stages.push(makeTransformStage(recordsTransform))
+ }
+
trace.getActiveSpan()?.setAttributes({
'logs.sampling.killswitch': this.samplingKillswitch,
'logs.sampling.enabled_teams_configured': Boolean((this.samplingEnabledTeamsRaw || '').trim()),
@@ -419,80 +453,46 @@ export class LogsIngestionConsumer {
'logs.transformations.enabled_for_team': Boolean(recordsTransform),
'logs.sampling.pipeline': useSamplingPipeline
? 'decode_sample_encode'
- : 'passthrough_processLogMessageBuffer',
+ : recordsTransform
+ ? 'decode_transform_encode'
+ : 'passthrough',
})
- if (useSamplingPipeline && ruleSet) {
- const sampled = await this.samplingService.processBuffer(
- message.message.value!,
- logsSettings,
- ruleSet,
- message.teamId,
- message.bytesUncompressed,
- onRecordsDecoded,
- recordsTransform
- )
- if (sampled.recordsDropped > 0) {
- logsSamplingRecordsDroppedCounter.inc({ team_id: message.teamId.toString() }, sampled.recordsDropped)
- }
- if (sampled.bytesDropped > 0) {
- logsBytesDroppedByRuleCounter.inc({ team_id: message.teamId.toString() }, sampled.bytesDropped)
- }
- if (sampled.allDropped) {
- return {
- outcome: 'all_dropped',
- reason:
- sampled.allDroppedBy === 'transformations'
- ? 'transformations_all_dropped'
- : 'sampling_all_dropped',
- pii: sampled.pii,
- recordsDropped: sampled.recordsDropped,
- recordsDroppedByRuleId: sampled.recordsDroppedByRuleId,
- bytesDroppedByRuleId: sampled.bytesDroppedByRuleId,
- contentBytesDropped: sampled.contentBytesDropped,
- contentBytesTotal: sampled.contentBytesTotal,
- }
- }
- return {
- outcome: 'produce',
- processedValue: sampled.value,
- pii: sampled.pii,
- recordsDropped: sampled.recordsDropped,
- recordsDroppedByRuleId: sampled.recordsDroppedByRuleId,
- bytesDroppedByRuleId: sampled.bytesDroppedByRuleId,
- contentBytesDropped: sampled.contentBytesDropped,
- contentBytesTotal: sampled.contentBytesTotal,
- }
+ const { value, pii, drops } = await processLogMessageBuffer(message.message.value!, logsSettings, {
+ onRecordsDecoded,
+ stages,
+ })
+
+ // Only the sampling stage attributes per-rule drops; the transform stage reports none, so
+ // these increments are no-ops on the transform-only and passthrough paths.
+ if (drops.recordsDropped > 0) {
+ logsSamplingRecordsDroppedCounter.inc({ team_id: message.teamId.toString() }, drops.recordsDropped)
+ }
+ if (drops.bytesDropped > 0) {
+ logsBytesDroppedByRuleCounter.inc({ team_id: message.teamId.toString() }, drops.bytesDropped)
}
- // Passthrough (sampling disabled / no rules): drop rules removed nothing, so nothing to credit.
- const res = await processLogMessageBuffer(
- message.message.value!,
- logsSettings,
- onRecordsDecoded,
- recordsTransform
- )
- if (res.value === null) {
+ if (value === null) {
return {
outcome: 'all_dropped',
- reason: 'transformations_all_dropped',
- pii: res.pii,
- recordsDropped: 0,
- recordsDroppedByRuleId: new Map(),
- bytesDroppedByRuleId: new Map(),
- contentBytesDropped: 0,
- contentBytesTotal: 0,
+ reason: drops.droppedBy === 'transformations' ? 'transformations_all_dropped' : 'sampling_all_dropped',
+ pii,
+ recordsDropped: drops.recordsDropped,
+ recordsDroppedByRuleId: drops.recordsDroppedByRuleId,
+ bytesDroppedByRuleId: drops.bytesDroppedByRuleId,
+ contentBytesDropped: drops.contentBytesDropped,
+ contentBytesTotal: drops.contentBytesTotal,
}
}
return {
outcome: 'produce',
- processedValue: res.value,
- pii: res.pii,
- recordsDropped: 0,
- recordsDroppedByRuleId: new Map(),
- bytesDroppedByRuleId: new Map(),
- contentBytesDropped: 0,
- contentBytesTotal: 0,
+ processedValue: value,
+ pii,
+ recordsDropped: drops.recordsDropped,
+ recordsDroppedByRuleId: drops.recordsDroppedByRuleId,
+ bytesDroppedByRuleId: drops.bytesDroppedByRuleId,
+ contentBytesDropped: drops.contentBytesDropped,
+ contentBytesTotal: drops.contentBytesTotal,
}
}
diff --git a/nodejs/src/logs/pipeline/log-processing-pipeline.test.ts b/nodejs/src/logs/pipeline/log-processing-pipeline.test.ts
new file mode 100644
index 000000000000..f3760ebf3c1f
--- /dev/null
+++ b/nodejs/src/logs/pipeline/log-processing-pipeline.test.ts
@@ -0,0 +1,63 @@
+import type { LogRecord } from '~/logs/log-record-avro'
+
+import { EMPTY_DROP_STATS, type PipelineStage, runPipelineStages } from './log-processing-pipeline'
+
+describe('runPipelineStages', () => {
+ const rec = (uuid: string): LogRecord =>
+ ({
+ uuid,
+ body: uuid,
+ service_name: 'api',
+ attributes: null,
+ event_name: null,
+ resource_attributes: null,
+ }) as LogRecord
+
+ const dropFirst = (name: 'sampling' | 'transformations'): PipelineStage => ({
+ kind: 'filter',
+ name,
+ run: (records) => {
+ const kept = records.slice(1)
+ return { kept, stats: { ...EMPTY_DROP_STATS(), recordsDropped: 1, droppedBy: name } }
+ },
+ })
+
+ it('runs a mutate stage over every record before a later filter drops any', async () => {
+ const seen: string[] = []
+ const stages: PipelineStage[] = [
+ { kind: 'mutate', name: 'stamp', run: (records) => records.forEach((r) => seen.push(r.uuid!)) },
+ dropFirst('sampling'),
+ ]
+ const { kept, stats } = await runPipelineStages([rec('a'), rec('b'), rec('c')], stages)
+ expect(seen).toEqual(['a', 'b', 'c'])
+ expect(kept.map((r) => r.uuid)).toEqual(['b', 'c'])
+ expect(stats.recordsDropped).toBe(1)
+ expect(stats.droppedBy).toBe('sampling')
+ })
+
+ it('attributes an emptied message to the last filter that dropped, not the first', async () => {
+ // Sampling drops one, then transformations drop the survivor — all-dropped is on transforms.
+ const stages: PipelineStage[] = [dropFirst('sampling'), dropFirst('transformations')]
+ const { kept, stats } = await runPipelineStages([rec('a'), rec('b')], stages)
+ expect(kept).toHaveLength(0)
+ expect(stats.recordsDropped).toBe(2)
+ expect(stats.droppedBy).toBe('transformations')
+ })
+
+ it('stops running stages once every record is dropped', async () => {
+ let laterRan = false
+ const dropAll: PipelineStage = {
+ kind: 'filter',
+ name: 'sampling',
+ run: (records) => ({
+ kept: [],
+ stats: { ...EMPTY_DROP_STATS(), recordsDropped: records.length, droppedBy: 'sampling' },
+ }),
+ }
+ const later: PipelineStage = { kind: 'mutate', name: 'later', run: () => void (laterRan = true) }
+ const { kept, stats } = await runPipelineStages([rec('a')], [dropAll, later])
+ expect(kept).toHaveLength(0)
+ expect(stats.droppedBy).toBe('sampling')
+ expect(laterRan).toBe(false)
+ })
+})
diff --git a/nodejs/src/logs/pipeline/log-processing-pipeline.ts b/nodejs/src/logs/pipeline/log-processing-pipeline.ts
new file mode 100644
index 000000000000..3578f26523a3
--- /dev/null
+++ b/nodejs/src/logs/pipeline/log-processing-pipeline.ts
@@ -0,0 +1,91 @@
+import type { LogRecord } from '~/logs/log-record-avro'
+
+/**
+ * Per-message drop accounting produced by `filter` stages (sampling drop rules, rate limits, hog
+ * transformations). Fields mirror the billing pro-rate inputs the consumer already consumes: dropped
+ * counts/bytes are attributed to the first matching rule UUID, and `contentBytes*` are the pro-rate
+ * numerator/denominator. `droppedBy` records which stage removed the final surviving records so the
+ * consumer can attribute an all-dropped message to sampling vs transformations.
+ */
+export type DropStats = {
+ recordsDropped: number
+ recordsDroppedByRuleId: Map<string, number>
+ bytesDropped: number
+ bytesDroppedByRuleId: Map<string, number>
+ contentBytesDropped: number
+ /** Sum of customer-content bytes across ALL decoded rows; only set by a stage that measures it. */
+ contentBytesTotal: number
+ /** Set by a filter stage when it removed records — the last such wins for all-dropped attribution. */
+ droppedBy?: 'sampling' | 'transformations'
+}
+
+export const EMPTY_DROP_STATS = (): DropStats => ({
+ recordsDropped: 0,
+ recordsDroppedByRuleId: new Map(),
+ bytesDropped: 0,
+ bytesDroppedByRuleId: new Map(),
+ contentBytesDropped: 0,
+ contentBytesTotal: 0,
+})
+
+/** Result of a `filter` stage: the surviving records plus what it dropped. */
+export type FilterResult = { kept: LogRecord[]; stats: DropStats }
+
+/**
+ * A stage in the decode → transform → encode pipeline. Stages run in list order over one decode:
+ * - `mutate` edits records in place (per-row retention stamping).
+ * - `filter` removes records and reports what it dropped (sampling drop rules, rate limits, hog
+ * transformations that drop).
+ *
+ * PII scrub / JSON enrich run as a fixed normalize step before the stages (see
+ * `processLogMessageBuffer`), and metric-rule extraction runs as the `onRecordsDecoded` visitor
+ * between normalize and the stages — both must see every record post-scrub and pre-drop.
+ */
+export type PipelineStage =
+ | { kind: 'mutate'; name: string; run: (records: LogRecord[]) => Promise<void> | void }
+ | { kind: 'filter'; name: string; run: (records: LogRecord[]) => Promise<FilterResult> | FilterResult }
+
+function mergeByRuleId(into: Map<string, number>, from: Map<string, number>): void {
+ for (const [ruleId, n] of from) {
+ into.set(ruleId, (into.get(ruleId) ?? 0) + n)
+ }
+}
+
+/**
+ * Runs the stages over the decoded records in order, mutating `records` in place for `mutate`/`visit`
+ * and replacing the working set on each `filter`. Returns the surviving records and the aggregated
+ * drop accounting. Stops early once every record has been dropped so later stages don't run on an
+ * empty set (and `droppedBy` reflects the stage that emptied it).
+ */
+export async function runPipelineStages(
+ records: LogRecord[],
+ stages: PipelineStage[]
+): Promise<{ kept: LogRecord[]; stats: DropStats }> {
+ const stats = EMPTY_DROP_STATS()
+ let working = records
+ for (const stage of stages) {
+ if (stage.kind === 'mutate') {
+ await stage.run(working)
+ continue
+ }
+ const { kept, stats: dropped } = await stage.run(working)
+ stats.recordsDropped += dropped.recordsDropped
+ stats.bytesDropped += dropped.bytesDropped
+ stats.contentBytesDropped += dropped.contentBytesDropped
+ if (dropped.contentBytesTotal > 0) {
+ stats.contentBytesTotal = dropped.contentBytesTotal
+ }
+ mergeByRuleId(stats.recordsDroppedByRuleId, dropped.recordsDroppedByRuleId)
+ mergeByRuleId(stats.bytesDroppedByRuleId, dropped.bytesDroppedByRuleId)
+ // Last filter that removed a record wins the all-dropped attribution — sampling runs before
+ // hog transforms, so a message emptied by the transform is attributed to it, not sampling.
+ if (dropped.droppedBy) {
+ stats.droppedBy = dropped.droppedBy
+ }
+ working = kept
+ if (working.length === 0) {
+ break
+ }
+ }
+ return { kept: working, stats }
+}
diff --git a/nodejs/src/logs/sampling/logs-sampling.service.test.ts b/nodejs/src/logs/sampling/logs-sampling.service.test.ts
index 04c7f0fc35b7..100063d765ae 100644
--- a/nodejs/src/logs/sampling/logs-sampling.service.test.ts
+++ b/nodejs/src/logs/sampling/logs-sampling.service.test.ts
@@ -2,9 +2,9 @@ import avro from 'avsc'
import type { RedisClientPipeline, RedisV2 } from '~/common/redis/redis-v2'
import { type LogRecord, decodeLogRecords, encodeLogRecords } from '~/logs/log-record-avro'
-import type { LogsSettings } from '~/types'
import { compileRuleSet } from './compile-rules'
+import type { CompiledRuleSet } from './evaluate'
import { LogsSamplingService } from './logs-sampling.service'
const LOG_RECORD_AVRO = avro.Type.forSchema({
@@ -29,8 +29,6 @@ const LOG_RECORD_AVRO = avro.Type.forSchema({
],
})
-const logsSettings: LogsSettings = { json_parse_logs: false, pii_scrub_logs: false }
-
function baseLog(uuid: string, serviceName: string, bytesUncompressed: number | null = null): LogRecord {
return {
uuid,
@@ -52,6 +50,22 @@ function baseLog(uuid: string, serviceName: string, bytesUncompressed: number |
}
describe('LogsSamplingService', () => {
+ // Decodes the buffer and runs the sampling stage over the records, mirroring what the pipeline
+ // does around it. Returns the drop accounting plus the survivors so assertions read as before.
+ async function sampleBuffer(
+ service: LogsSamplingService,
+ buffer: Buffer,
+ ruleSet: CompiledRuleSet,
+ teamId?: number,
+ headerBytesUncompressed = 0
+ ): Promise<
+ { kept: LogRecord[]; allDropped: boolean } & Awaited<ReturnType<LogsSamplingService['sampleRecords']>>['stats']
+ > {
+ const [, , records] = await decodeLogRecords(buffer)
+ const { kept, stats } = await service.sampleRecords(records, ruleSet, teamId, headerBytesUncompressed)
+ return { ...stats, kept, allDropped: kept.length === 0 }
+ }
+
it('batches rate_limit lines and drops when tokensBefore is below pending count', async () => {
const ruleSet = compileRuleSet([
{
@@ -80,7 +94,7 @@ describe('LogsSamplingService', () => {
}
const service = new LogsSamplingService(mockRedis, 60)
- const result = await service.processBuffer(buffer, logsSettings, ruleSet, 99)
+ const result = await sampleBuffer(service, buffer, ruleSet, 99)
expect(result.recordsDropped).toBe(1)
expect(result.recordsDroppedByRuleId.get('rl-1')).toBe(1)
@@ -89,8 +103,7 @@ describe('LogsSamplingService', () => {
expect(result.bytesDroppedByRuleId.get('rl-1')).toBe(100)
expect(result.allDropped).toBe(false)
- const [, , kept] = await decodeLogRecords(result.value)
- expect(kept).toHaveLength(2)
+ expect(result.kept).toHaveLength(2)
})
it('attributes per-row bytes to the dropping rule and contributes 0 for null bytes_uncompressed', async () => {
@@ -123,7 +136,7 @@ describe('LogsSamplingService', () => {
}
const service = new LogsSamplingService(mockRedis, 60)
- const result = await service.processBuffer(buffer, logsSettings, ruleSet, 99)
+ const result = await sampleBuffer(service, buffer, ruleSet, 99)
expect(result.recordsDropped).toBe(2)
// Only the row with a populated bytes_uncompressed contributes to the byte sum;
@@ -162,7 +175,7 @@ describe('LogsSamplingService', () => {
}
const service = new LogsSamplingService(mockRedis, 60)
- const result = await service.processBuffer(buffer, logsSettings, ruleSet, 99)
+ const result = await sampleBuffer(service, buffer, ruleSet, 99)
expect(result.recordsDropped).toBe(1)
expect(result.recordsDroppedByRuleId.get('rl-kb')).toBe(1)
@@ -174,8 +187,7 @@ describe('LogsSamplingService', () => {
expect(result.contentBytesTotal).toBe(9)
expect(result.contentBytesDropped).toBe(7)
- const [, , kept] = await decodeLogRecords(result.value)
- expect(kept).toHaveLength(2)
+ expect(result.kept).toHaveLength(2)
})
it('KB-mode treats null bytes_uncompressed as zero-cost (in-flight producer rollout)', async () => {
@@ -208,7 +220,7 @@ describe('LogsSamplingService', () => {
}
const service = new LogsSamplingService(mockRedis, 60)
- const result = await service.processBuffer(buffer, logsSettings, ruleSet, 99)
+ const result = await sampleBuffer(service, buffer, ruleSet, 99)
expect(result.recordsDropped).toBe(1)
expect(result.bytesDropped).toBe(1000)
@@ -218,8 +230,7 @@ describe('LogsSamplingService', () => {
expect(result.contentBytesTotal).toBe(3)
expect(result.contentBytesDropped).toBe(1)
- const [, , kept] = await decodeLogRecords(result.value)
- expect(kept).toHaveLength(2)
+ expect(result.kept).toHaveLength(2)
})
it('KB-mode meters each row against its pro-rata share of the batch header, not per-row bytes_uncompressed', async () => {
@@ -255,7 +266,7 @@ describe('LogsSamplingService', () => {
}
const service = new LogsSamplingService(mockRedis, 60)
- const result = await service.processBuffer(buffer, logsSettings, ruleSet, 99, 24)
+ const result = await sampleBuffer(service, buffer, ruleSet, 99, 24)
// The batch is metered at the header pro-rata total (= header bytes), not Σ bytes_uncompressed.
// Args are [key, now, cost, bucketSize, refillRate, ttl]; cost is index 2.
@@ -265,8 +276,7 @@ describe('LogsSamplingService', () => {
// The dropped-bytes metric still reports the row's real bytes_uncompressed.
expect(result.bytesDropped).toBe(900)
- const [, , kept] = await decodeLogRecords(result.value)
- expect(kept).toHaveLength(2)
+ expect(result.kept).toHaveLength(2)
})
it('fail-open keeps all rate_limit lines when Redis pipeline returns null', async () => {
@@ -288,14 +298,13 @@ describe('LogsSamplingService', () => {
}
const service = new LogsSamplingService(mockRedis, 60)
- const result = await service.processBuffer(buffer, logsSettings, ruleSet, 1)
+ const result = await sampleBuffer(service, buffer, ruleSet, 1)
expect(result.recordsDropped).toBe(0)
expect(result.recordsDroppedByRuleId.size).toBe(0)
expect(result.bytesDropped).toBe(0)
expect(result.bytesDroppedByRuleId.size).toBe(0)
- const [, , kept] = await decodeLogRecords(result.value)
- expect(kept).toHaveLength(2)
+ expect(result.kept).toHaveLength(2)
})
})
diff --git a/nodejs/src/logs/sampling/logs-sampling.service.ts b/nodejs/src/logs/sampling/logs-sampling.service.ts
index 5ad55983ad50..e8e936e8ec45 100644
--- a/nodejs/src/logs/sampling/logs-sampling.service.ts
+++ b/nodejs/src/logs/sampling/logs-sampling.service.ts
@@ -5,15 +5,8 @@ import { type RedisV2 } from '~/common/redis/redis-v2'
import { KeyedRateLimitRequest, KeyedRateLimiterService } from '~/common/services/keyed-rate-limiter.service'
import { instrumented } from '~/common/tracing/tracing-utils'
import { logger } from '~/common/utils/logger'
-import { type PiiScrubStats } from '~/logs/log-pii-scrub'
-import {
- type LogRecord,
- type LogRecordsTransform,
- decodeLogRecords,
- encodeLogRecords,
- transformDecodedLogRecordsInPlace,
-} from '~/logs/log-record-avro'
-import type { LogsSettings } from '~/types'
+import { type LogRecord } from '~/logs/log-record-avro'
+import type { FilterResult, PipelineStage } from '~/logs/pipeline/log-processing-pipeline'
import type { CompiledRuleSet, EvaluateResult, RateLimitPendingByRule, SamplingClassifyResult } from './evaluate'
import {
@@ -59,26 +52,6 @@ function safeEvaluateLogRecord(ruleSet: CompiledRuleSet, record: LogRecord, team
}
}
-export type ProcessBufferWithSamplingResult = {
- value: Buffer
- pii: PiiScrubStats
- recordsDropped: number
- /** Counts dropped lines (drop / sample_dropped) attributed to the first matching rule UUID. */
- recordsDroppedByRuleId: Map<string, number>
- /** Sum of per-row `bytes_uncompressed` for dropped lines. Rows from old producers contribute 0. */
- bytesDropped: number
- /** Sum of per-row `bytes_uncompressed` for dropped lines, attributed to the first matching rule UUID. */
- bytesDroppedByRuleId: Map<string, number>
- /** Sum of customer-content bytes (body + attributes + event_name) for dropped lines. Billing pro-rate numerator. */
- contentBytesDropped: number
- /** Sum of customer-content bytes across ALL decoded rows (kept + dropped). Billing pro-rate denominator. */
- contentBytesTotal: number
- /** When true, the caller must not produce this message to downstream Kafka (all lines removed). */
- allDropped: boolean
- /** What removed the final surviving lines when `allDropped` is true. */
- allDroppedBy?: 'sampling' | 'transformations'
-}
-
const recordBytes = (r: LogRecord): number => r.bytes_uncompressed ?? 0
/**
@@ -107,28 +80,23 @@ export class LogsSamplingService {
)
}
+ /**
+ * Applies drop rules + rate limits to already-decoded records, returning the survivors and the
+ * per-rule drop accounting. Decode/encode, PII scrub, metric extraction, and hog transforms are
+ * owned by the pipeline (`processLogMessageBuffer`); this is the body of the sampling `filter`
+ * stage (see `makeSamplingStage`).
+ */
@instrumented({
- key: 'logsIngestion.sampling.processBufferWithSampling',
+ key: 'logsIngestion.sampling.sampleRecords',
measureTime: false,
sendException: false,
})
- public async processBuffer(
- buffer: Buffer,
- settings: LogsSettings,
+ public async sampleRecords(
+ records: LogRecord[],
ruleSet: CompiledRuleSet,
teamId?: number,
- headerBytesUncompressed: number = 0,
- onRecordsDecoded?: (records: LogRecord[]) => void,
- recordsTransform?: LogRecordsTransform
- ): Promise<ProcessBufferWithSamplingResult> {
- const [logRecordType, compressionCodec, records] = await decodeLogRecords(buffer)
- if (!logRecordType) {
- throw new Error('avro schema metadata not found')
- }
- const pii = await transformDecodedLogRecordsInPlace(records, settings)
- // Metric-rule extraction sees every record post-PII-scrub and pre-drop-rules:
- // dropping a log must not stop it from feeding a generated metric.
- onRecordsDecoded?.(records)
+ headerBytesUncompressed: number = 0
+ ): Promise<FilterResult> {
const kept: LogRecord[] = []
let recordsDropped = 0
const recordsDroppedByRuleId = new Map<string, number>()
@@ -206,49 +174,37 @@ export class LogsSamplingService {
}
}
- // Hog log transformations run last, on the records that survived the drop rules
- let keptBeforeTransform = 0
- if (recordsTransform && kept.length > 0) {
- keptBeforeTransform = kept.length
- await recordsTransform(kept)
- }
-
trace.getActiveSpan()?.setAttributes({
'logs.sampling.input_record_count': records.length,
'logs.sampling.kept_record_count': kept.length,
'logs.sampling.dropped_record_count': recordsDropped,
'logs.sampling.all_dropped': kept.length === 0,
- 'logs.sampling.json_parse_logs': Boolean(settings.json_parse_logs),
- 'logs.sampling.pii_scrub_logs': Boolean(settings.pii_scrub_logs),
})
- if (kept.length === 0) {
- return {
- value: Buffer.alloc(0),
- pii,
+ return {
+ kept,
+ stats: {
recordsDropped,
recordsDroppedByRuleId,
bytesDropped,
bytesDroppedByRuleId,
contentBytesDropped,
contentBytesTotal,
- allDropped: true,
- // Sampling left survivors and the transform removed the rest — attribute
- // the full-message drop to transformations, not the drop rules.
- allDroppedBy: keptBeforeTransform > 0 ? 'transformations' : 'sampling',
- }
+ droppedBy: recordsDropped > 0 ? 'sampling' : undefined,
+ },
}
- const value = await encodeLogRecords(logRecordType, compressionCodec, kept)
+ }
+
+ /** The sampling drop-rules + rate-limit `filter` stage for the log processing pipeline. */
+ public makeSamplingStage(
+ ruleSet: CompiledRuleSet,
+ teamId?: number,
+ headerBytesUncompressed: number = 0
+ ): PipelineStage {
return {
- value,
- pii,
- recordsDropped,
- recordsDroppedByRuleId,
- bytesDropped,
- bytesDroppedByRuleId,
- contentBytesDropped,
- contentBytesTotal,
- allDropped: false,
+ kind: 'filter',
+ name: 'sampling',
+ run: (records) => this.sampleRecords(records, ruleSet, teamId, headerBytesUncompressed),
}
}
diff --git a/nodejs/tests/logs/sampling/logs-sampling.rate-limit-impact.integration.test.ts b/nodejs/tests/logs/sampling/logs-sampling.rate-limit-impact.integration.test.ts
index 33a5d799253d..6ceaa6d53dd0 100644
--- a/nodejs/tests/logs/sampling/logs-sampling.rate-limit-impact.integration.test.ts
+++ b/nodejs/tests/logs/sampling/logs-sampling.rate-limit-impact.integration.test.ts
@@ -37,7 +37,6 @@ const LOG_RECORD_AVRO = avro.Type.forSchema({
],
})
-const logsSettings = { json_parse_logs: false, pii_scrub_logs: false }
const SERVICE = 'smokescreen'
const TEAM_ID = 4242
// LogsSamplingService names its limiter 'logs-sampling-rate'; key prefix uses the test root.
@@ -126,7 +125,17 @@ describe('logs drop-rule rate limit — save-to-impact', () => {
mockNow.mockReturnValue(now)
}
- /** Push `recordsPerSecond` rows of `bytesEach` through one processBuffer call per simulated second. */
+ /** Decode → run the sampling stage over the records → survivors + drop count, as the pipeline does. */
+ async function sampleBuffer(
+ buffer: Buffer,
+ ruleSet: ReturnType<typeof compileRuleSet>
+ ): Promise<{ kept: LogRecord[]; recordsDropped: number; allDropped: boolean }> {
+ const [, , records] = await decodeLogRecords(buffer)
+ const { kept, stats } = await service.sampleRecords(records, ruleSet, TEAM_ID)
+ return { kept, recordsDropped: stats.recordsDropped, allDropped: kept.length === 0 }
+ }
+
+ /** Push `recordsPerSecond` rows of `bytesEach` through one sampling call per simulated second. */
async function streamForSeconds(
ruleSet: ReturnType<typeof compileRuleSet>,
seconds: number,
@@ -138,7 +147,7 @@ describe('logs drop-rule rate limit — save-to-impact', () => {
for (let s = 0; s < seconds; s++) {
const batch = Array.from({ length: recordsPerSecond }, (_, i) => logRow(`s${s}-r${i}`, bytesEach))
const buffer = await encodeLogRecords(LOG_RECORD_AVRO, 'zstandard', batch)
- const result = await service.processBuffer(buffer, logsSettings, ruleSet, TEAM_ID)
+ const result = await sampleBuffer(buffer, ruleSet)
dropped += result.recordsDropped
kept += recordsPerSecond - result.recordsDropped
advanceOneSecond()
@@ -204,10 +213,9 @@ describe('logs drop-rule rate limit — save-to-impact', () => {
// Decoding a sampled batch still yields valid avro (the kept rows re-encode cleanly).
const batch = Array.from({ length: 400 }, (_, i) => logRow(`final-${i}`, BYTES_EACH))
const buffer = await encodeLogRecords(LOG_RECORD_AVRO, 'zstandard', batch)
- const result = await service.processBuffer(buffer, logsSettings, ruleSet, TEAM_ID)
+ const result = await sampleBuffer(buffer, ruleSet)
if (!result.allDropped) {
- const [, , kept] = await decodeLogRecords(result.value)
- expect(kept.length).toBe(400 - result.recordsDropped)
+ expect(result.kept.length).toBe(400 - result.recordsDropped)
}
})
})