: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
fix(logs): meter drop-rule rate limit on pro-rata header bytes (#67381)
Frank Hamand036f682e83fb
diff --git a/nodejs/src/logs/logs-ingestion-consumer.ts b/nodejs/src/logs/logs-ingestion-consumer.tsindex c5aeb0e3877b..62e4be1e995c 100644--- a/nodejs/src/logs/logs-ingestion-consumer.ts+++ b/nodejs/src/logs/logs-ingestion-consumer.ts@@ -330,7 +330,8 @@ export class LogsIngestionConsumer {message.message.value!,logsSettings,ruleSet,- message.teamId+ message.teamId,+ message.bytesUncompressed)if (sampled.recordsDropped > 0) {logsSamplingRecordsDroppedCounter.inc({ team_id: message.teamId.toString() }, sampled.recordsDropped)diff --git a/nodejs/src/logs/sampling/logs-sampling.service.test.ts b/nodejs/src/logs/sampling/logs-sampling.service.test.tsindex 7b1f995e3202..04c7f0fc35b7 100644--- a/nodejs/src/logs/sampling/logs-sampling.service.test.ts+++ b/nodejs/src/logs/sampling/logs-sampling.service.test.ts@@ -222,6 +222,53 @@ describe('LogsSamplingService', () => {expect(kept).toHaveLength(2)})+ it('KB-mode meters each row against its pro-rata share of the batch header, not per-row bytes_uncompressed', async () => {+ const ruleSet = compileRuleSet([+ {+ id: 'rl-kb',+ rule_type: 'rate_limit',+ scope_service: 'api',+ scope_path_pattern: null,+ scope_attribute_filters: [],+ config: { kb_per_second: 1, burst_kb: 2 },+ },+ ])+ // Per-row bytes_uncompressed is inflated (900 each) because shared batch data is+ // re-counted on every row; content bytes (body only here) are 2/4/6 → total 12.+ // Header = 24 → pro-rata scale 2 → per-row cost 4/8/12. Budget = 12:+ // 4 (admit), 4+8=12 (admit), 12+12=24 > 12 (drop row c). Metering on the raw+ // bytes_uncompressed sum (900 each) would have dropped every row.+ const buffer = await encodeLogRecords(LOG_RECORD_AVRO, 'zstandard', [+ { ...baseLog('a', 'api', 900), body: 'aa' },+ { ...baseLog('b', 'api', 900), body: 'bbbb' },+ { ...baseLog('c', 'api', 900), body: 'cccccc' },+ ])++ const checkRateLimitV3 = jest.fn()+ const mockRedis: RedisV2 = {+ useClient: jest.fn(() => Promise.resolve(null)),+ usePipeline: jest.fn((_opts, cb) => {+ cb({ checkRateLimitV3 } as unknown as RedisClientPipeline)+ const pipelineResult: [Error | null, any][] = [[null, [12, 0] as const]]+ return Promise.resolve(pipelineResult)+ }),+ }++ const service = new LogsSamplingService(mockRedis, 60)+ const result = await service.processBuffer(buffer, logsSettings, 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.+ expect(checkRateLimitV3.mock.calls[0]![2]).toBe(24)+ expect(result.recordsDropped).toBe(1)+ expect(result.recordsDroppedByRuleId.get('rl-kb')).toBe(1)+ // 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)+ })+it('fail-open keeps all rate_limit lines when Redis pipeline returns null', async () => {const ruleSet = compileRuleSet([{diff --git a/nodejs/src/logs/sampling/logs-sampling.service.ts b/nodejs/src/logs/sampling/logs-sampling.service.tsindex d1658e2da83e..ff645d8900f7 100644--- a/nodejs/src/logs/sampling/logs-sampling.service.ts+++ b/nodejs/src/logs/sampling/logs-sampling.service.ts@@ -113,7 +113,8 @@ export class LogsSamplingService {buffer: Buffer,settings: LogsSettings,ruleSet: CompiledRuleSet,- teamId?: number+ teamId?: number,+ headerBytesUncompressed: number = 0): Promise<ProcessBufferWithSamplingResult> {const [logRecordType, compressionCodec, records] = await decodeLogRecords(buffer)if (!logRecordType) {@@ -141,7 +142,14 @@ export class LogsSamplingService {pendingByRule.set(c.ruleId, list)}}- const rateKeep = await this.applyRateLimits(teamId, ruleSet, pendingByRule, records)+ const rateKeep = await this.applyRateLimits(+ teamId,+ ruleSet,+ pendingByRule,+ records,+ headerBytesUncompressed,+ contentBytesTotal+ )for (let i = 0; i < records.length; i++) {const record = records[i]!@@ -230,20 +238,32 @@ export class LogsSamplingService {* Maps a recordIndex -> keep (true) or drop (false) decision per rate_limit rule.* Each rule's pending lines share one Lua call; lines are admitted while their* accumulated cost stays within the pre-batch token budget. Cost is one token- * per record (`costUnit: 'records'`) or each record's `bytes_uncompressed`- * (`costUnit: 'bytes'`); rows missing the field contribute 0.+ * per record (`costUnit: 'records'`) or, for `costUnit: 'bytes'`, each row's+ * pro-rata share of the batch header `bytesUncompressed`+ * (`headerBytesUncompressed × contentBytes(row) / contentBytesTotal`) — the same+ * unit billing meters, so the limiter admits at the configured byte rate instead+ * of over-counting the per-row `bytes_uncompressed` (which re-includes shared+ * batch data on every row). Falls back to per-row `bytes_uncompressed` when the+ * header is unavailable (older producers).*/private async applyRateLimits(teamId: number,ruleSet: CompiledRuleSet,pendingByRule: RateLimitPendingByRule,- records: LogRecord[]+ records: LogRecord[],+ headerBytesUncompressed: number,+ contentBytesTotal: number): Promise<Map<number, boolean>> {const keepByIndex = new Map<number, boolean>()if (pendingByRule.size === 0) {return keepByIndex}+ const proRataScale =+ headerBytesUncompressed > 0 && contentBytesTotal > 0 ? headerBytesUncompressed / contentBytesTotal : 0+ const byteCost = (idx: number): number =>+ proRataScale > 0 ? contentBytes(records[idx]!) * proRataScale : recordBytes(records[idx]!)+const ruleById = new Map(ruleSet.rules.map((r) => [r.id, r]))type Entry = { indices: number[]; costs: number[]; req: KeyedRateLimitRequest }const entries: Entry[] = []@@ -253,8 +273,7 @@ export class LogsSamplingService {if (!rl || indices.length === 0) {continue}- const costs =- rl.costUnit === 'bytes' ? indices.map((idx) => recordBytes(records[idx]!)) : indices.map(() => 1)+ const costs = rl.costUnit === 'bytes' ? indices.map(byteCost) : indices.map(() => 1)const totalCost = costs.reduce((a, b) => a + b, 0)entries.push({indices,