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): evaluate filter_group in ingestion drop rules (#58924)

Daniel Viscafc22101edc14
diff --git a/nodejs/src/logs-ingestion/sampling/compile-rules.ts b/nodejs/src/logs-ingestion/sampling/compile-rules.ts
index 73c0510e48b2..2ecb3fdf8f28 100644
--- a/nodejs/src/logs-ingestion/sampling/compile-rules.ts
+++ b/nodejs/src/logs-ingestion/sampling/compile-rules.ts
@@ -1,4 +1,16 @@
+import { createTrackedRE2 } from '~/utils/tracked-re2'
+
import type { CompiledRuleSet, CompiledSamplingRule, SeverityAction } from './evaluate'
+import { type FilterGroupNode, MAX_FILTER_GROUP_DEPTH } from './filter-group-match'
+import { type PropertyFilterLeaf, compileLeafRegex } from './property-filter-match'
+
+/**
+ * Bound on the total node count (groups + leaves) of a filter_group tree. Depth
+ * alone does not bound per-record work: a single AND with thousands of sibling
+ * leaves passes MAX_FILTER_GROUP_DEPTH but costs O(leaves) per log line. Kept
+ * in sync with `MAX_FILTER_GROUP_NODES` in `products/logs/backend/sampling_api.py`.
+ */
+export const MAX_FILTER_GROUP_NODES = 256
export type SamplingRuleRow = {
id: string
@@ -66,6 +78,98 @@ function parseRateLimitFromConfig(
return { refillPerSecond: refill, poolMax }
}
+/**
+ * The drop-rules UI writes the inner group wrapped in another AND envelope:
+ * { type: AND, values: [ { type: AND|OR, values: [<leaves>] } ] }
+ * Earlier shapes may have stored the bare inner group. Accept either; reject
+ * anything that doesn't look like a group.
+ */
+function parseFilterGroup(raw: unknown): FilterGroupNode | null {
+ if (!raw || typeof raw !== 'object') {
+ return null
+ }
+ const candidate = raw as { type?: unknown; values?: unknown }
+ if (!Array.isArray(candidate.values) || (candidate.type !== 'AND' && candidate.type !== 'OR')) {
+ return null
+ }
+ let parsed: FilterGroupNode = candidate as FilterGroupNode
+ // If the outer envelope contains a single inner group, unwrap it.
+ if (candidate.values.length === 1) {
+ const inner = candidate.values[0] as { type?: unknown; values?: unknown } | null
+ if (
+ inner &&
+ typeof inner === 'object' &&
+ Array.isArray(inner.values) &&
+ (inner.type === 'AND' || inner.type === 'OR')
+ ) {
+ parsed = inner as FilterGroupNode
+ }
+ }
+ // Reject pathologically deep trees at compile time so the worker hot path
+ // never recurses past MAX_FILTER_GROUP_DEPTH. Same bound is enforced in
+ // sampling_api.py's Pydantic validator at write time; this is defense in
+ // depth for rows that predate the validator.
+ if (filterGroupDepth(parsed, 0) > MAX_FILTER_GROUP_DEPTH) {
+ return null
+ }
+ // Also bound total breadth — a flat AND with thousands of sibling leaves
+ // passes the depth check but costs O(leaves) per record. Matches the
+ // server-side check in sampling_api.py and protects rows that predate it.
+ if (filterGroupNodeCount(parsed) > MAX_FILTER_GROUP_NODES) {
+ return null
+ }
+ // Walk the tree once and stamp pre-compiled regex onto each regex leaf so
+ // the per-record hot path doesn't allocate a fresh `RegExp` per match.
+ // Legacy `pathDropPatterns` already follow this pattern; this brings the
+ // filter-group path in line.
+ compileRegexLeavesInPlace(parsed)
+ return parsed
+}
+
+function filterGroupNodeCount(node: FilterGroupNode | PropertyFilterLeaf): number {
+ const maybe = node as { type?: unknown; values?: unknown }
+ if (!Array.isArray(maybe.values) || (maybe.type !== 'AND' && maybe.type !== 'OR')) {
+ return 1
+ }
+ let total = 1
+ for (const child of maybe.values as Array<FilterGroupNode | PropertyFilterLeaf>) {
+ total += filterGroupNodeCount(child)
+ if (total > MAX_FILTER_GROUP_NODES) {
+ return total
+ }
+ }
+ return total
+}
+
+function filterGroupDepth(node: FilterGroupNode | PropertyFilterLeaf, depth: number): number {
+ const maybe = node as { type?: unknown; values?: unknown }
+ if (!Array.isArray(maybe.values) || (maybe.type !== 'AND' && maybe.type !== 'OR')) {
+ return depth
+ }
+ let maxChild = depth
+ for (const child of maybe.values as Array<FilterGroupNode | PropertyFilterLeaf>) {
+ const d = filterGroupDepth(child, depth + 1)
+ if (d > maxChild) {
+ maxChild = d
+ }
+ }
+ return maxChild
+}
+
+function compileRegexLeavesInPlace(node: FilterGroupNode | PropertyFilterLeaf): void {
+ const maybe = node as { type?: unknown; values?: unknown }
+ if (Array.isArray(maybe.values) && (maybe.type === 'AND' || maybe.type === 'OR')) {
+ for (const child of maybe.values as Array<FilterGroupNode | PropertyFilterLeaf>) {
+ compileRegexLeavesInPlace(child)
+ }
+ return
+ }
+ const leaf = node as PropertyFilterLeaf
+ if (leaf.operator === 'regex' || leaf.operator === 'not_regex') {
+ leaf._compiledRegex = leaf.value == null ? null : compileLeafRegex(leaf.value)
+ }
+}
+
function parseAlwaysKeep(config: Record<string, unknown>): CompiledSamplingRule['alwaysKeep'] {
const ak = config.always_keep as Record<string, unknown> | undefined
if (!ak || typeof ak !== 'object') {
@@ -91,16 +195,23 @@ export function compileRuleSet(rows: SamplingRuleRow[]): CompiledRuleSet {
const rules: CompiledSamplingRule[] = []
let hasRateLimitRules = false
for (const row of rows) {
- let pathRegex: RegExp | null = null
+ // RE2 has linear-time matching; native RegExp here would expose the ingestion
+ // worker to catastrophic-backtracking ReDoS from any admin-authored pattern.
+ // Same engine choice as the new filter-group regex leaves and the rest of
+ // `nodejs/src/cdp/` regex sites.
+ let pathRegex: CompiledSamplingRule['pathRegex'] = null
if (row.scope_path_pattern) {
try {
- pathRegex = new RegExp(row.scope_path_pattern)
+ pathRegex = createTrackedRE2(row.scope_path_pattern, undefined, 'logs-sampling:scope-path')
} catch {
- pathRegex = /^$/
+ // Treat invalid / RE2-rejected patterns as match-nothing so the rule
+ // never accidentally over-scopes. Mirrors prior `/^$/` sentinel.
+ pathRegex = createTrackedRE2('^$', undefined, 'logs-sampling:scope-path-fallback')
}
}
- let pathDropPatterns: RegExp[] | null = null
+ let pathDropPatterns: CompiledSamplingRule['pathDropPatterns'] = null
let pathDropMatchAttributeKey: string | null = null
+ let filterGroup: FilterGroupNode | null = null
if (row.rule_type === 'path_drop') {
const patterns = (row.config.patterns as unknown[]) || []
pathDropPatterns = []
@@ -109,9 +220,9 @@ export function compileRuleSet(rows: SamplingRuleRow[]): CompiledRuleSet {
continue
}
try {
- pathDropPatterns.push(new RegExp(p))
+ pathDropPatterns.push(createTrackedRE2(p, undefined, 'logs-sampling:path-drop-pattern'))
} catch {
- /* skip invalid */
+ /* skip invalid (incl. RE2-rejected lookahead/backreference patterns) */
}
}
const mak = row.config.match_attribute_key
@@ -119,6 +230,7 @@ export function compileRuleSet(rows: SamplingRuleRow[]): CompiledRuleSet {
const t = mak.trim()
pathDropMatchAttributeKey = t === '' ? null : t
}
+ filterGroup = parseFilterGroup(row.config.filter_group)
}
const rt = row.rule_type as CompiledSamplingRule['ruleType']
const ruleType: CompiledSamplingRule['ruleType'] =
@@ -137,6 +249,7 @@ export function compileRuleSet(rows: SamplingRuleRow[]): CompiledRuleSet {
pathRegex,
pathDropPatterns,
pathDropMatchAttributeKey,
+ filterGroup,
severityActions: parseSeverityActions(row.config),
alwaysKeep: parseAlwaysKeep(row.config),
rateLimit,
diff --git a/nodejs/src/logs-ingestion/sampling/evaluate.test.ts b/nodejs/src/logs-ingestion/sampling/evaluate.test.ts
index d6a4010ca80f..8b392fdc118d 100644
--- a/nodejs/src/logs-ingestion/sampling/evaluate.test.ts
+++ b/nodejs/src/logs-ingestion/sampling/evaluate.test.ts
@@ -233,4 +233,143 @@ describe('evaluateLogRecord', () => {
ruleId: 'pd',
})
})
+
+ describe('path_drop with config.filter_group', () => {
+ // The drop-rules UI writes the inner group wrapped in an outer AND envelope:
+ // { type: 'AND', values: [ { type: 'AND'|'OR', values: [<leaves>] } ] }
+ const wrap = (inner: object): object => ({ type: 'AND', values: [inner] })
+
+ it('drops when filter_group matches alone (no patterns)', () => {
+ const rules = compileRuleSet([
+ {
+ id: 'fg',
+ rule_type: 'path_drop',
+ scope_service: null,
+ scope_path_pattern: null,
+ scope_attribute_filters: [],
+ config: {
+ patterns: [],
+ filter_group: wrap({
+ type: 'AND',
+ values: [{ key: 'service.name', operator: 'exact', value: 'api' }],
+ }),
+ },
+ },
+ ])
+ const matching = baseRecord()
+ matching.service_name = 'api'
+ expect(evaluateLogRecord(rules, matching).decision).toBe(SAMPLING_DECISION_DROP)
+
+ const nonMatching = baseRecord()
+ nonMatching.service_name = 'other'
+ expect(evaluateLogRecord(rules, nonMatching).decision).not.toBe(SAMPLING_DECISION_DROP)
+ })
+
+ it('drops when EITHER patterns OR filter_group matches (transition OR semantics)', () => {
+ const rules = compileRuleSet([
+ {
+ id: 'both',
+ rule_type: 'path_drop',
+ scope_service: null,
+ scope_path_pattern: null,
+ scope_attribute_filters: [],
+ config: {
+ patterns: ['/healthz'],
+ filter_group: wrap({
+ type: 'AND',
+ values: [{ key: 'severity_text', operator: 'exact', value: 'fatal' }],
+ }),
+ },
+ },
+ ])
+ // Match via legacy patterns only
+ const patternsOnly = baseRecord()
+ patternsOnly.attributes = { 'http.route': '/healthz' }
+ expect(evaluateLogRecord(rules, patternsOnly).decision).toBe(SAMPLING_DECISION_DROP)
+
+ // Match via filter_group only
+ const filterOnly = baseRecord()
+ filterOnly.attributes = { 'http.route': '/api' }
+ filterOnly.severity_text = 'fatal'
+ expect(evaluateLogRecord(rules, filterOnly).decision).toBe(SAMPLING_DECISION_DROP)
+
+ // Match neither
+ const neither = baseRecord()
+ neither.attributes = { 'http.route': '/api' }
+ neither.severity_text = 'info'
+ expect(evaluateLogRecord(rules, neither).decision).not.toBe(SAMPLING_DECISION_DROP)
+ })
+
+ it('empty filter_group does not drop (conservative)', () => {
+ const rules = compileRuleSet([
+ {
+ id: 'empty',
+ rule_type: 'path_drop',
+ scope_service: null,
+ scope_path_pattern: null,
+ scope_attribute_filters: [],
+ config: {
+ patterns: [],
+ filter_group: wrap({ type: 'AND', values: [] }),
+ },
+ },
+ ])
+ expect(evaluateLogRecord(rules, baseRecord()).decision).not.toBe(SAMPLING_DECISION_DROP)
+ })
+
+ it('filter_group with too many sibling nodes is dropped at compile time (legacy row above breadth cap)', () => {
+ // Pre-validator rows could have grown beyond the breadth cap. Walking
+ // them per record would amount to O(leaves) per log line, so
+ // parseFilterGroup discards the group entirely — the rule becomes a
+ // patterns-only rule. Matches MAX_FILTER_GROUP_NODES in compile-rules.ts.
+ const tooMany = Array.from({ length: 300 }, (_, i) => ({
+ key: 'service.name',
+ operator: 'exact',
+ value: `svc-${i}`,
+ }))
+ const rules = compileRuleSet([
+ {
+ id: 'oversize',
+ rule_type: 'path_drop',
+ scope_service: null,
+ scope_path_pattern: null,
+ scope_attribute_filters: [],
+ config: {
+ patterns: [],
+ filter_group: wrap({ type: 'AND', values: tooMany }),
+ },
+ },
+ ])
+ const rec = baseRecord()
+ rec.service_name = 'svc-1'
+ // Group was discarded → no patterns → rule never drops.
+ expect(evaluateLogRecord(rules, rec).decision).not.toBe(SAMPLING_DECISION_DROP)
+ })
+
+ it('classifySamplingRecord drops via filter_group match', () => {
+ const rules = compileRuleSet([
+ {
+ id: 'fg',
+ rule_type: 'path_drop',
+ scope_service: null,
+ scope_path_pattern: null,
+ scope_attribute_filters: [],
+ config: {
+ patterns: [],
+ filter_group: wrap({
+ type: 'AND',
+ values: [{ key: 'severity_text', operator: 'in', value: ['error', 'fatal'] }],
+ }),
+ },
+ },
+ ])
+ const rec = baseRecord()
+ rec.severity_text = 'error'
+ expect(classifySamplingRecord(rules, rec)).toEqual({
+ kind: 'resolved',
+ decision: SAMPLING_DECISION_DROP,
+ ruleId: 'fg',
+ })
+ })
+ })
})
diff --git a/nodejs/src/logs-ingestion/sampling/evaluate.ts b/nodejs/src/logs-ingestion/sampling/evaluate.ts
index 523eeb4888c1..9abb30a5e6fc 100644
--- a/nodejs/src/logs-ingestion/sampling/evaluate.ts
+++ b/nodejs/src/logs-ingestion/sampling/evaluate.ts
@@ -1,6 +1,8 @@
import { createHash } from 'crypto'
+import type RE2 from 're2'
import type { LogRecord } from '../log-record-avro'
+import { type FilterGroupNode, matchFilterGroup } from './filter-group-match'
export const SAMPLING_DECISION_KEEP = 'keep' as const
export const SAMPLING_DECISION_DROP = 'drop' as const
@@ -19,10 +21,16 @@ export type CompiledSamplingRule = {
id: string
ruleType: 'severity_sampling' | 'path_drop' | 'rate_limit'
scopeService: string | null
- pathRegex: RegExp | null
- pathDropPatterns: RegExp[] | null
+ pathRegex: RE2 | null
+ pathDropPatterns: RE2[] | null
/** When set, path_drop regexes match only this attribute; null uses pathForMatching(). */
pathDropMatchAttributeKey: string | null
+ /**
+ * Universal filter group from the drop-rule UI. Evaluated per record alongside
+ * legacy `pathDropPatterns`: a record is dropped if EITHER matches. Null when
+ * the rule has no filter_group configured (legacy / patterns-only rules).
+ */
+ filterGroup: FilterGroupNode | null
severityActions: [SeverityAction, SeverityAction, SeverityAction, SeverityAction]
alwaysKeep: {
statusGte: number | null
@@ -135,6 +143,29 @@ function alwaysKeepMatches(rule: CompiledSamplingRule, record: LogRecord): boole
return false
}
+/**
+ * A path_drop rule matches when EITHER the legacy regex patterns match the
+ * resolved path/attribute, OR the universal filter_group matches the record.
+ * Both shapes are supported during the transition off `config.patterns` —
+ * once all rules carry a filter_group, the patterns branch will be retired.
+ */
+function pathDropMatches(rule: CompiledSamplingRule, record: LogRecord): boolean {
+ if (rule.pathDropPatterns && rule.pathDropPatterns.length > 0) {
+ const p = rule.pathDropMatchAttributeKey
+ ? (getAttribute(record, rule.pathDropMatchAttributeKey) ?? '')
+ : pathForMatching(record)
+ for (const rx of rule.pathDropPatterns) {
+ if (rx.test(p)) {
+ return true
+ }
+ }
+ }
+ if (rule.filterGroup && matchFilterGroup(rule.filterGroup, record)) {
+ return true
+ }
+ return false
+}
+
function matchesScope(rule: CompiledSamplingRule, record: LogRecord): boolean {
if (rule.scopeService != null && rule.scopeService !== '') {
const sn = record.service_name || ''
@@ -180,16 +211,8 @@ export function classifySamplingRecord(teamRuleSet: CompiledRuleSet | null, reco
return { kind: 'resolved', decision: SAMPLING_DECISION_KEEP, ruleId: rule.id }
}
if (rule.ruleType === 'path_drop') {
- if (!rule.pathDropPatterns || rule.pathDropPatterns.length === 0) {
- continue
- }
- const p = rule.pathDropMatchAttributeKey
- ? (getAttribute(record, rule.pathDropMatchAttributeKey) ?? '')
- : pathForMatching(record)
- for (const rx of rule.pathDropPatterns) {
- if (rx.test(p)) {
- return { kind: 'resolved', decision: SAMPLING_DECISION_DROP, ruleId: rule.id }
- }
+ if (pathDropMatches(rule, record)) {
+ return { kind: 'resolved', decision: SAMPLING_DECISION_DROP, ruleId: rule.id }
}
continue
}
@@ -230,16 +253,8 @@ export function evaluateLogRecord(teamRuleSet: CompiledRuleSet | null, record: L
return { decision: SAMPLING_DECISION_KEEP, ruleId: rule.id }
}
if (rule.ruleType === 'path_drop') {
- if (!rule.pathDropPatterns || rule.pathDropPatterns.length === 0) {
- continue
- }
- const p = rule.pathDropMatchAttributeKey
- ? (getAttribute(record, rule.pathDropMatchAttributeKey) ?? '')
- : pathForMatching(record)
- for (const rx of rule.pathDropPatterns) {
- if (rx.test(p)) {
- return { decision: SAMPLING_DECISION_DROP, ruleId: rule.id }
- }
+ if (pathDropMatches(rule, record)) {
+ return { decision: SAMPLING_DECISION_DROP, ruleId: rule.id }
}
continue
}
diff --git a/nodejs/src/logs-ingestion/sampling/filter-group-match.test.ts b/nodejs/src/logs-ingestion/sampling/filter-group-match.test.ts
new file mode 100644
index 000000000000..28a8e2950d56
--- /dev/null
+++ b/nodejs/src/logs-ingestion/sampling/filter-group-match.test.ts
@@ -0,0 +1,201 @@
+import type { LogRecord } from '../log-record-avro'
+import { type FilterGroupNode, MAX_FILTER_GROUP_DEPTH, matchFilterGroup } from './filter-group-match'
+
+const baseRecord = (overrides: Partial<LogRecord> = {}): LogRecord => ({
+ uuid: null,
+ trace_id: null,
+ span_id: null,
+ trace_flags: null,
+ timestamp: null,
+ observed_timestamp: null,
+ body: null,
+ severity_text: null,
+ severity_number: null,
+ service_name: null,
+ resource_attributes: null,
+ instrumentation_scope: null,
+ event_name: null,
+ attributes: null,
+ ...overrides,
+})
+
+const group = (overrides: Partial<FilterGroupNode>): FilterGroupNode => ({
+ type: 'AND',
+ values: [],
+ ...overrides,
+})
+
+describe('matchFilterGroup', () => {
+ describe('empty groups', () => {
+ it('AND with no values returns false (conservative — do not drop)', () => {
+ expect(matchFilterGroup(group({ type: 'AND', values: [] }), baseRecord())).toBe(false)
+ })
+ it('OR with no values returns false', () => {
+ expect(matchFilterGroup(group({ type: 'OR', values: [] }), baseRecord())).toBe(false)
+ })
+ })
+
+ describe('AND / OR semantics', () => {
+ it('AND requires every leaf to match', () => {
+ const g = group({
+ type: 'AND',
+ values: [
+ { key: 'service.name', operator: 'exact', value: 'api' },
+ { key: 'severity_text', operator: 'exact', value: 'error' },
+ ],
+ })
+ expect(matchFilterGroup(g, baseRecord({ service_name: 'api', severity_text: 'error' }))).toBe(true)
+ expect(matchFilterGroup(g, baseRecord({ service_name: 'api', severity_text: 'warn' }))).toBe(false)
+ })
+ it('OR matches when any leaf matches', () => {
+ const g = group({
+ type: 'OR',
+ values: [
+ { key: 'severity_text', operator: 'exact', value: 'error' },
+ { key: 'severity_text', operator: 'exact', value: 'fatal' },
+ ],
+ })
+ expect(matchFilterGroup(g, baseRecord({ severity_text: 'error' }))).toBe(true)
+ expect(matchFilterGroup(g, baseRecord({ severity_text: 'fatal' }))).toBe(true)
+ expect(matchFilterGroup(g, baseRecord({ severity_text: 'warn' }))).toBe(false)
+ })
+ })
+
+ describe('nested groups', () => {
+ it('AND-of-ORs evaluates correctly', () => {
+ const g: FilterGroupNode = {
+ type: 'AND',
+ values: [
+ { key: 'service.name', operator: 'exact', value: 'api' },
+ {
+ type: 'OR',
+ values: [
+ { key: 'severity_text', operator: 'exact', value: 'error' },
+ { key: 'severity_text', operator: 'exact', value: 'fatal' },
+ ],
+ },
+ ],
+ }
+ expect(matchFilterGroup(g, baseRecord({ service_name: 'api', severity_text: 'error' }))).toBe(true)
+ expect(matchFilterGroup(g, baseRecord({ service_name: 'api', severity_text: 'warn' }))).toBe(false)
+ expect(matchFilterGroup(g, baseRecord({ service_name: 'other', severity_text: 'error' }))).toBe(false)
+ })
+ })
+
+ describe('record value lookup', () => {
+ it('service.name resolves to LogRecord.service_name (first-class column)', () => {
+ const g = group({ values: [{ key: 'service.name', operator: 'exact', value: 'api' }] })
+ expect(matchFilterGroup(g, baseRecord({ service_name: 'api' }))).toBe(true)
+ expect(matchFilterGroup(g, baseRecord({ resource_attributes: { 'service.name': 'api' } }))).toBe(true)
+ })
+ it('service_name (underscore) key still resolves via the OTel-canonical service.name attribute', () => {
+ // Regression guard for the prior bug where the underscore-form filter
+ // looked up `resource_attributes['service_name']`, which OTel never
+ // populates — the value only lives under the dotted key.
+ const g = group({ values: [{ key: 'service_name', operator: 'exact', value: 'api' }] })
+ expect(matchFilterGroup(g, baseRecord({ service_name: 'api' }))).toBe(true)
+ expect(matchFilterGroup(g, baseRecord({ resource_attributes: { 'service.name': 'api' } }))).toBe(true)
+ expect(matchFilterGroup(g, baseRecord({ resource_attributes: { service_name: 'api' } }))).toBe(false)
+ })
+ it('severity_text resolves to LogRecord.severity_text (first-class column)', () => {
+ const g = group({ values: [{ key: 'severity_text', operator: 'in', value: ['error', 'fatal'] }] })
+ expect(matchFilterGroup(g, baseRecord({ severity_text: 'error' }))).toBe(true)
+ expect(matchFilterGroup(g, baseRecord({ severity_text: 'info' }))).toBe(false)
+ })
+ it('level is an alias for severity_text (UI surfaces it this way)', () => {
+ const g = group({
+ values: [{ key: 'level', type: 'log_attribute', operator: 'exact', value: ['info', 'INFO'] }],
+ })
+ expect(matchFilterGroup(g, baseRecord({ severity_text: 'info' }))).toBe(true)
+ expect(matchFilterGroup(g, baseRecord({ severity_text: 'error' }))).toBe(false)
+ })
+ it('level / severity_text resolve symmetrically when only an attribute is populated', () => {
+ // When the first-class column is null, the attribute fallback must
+ // produce the same value for both filter keys. The SDK convention
+ // (Winston/Pino/etc.) stores severity under `level`; we fall back
+ // to both attribute names regardless of which key the filter used.
+ const recordWithLevelAttr = baseRecord({
+ severity_text: null,
+ attributes: { level: 'info' },
+ })
+ const levelFilter = group({ values: [{ key: 'level', operator: 'exact', value: 'info' }] })
+ const severityFilter = group({ values: [{ key: 'severity_text', operator: 'exact', value: 'info' }] })
+ expect(matchFilterGroup(levelFilter, recordWithLevelAttr)).toBe(true)
+ expect(matchFilterGroup(severityFilter, recordWithLevelAttr)).toBe(true)
+
+ // Same symmetry when the (rare) `severity_text` attribute is populated instead.
+ const recordWithSeverityAttr = baseRecord({
+ severity_text: null,
+ attributes: { severity_text: 'info' },
+ })
+ expect(matchFilterGroup(levelFilter, recordWithSeverityAttr)).toBe(true)
+ expect(matchFilterGroup(severityFilter, recordWithSeverityAttr)).toBe(true)
+ })
+ it('message resolves to LogRecord.body', () => {
+ const g = group({ values: [{ key: 'message', type: 'log', operator: 'icontains', value: 'health' }] })
+ expect(matchFilterGroup(g, baseRecord({ body: 'GET /healthz' }))).toBe(true)
+ expect(matchFilterGroup(g, baseRecord({ body: 'GET /api/v1' }))).toBe(false)
+ })
+ it('log_resource_attribute reads from record.resource_attributes', () => {
+ const g = group({
+ values: [
+ {
+ key: 'deployment.environment',
+ type: 'log_resource_attribute',
+ operator: 'exact',
+ value: 'staging',
+ },
+ ],
+ })
+ expect(
+ matchFilterGroup(g, baseRecord({ resource_attributes: { 'deployment.environment': 'staging' } }))
+ ).toBe(true)
+ expect(matchFilterGroup(g, baseRecord({ attributes: { 'deployment.environment': 'staging' } }))).toBe(false)
+ })
+ it('log_attribute reads from record.attributes', () => {
+ const g = group({
+ values: [{ key: 'http.route', type: 'log_attribute', operator: 'exact', value: '/healthz' }],
+ })
+ expect(matchFilterGroup(g, baseRecord({ attributes: { 'http.route': '/healthz' } }))).toBe(true)
+ expect(matchFilterGroup(g, baseRecord({ resource_attributes: { 'http.route': '/healthz' } }))).toBe(false)
+ })
+ it('untyped leaf falls back through attributes then resource_attributes', () => {
+ const g = group({ values: [{ key: 'http.route', operator: 'exact', value: '/healthz' }] })
+ expect(matchFilterGroup(g, baseRecord({ attributes: { 'http.route': '/healthz' } }))).toBe(true)
+ expect(matchFilterGroup(g, baseRecord({ resource_attributes: { 'http.route': '/healthz' } }))).toBe(true)
+ })
+ it('missing attribute does not match comparison operators', () => {
+ const g = group({ values: [{ key: 'http.route', operator: 'exact', value: '/healthz' }] })
+ expect(matchFilterGroup(g, baseRecord())).toBe(false)
+ })
+ })
+
+ describe('recursion depth cap', () => {
+ // Build a degenerate AND-chain N levels deep wrapping a single matching leaf.
+ function deepGroup(depth: number, leaf: { key: string; value: string; operator: string }): FilterGroupNode {
+ let node: FilterGroupNode = { type: 'AND', values: [leaf] }
+ for (let i = 0; i < depth; i++) {
+ node = { type: 'AND', values: [node] }
+ }
+ return node
+ }
+
+ it('matches at exactly the depth cap boundary', () => {
+ const g = deepGroup(MAX_FILTER_GROUP_DEPTH - 2, {
+ key: 'service.name',
+ value: 'api',
+ operator: 'exact',
+ })
+ expect(matchFilterGroup(g, baseRecord({ service_name: 'api' }))).toBe(true)
+ })
+
+ it('returns false past the depth cap without throwing', () => {
+ const g = deepGroup(MAX_FILTER_GROUP_DEPTH + 5, {
+ key: 'service.name',
+ value: 'api',
+ operator: 'exact',
+ })
+ expect(matchFilterGroup(g, baseRecord({ service_name: 'api' }))).toBe(false)
+ })
+ })
+})
diff --git a/nodejs/src/logs-ingestion/sampling/filter-group-match.ts b/nodejs/src/logs-ingestion/sampling/filter-group-match.ts
new file mode 100644
index 000000000000..e20e7476160c
--- /dev/null
+++ b/nodejs/src/logs-ingestion/sampling/filter-group-match.ts
@@ -0,0 +1,104 @@
+/**
+ * Recursive evaluator for the UniversalFiltersGroup shape (the matcher the
+ * drop-rules UI writes into `config.filter_group`).
+ *
+ * Group nodes have `{type: 'AND' | 'OR', values: [...]}`; leaves are
+ * PropertyFilters (see property-filter-match.ts). Nested groups are supported.
+ *
+ * SAFETY: empty groups return false (no match → don't drop). Dropping is
+ * irreversible, so when the filter is vacuous we let the line through.
+ * The drop-rule form validates non-empty before submit; this is defense in
+ * depth at the worker boundary.
+ */
+import type { LogRecord } from '../log-record-avro'
+import { type PropertyFilterLeaf, matchPropertyFilter } from './property-filter-match'
+
+export type FilterGroupNode = {
+ type: 'AND' | 'OR'
+ values: Array<PropertyFilterLeaf | FilterGroupNode>
+}
+
+const PROPERTY_FILTER_TYPE_LOG = 'log'
+const PROPERTY_FILTER_TYPE_LOG_ATTRIBUTE = 'log_attribute'
+const PROPERTY_FILTER_TYPE_LOG_RESOURCE_ATTRIBUTE = 'log_resource_attribute'
+
+/**
+ * Hard ceiling on filter-group nesting depth. The drop-rules UI surfaces at
+ * most 2 levels in practice; we leave generous headroom for hand-edited or
+ * future shapes. Beyond this we return false (no match → don't drop) so a
+ * pathological deeply-nested rule cannot blow the Node stack on every record.
+ * Pydantic validation in `sampling_api.py` enforces the same bound at write
+ * time; both sides exist so existing rows that predate the validator still
+ * degrade safely.
+ */
+export const MAX_FILTER_GROUP_DEPTH = 16
+
+export function matchFilterGroup(group: FilterGroupNode, record: LogRecord, depth: number = 0): boolean {
+ if (depth >= MAX_FILTER_GROUP_DEPTH) {
+ return false
+ }
+ if (!group.values || group.values.length === 0) {
+ return false
+ }
+ if (group.type === 'OR') {
+ return group.values.some((child) => matchOne(child, record, depth + 1))
+ }
+ // Default to AND for any unrecognised operator.
+ return group.values.every((child) => matchOne(child, record, depth + 1))
+}
+
+function matchOne(node: PropertyFilterLeaf | FilterGroupNode, record: LogRecord, depth: number): boolean {
+ if (isGroupNode(node)) {
+ return matchFilterGroup(node, record, depth)
+ }
+ return matchPropertyFilter(node, lookupRecordValue(node, record))
+}
+
+function isGroupNode(node: PropertyFilterLeaf | FilterGroupNode): node is FilterGroupNode {
+ const maybe = node as FilterGroupNode
+ return Array.isArray(maybe.values) && (maybe.type === 'AND' || maybe.type === 'OR')
+}
+
+/**
+ * Map a property filter's `key` (and `type` when present) to the corresponding
+ * value on the LogRecord. First-class columns (service_name, severity_text,
+ * body) win over the attribute maps; otherwise the declared filter type picks
+ * `attributes` vs `resource_attributes`; missing type falls back to attribute
+ * map then resource map.
+ */
+function lookupRecordValue(filter: PropertyFilterLeaf, record: LogRecord): string | null | undefined {
+ const key = filter.key
+
+ // First-class columns win when populated; otherwise fall back to the
+ // matching attribute map. Ingestion denormalises service.name + severity_text
+ // onto first-class fields, but partial decodes / older records may have only
+ // the resource/log attribute present.
+ if (key === 'service_name' || key === 'service.name') {
+ // Always fall back via the OTel-canonical dotted key — `service_name`
+ // (underscore) is only the in-memory Avro field name, never an OTel
+ // resource attribute. Looking up `resource_attributes['service_name']`
+ // would silently miss real data.
+ return record.service_name ?? record.resource_attributes?.['service.name']
+ }
+ if (key === 'severity_text' || key === 'level') {
+ // First-class column wins. Otherwise fall back to attribute storage,
+ // trying the SDK convention (`level` — Winston/Pino/Bunyan/log4j2) first
+ // and the OTel-style `severity_text` second. The fallback chain does not
+ // depend on which key the filter used, so `level: info` and
+ // `severity_text: info` always resolve to the same value for the same
+ // record (otherwise we'd silently disagree when only one of the two
+ // attribute names is populated).
+ return record.severity_text ?? record.attributes?.['level'] ?? record.attributes?.['severity_text']
+ }
+ if (key === 'message' || filter.type === PROPERTY_FILTER_TYPE_LOG) {
+ return record.body ?? undefined
+ }
+
+ if (filter.type === PROPERTY_FILTER_TYPE_LOG_RESOURCE_ATTRIBUTE) {
+ return record.resource_attributes?.[key]
+ }
+ if (filter.type === PROPERTY_FILTER_TYPE_LOG_ATTRIBUTE) {
+ return record.attributes?.[key]
+ }
+ return record.attributes?.[key] ?? record.resource_attributes?.[key]
+}
diff --git a/nodejs/src/logs-ingestion/sampling/logs-sampling.service.ts b/nodejs/src/logs-ingestion/sampling/logs-sampling.service.ts
index cde7de2cd8fa..b06a83eb8dbb 100644
--- a/nodejs/src/logs-ingestion/sampling/logs-sampling.service.ts
+++ b/nodejs/src/logs-ingestion/sampling/logs-sampling.service.ts
@@ -1,9 +1,11 @@
import { trace } from '@opentelemetry/api'
+import { Counter } from 'prom-client'
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 type { LogsSettings } from '~/types'
+import { logger } from '~/utils/logger'
import { type PiiScrubStats } from '../log-pii-scrub'
import {
@@ -12,14 +14,50 @@ import {
encodeLogRecords,
transformDecodedLogRecordsInPlace,
} from '../log-record-avro'
-import type { CompiledRuleSet, RateLimitPendingByRule } from './evaluate'
+import type { CompiledRuleSet, EvaluateResult, RateLimitPendingByRule, SamplingClassifyResult } from './evaluate'
import {
SAMPLING_DECISION_DROP,
+ SAMPLING_DECISION_KEEP,
SAMPLING_DECISION_SAMPLE_DROPPED,
classifySamplingRecord,
evaluateLogRecord,
} from './evaluate'
+/**
+ * Incremented when a per-record sampling evaluation throws. The record is kept
+ * (fail-open) so an adversarial or malformed rule cannot drop traffic via an
+ * uncaught exception, but the counter makes the silent failure observable.
+ */
+export const logsSamplingEvalErrorCounter = new Counter({
+ name: 'logs_ingestion_sampling_eval_error_total',
+ help: 'Per-record sampling evaluation threw an exception; record was kept (fail-open).',
+ labelNames: ['team_id', 'phase'],
+})
+
+function safeClassifySamplingRecord(
+ ruleSet: CompiledRuleSet,
+ record: LogRecord,
+ teamId: number
+): SamplingClassifyResult {
+ try {
+ return classifySamplingRecord(ruleSet, record)
+ } catch (err) {
+ logsSamplingEvalErrorCounter.inc({ team_id: String(teamId), phase: 'classify' })
+ logger.warn('[logs-sampling] classifySamplingRecord threw — keeping record', { teamId, err })
+ return { kind: 'resolved', decision: SAMPLING_DECISION_KEEP, ruleId: null }
+ }
+}
+
+function safeEvaluateLogRecord(ruleSet: CompiledRuleSet, record: LogRecord, teamId: number): EvaluateResult {
+ try {
+ return evaluateLogRecord(ruleSet, record)
+ } catch (err) {
+ logsSamplingEvalErrorCounter.inc({ team_id: String(teamId), phase: 'evaluate' })
+ logger.warn('[logs-sampling] evaluateLogRecord threw — keeping record', { teamId, err })
+ return { decision: SAMPLING_DECISION_KEEP, ruleId: null }
+ }
+}
+
export type ProcessBufferWithSamplingResult = {
value: Buffer
pii: PiiScrubStats
@@ -60,7 +98,7 @@ export class LogsSamplingService {
const useRate = Boolean(ruleSet.hasRateLimitRules && teamId != null)
if (useRate && teamId != null) {
- const classifications = records.map((r) => classifySamplingRecord(ruleSet, r))
+ const classifications = records.map((r) => safeClassifySamplingRecord(ruleSet, r, teamId))
const pendingByRule: RateLimitPendingByRule = new Map()
for (let i = 0; i < records.length; i++) {
const c = classifications[i]!
@@ -95,7 +133,7 @@ export class LogsSamplingService {
}
} else {
for (const record of records) {
- const { decision, ruleId } = evaluateLogRecord(ruleSet, record)
+ const { decision, ruleId } = safeEvaluateLogRecord(ruleSet, record, teamId ?? 0)
if (decision === SAMPLING_DECISION_DROP || decision === SAMPLING_DECISION_SAMPLE_DROPPED) {
recordsDropped++
if (ruleId != null) {
diff --git a/nodejs/src/logs-ingestion/sampling/property-filter-match.test.ts b/nodejs/src/logs-ingestion/sampling/property-filter-match.test.ts
new file mode 100644
index 000000000000..a95d87f2a870
--- /dev/null
+++ b/nodejs/src/logs-ingestion/sampling/property-filter-match.test.ts
@@ -0,0 +1,161 @@
+import { type PropertyFilterLeaf, compileLeafRegex, matchPropertyFilter } from './property-filter-match'
+
+const filter = (overrides: Partial<PropertyFilterLeaf>): PropertyFilterLeaf => ({
+ key: 'k',
+ ...overrides,
+})
+
+describe('matchPropertyFilter', () => {
+ describe('exact / is_not / in / not_in', () => {
+ it('exact matches case-insensitively', () => {
+ expect(matchPropertyFilter(filter({ operator: 'exact', value: 'prod' }), 'PROD')).toBe(true)
+ expect(matchPropertyFilter(filter({ operator: 'exact', value: 'prod' }), 'staging')).toBe(false)
+ })
+ it('is_not is the negation of exact', () => {
+ expect(matchPropertyFilter(filter({ operator: 'is_not', value: 'prod' }), 'staging')).toBe(true)
+ expect(matchPropertyFilter(filter({ operator: 'is_not', value: 'prod' }), 'prod')).toBe(false)
+ })
+ it('exact with a list matches when any value matches case-insensitively', () => {
+ expect(matchPropertyFilter(filter({ operator: 'exact', value: ['a', 'b'] }), 'A')).toBe(true)
+ expect(matchPropertyFilter(filter({ operator: 'exact', value: ['a', 'b'] }), 'c')).toBe(false)
+ })
+ it('in is an alias for exact-with-list', () => {
+ expect(matchPropertyFilter(filter({ operator: 'in', value: ['error', 'fatal'] }), 'error')).toBe(true)
+ expect(matchPropertyFilter(filter({ operator: 'in', value: ['error', 'fatal'] }), 'warn')).toBe(false)
+ })
+ it('not_in is the negation of in', () => {
+ expect(matchPropertyFilter(filter({ operator: 'not_in', value: ['error', 'fatal'] }), 'warn')).toBe(true)
+ expect(matchPropertyFilter(filter({ operator: 'not_in', value: ['error', 'fatal'] }), 'error')).toBe(false)
+ })
+ it('truthy values normalise to "true"/"false" strings', () => {
+ expect(matchPropertyFilter(filter({ operator: 'exact', value: true }), 'true')).toBe(true)
+ expect(matchPropertyFilter(filter({ operator: 'exact', value: 'True' }), 'true')).toBe(true)
+ expect(matchPropertyFilter(filter({ operator: 'exact', value: false }), 'false')).toBe(true)
+ expect(matchPropertyFilter(filter({ operator: 'exact', value: true }), 'false')).toBe(false)
+ })
+ })
+
+ describe('icontains / not_icontains', () => {
+ it('icontains is case-insensitive substring', () => {
+ expect(matchPropertyFilter(filter({ operator: 'icontains', value: 'HEALTH' }), '/healthz')).toBe(true)
+ expect(matchPropertyFilter(filter({ operator: 'icontains', value: 'foo' }), '/healthz')).toBe(false)
+ })
+ it('not_icontains negates icontains', () => {
+ expect(matchPropertyFilter(filter({ operator: 'not_icontains', value: 'foo' }), '/healthz')).toBe(true)
+ expect(matchPropertyFilter(filter({ operator: 'not_icontains', value: 'HEALTH' }), '/healthz')).toBe(false)
+ })
+ })
+
+ describe('regex / not_regex', () => {
+ it('regex matches with dotall + ignorecase semantics (Python parity)', () => {
+ expect(matchPropertyFilter(filter({ operator: 'regex', value: '^/api/' }), '/API/v1')).toBe(true)
+ expect(matchPropertyFilter(filter({ operator: 'regex', value: '^/api/' }), '/health')).toBe(false)
+ // `.` matches newline thanks to the `s` flag
+ expect(matchPropertyFilter(filter({ operator: 'regex', value: 'first.second' }), 'first\nsecond')).toBe(
+ true
+ )
+ })
+ it('invalid regex returns false without throwing', () => {
+ expect(matchPropertyFilter(filter({ operator: 'regex', value: '[unclosed' }), 'anything')).toBe(false)
+ })
+ it('not_regex negates regex', () => {
+ expect(matchPropertyFilter(filter({ operator: 'not_regex', value: '^/api/' }), '/health')).toBe(true)
+ expect(matchPropertyFilter(filter({ operator: 'not_regex', value: '^/api/' }), '/API/v1')).toBe(false)
+ })
+ })
+
+ describe('is_set / is_not_set', () => {
+ it('is_set matches when override is a non-empty value', () => {
+ expect(matchPropertyFilter(filter({ operator: 'is_set' }), 'anything')).toBe(true)
+ expect(matchPropertyFilter(filter({ operator: 'is_set' }), '')).toBe(false)
+ expect(matchPropertyFilter(filter({ operator: 'is_set' }), undefined)).toBe(false)
+ expect(matchPropertyFilter(filter({ operator: 'is_set' }), null)).toBe(false)
+ })
+ it('is_not_set matches when override is undefined / null / empty', () => {
+ expect(matchPropertyFilter(filter({ operator: 'is_not_set' }), undefined)).toBe(true)
+ expect(matchPropertyFilter(filter({ operator: 'is_not_set' }), null)).toBe(true)
+ expect(matchPropertyFilter(filter({ operator: 'is_not_set' }), '')).toBe(true)
+ expect(matchPropertyFilter(filter({ operator: 'is_not_set' }), 'anything')).toBe(false)
+ })
+ })
+
+ describe('gt / gte / lt / lte', () => {
+ it('compares numerically when both sides parse as numbers', () => {
+ expect(matchPropertyFilter(filter({ operator: 'gt', value: '100' }), '200')).toBe(true)
+ expect(matchPropertyFilter(filter({ operator: 'gt', value: '100' }), '50')).toBe(false)
+ expect(matchPropertyFilter(filter({ operator: 'gte', value: 100 }), 100)).toBe(true)
+ expect(matchPropertyFilter(filter({ operator: 'lt', value: 100 }), 50)).toBe(true)
+ expect(matchPropertyFilter(filter({ operator: 'lte', value: 100 }), 100)).toBe(true)
+ })
+ it('falls back to lexicographic compare when override does not parse', () => {
+ expect(matchPropertyFilter(filter({ operator: 'gt', value: 'apple' }), 'banana')).toBe(true)
+ expect(matchPropertyFilter(filter({ operator: 'lt', value: 'banana' }), 'apple')).toBe(true)
+ })
+ })
+
+ describe('missing override', () => {
+ it.each(['exact', 'is_not', 'icontains', 'not_icontains', 'regex', 'not_regex', 'gt', 'in'])(
+ 'returns false for %s when override is undefined or null',
+ (op) => {
+ expect(matchPropertyFilter(filter({ operator: op, value: 'x' }), undefined)).toBe(false)
+ expect(matchPropertyFilter(filter({ operator: op, value: 'x' }), null)).toBe(false)
+ }
+ )
+ })
+
+ describe('unknown / missing operator', () => {
+ it('defaults to exact when operator is omitted', () => {
+ expect(matchPropertyFilter(filter({ value: 'prod' }), 'prod')).toBe(true)
+ expect(matchPropertyFilter(filter({ value: 'prod' }), 'staging')).toBe(false)
+ })
+ it('returns false for unknown operators (conservative — do not drop)', () => {
+ expect(matchPropertyFilter(filter({ operator: 'unsupported_op', value: 'x' }), 'x')).toBe(false)
+ })
+ })
+
+ describe('missing filter value', () => {
+ // Regression guard: without the value-null check, `String(undefined).toLowerCase()`
+ // yields `"undefined"` and `icontains` matches every log body containing that string.
+ it.each(['exact', 'is_not', 'icontains', 'not_icontains', 'regex', 'not_regex', 'gt', 'in'])(
+ 'returns false for %s when filter value is undefined',
+ (op) => {
+ expect(matchPropertyFilter(filter({ operator: op }), 'undefined')).toBe(false)
+ expect(matchPropertyFilter(filter({ operator: op }), 'anything')).toBe(false)
+ }
+ )
+ it.each(['exact', 'is_not', 'icontains', 'not_icontains', 'regex', 'not_regex', 'gt', 'in'])(
+ 'returns false for %s when filter value is null',
+ (op) => {
+ expect(matchPropertyFilter(filter({ operator: op, value: null }), 'undefined')).toBe(false)
+ expect(matchPropertyFilter(filter({ operator: op, value: null }), 'anything')).toBe(false)
+ }
+ )
+ })
+
+ describe('pre-compiled regex', () => {
+ it('uses the leaf _compiledRegex when present and skips ad-hoc compile', () => {
+ const compiled = compileLeafRegex('precompiled')
+ // Set `value` to a different pattern so it's clear the compiled regex won.
+ expect(
+ matchPropertyFilter(
+ { ...filter({ operator: 'regex', value: 'ad-hoc' }), _compiledRegex: compiled },
+ 'precompiled body'
+ )
+ ).toBe(true)
+ })
+ it('treats _compiledRegex === null as "compile failed, never match"', () => {
+ expect(
+ matchPropertyFilter(
+ { ...filter({ operator: 'regex', value: 'whatever' }), _compiledRegex: null },
+ 'whatever'
+ )
+ ).toBe(false)
+ expect(
+ matchPropertyFilter(
+ { ...filter({ operator: 'not_regex', value: 'whatever' }), _compiledRegex: null },
+ 'whatever'
+ )
+ ).toBe(false)
+ })
+ })
+})
diff --git a/nodejs/src/logs-ingestion/sampling/property-filter-match.ts b/nodejs/src/logs-ingestion/sampling/property-filter-match.ts
new file mode 100644
index 000000000000..7f595e0475f9
--- /dev/null
+++ b/nodejs/src/logs-ingestion/sampling/property-filter-match.ts
@@ -0,0 +1,202 @@
+/**
+ * Per-record property filter evaluator for log drop rules.
+ *
+ * Ported from `posthog/queries/base.py:match_property`. Keep semantics aligned
+ * with the Python implementation; if you change one side, change the other.
+ *
+ * - `is_set` / `is_not_set` are the only operators that match a missing override.
+ * - Date operators (is_date_before / after / exact) are intentionally omitted —
+ * the drop rule UI does not surface them and ingestion has no need.
+ * - Unknown operators return false (no match → don't drop). Dropping is
+ * irreversible, so defaults are conservative.
+ * - Regex evaluation uses RE2 (linear-time, no catastrophic backtracking) via
+ * `createTrackedRE2`, matching the rest of `nodejs/src/cdp/` for ReDoS safety.
+ * RE2 does not support lookahead / lookbehind / backreferences — a pattern
+ * using those fails to compile and the leaf permanently no-matches.
+ */
+import type RE2 from 're2'
+
+import { createTrackedRE2 } from '~/utils/tracked-re2'
+
+export type SupportedPropertyOperator =
+ | 'exact'
+ | 'is_not'
+ | 'is_set'
+ | 'is_not_set'
+ | 'icontains'
+ | 'not_icontains'
+ | 'regex'
+ | 'not_regex'
+ | 'gt'
+ | 'gte'
+ | 'lt'
+ | 'lte'
+ | 'in'
+ | 'not_in'
+
+/**
+ * Leaf filter shape — mirrors the AnyPropertyFilter wire format. `_compiledRegex`
+ * is populated by `parseFilterGroup` for `regex` / `not_regex` leaves so the hot
+ * path does not allocate a fresh regex per log record. `null` means the pattern
+ * failed to compile under RE2 (invalid syntax, lookahead, etc.) and the leaf
+ * will never match.
+ */
+export interface PropertyFilterLeaf {
+ key: string
+ operator?: string
+ value?: string | number | boolean | (string | number | boolean)[] | null
+ type?: string
+ /** Internal — set during compile, do not write from outside compile-rules. */
+ _compiledRegex?: RE2 | null
+}
+
+/** Pre-compile a regex pattern for a leaf with the same flags `matchPropertyFilter` uses. */
+export function compileLeafRegex(pattern: unknown): RE2 | null {
+ try {
+ // Python source uses re.DOTALL | re.IGNORECASE — same as RE2 `s` + `i` flags.
+ return createTrackedRE2(String(pattern), 'is', 'logs-sampling:property-filter-regex')
+ } catch {
+ return null
+ }
+}
+
+export function matchPropertyFilter(
+ filter: PropertyFilterLeaf,
+ overrideValue: string | number | boolean | null | undefined
+): boolean {
+ const operator = (filter.operator ?? 'exact') as SupportedPropertyOperator
+ const value = filter.value
+
+ if (operator === 'is_set') {
+ return overrideValue !== undefined && overrideValue !== null && overrideValue !== ''
+ }
+ if (operator === 'is_not_set') {
+ return overrideValue === undefined || overrideValue === null || overrideValue === ''
+ }
+
+ // For every remaining operator, a missing override never matches.
+ if (overrideValue === undefined || overrideValue === null) {
+ return false
+ }
+
+ // A missing filter value never matches either — without this guard, the
+ // operators below silently coerce `undefined` to the literal string
+ // `"undefined"` and match any log line containing that substring.
+ // `is_set` / `is_not_set` above are the only operators that legitimately
+ // run without a filter value.
+ if (value === undefined || value === null) {
+ return false
+ }
+
+ if (operator === 'exact' || operator === 'in') {
+ return matchExact(value, overrideValue)
+ }
+ if (operator === 'is_not' || operator === 'not_in') {
+ return !matchExact(value, overrideValue)
+ }
+
+ if (operator === 'icontains') {
+ return String(overrideValue).toLowerCase().includes(String(value).toLowerCase())
+ }
+ if (operator === 'not_icontains') {
+ return !String(overrideValue).toLowerCase().includes(String(value).toLowerCase())
+ }
+
+ if (operator === 'regex' || operator === 'not_regex') {
+ // Prefer the compile-time regex if `parseFilterGroup` stamped one onto the
+ // leaf. `_compiledRegex === null` means the pattern failed to compile and
+ // the leaf should never match (mirrors the catch branch below).
+ let rx: RE2 | null | undefined = filter._compiledRegex
+ if (rx === undefined) {
+ // Fallback for callers that didn't pre-compile (mostly tests).
+ rx = compileLeafRegex(value)
+ }
+ if (rx === null) {
+ return false
+ }
+ const matches = rx.test(String(overrideValue))
+ return operator === 'regex' ? matches : !matches
+ }
+
+ if (operator === 'gt' || operator === 'gte' || operator === 'lt' || operator === 'lte') {
+ return compareNumeric(value, overrideValue, operator)
+ }
+
+ return false
+}
+
+function matchExact(value: PropertyFilterLeaf['value'], overrideValue: string | number | boolean): boolean {
+ if (isTruthyOrFalsyValue(value)) {
+ const truthy = isTrueValue(value)
+ return String(overrideValue).toLowerCase() === String(truthy).toLowerCase()
+ }
+ if (Array.isArray(value)) {
+ const overrideStr = String(overrideValue).toLowerCase()
+ return value.some((v) => String(v).toLowerCase() === overrideStr)
+ }
+ return String(value).toLowerCase() === String(overrideValue).toLowerCase()
+}
+
+// Mirrors `is_truthy_or_falsy_property_value` in posthog/queries/base.py.
+function isTruthyOrFalsyValue(v: unknown): boolean {
+ if (v === true || v === false) {
+ return true
+ }
+ const truthyOrFalsy = ['true', 'True', 'false', 'False']
+ if (typeof v === 'string') {
+ return truthyOrFalsy.includes(v)
+ }
+ if (Array.isArray(v) && v.length === 1) {
+ const inner = v[0]
+ if (inner === true || inner === false) {
+ return true
+ }
+ if (typeof inner === 'string') {
+ return truthyOrFalsy.includes(inner)
+ }
+ }
+ return false
+}
+
+function isTrueValue(v: unknown): boolean {
+ if (v === true) {
+ return true
+ }
+ if (typeof v === 'string') {
+ return v === 'true' || v === 'True'
+ }
+ if (Array.isArray(v) && v.length === 1) {
+ return isTrueValue(v[0])
+ }
+ return false
+}
+
+function compareNumeric(
+ value: PropertyFilterLeaf['value'],
+ overrideValue: string | number | boolean,
+ operator: 'gt' | 'gte' | 'lt' | 'lte'
+): boolean {
+ // Mirrors Python: try numeric parse of `value`; if numeric and override parses to
+ // a number, compare numerically. Otherwise fall back to lexicographic string compare.
+ const parsedValue = typeof value === 'number' ? value : parseFloat(String(value))
+ if (Number.isFinite(parsedValue)) {
+ const overrideNum = typeof overrideValue === 'number' ? overrideValue : parseFloat(String(overrideValue))
+ if (Number.isFinite(overrideNum)) {
+ return cmp(overrideNum, parsedValue, operator)
+ }
+ }
+ return cmp(String(overrideValue), String(value), operator)
+}
+
+function cmp<T extends number | string>(lhs: T, rhs: T, operator: 'gt' | 'gte' | 'lt' | 'lte'): boolean {
+ switch (operator) {
+ case 'gt':
+ return lhs > rhs
+ case 'gte':
+ return lhs >= rhs
+ case 'lt':
+ return lhs < rhs
+ case 'lte':
+ return lhs <= rhs
+ }
+}
diff --git a/products/logs/backend/sampling_api.py b/products/logs/backend/sampling_api.py
index f1c8fc6d3d20..3206c6e8e838 100644
--- a/products/logs/backend/sampling_api.py
+++ b/products/logs/backend/sampling_api.py
@@ -6,12 +6,15 @@ from django.db import transaction
from django.db.models import F, Max, QuerySet
from drf_spectacular.utils import extend_schema
+from pydantic import ValidationError as PydanticValidationError
from rest_framework import serializers, status, viewsets
from rest_framework.decorators import action
from rest_framework.exceptions import ValidationError
from rest_framework.request import Request
from rest_framework.response import Response
+from posthog.schema import PropertyGroupFilter
+
from posthog.api.routing import TeamAndOrgViewSetMixin
from posthog.event_usage import report_user_action
from posthog.models.activity_logging.activity_log import ActivityScope, Detail, changes_between, log_activity
@@ -21,6 +24,52 @@ from posthog.permissions import PostHogFeatureFlagPermission
from products.logs.backend.models import LogsExclusionRule
+# Keep aligned with `MAX_FILTER_GROUP_DEPTH` / `MAX_FILTER_GROUP_NODES` in
+# `nodejs/src/logs-ingestion/sampling/filter-group-match.ts` and
+# `compile-rules.ts`. Both depth and breadth are bounded so an adversarially
+# deep or wide filter_group cannot stack-overflow or CPU-burn the per-record
+# evaluator in the Node ingestion worker. The breadth cap is the more
+# realistic abuse vector — depth 1 with 10k sibling leaves passes the depth
+# check but costs O(leaves) per log record.
+MAX_FILTER_GROUP_DEPTH = 16
+MAX_FILTER_GROUP_NODES = 256
+
+
+def _filter_group_depth(node: Any, depth: int = 0) -> int:
+ # Short-circuit once we've crossed the cap — we don't need the true depth,
+ # just that it exceeds MAX_FILTER_GROUP_DEPTH. Prevents Python RecursionError
+ # on adversarial payloads that pass pydantic-core (Rust) validation, which
+ # has a more generous recursion limit than ours.
+ if depth > MAX_FILTER_GROUP_DEPTH:
+ return depth
+ if not isinstance(node, dict):
+ return depth
+ values = node.get("values")
+ if not isinstance(values, list) or node.get("type") not in ("AND", "OR"):
+ return depth
+ max_child = depth
+ for child in values:
+ d = _filter_group_depth(child, depth + 1)
+ if d > max_child:
+ max_child = d
+ return max_child
+
+
+def _filter_group_node_count(node: Any) -> int:
+ """Total node count across the filter group (groups + leaves). Short-circuits
+ once the cap is exceeded so adversarial payloads don't get fully traversed."""
+ if not isinstance(node, dict):
+ return 1
+ total = 1
+ values = node.get("values")
+ if not isinstance(values, list) or node.get("type") not in ("AND", "OR"):
+ return total
+ for child in values:
+ total += _filter_group_node_count(child)
+ if total > MAX_FILTER_GROUP_NODES:
+ return total
+ return total
+
class LogsSamplingRuleSerializer(serializers.ModelSerializer):
id = serializers.UUIDField(read_only=True, help_text="Unique identifier for this sampling rule.")
@@ -61,13 +110,15 @@ class LogsSamplingRuleSerializer(serializers.ModelSerializer):
)
config = serializers.JSONField(
help_text=(
- "Type-specific JSON. For path_drop: object with required `patterns` (list of regex strings) and optional "
- "`match_attribute_key` (string). When `match_attribute_key` is omitted or empty, patterns match the same "
- "virtual path string as ingestion (url.path, http.path, http.route, path). When set, each pattern is "
- "tested only against that string attribute on the log record. For severity_sampling: object with "
- "`actions` per severity level and optional `always_keep`. For rate_limit: object with required "
- "`logs_per_second` (integer 1–1000000) and optional `burst_logs` (integer ≥ logs_per_second, max 60000000); "
- "rate_limit rules require non-null `scope_service` matching `service.name` on each log line."
+ "Type-specific JSON. For path_drop: object with optional `filter_group` (PropertyGroupFilter shape — "
+ "AND/OR tree of property predicates evaluated per record) and/or legacy `patterns` (list of regex strings) "
+ "+ `match_attribute_key` (string). When both are present a record is dropped if EITHER matches. "
+ 'Filter group example: `{"type":"AND","values":[{"type":"AND","values":['
+ '{"key":"service.name","operator":"exact","value":"api"}]}]}`. '
+ "For severity_sampling: object with `actions` per severity level and optional `always_keep`. "
+ "For rate_limit: object with required `logs_per_second` (integer 1–1000000) and optional `burst_logs` "
+ "(integer ≥ logs_per_second, max 60000000); rate_limit rules require non-null `scope_service` matching "
+ "`service.name` on each log line."
)
)
version = serializers.IntegerField(
@@ -116,6 +167,44 @@ class LogsSamplingRuleSerializer(serializers.ModelSerializer):
mak = config.get("match_attribute_key")
if mak is not None and mak != "" and not isinstance(mak, str):
raise ValidationError({"config": {"match_attribute_key": "Must be a string when provided."}})
+ filter_group = config.get("filter_group")
+ if filter_group is not None:
+ # Validate shape against PropertyGroupFilter so malformed payloads
+ # (e.g. a list where an object is expected) are rejected at write
+ # time rather than letting them flow through to the ingestion worker.
+ # Mirrors the pattern used for alert filters in alerts_api.py.
+ try:
+ PropertyGroupFilter.model_validate(filter_group)
+ except PydanticValidationError as e:
+ raise ValidationError(
+ {"config": {"filter_group": f"Invalid filter_group shape: {e.errors()[0]['msg']}"}}
+ )
+ # Bound nesting depth — the Node ingestion worker recurses per
+ # record over this tree, so an adversarially deep group is a
+ # stack-overflow + CPU footgun on every log line. Matches
+ # `MAX_FILTER_GROUP_DEPTH` in
+ # `nodejs/src/logs-ingestion/sampling/filter-group-match.ts`.
+ if _filter_group_depth(filter_group) > MAX_FILTER_GROUP_DEPTH:
+ raise ValidationError(
+ {
+ "config": {
+ "filter_group": f"filter_group is nested too deeply (max depth {MAX_FILTER_GROUP_DEPTH})."
+ }
+ }
+ )
+ # Bound total node count — depth alone doesn't bound work per
+ # record. A single AND with thousands of sibling leaves is the
+ # more realistic abuse vector: it passes the depth check but
+ # costs O(leaves) on every log line through the ingestion
+ # worker. Matches `MAX_FILTER_GROUP_NODES` in `compile-rules.ts`.
+ if _filter_group_node_count(filter_group) > MAX_FILTER_GROUP_NODES:
+ raise ValidationError(
+ {
+ "config": {
+ "filter_group": f"filter_group has too many nodes (max {MAX_FILTER_GROUP_NODES} groups + leaves)."
+ }
+ }
+ )
if rule_type == LogsExclusionRule.RuleType.RATE_LIMIT:
if not isinstance(config, dict):
raise ValidationError({"config": "rate_limit rules require config to be a JSON object."})
diff --git a/products/logs/backend/test/test_sampling_rules_api.py b/products/logs/backend/test/test_sampling_rules_api.py
index 5fee2c1e0902..f51b275c3f5f 100644
--- a/products/logs/backend/test/test_sampling_rules_api.py
+++ b/products/logs/backend/test/test_sampling_rules_api.py
@@ -1,6 +1,7 @@
from posthog.test.base import APIBaseTest
from unittest.mock import patch
+from parameterized import parameterized
from rest_framework import status
from products.logs.backend.models import LogsExclusionRule
@@ -96,3 +97,97 @@ class TestLogsSamplingRulesAPI(APIBaseTest):
assert body["scope_service"] == "payment-api"
assert body["config"]["logs_per_second"] == 5000
assert body["config"]["burst_logs"] == 15000
+
+ def test_create_path_drop_with_valid_filter_group(self):
+ # The drop-rules UI writes the inner group wrapped in an outer AND envelope.
+ filter_group = {
+ "type": "AND",
+ "values": [
+ {
+ "type": "AND",
+ "values": [
+ {"key": "service.name", "operator": "exact", "value": "api", "type": "log_resource_attribute"}
+ ],
+ }
+ ],
+ }
+ response = self.client.post(
+ self.base_url,
+ self._payload(
+ name="Drop api logs",
+ config={"patterns": [], "filter_group": filter_group},
+ ),
+ format="json",
+ )
+ assert response.status_code == status.HTTP_201_CREATED, response.json()
+ assert response.json()["config"]["filter_group"] == filter_group
+
+ # Each case is a config payload that the Pydantic PropertyGroupFilter validator
+ # should reject at write time, so a malformed shape never reaches the worker.
+ MALFORMED_FILTER_GROUPS = [
+ ("filter_group_is_list", []),
+ ("filter_group_is_string", "not a group"),
+ ("missing_type", {"values": []}),
+ ("invalid_logical_operator", {"type": "XOR", "values": []}),
+ ("values_is_not_list", {"type": "AND", "values": "oops"}),
+ ("inner_group_is_list", {"type": "AND", "values": [[{"key": "x"}]]}),
+ ]
+
+ @parameterized.expand([(label, payload) for label, payload in MALFORMED_FILTER_GROUPS])
+ def test_create_path_drop_rejects_malformed_filter_group(self, _label, malformed):
+ response = self.client.post(
+ self.base_url,
+ self._payload(config={"patterns": [], "filter_group": malformed}),
+ format="json",
+ )
+ assert response.status_code == status.HTTP_400_BAD_REQUEST, response.json()
+ # The error attaches under config → filter_group; precise message comes from Pydantic.
+ body = response.json()
+ assert "filter_group" in str(body), body
+
+ @parameterized.expand([(label, payload) for label, payload in MALFORMED_FILTER_GROUPS])
+ def test_patch_path_drop_rejects_malformed_filter_group(self, _label, malformed):
+ create = self.client.post(self.base_url, self._payload(), format="json")
+ assert create.status_code == status.HTTP_201_CREATED, create.json()
+ rule_id = create.json()["id"]
+
+ response = self.client.patch(
+ f"{self.base_url}{rule_id}/",
+ {"config": {"patterns": [], "filter_group": malformed}},
+ format="json",
+ )
+ assert response.status_code == status.HTTP_400_BAD_REQUEST, response.json()
+
+ def test_create_path_drop_rejects_filter_group_nested_too_deeply(self):
+ # 20 nested AND groups around a single leaf — well past the cap of 16.
+ # Worker recurses per record, so an unbounded depth is a stack-overflow + CPU footgun.
+ node = {
+ "type": "AND",
+ "values": [{"key": "service.name", "operator": "exact", "value": "api", "type": "log_resource_attribute"}],
+ }
+ for _ in range(20):
+ node = {"type": "AND", "values": [node]}
+ response = self.client.post(
+ self.base_url,
+ self._payload(config={"patterns": [], "filter_group": node}),
+ format="json",
+ )
+ assert response.status_code == status.HTTP_400_BAD_REQUEST, response.json()
+ assert "nested too deeply" in str(response.json()), response.json()
+
+ def test_create_path_drop_rejects_filter_group_with_too_many_nodes(self):
+ # A shallow group with 300 sibling leaves passes the depth check but
+ # forces the ingestion worker to evaluate every leaf on every log
+ # record. MAX_FILTER_GROUP_NODES (256) is enforced server-side.
+ leaves = [
+ {"key": "service.name", "operator": "exact", "value": f"svc-{i}", "type": "log_resource_attribute"}
+ for i in range(300)
+ ]
+ filter_group = {"type": "AND", "values": [{"type": "AND", "values": leaves}]}
+ response = self.client.post(
+ self.base_url,
+ self._payload(config={"patterns": [], "filter_group": filter_group}),
+ format="json",
+ )
+ assert response.status_code == status.HTTP_400_BAD_REQUEST, response.json()
+ assert "too many nodes" in str(response.json()), response.json()
diff --git a/products/logs/frontend/generated/api.schemas.ts b/products/logs/frontend/generated/api.schemas.ts
index e69e43fb7051..4b268369be0e 100644
--- a/products/logs/frontend/generated/api.schemas.ts
+++ b/products/logs/frontend/generated/api.schemas.ts
@@ -1180,7 +1180,7 @@ export interface LogsSamplingRuleApi {
scope_path_pattern?: string | null
/** Optional list of predicates over string attributes, e.g. [{"key":"http.route","op":"eq","value":"/api"}]. */
scope_attribute_filters?: LogsSamplingRuleApiScopeAttributeFiltersItem[]
- /** Type-specific JSON. For path_drop: object with required `patterns` (list of regex strings) and optional `match_attribute_key` (string). When `match_attribute_key` is omitted or empty, patterns match the same virtual path string as ingestion (url.path, http.path, http.route, path). When set, each pattern is tested only against that string attribute on the log record. For severity_sampling: object with `actions` per severity level and optional `always_keep`. For rate_limit: object with required `logs_per_second` (integer 1–1000000) and optional `burst_logs` (integer ≥ logs_per_second, max 60000000); rate_limit rules require non-null `scope_service` matching `service.name` on each log line. */
+ /** Type-specific JSON. For path_drop: object with optional `filter_group` (PropertyGroupFilter shape — AND/OR tree of property predicates evaluated per record) and/or legacy `patterns` (list of regex strings) + `match_attribute_key` (string). When both are present a record is dropped if EITHER matches. Filter group example: `{"type":"AND","values":[{"type":"AND","values":[{"key":"service.name","operator":"exact","value":"api"}]}]}`. For severity_sampling: object with `actions` per severity level and optional `always_keep`. For rate_limit: object with required `logs_per_second` (integer 1–1000000) and optional `burst_logs` (integer ≥ logs_per_second, max 60000000); rate_limit rules require non-null `scope_service` matching `service.name` on each log line. */
config: unknown
/** Incremented on each update for worker cache coherency. */
readonly version: number
@@ -1237,7 +1237,7 @@ export interface PatchedLogsSamplingRuleApi {
scope_path_pattern?: string | null
/** Optional list of predicates over string attributes, e.g. [{"key":"http.route","op":"eq","value":"/api"}]. */
scope_attribute_filters?: PatchedLogsSamplingRuleApiScopeAttributeFiltersItem[]
- /** Type-specific JSON. For path_drop: object with required `patterns` (list of regex strings) and optional `match_attribute_key` (string). When `match_attribute_key` is omitted or empty, patterns match the same virtual path string as ingestion (url.path, http.path, http.route, path). When set, each pattern is tested only against that string attribute on the log record. For severity_sampling: object with `actions` per severity level and optional `always_keep`. For rate_limit: object with required `logs_per_second` (integer 1–1000000) and optional `burst_logs` (integer ≥ logs_per_second, max 60000000); rate_limit rules require non-null `scope_service` matching `service.name` on each log line. */
+ /** Type-specific JSON. For path_drop: object with optional `filter_group` (PropertyGroupFilter shape — AND/OR tree of property predicates evaluated per record) and/or legacy `patterns` (list of regex strings) + `match_attribute_key` (string). When both are present a record is dropped if EITHER matches. Filter group example: `{"type":"AND","values":[{"type":"AND","values":[{"key":"service.name","operator":"exact","value":"api"}]}]}`. For severity_sampling: object with `actions` per severity level and optional `always_keep`. For rate_limit: object with required `logs_per_second` (integer 1–1000000) and optional `burst_logs` (integer ≥ logs_per_second, max 60000000); rate_limit rules require non-null `scope_service` matching `service.name` on each log line. */
config?: unknown
/** Incremented on each update for worker cache coherency. */
readonly version?: number
diff --git a/products/logs/frontend/generated/api.zod.ts b/products/logs/frontend/generated/api.zod.ts
index cc50e91f1aa5..0f150aba0e42 100644
--- a/products/logs/frontend/generated/api.zod.ts
+++ b/products/logs/frontend/generated/api.zod.ts
@@ -797,7 +797,7 @@ export const LogsSamplingRulesCreateBody = /* @__PURE__ */ zod.object({
config: zod
.unknown()
.describe(
- 'Type-specific JSON. For path_drop: object with required `patterns` (list of regex strings) and optional `match_attribute_key` (string). When `match_attribute_key` is omitted or empty, patterns match the same virtual path string as ingestion (url.path, http.path, http.route, path). When set, each pattern is tested only against that string attribute on the log record. For severity_sampling: object with `actions` per severity level and optional `always_keep`. For rate_limit: object with required `logs_per_second` (integer 1–1000000) and optional `burst_logs` (integer ≥ logs_per_second, max 60000000); rate_limit rules require non-null `scope_service` matching `service.name` on each log line.'
+ 'Type-specific JSON. For path_drop: object with optional `filter_group` (PropertyGroupFilter shape — AND\/OR tree of property predicates evaluated per record) and\/or legacy `patterns` (list of regex strings) + `match_attribute_key` (string). When both are present a record is dropped if EITHER matches. Filter group example: `{\"type\":\"AND\",\"values\":[{\"type\":\"AND\",\"values\":[{\"key\":\"service.name\",\"operator\":\"exact\",\"value\":\"api\"}]}]}`. For severity_sampling: object with `actions` per severity level and optional `always_keep`. For rate_limit: object with required `logs_per_second` (integer 1–1000000) and optional `burst_logs` (integer ≥ logs_per_second, max 60000000); rate_limit rules require non-null `scope_service` matching `service.name` on each log line.'
),
})
@@ -850,7 +850,7 @@ export const LogsSamplingRulesUpdateBody = /* @__PURE__ */ zod.object({
config: zod
.unknown()
.describe(
- 'Type-specific JSON. For path_drop: object with required `patterns` (list of regex strings) and optional `match_attribute_key` (string). When `match_attribute_key` is omitted or empty, patterns match the same virtual path string as ingestion (url.path, http.path, http.route, path). When set, each pattern is tested only against that string attribute on the log record. For severity_sampling: object with `actions` per severity level and optional `always_keep`. For rate_limit: object with required `logs_per_second` (integer 1–1000000) and optional `burst_logs` (integer ≥ logs_per_second, max 60000000); rate_limit rules require non-null `scope_service` matching `service.name` on each log line.'
+ 'Type-specific JSON. For path_drop: object with optional `filter_group` (PropertyGroupFilter shape — AND\/OR tree of property predicates evaluated per record) and\/or legacy `patterns` (list of regex strings) + `match_attribute_key` (string). When both are present a record is dropped if EITHER matches. Filter group example: `{\"type\":\"AND\",\"values\":[{\"type\":\"AND\",\"values\":[{\"key\":\"service.name\",\"operator\":\"exact\",\"value\":\"api\"}]}]}`. For severity_sampling: object with `actions` per severity level and optional `always_keep`. For rate_limit: object with required `logs_per_second` (integer 1–1000000) and optional `burst_logs` (integer ≥ logs_per_second, max 60000000); rate_limit rules require non-null `scope_service` matching `service.name` on each log line.'
),
})
@@ -909,7 +909,7 @@ export const LogsSamplingRulesPartialUpdateBody = /* @__PURE__ */ zod.object({
.unknown()
.optional()
.describe(
- 'Type-specific JSON. For path_drop: object with required `patterns` (list of regex strings) and optional `match_attribute_key` (string). When `match_attribute_key` is omitted or empty, patterns match the same virtual path string as ingestion (url.path, http.path, http.route, path). When set, each pattern is tested only against that string attribute on the log record. For severity_sampling: object with `actions` per severity level and optional `always_keep`. For rate_limit: object with required `logs_per_second` (integer 1–1000000) and optional `burst_logs` (integer ≥ logs_per_second, max 60000000); rate_limit rules require non-null `scope_service` matching `service.name` on each log line.'
+ 'Type-specific JSON. For path_drop: object with optional `filter_group` (PropertyGroupFilter shape — AND\/OR tree of property predicates evaluated per record) and\/or legacy `patterns` (list of regex strings) + `match_attribute_key` (string). When both are present a record is dropped if EITHER matches. Filter group example: `{\"type\":\"AND\",\"values\":[{\"type\":\"AND\",\"values\":[{\"key\":\"service.name\",\"operator\":\"exact\",\"value\":\"api\"}]}]}`. For severity_sampling: object with `actions` per severity level and optional `always_keep`. For rate_limit: object with required `logs_per_second` (integer 1–1000000) and optional `burst_logs` (integer ≥ logs_per_second, max 60000000); rate_limit rules require non-null `scope_service` matching `service.name` on each log line.'
),
})
diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.ts
index dec0449e8765..726aba6fe956 100644
--- a/services/mcp/src/api/generated.ts
+++ b/services/mcp/src/api/generated.ts
@@ -20159,7 +20159,7 @@ export namespace Schemas {
scope_path_pattern?: string | null;
/** Optional list of predicates over string attributes, e.g. [{"key":"http.route","op":"eq","value":"/api"}]. */
scope_attribute_filters?: LogsSamplingRuleScopeAttributeFiltersItem[];
- /** Type-specific JSON. For path_drop: object with required `patterns` (list of regex strings) and optional `match_attribute_key` (string). When `match_attribute_key` is omitted or empty, patterns match the same virtual path string as ingestion (url.path, http.path, http.route, path). When set, each pattern is tested only against that string attribute on the log record. For severity_sampling: object with `actions` per severity level and optional `always_keep`. For rate_limit: object with required `logs_per_second` (integer 1–1000000) and optional `burst_logs` (integer ≥ logs_per_second, max 60000000); rate_limit rules require non-null `scope_service` matching `service.name` on each log line. */
+ /** Type-specific JSON. For path_drop: object with optional `filter_group` (PropertyGroupFilter shape — AND/OR tree of property predicates evaluated per record) and/or legacy `patterns` (list of regex strings) + `match_attribute_key` (string). When both are present a record is dropped if EITHER matches. Filter group example: `{"type":"AND","values":[{"type":"AND","values":[{"key":"service.name","operator":"exact","value":"api"}]}]}`. For severity_sampling: object with `actions` per severity level and optional `always_keep`. For rate_limit: object with required `logs_per_second` (integer 1–1000000) and optional `burst_logs` (integer ≥ logs_per_second, max 60000000); rate_limit rules require non-null `scope_service` matching `service.name` on each log line. */
config: unknown;
/** Incremented on each update for worker cache coherency. */
readonly version: number;
@@ -27551,7 +27551,7 @@ export namespace Schemas {
scope_path_pattern?: string | null;
/** Optional list of predicates over string attributes, e.g. [{"key":"http.route","op":"eq","value":"/api"}]. */
scope_attribute_filters?: PatchedLogsSamplingRuleScopeAttributeFiltersItem[];
- /** Type-specific JSON. For path_drop: object with required `patterns` (list of regex strings) and optional `match_attribute_key` (string). When `match_attribute_key` is omitted or empty, patterns match the same virtual path string as ingestion (url.path, http.path, http.route, path). When set, each pattern is tested only against that string attribute on the log record. For severity_sampling: object with `actions` per severity level and optional `always_keep`. For rate_limit: object with required `logs_per_second` (integer 1–1000000) and optional `burst_logs` (integer ≥ logs_per_second, max 60000000); rate_limit rules require non-null `scope_service` matching `service.name` on each log line. */
+ /** Type-specific JSON. For path_drop: object with optional `filter_group` (PropertyGroupFilter shape — AND/OR tree of property predicates evaluated per record) and/or legacy `patterns` (list of regex strings) + `match_attribute_key` (string). When both are present a record is dropped if EITHER matches. Filter group example: `{"type":"AND","values":[{"type":"AND","values":[{"key":"service.name","operator":"exact","value":"api"}]}]}`. For severity_sampling: object with `actions` per severity level and optional `always_keep`. For rate_limit: object with required `logs_per_second` (integer 1–1000000) and optional `burst_logs` (integer ≥ logs_per_second, max 60000000); rate_limit rules require non-null `scope_service` matching `service.name` on each log line. */
config?: unknown;
/** Incremented on each update for worker cache coherency. */
readonly version?: number;