Skip to content

:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.

feat(logs): drop expired rows and unflagged backfills before writing (#112111)

Jimmy Zhuee05d6103cb5
diff --git a/nodejs/src/logs/config.ts b/nodejs/src/logs/config.ts
index db49bb97e80f..f84a4f05e705 100644
--- a/nodejs/src/logs/config.ts
+++ b/nodejs/src/logs/config.ts
@@ -63,6 +63,8 @@ export type LogsIngestionConsumerConfig = {
LOGS_METRICS_RULES_EXPORT_URL: string
/** Comma-separated team IDs, or `*` for all teams, or empty to disable per-row retention rule evaluation entirely. */
LOGS_RETENTION_ENABLED_TEAMS: string
+ /** Comma-separated team IDs, or `*` for all teams. A `backfill_days` message from any other team is dropped. */
+ LOGS_BACKFILL_ENABLED_TEAMS: string
/** When `true`, retention rules are never evaluated (rows keep the team default via the batch header). */
LOGS_RETENTION_KILLSWITCH: boolean
/** Comma-separated team IDs, or `*` for all teams, or empty (default) to disable measure-only pattern masking. */
@@ -119,6 +121,7 @@ export function getDefaultLogsIngestionConsumerConfig(): LogsIngestionConsumerCo
LOGS_METRICS_RULES_EXPORT_URL: '',
// Off in prod until per-team rollout; on in dev for local end-to-end testing.
LOGS_RETENTION_ENABLED_TEAMS: isProdEnv() ? '' : '*',
+ LOGS_BACKFILL_ENABLED_TEAMS: isProdEnv() ? '' : '*',
LOGS_RETENTION_KILLSWITCH: false,
// Off by default: enabling forces decode+re-encode for allowlisted teams.
LOGS_PATTERN_MASKING_ENABLED_TEAMS: '',
diff --git a/nodejs/src/logs/log-pattern-stage.ts b/nodejs/src/logs/log-pattern-stage.ts
index 3e032c937587..4b8ef82c2a9f 100644
--- a/nodejs/src/logs/log-pattern-stage.ts
+++ b/nodejs/src/logs/log-pattern-stage.ts
@@ -3,7 +3,7 @@ import { Counter, Histogram } from 'prom-client'
import { MASK_RULES, MESSAGE_KEYS, PATTERN_VERSION, buildLogPattern, zeroRuleFires } from './log-pattern-mask'
import type { LogRecord } from './log-record-avro'
-import type { PipelineStage } from './pipeline/log-processing-pipeline'
+import type { MutateStage } from './pipeline/log-processing-pipeline'
export const logsPatternBodyKindCounter = new Counter({
name: 'logs_ingestion_pattern_body_kind_total',
@@ -51,7 +51,7 @@ export const logsPatternStageErrorCounter = new Counter({
help: 'Batches where the pattern masking stage threw. The records survive. Any record the throw came before keeps its stamp, and the rest stay unstamped, which reads as version 0.',
})
-export function makePatternMaskingStage(): PipelineStage {
+export function makePatternMaskingStage(): MutateStage {
return {
kind: 'mutate',
name: 'pattern_masking',
diff --git a/nodejs/src/logs/log-record-avro.ts b/nodejs/src/logs/log-record-avro.ts
index 1278153d5cdf..73e4db8b3e1c 100644
--- a/nodejs/src/logs/log-record-avro.ts
+++ b/nodejs/src/logs/log-record-avro.ts
@@ -610,7 +610,7 @@ export const processLogMessageBuffer = instrumented({
// No surviving records — signal the caller to suppress the message rather than forward or
// re-encode an empty batch downstream. Checked before the visitor-only shortcut below so a
// zero-record batch decoded solely for metric-rule tallying is suppressed too.
- // `stats.droppedBy` distinguishes a filter drop (sampling / transformations) from an
+ // `stats.droppedBy` distinguishes a filter drop (it names the stage) from an
// already-empty batch so the caller can attribute it correctly.
return { value: null, pii, drops: stats }
}
diff --git a/nodejs/src/logs/logs-ingestion-consumer.test.ts b/nodejs/src/logs/logs-ingestion-consumer.test.ts
index 65b4c846a411..9cba41528b6b 100644
--- a/nodejs/src/logs/logs-ingestion-consumer.test.ts
+++ b/nodejs/src/logs/logs-ingestion-consumer.test.ts
@@ -45,6 +45,7 @@ import {
logsRecordsBytesExceedPayloadCounter,
logsRecordsDroppedCounter,
logsRecordsReceivedCounter,
+ parseMinTimestampHeader,
parseSizeHeader,
} from './logs-ingestion-consumer'
import { compileMetricRules } from './metrics-rules/compile-metric-rules'
@@ -171,7 +172,7 @@ const createMultiRecordKafkaMessage = async (
trace_id: null,
span_id: null,
trace_flags: null,
- timestamp: DateTime.now().toMillis() * 1000,
+ timestamp: logData.timestampMicros ?? DateTime.now().toMillis() * 1000,
observed_timestamp: DateTime.now().toMillis() * 1000,
body: JSON.stringify(logData),
severity_text: logData.level || 'info',
@@ -759,6 +760,17 @@ describe('LogsIngestionConsumer', () => {
})
})
+ describe('parseMinTimestampHeader', () => {
+ it.each([
+ ['1790000000000000', 1790000000000000],
+ [undefined, undefined],
+ ['', undefined],
+ ['not-a-number', undefined],
+ ])('parses %p as %p', (raw, expected) => {
+ expect(parseMinTimestampHeader(raw)).toEqual(expected)
+ })
+ })
+
describe('message routing', () => {
it('should route messages to correct ClickHouse topic', async () => {
const logData = createLogMessage()
@@ -983,6 +995,41 @@ describe('LogsIngestionConsumer', () => {
})
})
+ describe('backfill gate', () => {
+ it.each([
+ {
+ name: 'refuses a backfill request from a team not on the list',
+ header: true,
+ listed: false,
+ produced: 0,
+ },
+ { name: 'accepts a backfill request from a listed team', header: true, listed: true, produced: 1 },
+ { name: 'leaves live traffic alone', header: false, listed: false, produced: 1 },
+ ])('$name', async ({ header, listed, produced }) => {
+ await consumer.stop()
+ consumer = await createLogsIngestionConsumer(hub, {
+ LOGS_BACKFILL_ENABLED_TEAMS: listed ? String(team.id) : String(team2.id),
+ })
+
+ // The row is recent on purpose: a backfill request can carry rows from the last day.
+ const messages = await createKafkaMessages([createLogMessage()], {
+ token: team.api_token,
+ record_count: '1',
+ ...(header ? { backfill_days: '540' } : {}),
+ })
+
+ await waitForBackgroundTasks(consumer.processKafkaBatch(messages))
+
+ expect(getProducedKafkaMessages().filter((m) => m.topic === KAFKA_LOGS_CLICKHOUSE)).toHaveLength(produced)
+ if (produced === 0) {
+ expect(logMessageDroppedCounterSpy).toHaveBeenCalledWith(
+ { reason: 'backfill_not_enabled', team_id: team.id.toString() },
+ 1
+ )
+ }
+ })
+ })
+
describe('filterQuotaLimitedMessages', () => {
it('should allow messages when not quota limited', async () => {
jest.mocked(hub.quotaLimiting.isTeamTokenQuotaLimited).mockResolvedValue(false)
@@ -1872,6 +1919,29 @@ describe('LogsIngestionConsumer', () => {
expect(droppedMetrics).toHaveLength(0)
})
+ it('drops a row already past retention and reports it, when the header says the message can hold one', async () => {
+ const fourHundredDaysAgoMicros = DateTime.now().minus({ days: 400 }).toMillis() * 1000
+ const message = await createMultiRecordKafkaMessage(
+ [{ level: 'info', timestampMicros: fourHundredDaysAgoMicros }],
+ {
+ token: team.api_token,
+ bytes_uncompressed: '400',
+ record_count: '1',
+ min_timestamp: fourHundredDaysAgoMicros.toString(),
+ }
+ )
+
+ await waitForBackgroundTasks(consumer.processKafkaBatch([message]))
+
+ const produced = getProducedKafkaMessages()
+ expect(produced.some((m) => m.topic === KAFKA_LOGS_CLICKHOUSE)).toBe(false)
+ const expiredMetric = produced
+ .filter((m) => m.topic === KAFKA_APP_METRICS_2)
+ .map((m) => parseMetricValue(m.value))
+ .find((v) => v.metric_name === 'records_dropped_retention_expired' && v.team_id === team.id)
+ expect(expiredMetric?.count).toBe(1)
+ })
+
describe('sampling usage to app_metrics2', () => {
let mockSamplingCache: Pick<SamplingRulesCache, 'getCompiledRuleSet'>
diff --git a/nodejs/src/logs/logs-ingestion-consumer.ts b/nodejs/src/logs/logs-ingestion-consumer.ts
index 5cfd1845be1c..9ce4c164ba54 100644
--- a/nodejs/src/logs/logs-ingestion-consumer.ts
+++ b/nodejs/src/logs/logs-ingestion-consumer.ts
@@ -44,13 +44,18 @@ 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 { EMPTY_STAGE_DROP_STATS, type PipelineStage } from './pipeline/log-processing-pipeline'
import type { RetentionRuleSource } from './retention/compile-retention-rules'
import type { CompiledRetentionRuleSet } from './retention/evaluate-retention'
+import {
+ RETENTION_EXPIRED_STAGE_NAME,
+ canHoldExpiredRow,
+ makeRetentionExpiredStage,
+} from './retention/retention-expired-stage'
import { RetentionRulesCache } from './retention/retention-rules-cache'
import { makeRetentionStage } from './retention/retention-stage'
import type { CompiledRuleSet } from './sampling/evaluate'
-import { LogsSamplingService } from './sampling/logs-sampling.service'
+import { LogsSamplingService, SAMPLING_STAGE_NAME } from './sampling/logs-sampling.service'
import { SamplingRulesCache } from './sampling/sampling-rules-cache'
import { LogsRateLimiterService } from './services/logs-rate-limiter.service'
import { LogsTransformerService, TransformationBatchBudget } from './transformations/logs-transformer.service'
@@ -159,6 +164,14 @@ export function parseSizeHeader(raw: string | undefined): number | null {
return Number.isFinite(parsed) && parsed >= 0 ? parsed : null
}
+export function parseMinTimestampHeader(raw: string | undefined): number | undefined {
+ if (raw === undefined || raw.trim() === '') {
+ return undefined
+ }
+ const parsed = Number(raw)
+ return Number.isSafeInteger(parsed) ? parsed : undefined
+}
+
const DEFAULT_USAGE_STATS: UsageStats = {
bytesReceived: 0,
recordsReceived: 0,
@@ -306,11 +319,9 @@ export const logsDropFractionHistogram = new Histogram({
* decided per row (content bytes), so we scale the header down by the dropped content fraction
* to bill only what survived.
*
- * Weights are customer-content bytes per row (body + attributes + event_name) — NOT the per-row
- * `bytes_uncompressed` field, whose near-constant denormalization overhead (duplicated resource
- * attributes, server uuid) would skew the ratio toward record-count weighting. Content weights
- * track "share of what the customer sent"; residual error vs true wire share (protobuf framing,
- * per-batch resource blocks) is small and direction-neutral. The result is always ≤ the gross
+ * Weights come from `measureContentWeights`: every sender-controlled field of a row, with resource
+ * and scope bytes split across the rows that share them. The per-row `bytes_uncompressed` field is
+ * not used, because it counts shared resource attributes once per row. The result is always ≤ the gross
* header (droppedFraction ≤ 1), so a message is never billed above today's gross. Returns 0 when
* we can't measure (no header or no content bytes), i.e. no credit rather than a wrong one.
*/
@@ -333,13 +344,8 @@ function makeTransformStage(transform: LogRecordsTransform): PipelineStage {
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 }
+ return { kept: records, stats: EMPTY_STAGE_DROP_STATS() }
},
}
}
@@ -361,6 +367,7 @@ export class LogsIngestionConsumer {
private appMetricsAggregator: AppMetricsAggregator
private redis: RedisV2
private rateLimiter: LogsRateLimiterService
+ private readonly backfillEnabledTeamsRaw: string
private samplingService: LogsSamplingService
private readonly samplingEnabledTeamsRaw: string
private readonly samplingKillswitch: boolean
@@ -414,6 +421,7 @@ export class LogsIngestionConsumer {
poolMaxSize: mergedConfig.REDIS_POOL_MAX_SIZE,
})
this.rateLimiter = new LogsRateLimiterService(mergedConfig, this.redis, rateLimiterName)
+ this.backfillEnabledTeamsRaw = mergedConfig.LOGS_BACKFILL_ENABLED_TEAMS
this.samplingService = new LogsSamplingService(this.redis, mergedConfig.LOGS_LIMITER_TTL_SECONDS)
this.samplingEnabledTeamsRaw = mergedConfig.LOGS_SAMPLING_ENABLED_TEAMS
this.samplingKillswitch = mergedConfig.LOGS_SAMPLING_KILLSWITCH
@@ -502,6 +510,7 @@ export class LogsIngestionConsumer {
private async resolveLogMessageBufferWithOptionalSampling(
message: LogsIngestionMessage,
logsSettings: LogsSettings,
+ defaultRetentionDays: number,
onRecordsDecoded?: (records: LogRecord[]) => void,
batchBudget?: TransformationBatchBudget
): Promise<
@@ -510,6 +519,7 @@ export class LogsIngestionConsumer {
processedValue: Buffer
pii: PiiScrubStats
recordsDropped: number
+ recordsDroppedByStage: Map<string, number>
recordsDroppedByRuleId: Map<string, number>
bytesDroppedByRuleId: Map<string, number>
contentBytesDropped: number
@@ -517,9 +527,10 @@ export class LogsIngestionConsumer {
}
| {
outcome: 'all_dropped'
- reason: 'sampling_all_dropped' | 'transformations_all_dropped' | 'empty_batch'
+ reason: string
pii: PiiScrubStats
recordsDropped: number
+ recordsDroppedByStage: Map<string, number>
recordsDroppedByRuleId: Map<string, number>
bytesDroppedByRuleId: Map<string, number>
contentBytesDropped: number
@@ -558,9 +569,21 @@ export class LogsIngestionConsumer {
if (recordsTransform) {
stages.push(makeTransformStage(recordsTransform))
}
+ let shortestRetentionDays = defaultRetentionDays
if (useRetention && retentionRuleSet) {
- const defaultRetentionDays = await this.defaultRetentionDays(message.teamId, logsSettings)
stages.push(makeRetentionStage(retentionRuleSet, message.teamId, defaultRetentionDays))
+ shortestRetentionDays = Math.min(
+ defaultRetentionDays,
+ ...retentionRuleSet.rules.map((rule) => rule.retentionDays)
+ )
+ }
+
+ // Checking rows for expiry needs a decode, which every message would otherwise pay to find rows
+ // that only backdated imports produce. The stage runs after the retention stage, so it reads the
+ // per-row retention that ClickHouse will use.
+ const nowMicros = Date.now() * 1000
+ if (canHoldExpiredRow(message.minTimestampMicros, shortestRetentionDays, nowMicros)) {
+ stages.push(makeRetentionExpiredStage(message.teamId, defaultRetentionDays, nowMicros))
}
// Runs last so it only sees survivors. Adding any stage forces the full decode and re-encode,
@@ -598,10 +621,9 @@ export class LogsIngestionConsumer {
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)
+ const recordsDroppedBySampling = drops.recordsDroppedByStage.get(SAMPLING_STAGE_NAME) ?? 0
+ if (recordsDroppedBySampling > 0) {
+ logsSamplingRecordsDroppedCounter.inc({ team_id: message.teamId.toString() }, recordsDroppedBySampling)
}
if (drops.bytesDropped > 0) {
logsBytesDroppedByRuleCounter.inc({ team_id: message.teamId.toString() }, drops.bytesDropped)
@@ -610,17 +632,13 @@ export class LogsIngestionConsumer {
if (value === null) {
// `droppedBy` tells us which filter emptied the batch; its absence means the batch decoded
// to zero records to begin with, so attribute it to an empty batch rather than sampling.
- const reason =
- drops.droppedBy === 'transformations'
- ? 'transformations_all_dropped'
- : drops.droppedBy === 'sampling'
- ? 'sampling_all_dropped'
- : 'empty_batch'
+ const reason = drops.droppedBy ? `${drops.droppedBy}_all_dropped` : 'empty_batch'
return {
outcome: 'all_dropped',
reason,
pii,
recordsDropped: drops.recordsDropped,
+ recordsDroppedByStage: drops.recordsDroppedByStage,
recordsDroppedByRuleId: drops.recordsDroppedByRuleId,
bytesDroppedByRuleId: drops.bytesDroppedByRuleId,
contentBytesDropped: drops.contentBytesDropped,
@@ -632,6 +650,7 @@ export class LogsIngestionConsumer {
processedValue: value,
pii,
recordsDropped: drops.recordsDropped,
+ recordsDroppedByStage: drops.recordsDroppedByStage,
recordsDroppedByRuleId: drops.recordsDroppedByRuleId,
bytesDroppedByRuleId: drops.bytesDroppedByRuleId,
contentBytesDropped: drops.contentBytesDropped,
@@ -656,11 +675,14 @@ export class LogsIngestionConsumer {
this.trackIncomingTraffic(messages)
- const { quotaAllowedMessages, quotaDroppedMessages } = await this.filterQuotaLimitedMessages(messages)
+ const { backfillAllowedMessages, backfillDroppedMessages } = this.filterBackfillNotEnabledMessages(messages)
+ const { quotaAllowedMessages, quotaDroppedMessages } =
+ await this.filterQuotaLimitedMessages(backfillAllowedMessages)
const { rateLimiterAllowedMessages, rateLimiterDroppedMessages } =
await this.filterRateLimitedMessages(quotaAllowedMessages)
const usageStats = this.trackOutgoingTrafficAndBuildUsageStats(rateLimiterAllowedMessages, [
+ ...backfillDroppedMessages,
...quotaDroppedMessages,
...rateLimiterDroppedMessages,
])
@@ -762,6 +784,38 @@ export class LogsIngestionConsumer {
usage.set(teamId, row)
}
+ // Clamping these rows to the ingest time would write the import onto today, so the whole message is dropped.
+ private filterBackfillNotEnabledMessages(messages: LogsIngestionMessage[]): {
+ backfillAllowedMessages: LogsIngestionMessage[]
+ backfillDroppedMessages: LogsIngestionMessage[]
+ } {
+ const backfillAllowedMessages: LogsIngestionMessage[] = []
+ const backfillDroppedMessages: LogsIngestionMessage[] = []
+ const droppedRecordsByTeam = new Map<number, { messages: number; records: number }>()
+ for (const message of messages) {
+ if (message.backfillRequested && !teamIdMatchesCsv(this.backfillEnabledTeamsRaw, message.teamId)) {
+ backfillDroppedMessages.push(message)
+ const dropped = droppedRecordsByTeam.get(message.teamId) ?? { messages: 0, records: 0 }
+ dropped.messages++
+ dropped.records += message.recordCount
+ droppedRecordsByTeam.set(message.teamId, dropped)
+ } else {
+ backfillAllowedMessages.push(message)
+ }
+ }
+
+ for (const [teamId, dropped] of droppedRecordsByTeam) {
+ logMessageDroppedCounter.inc(
+ { reason: 'backfill_not_enabled', team_id: teamId.toString() },
+ dropped.messages
+ )
+ recordLogMessageDropped('backfill_not_enabled', teamId.toString(), dropped.messages)
+ this.queueUsageMetric(teamId, 'records_dropped_backfill_not_enabled', dropped.records)
+ }
+
+ return { backfillAllowedMessages, backfillDroppedMessages }
+ }
+
private async filterQuotaLimitedMessages(
messages: LogsIngestionMessage[]
): Promise<{ quotaAllowedMessages: LogsIngestionMessage[]; quotaDroppedMessages: LogsIngestionMessage[] }> {
@@ -985,11 +1039,18 @@ export class LogsIngestionConsumer {
? logsSettings.json_parse_logs_attribute_key
: undefined,
},
+ retentionDays,
onRecordsDecoded,
transformationBatchBudget
)
)
+ this.queueUsageMetric(
+ message.teamId,
+ 'records_dropped_retention_expired',
+ resolved.recordsDroppedByStage.get(RETENTION_EXPIRED_STAGE_NAME) ?? 0
+ )
+
let bytesUncompressedHeaderOverride: number | undefined
let bytesCompressedHeaderOverride: number | undefined
let recordCountHeaderOverride: number | undefined
@@ -1397,6 +1458,8 @@ export class LogsIngestionConsumer {
bytesUncompressedRecords,
bytesCompressed,
recordCount,
+ minTimestampMicros: parseMinTimestampHeader(headers.min_timestamp),
+ backfillRequested: headers.backfill_days !== undefined,
})
} catch (e) {
// A message we cannot parse is message-scoped and will fail the same way on
diff --git a/nodejs/src/logs/pipeline/log-processing-pipeline.test.ts b/nodejs/src/logs/pipeline/log-processing-pipeline.test.ts
index f3760ebf3c1f..99f5cce59e01 100644
--- a/nodejs/src/logs/pipeline/log-processing-pipeline.test.ts
+++ b/nodejs/src/logs/pipeline/log-processing-pipeline.test.ts
@@ -1,6 +1,6 @@
import type { LogRecord } from '~/logs/log-record-avro'
-import { EMPTY_DROP_STATS, type PipelineStage, runPipelineStages } from './log-processing-pipeline'
+import { EMPTY_STAGE_DROP_STATS, type PipelineStage, runPipelineStages } from './log-processing-pipeline'
describe('runPipelineStages', () => {
const rec = (uuid: string): LogRecord =>
@@ -13,12 +13,12 @@ describe('runPipelineStages', () => {
resource_attributes: null,
}) as LogRecord
- const dropFirst = (name: 'sampling' | 'transformations'): PipelineStage => ({
+ const dropFirst = (name: 'sampling' | 'transformations' | 'retention_expired'): PipelineStage => ({
kind: 'filter',
name,
run: (records) => {
const kept = records.slice(1)
- return { kept, stats: { ...EMPTY_DROP_STATS(), recordsDropped: 1, droppedBy: name } }
+ return { kept, stats: { ...EMPTY_STAGE_DROP_STATS(), recordsDropped: 1 } }
},
})
@@ -44,6 +44,59 @@ describe('runPipelineStages', () => {
expect(stats.droppedBy).toBe('transformations')
})
+ it('measures the billing pro-rate total over the whole batch when a later filter drops after an earlier one', async () => {
+ // Each record's content is its one-byte body. The transform drops one row before the expiry
+ // filter runs, so a total measured by that filter would cover two rows instead of three.
+ const stages: PipelineStage[] = [dropFirst('transformations'), dropFirst('retention_expired')]
+ const { stats } = await runPipelineStages([rec('a'), rec('b'), rec('c')], stages)
+ expect(stats.contentBytesTotal).toBe(3)
+ expect(Object.fromEntries(stats.recordsDroppedByStage)).toEqual({ transformations: 1, retention_expired: 1 })
+ })
+
+ it.each([
+ {
+ name: 'a surviving row that carries its content in resource attributes',
+ records: [
+ { uuid: 'expired', body: 'x', resource_attributes: null },
+ { uuid: 'fresh', body: '', resource_attributes: { blob: 'r'.repeat(65_536) } },
+ ],
+ minShare: 0,
+ maxShare: 0.001,
+ },
+ {
+ name: 'many dropped rows that share one large resource',
+ records: [
+ ...Array.from({ length: 1000 }, (_, i) => ({
+ uuid: `expired-${i}`,
+ body: 'x',
+ resource_attributes: { blob: 'r'.repeat(65_536) },
+ })),
+ { uuid: 'fresh', body: 'f'.repeat(65_536), resource_attributes: null },
+ ],
+ minShare: 0.45,
+ maxShare: 0.55,
+ },
+ ])('credits only the share of the request that was dropped: $name', async ({ records, minShare, maxShare }) => {
+ const dropExpired: PipelineStage = {
+ kind: 'filter',
+ name: 'retention_expired',
+ run: (rows, batch) => {
+ const stats = EMPTY_STAGE_DROP_STATS()
+ const kept = rows.filter((r) => !r.uuid!.startsWith('expired'))
+ for (const r of rows.filter((r) => r.uuid!.startsWith('expired'))) {
+ stats.recordsDropped++
+ stats.contentBytesDropped += batch.contentBytesOf(r)
+ }
+ return { kept, stats }
+ },
+ }
+ const rows = records.map((r) => ({ ...rec(r.uuid), ...r }) as LogRecord)
+ const { stats } = await runPipelineStages(rows, [dropExpired])
+ const share = stats.contentBytesDropped / stats.contentBytesTotal
+ expect(share).toBeGreaterThanOrEqual(minShare)
+ expect(share).toBeLessThanOrEqual(maxShare)
+ })
+
it('stops running stages once every record is dropped', async () => {
let laterRan = false
const dropAll: PipelineStage = {
@@ -51,7 +104,7 @@ describe('runPipelineStages', () => {
name: 'sampling',
run: (records) => ({
kept: [],
- stats: { ...EMPTY_DROP_STATS(), recordsDropped: records.length, droppedBy: 'sampling' },
+ stats: { ...EMPTY_STAGE_DROP_STATS(), recordsDropped: records.length },
}),
}
const later: PipelineStage = { kind: 'mutate', name: 'later', run: () => void (laterRan = true) }
diff --git a/nodejs/src/logs/pipeline/log-processing-pipeline.ts b/nodejs/src/logs/pipeline/log-processing-pipeline.ts
index 3578f26523a3..49e99ef2280f 100644
--- a/nodejs/src/logs/pipeline/log-processing-pipeline.ts
+++ b/nodejs/src/logs/pipeline/log-processing-pipeline.ts
@@ -1,35 +1,99 @@
import type { LogRecord } from '~/logs/log-record-avro'
+function stringBytes(value: string | null | undefined): number {
+ return value ? Buffer.byteLength(value) : 0
+}
+
+function mapBytes(map: Record<string, string> | null | undefined): number {
+ let total = 0
+ for (const [k, v] of Object.entries(map ?? {})) {
+ total += Buffer.byteLength(k) + stringBytes(v)
+ }
+ return total
+}
+
+function resourceKey(map: Record<string, string> | null | undefined): string {
+ return JSON.stringify(Object.entries(map ?? {}).sort(([a], [b]) => (a < b ? -1 : a > b ? 1 : 0)))
+}
+
/**
- * 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.
+ * Every sender-controlled field counts, or a surviving row can hold its content where it weighs
+ * nothing and a dropped neighbor refunds the whole batch. Resource and scope bytes are split across
+ * the rows that share them, because a per-row count lets a sender inflate the rows it expects to drop.
*/
-export type DropStats = {
+export function measureContentWeights(records: LogRecord[]): Map<LogRecord, number> {
+ const rowsByResource = new Map<string, number>()
+ const rowsByScope = new Map<string, number>()
+ const keys = records.map((record) => {
+ const resource = resourceKey(record.resource_attributes)
+ const scope = JSON.stringify([resource, record.instrumentation_scope ?? ''])
+ rowsByResource.set(resource, (rowsByResource.get(resource) ?? 0) + 1)
+ rowsByScope.set(scope, (rowsByScope.get(scope) ?? 0) + 1)
+ return { resource, scope }
+ })
+
+ const weights = new Map<LogRecord, number>()
+ records.forEach((record, i) => {
+ const { resource, scope } = keys[i]
+ weights.set(
+ record,
+ stringBytes(record.body) +
+ stringBytes(record.event_name) +
+ stringBytes(record.severity_text) +
+ mapBytes(record.attributes) +
+ mapBytes(record.resource_attributes) / rowsByResource.get(resource)! +
+ stringBytes(record.instrumentation_scope) / rowsByScope.get(scope)!
+ )
+ })
+ return weights
+}
+
+export type StageDropStats = {
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 => ({
+export const EMPTY_STAGE_DROP_STATS = (): StageDropStats => ({
recordsDropped: 0,
recordsDroppedByRuleId: new Map(),
bytesDropped: 0,
bytesDroppedByRuleId: new Map(),
contentBytesDropped: 0,
+})
+
+/**
+ * Per-message drop accounting: the stages' reports summed, plus what the pipeline measures itself.
+ * `contentBytesTotal` is the billing pro-rate denominator, measured over the whole decoded batch
+ * before any stage runs, because the header bytes it is applied to describe the whole batch.
+ * `droppedBy` names the last stage that removed records, which attributes an all-dropped message.
+ */
+export type DropStats = StageDropStats & {
+ contentBytesTotal: number
+ recordsDroppedByStage: Map<string, number>
+ droppedBy?: string
+}
+
+export const EMPTY_DROP_STATS = (): DropStats => ({
+ ...EMPTY_STAGE_DROP_STATS(),
contentBytesTotal: 0,
+ recordsDroppedByStage: new Map(),
})
/** Result of a `filter` stage: the surviving records plus what it dropped. */
-export type FilterResult = { kept: LogRecord[]; stats: DropStats }
+export type FilterResult = { kept: LogRecord[]; stats: StageDropStats }
+
+/**
+ * Content weights fixed before any stage runs. A drop credit must use them, never the row's current
+ * size: a hog transformation can grow a row before a later stage drops it, and crediting the grown
+ * size would let a team buy back more of the batch than it sent.
+ */
+export type BatchContext = {
+ contentBytesTotal: number
+ contentBytesOf: (record: LogRecord) => number
+}
/**
* A stage in the decode → transform → encode pipeline. Stages run in list order over one decode:
@@ -41,9 +105,13 @@ export type FilterResult = { kept: LogRecord[]; stats: DropStats }
* `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 }
+export type MutateStage = { kind: 'mutate'; name: string; run: (records: LogRecord[]) => Promise<void> | void }
+export type FilterStage = {
+ kind: 'filter'
+ name: string
+ run: (records: LogRecord[], batch: BatchContext) => Promise<FilterResult> | FilterResult
+}
+export type PipelineStage = MutateStage | FilterStage
function mergeByRuleId(into: Map<string, number>, from: Map<string, number>): void {
for (const [ruleId, n] of from) {
@@ -62,25 +130,36 @@ export async function runPipelineStages(
stages: PipelineStage[]
): Promise<{ kept: LogRecord[]; stats: DropStats }> {
const stats = EMPTY_DROP_STATS()
+ const weights = stages.some((stage) => stage.kind === 'filter')
+ ? measureContentWeights(records)
+ : new Map<LogRecord, number>()
+ for (const weight of weights.values()) {
+ stats.contentBytesTotal += weight
+ }
+ const batch: BatchContext = {
+ contentBytesTotal: stats.contentBytesTotal,
+ contentBytesOf: (record) => weights.get(record) ?? 0,
+ }
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)
+ // A hog transform removes rows from the array it is given, so count before the stage runs.
+ const before = working.length
+ const { kept, stats: dropped } = await stage.run(working, batch)
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
+ const removed = before - kept.length
+ if (removed > 0) {
+ stats.recordsDroppedByStage.set(stage.name, (stats.recordsDroppedByStage.get(stage.name) ?? 0) + removed)
+ // 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.
+ stats.droppedBy = stage.name
}
working = kept
if (working.length === 0) {
diff --git a/nodejs/src/logs/retention/retention-expired-stage.test.ts b/nodejs/src/logs/retention/retention-expired-stage.test.ts
new file mode 100644
index 000000000000..328364201e5b
--- /dev/null
+++ b/nodejs/src/logs/retention/retention-expired-stage.test.ts
@@ -0,0 +1,92 @@
+import type { LogRecord } from '~/logs/log-record-avro'
+import { EMPTY_STAGE_DROP_STATS, type PipelineStage, runPipelineStages } from '~/logs/pipeline/log-processing-pipeline'
+
+import { canHoldExpiredRow, makeRetentionExpiredStage } from './retention-expired-stage'
+
+const MICROS_PER_DAY = 86_400_000_000
+const NOW_MICROS = 1_790_000_000_000_000
+const daysAgo = (days: number): number => NOW_MICROS - days * MICROS_PER_DAY
+
+describe('retention expired stage', () => {
+ const record = (uuid: string, timestamp: number, retentionDays?: number): LogRecord => ({
+ uuid,
+ trace_id: null,
+ span_id: null,
+ trace_flags: null,
+ timestamp,
+ observed_timestamp: NOW_MICROS,
+ body: 'x',
+ severity_text: 'info',
+ severity_number: 9,
+ service_name: 'api',
+ resource_attributes: null,
+ instrumentation_scope: null,
+ event_name: null,
+ attributes: null,
+ retention_days: retentionDays,
+ })
+
+ it.each([
+ { label: 'older than the team default', timestamp: daysAgo(31), retentionDays: undefined, kept: false },
+ { label: 'one day inside the team default', timestamp: daysAgo(29), retentionDays: undefined, kept: true },
+ {
+ label: 'inside the default but past a shorter stamped rule',
+ timestamp: daysAgo(20),
+ retentionDays: 14,
+ kept: false,
+ },
+ {
+ label: 'stamped with 0 days, which falls back to the team default like ClickHouse does',
+ timestamp: daysAgo(20),
+ retentionDays: 0,
+ kept: true,
+ },
+ {
+ label: 'past the default but inside a longer stamped rule',
+ timestamp: daysAgo(60),
+ retentionDays: 90,
+ kept: true,
+ },
+ ])('a row $label is kept: $kept', async ({ timestamp, retentionDays, kept }) => {
+ const result = await runPipelineStages(
+ [record('row', timestamp, retentionDays)],
+ [makeRetentionExpiredStage(1, 30, NOW_MICROS)]
+ )
+ expect(result.kept.length === 1).toBe(kept)
+ expect(result.stats.droppedBy).toBe(kept ? undefined : 'retention_expired')
+ expect(result.stats.contentBytesTotal).toBe(5)
+ })
+
+ it('credits an expired row by the size it arrived with, not the size a transformation gave it', async () => {
+ const expired = record('expired', daysAgo(31))
+ const fresh = { ...record('fresh', daysAgo(1)), body: 'y'.repeat(1000) }
+ const growExpired: PipelineStage = {
+ kind: 'filter',
+ name: 'transformations',
+ run: (records) => {
+ expired.body = 'x'.repeat(4096)
+ return { kept: records, stats: EMPTY_STAGE_DROP_STATS() }
+ },
+ }
+
+ const { stats } = await runPipelineStages(
+ [expired, fresh],
+ [growExpired, makeRetentionExpiredStage(1, 30, NOW_MICROS)]
+ )
+
+ expect(stats).toMatchObject({ contentBytesTotal: 1009, contentBytesDropped: 5 })
+ })
+
+ it.each([
+ { label: 'has no header', minTimestamp: undefined, shortest: 14, expected: false },
+ {
+ label: 'holds only rows inside the shortest retention',
+ minTimestamp: daysAgo(13),
+ shortest: 14,
+ expected: false,
+ },
+ { label: 'holds a row past the shortest retention', minTimestamp: daysAgo(15), shortest: 14, expected: true },
+ ])('a message that $label is checked: $expected', ({ minTimestamp, shortest, expected }) => {
+ expect(canHoldExpiredRow(minTimestamp, shortest, NOW_MICROS)).toBe(expected)
+ })
+})
diff --git a/nodejs/src/logs/retention/retention-expired-stage.ts b/nodejs/src/logs/retention/retention-expired-stage.ts
new file mode 100644
index 000000000000..d17c39fab6db
--- /dev/null
+++ b/nodejs/src/logs/retention/retention-expired-stage.ts
@@ -0,0 +1,77 @@
+import { Counter } from 'prom-client'
+
+import type { LogRecord } from '~/logs/log-record-avro'
+import { EMPTY_STAGE_DROP_STATS, type PipelineStage } from '~/logs/pipeline/log-processing-pipeline'
+
+const MICROS_PER_DAY = 86_400_000_000
+
+export const RETENTION_EXPIRED_STAGE_NAME = 'retention_expired'
+
+function isPastRetention(timestampMicros: number, retentionDays: number, nowMicros: number): boolean {
+ return timestampMicros + retentionDays * MICROS_PER_DAY <= nowMicros
+}
+
+export const logsRetentionExpiredRowsDroppedCounter = new Counter({
+ name: 'logs_ingestion_retention_expired_rows_dropped_total',
+ help: 'Log rows dropped because their timestamp plus their retention was already in the past when they arrived.',
+ labelNames: ['team_id'],
+})
+
+/**
+ * A message without the header comes from a capture-logs build older than the header, and that build
+ * still accepts `backfill_days`, so its rows can be old. Skipping the check for it is safe only while
+ * ClickHouse counts expiry from the ingest time. Every capture-logs instance must send the header
+ * before ClickHouse counts expiry from the row timestamp.
+ */
+export function canHoldExpiredRow(
+ minTimestampMicros: number | undefined,
+ shortestRetentionDays: number,
+ nowMicros: number
+): boolean {
+ if (minTimestampMicros === undefined) {
+ return false
+ }
+ return isPastRetention(minTimestampMicros, shortestRetentionDays, nowMicros)
+}
+
+/**
+ * Keep this fallback the same as `original_expiry_timestamp` in `kafka_logs34_avro_mv`: the row's
+ * `retention_days` when it is above 0, else the batch `retention-days` header, which carries the team
+ * default. If the two disagree, this drops rows that ClickHouse would keep, or writes rows that it
+ * treats as expired.
+ */
+function isExpired(record: LogRecord, defaultRetentionDays: number, nowMicros: number): boolean {
+ if (record.timestamp === null) {
+ return false
+ }
+ const rowRetentionDays = record.retention_days ?? 0
+ const retentionDays = rowRetentionDays > 0 ? rowRetentionDays : defaultRetentionDays
+ return isPastRetention(record.timestamp, retentionDays, nowMicros)
+}
+
+export function makeRetentionExpiredStage(
+ teamId: number,
+ defaultRetentionDays: number,
+ nowMicros: number
+): PipelineStage {
+ return {
+ kind: 'filter',
+ name: RETENTION_EXPIRED_STAGE_NAME,
+ run: (records, batch) => {
+ const stats = EMPTY_STAGE_DROP_STATS()
+ const kept: LogRecord[] = []
+ for (const record of records) {
+ if (isExpired(record, defaultRetentionDays, nowMicros)) {
+ stats.recordsDropped++
+ stats.contentBytesDropped += batch.contentBytesOf(record)
+ } else {
+ kept.push(record)
+ }
+ }
+ if (stats.recordsDropped > 0) {
+ logsRetentionExpiredRowsDroppedCounter.inc({ team_id: String(teamId) }, stats.recordsDropped)
+ }
+ return { kept, stats }
+ },
+ }
+}
diff --git a/nodejs/src/logs/sampling/logs-sampling.service.test.ts b/nodejs/src/logs/sampling/logs-sampling.service.test.ts
index 100063d765ae..377b2e4a5ee9 100644
--- a/nodejs/src/logs/sampling/logs-sampling.service.test.ts
+++ b/nodejs/src/logs/sampling/logs-sampling.service.test.ts
@@ -2,6 +2,7 @@ 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 DropStats, runPipelineStages } from '~/logs/pipeline/log-processing-pipeline'
import { compileRuleSet } from './compile-rules'
import type { CompiledRuleSet } from './evaluate'
@@ -58,11 +59,11 @@ describe('LogsSamplingService', () => {
ruleSet: CompiledRuleSet,
teamId?: number,
headerBytesUncompressed = 0
- ): Promise<
- { kept: LogRecord[]; allDropped: boolean } & Awaited<ReturnType<LogsSamplingService['sampleRecords']>>['stats']
- > {
+ ): Promise<{ kept: LogRecord[]; allDropped: boolean } & DropStats> {
const [, , records] = await decodeLogRecords(buffer)
- const { kept, stats } = await service.sampleRecords(records, ruleSet, teamId, headerBytesUncompressed)
+ const { kept, stats } = await runPipelineStages(records, [
+ service.makeSamplingStage(ruleSet, teamId, headerBytesUncompressed),
+ ])
return { ...stats, kept, allDropped: kept.length === 0 }
}
@@ -181,11 +182,11 @@ describe('LogsSamplingService', () => {
expect(result.recordsDroppedByRuleId.get('rl-kb')).toBe(1)
expect(result.bytesDropped).toBe(500)
expect(result.bytesDroppedByRuleId.get('rl-kb')).toBe(500)
- // Billing pro-rate weights are customer-content bytes (body + attributes + event_name),
- // independent of the per-row bytes_uncompressed field used for rate limiting:
- // rows a,b = body 'x' (1 each); dropped row c = body(1) + attrs 'k'+'vv'(3) + 'evt'(3) = 7.
- expect(result.contentBytesTotal).toBe(9)
- expect(result.contentBytesDropped).toBe(7)
+ // Billing pro-rate weights are sender-content bytes, independent of the per-row
+ // bytes_uncompressed field used for rate limiting: rows a,b = body 'x' + severity 'info' (5 each);
+ // dropped row c = 5 + attrs 'k'+'vv'(3) + 'evt'(3) = 11.
+ expect(result.contentBytesTotal).toBe(21)
+ expect(result.contentBytesDropped).toBe(11)
expect(result.kept).toHaveLength(2)
})
@@ -226,9 +227,9 @@ describe('LogsSamplingService', () => {
expect(result.bytesDropped).toBe(1000)
expect(result.bytesDroppedByRuleId.get('rl-kb')).toBe(1000)
// Content weights don't depend on the per-row bytes_uncompressed field at all:
- // the null-field row still weighs its body bytes (1 each, 3 rows, 1 dropped).
- expect(result.contentBytesTotal).toBe(3)
- expect(result.contentBytesDropped).toBe(1)
+ // the null-field row still weighs its body and severity (5 each, 3 rows, 1 dropped).
+ expect(result.contentBytesTotal).toBe(15)
+ expect(result.contentBytesDropped).toBe(5)
expect(result.kept).toHaveLength(2)
})
@@ -250,9 +251,9 @@ describe('LogsSamplingService', () => {
// 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' },
+ { ...baseLog('a', 'api', 900), body: 'aa', severity_text: null },
+ { ...baseLog('b', 'api', 900), body: 'bbbb', severity_text: null },
+ { ...baseLog('c', 'api', 900), body: 'cccccc', severity_text: null },
])
const checkRateLimitV3 = jest.fn()
diff --git a/nodejs/src/logs/sampling/logs-sampling.service.ts b/nodejs/src/logs/sampling/logs-sampling.service.ts
index e8e936e8ec45..efc44fdba243 100644
--- a/nodejs/src/logs/sampling/logs-sampling.service.ts
+++ b/nodejs/src/logs/sampling/logs-sampling.service.ts
@@ -6,7 +6,7 @@ import { KeyedRateLimitRequest, KeyedRateLimiterService } from '~/common/service
import { instrumented } from '~/common/tracing/tracing-utils'
import { logger } from '~/common/utils/logger'
import { type LogRecord } from '~/logs/log-record-avro'
-import type { FilterResult, PipelineStage } from '~/logs/pipeline/log-processing-pipeline'
+import { type BatchContext, type FilterResult, type PipelineStage } from '~/logs/pipeline/log-processing-pipeline'
import type { CompiledRuleSet, EvaluateResult, RateLimitPendingByRule, SamplingClassifyResult } from './evaluate'
import {
@@ -54,21 +54,7 @@ function safeEvaluateLogRecord(ruleSet: CompiledRuleSet, record: LogRecord, team
const recordBytes = (r: LogRecord): number => r.bytes_uncompressed ?? 0
-/**
- * Customer-sent content bytes of a row: body + attributes + event_name. The billing
- * pro-rate weight — deliberately NOT `bytes_uncompressed`, which includes per-row
- * denormalization overhead (resource attributes duplicated onto every row, server
- * uuid, id placeholders). That overhead is near-constant per row, so as a ratio
- * weight it would skew the pro-rate toward record-count weighting instead of
- * "share of what the customer sent".
- */
-const contentBytes = (r: LogRecord): number => {
- let total = Buffer.byteLength(r.body ?? '') + Buffer.byteLength(r.event_name ?? '')
- for (const [k, v] of Object.entries(r.attributes ?? {})) {
- total += Buffer.byteLength(k) + Buffer.byteLength(v ?? '')
- }
- return total
-}
+export const SAMPLING_STAGE_NAME = 'sampling'
export class LogsSamplingService {
private rateLimiter: KeyedRateLimiterService
@@ -94,6 +80,7 @@ export class LogsSamplingService {
public async sampleRecords(
records: LogRecord[],
ruleSet: CompiledRuleSet,
+ batch: BatchContext,
teamId?: number,
headerBytesUncompressed: number = 0
): Promise<FilterResult> {
@@ -103,7 +90,6 @@ export class LogsSamplingService {
let bytesDropped = 0
const bytesDroppedByRuleId = new Map<string, number>()
let contentBytesDropped = 0
- const contentBytesTotal = records.reduce((sum, r) => sum + contentBytes(r), 0)
const useRate = Boolean(ruleSet.hasRateLimitRules && teamId != null)
@@ -124,7 +110,7 @@ export class LogsSamplingService {
pendingByRule,
records,
headerBytesUncompressed,
- contentBytesTotal
+ batch
)
for (let i = 0; i < records.length; i++) {
@@ -135,7 +121,7 @@ export class LogsSamplingService {
const rb = recordBytes(record)
recordsDropped++
bytesDropped += rb
- contentBytesDropped += contentBytes(record)
+ contentBytesDropped += batch.contentBytesOf(record)
recordsDroppedByRuleId.set(c.ruleId, (recordsDroppedByRuleId.get(c.ruleId) ?? 0) + 1)
bytesDroppedByRuleId.set(c.ruleId, (bytesDroppedByRuleId.get(c.ruleId) ?? 0) + rb)
continue
@@ -147,7 +133,7 @@ export class LogsSamplingService {
const rb = recordBytes(record)
recordsDropped++
bytesDropped += rb
- contentBytesDropped += contentBytes(record)
+ contentBytesDropped += batch.contentBytesOf(record)
if (c.ruleId != null) {
recordsDroppedByRuleId.set(c.ruleId, (recordsDroppedByRuleId.get(c.ruleId) ?? 0) + 1)
bytesDroppedByRuleId.set(c.ruleId, (bytesDroppedByRuleId.get(c.ruleId) ?? 0) + rb)
@@ -163,7 +149,7 @@ export class LogsSamplingService {
const rb = recordBytes(record)
recordsDropped++
bytesDropped += rb
- contentBytesDropped += contentBytes(record)
+ contentBytesDropped += batch.contentBytesOf(record)
if (ruleId != null) {
recordsDroppedByRuleId.set(ruleId, (recordsDroppedByRuleId.get(ruleId) ?? 0) + 1)
bytesDroppedByRuleId.set(ruleId, (bytesDroppedByRuleId.get(ruleId) ?? 0) + rb)
@@ -189,8 +175,6 @@ export class LogsSamplingService {
bytesDropped,
bytesDroppedByRuleId,
contentBytesDropped,
- contentBytesTotal,
- droppedBy: recordsDropped > 0 ? 'sampling' : undefined,
},
}
}
@@ -203,8 +187,8 @@ export class LogsSamplingService {
): PipelineStage {
return {
kind: 'filter',
- name: 'sampling',
- run: (records) => this.sampleRecords(records, ruleSet, teamId, headerBytesUncompressed),
+ name: SAMPLING_STAGE_NAME,
+ run: (records, batch) => this.sampleRecords(records, ruleSet, batch, teamId, headerBytesUncompressed),
}
}
@@ -214,7 +198,7 @@ export class LogsSamplingService {
* accumulated cost stays within the pre-batch token budget. Cost is one token
* 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
+ * (`headerBytesUncompressed × contentBytesOf(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
@@ -226,7 +210,7 @@ export class LogsSamplingService {
pendingByRule: RateLimitPendingByRule,
records: LogRecord[],
headerBytesUncompressed: number,
- contentBytesTotal: number
+ batch: BatchContext
): Promise<Map<number, boolean>> {
const keepByIndex = new Map<number, boolean>()
if (pendingByRule.size === 0) {
@@ -234,9 +218,11 @@ export class LogsSamplingService {
}
const proRataScale =
- headerBytesUncompressed > 0 && contentBytesTotal > 0 ? headerBytesUncompressed / contentBytesTotal : 0
+ headerBytesUncompressed > 0 && batch.contentBytesTotal > 0
+ ? headerBytesUncompressed / batch.contentBytesTotal
+ : 0
const byteCost = (idx: number): number =>
- proRataScale > 0 ? contentBytes(records[idx]!) * proRataScale : recordBytes(records[idx]!)
+ proRataScale > 0 ? batch.contentBytesOf(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 }
diff --git a/nodejs/src/logs/types.ts b/nodejs/src/logs/types.ts
index 5636aba204e3..51bf8a1f3f21 100644
--- a/nodejs/src/logs/types.ts
+++ b/nodejs/src/logs/types.ts
@@ -9,4 +9,7 @@ export type LogsIngestionMessage = {
bytesUncompressedRecords: number
bytesCompressed: number
recordCount: number
+ /** Earliest row timestamp in epoch microseconds, from the `min_timestamp` header; absent from older producers. */
+ minTimestampMicros?: number
+ backfillRequested?: boolean
}
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 c3830cc9ce0b..e95dd97933a5 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
@@ -5,6 +5,7 @@ import { deleteKeysWithPrefix } from '~/common/redis/_tests/redis'
import { RedisV2, createRedisV2PoolFromConfig } from '~/common/redis/redis-v2'
import { closeHub, createHub } from '~/common/utils/db/hub'
import { type LogRecord, decodeLogRecords, encodeLogRecords } from '~/logs/log-record-avro'
+import { runPipelineStages } from '~/logs/pipeline/log-processing-pipeline'
import { compileRuleSet } from '~/logs/sampling/compile-rules'
import { LogsSamplingService } from '~/logs/sampling/logs-sampling.service'
import { Hub } from '~/types'
@@ -132,7 +133,7 @@ describe('logs drop-rule rate limit — save-to-impact', () => {
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)
+ const { kept, stats } = await runPipelineStages(records, [service.makeSamplingStage(ruleSet, TEAM_ID)])
return { kept, recordsDropped: stats.recordsDropped, allDropped: kept.length === 0 }
}
diff --git a/rust/capture-logs/README.md b/rust/capture-logs/README.md
index ae0c899160d4..c1e4de462dbd 100644
--- a/rust/capture-logs/README.md
+++ b/rust/capture-logs/README.md
@@ -64,15 +64,25 @@ The value must be between 1 and `MAX_BACKFILL_DAYS`. A request outside that rang
rather than being narrowed to the default, because an import whose timestamps are quietly replaced
looks successful and writes most of its records onto the ingest time.
-`MAX_BACKFILL_DAYS` is per-deployment, so turning it on grants the capability to every project on
-that deployment.
+`MAX_BACKFILL_DAYS` is per-deployment. Which teams may use it is decided by the logs consumer's
+`LOGS_BACKFILL_ENABLED_TEAMS` list, which is empty in production by default. This service has no team
+ID, so it marks each message from a `backfill_days` request with a `backfill_days` header, and the
+logs consumer drops the whole message when the team is not on the list. That drop also happens
+after a 200, and is counted per team in the `records_dropped_backfill_not_enabled` usage metric.
+Row age cannot replace the header, because a backfill request can carry recent records.
The future bound stays at 24 hours whatever `backfill_days` says. A timestamp ahead of the
ingest time is a client clock error in every case, and accepting one would let a single client
write rows past the end of every other query range on the team.
-Imported records take their retention from the ingest time, not from their own timestamp, so a
-backfill expires `retention_days` after it is imported.
+A backfill keeps only the records that are still inside the team's retention. A record whose
+timestamp plus its retention is already in the past is dropped by the logs consumer before it is
+written, even though this service answered the request with a 200. Dropped records are counted
+per team in the `records_dropped_retention_expired` usage metric. A record that is kept expires
+`retention_days` after it is imported, not after its own timestamp.
+
+Each message carries a `min_timestamp` header, the earliest record timestamp in it, so the
+consumer only decodes and checks the messages that can hold an expired record.
## Response codes