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.

fix(logs): decode attribute values in drop and metric rule matching (#88743)

Daniel Visca27c2aeee5129
diff --git a/nodejs/src/logs/attribute-value.ts b/nodejs/src/logs/attribute-value.ts
new file mode 100644
index 000000000000..4e9c239eb97b
--- /dev/null
+++ b/nodejs/src/logs/attribute-value.ts
@@ -0,0 +1,38 @@
+import { parseJSON } from '~/common/utils/json-parse'
+
+/**
+ * Attribute values arrive JSON-encoded from capture (`any_value_to_json`): a string
+ * attribute is stored as `"error"` (with quotes), a number as `123`. The ClickHouse
+ * sink decodes string values with `JSONExtractString`, so that is what users see in
+ * the Logs UI. Every ingestion-time consumer of the attribute maps (transformations,
+ * drop-rule matching, metric-rule tallying) must see the same decoded values —
+ * otherwise `record.attributes['level'] == 'error'` silently never matches.
+ */
+export function decodeLogAttributeValue(value: string): string {
+ if (value.length >= 2 && value.startsWith('"') && value.endsWith('"')) {
+ try {
+ const parsed = parseJSON(value)
+ if (typeof parsed === 'string') {
+ return parsed
+ }
+ } catch {
+ // Not valid JSON — treat as a plain string
+ }
+ }
+ return value
+}
+
+/**
+ * Inverse of `decodeLogAttributeValue` for values written back onto the record:
+ * plain strings are JSON-encoded so the ClickHouse sink's `JSONExtractString`
+ * surfaces them; values that are already valid JSON (numbers, booleans, objects,
+ * pre-encoded strings) pass through unchanged.
+ */
+export function encodeLogAttributeValue(value: string): string {
+ try {
+ parseJSON(value)
+ return value
+ } catch {
+ return JSON.stringify(value)
+ }
+}
diff --git a/nodejs/src/logs/metrics-rules/metric-rules.test.ts b/nodejs/src/logs/metrics-rules/metric-rules.test.ts
index c8e807f2d433..25108eed3a7d 100644
--- a/nodejs/src/logs/metrics-rules/metric-rules.test.ts
+++ b/nodejs/src/logs/metrics-rules/metric-rules.test.ts
@@ -118,6 +118,31 @@ describe('metric rules compile + tally', () => {
expect(entries[0]!.labelValues).toEqual([longValue.slice(0, MAX_LABEL_VALUE_LENGTH), '500', ''])
})
+ it('decodes JSON-encoded attribute values for value_attribute sums', () => {
+ // Attribute values arrive JSON-encoded from capture: a numeric string
+ // attribute is `'"7.5"'` on the wire. parseFloat over the raw value is
+ // NaN, so without decoding the record is silently skipped.
+ const rules = compileMetricRules([
+ ruleRow({ value_attribute: 'attributes.duration_ms', filter_group: null }),
+ ])
+ const tallies = createBatchTallies()
+ tallyRecords(rules, [record({ attributes: { duration_ms: '"7.5"' } })], tallies, NOW_MS)
+ const entries = [...tallies.byRule.get('rule-1')!.values()]
+ expect(entries[0]!.count).toBe(1)
+ expect(entries[0]!.sum).toBe(7.5)
+ expect(tallies.valueSkipped).toBe(0)
+ })
+
+ it('decodes JSON-encoded attribute values for group-by labels', () => {
+ const rules = compileMetricRules([
+ ruleRow({ filter_group: null, group_by: ['resource_attributes.k8s.pod'] }),
+ ])
+ const tallies = createBatchTallies()
+ tallyRecords(rules, [record({ resource_attributes: { 'k8s.pod': '"pod-1"' } })], tallies, NOW_MS)
+ const entries = [...tallies.byRule.get('rule-1')!.values()]
+ expect(entries[0]!.labelValues).toEqual(['pod-1'])
+ })
+
it('accumulates records with identical label values into one entry', () => {
const rules = compileMetricRules([ruleRow({ filter_group: null, group_by: ['severity_text'] })])
const tallies = createBatchTallies()
diff --git a/nodejs/src/logs/metrics-rules/tally.ts b/nodejs/src/logs/metrics-rules/tally.ts
index 9c874f58824d..c4a8c505e779 100644
--- a/nodejs/src/logs/metrics-rules/tally.ts
+++ b/nodejs/src/logs/metrics-rules/tally.ts
@@ -1,3 +1,4 @@
+import { decodeLogAttributeValue } from '../attribute-value'
import type { LogRecord } from '../log-record-avro'
import { matchFilterGroup } from '../sampling/filter-group-match'
import type { CompiledMetricRule } from './compile-metric-rules'
@@ -51,14 +52,24 @@ function lookupKey(key: string, record: LogRecord): string | null | undefined {
return record.event_name
}
if (key.startsWith(ATTRIBUTES_PREFIX)) {
- return record.attributes?.[key.slice(ATTRIBUTES_PREFIX.length)]
+ return decodedAttr(record.attributes, key.slice(ATTRIBUTES_PREFIX.length))
}
if (key.startsWith(RESOURCE_ATTRIBUTES_PREFIX)) {
- return record.resource_attributes?.[key.slice(RESOURCE_ATTRIBUTES_PREFIX.length)]
+ return decodedAttr(record.resource_attributes, key.slice(RESOURCE_ATTRIBUTES_PREFIX.length))
}
return undefined
}
+/**
+ * Attribute map values are JSON-encoded on the Avro wire (a string arrives as
+ * `"pod-1"`, quotes included). Decode at the read so labels match what the Logs
+ * UI shows and numeric value attributes parse instead of tallying as NaN.
+ */
+function decodedAttr(map: Record<string, string> | null | undefined, key: string): string | undefined {
+ const raw = map?.[key]
+ return raw === undefined ? undefined : decodeLogAttributeValue(raw)
+}
+
function resolveLabelValue(key: string, record: LogRecord): string {
const value = lookupKey(key, record) ?? ''
return value.length > MAX_LABEL_VALUE_LENGTH ? value.slice(0, MAX_LABEL_VALUE_LENGTH) : value
diff --git a/nodejs/src/logs/sampling/filter-group-match.test.ts b/nodejs/src/logs/sampling/filter-group-match.test.ts
index d65e5acf2095..7a86e425215f 100644
--- a/nodejs/src/logs/sampling/filter-group-match.test.ts
+++ b/nodejs/src/logs/sampling/filter-group-match.test.ts
@@ -184,6 +184,62 @@ describe('matchFilterGroup', () => {
})
})
+ describe('wire-encoded attribute values', () => {
+ // Capture JSON-encodes attribute values onto the Avro wire, so a string
+ // attribute reaches this matcher as `"production"` — quotes included. The
+ // ClickHouse sink and the transformation path both decode before they
+ // compare. The matcher must see the same decoded values: without decoding,
+ // an enabled rule silently never fires, and a negated operator fires on
+ // exactly the lines it was meant to keep.
+ const wireRecord = () =>
+ baseRecord({
+ resource_attributes: { 'deployment.environment': '"production"' },
+ attributes: { 'http.status_code': '500', ratio: '"12.5"' },
+ })
+
+ it.each<[string, string | string[], boolean]>([
+ ['exact', ['production'], true],
+ ['in', ['staging', 'production'], true],
+ // Negation must not fire on the value it names — that would drop
+ // the lines the rule was written to keep.
+ ['is_not', ['production'], false],
+ ['starts_with', 'prod', true],
+ ['ends_with', 'tion', true],
+ ['regex', '^production$', true],
+ ['icontains', 'production', true],
+ ])('%s %j sees the decoded resource attribute → %s', (operator, value, expected) => {
+ const g = group({
+ values: [{ key: 'deployment.environment', type: 'log_resource_attribute', operator, value }],
+ })
+ expect(matchFilterGroup(g, wireRecord())).toBe(expected)
+ })
+
+ it('numeric comparison parses a JSON-encoded numeric string', () => {
+ const g = group({ values: [{ key: 'ratio', type: 'log_attribute', operator: 'gt', value: 10 }] })
+ expect(matchFilterGroup(g, wireRecord())).toBe(true)
+ })
+ it('unquoted JSON numbers pass through unchanged', () => {
+ const g = group({
+ values: [{ key: 'http.status_code', type: 'log_attribute', operator: 'exact', value: '500' }],
+ })
+ expect(matchFilterGroup(g, wireRecord())).toBe(true)
+ })
+ it('severity fallback through the attribute map is decoded', () => {
+ const g = group({ values: [{ key: 'severity_text', operator: 'exact', value: ['error'] }] })
+ expect(matchFilterGroup(g, baseRecord({ attributes: { level: '"error"' } }))).toBe(true)
+ })
+ it('service.name fallback through the resource map is decoded', () => {
+ const g = group({ values: [{ key: 'service.name', operator: 'exact', value: 'api' }] })
+ expect(matchFilterGroup(g, baseRecord({ resource_attributes: { 'service.name': '"api"' } }))).toBe(true)
+ })
+ it('a quoted-but-invalid-JSON value is compared as-is', () => {
+ const g = group({
+ values: [{ key: 'raw', type: 'log_attribute', operator: 'exact', value: '"a"b"' }],
+ })
+ expect(matchFilterGroup(g, baseRecord({ attributes: { raw: '"a"b"' } }))).toBe(true)
+ })
+ })
+
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 {
diff --git a/nodejs/src/logs/sampling/filter-group-match.ts b/nodejs/src/logs/sampling/filter-group-match.ts
index 50181422ada5..f3e6ea8b729b 100644
--- a/nodejs/src/logs/sampling/filter-group-match.ts
+++ b/nodejs/src/logs/sampling/filter-group-match.ts
@@ -10,6 +10,7 @@
* The drop-rule form validates non-empty before submit; this is defense in
* depth at the worker boundary.
*/
+import { decodeLogAttributeValue } from '~/logs/attribute-value'
import type { LogRecord } from '~/logs/log-record-avro'
import { type PropertyFilterLeaf, matchPropertyFilter } from './property-filter-match'
@@ -79,7 +80,7 @@ function lookupRecordValue(filter: PropertyFilterLeaf, record: LogRecord): strin
// (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']
+ return record.service_name ?? decodedAttr(record.resource_attributes, 'service.name')
}
if (key === 'severity_text' || key === 'level' || key === 'severity_level') {
// First-class column wins. Otherwise fall back to attribute storage,
@@ -91,17 +92,32 @@ function lookupRecordValue(filter: PropertyFilterLeaf, record: LogRecord): strin
// attribute names is populated). `severity_level` is the logs UI / HogQL
// alias and the key the drop-rule builder writes; without this branch it
// falls through to the `type: 'log'` body fallback and never matches.
- return record.severity_text ?? record.attributes?.['level'] ?? record.attributes?.['severity_text']
+ return (
+ record.severity_text ??
+ decodedAttr(record.attributes, 'level') ??
+ decodedAttr(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]
+ return decodedAttr(record.resource_attributes, key)
}
if (filter.type === PROPERTY_FILTER_TYPE_LOG_ATTRIBUTE) {
- return record.attributes?.[key]
+ return decodedAttr(record.attributes, key)
}
- return record.attributes?.[key] ?? record.resource_attributes?.[key]
+ return decodedAttr(record.attributes, key) ?? decodedAttr(record.resource_attributes, key)
+}
+
+/**
+ * Attribute map values are JSON-encoded on the Avro wire (a string arrives as
+ * `"production"`, quotes included), while filter values and first-class columns
+ * are plain. Decode at the read so every operator compares like against like —
+ * the same decoding the ClickHouse sink applies before the preview queries it.
+ */
+function decodedAttr(map: Record<string, string> | null | undefined, key: string): string | undefined {
+ const raw = map?.[key]
+ return raw === undefined ? undefined : decodeLogAttributeValue(raw)
}
diff --git a/nodejs/src/logs/transformations/hog-log-exec.ts b/nodejs/src/logs/transformations/hog-log-exec.ts
index ccf80303c83f..f4b7a8c0fa54 100644
--- a/nodejs/src/logs/transformations/hog-log-exec.ts
+++ b/nodejs/src/logs/transformations/hog-log-exec.ts
@@ -3,8 +3,8 @@ import { convertHogToJS } from '@posthog/hogvm'
import type { HogFunctionType } from '~/cdp/types'
import { sanitizeLogMessage } from '~/cdp/utils'
import { execHogImmediate } from '~/cdp/utils/hog-exec'
-import { parseJSON } from '~/common/utils/json-parse'
+import { decodeLogAttributeValue, encodeLogAttributeValue } from '../attribute-value'
import type { LogRecord } from '../log-record-avro'
import { idToHex } from '../metrics-rules/tally'
@@ -75,42 +75,6 @@ export function buildLogRecordGlobals(
}
}
-/**
- * Attribute values arrive JSON-encoded from capture (`any_value_to_json`): a string
- * attribute is stored as `"error"` (with quotes), a number as `123`. The ClickHouse
- * sink decodes string values with `JSONExtractString`, so that is what users see in
- * the Logs UI. Transformations must see the same decoded values — otherwise
- * `record.attributes['level'] == 'error'` silently never matches.
- */
-export function decodeLogAttributeValue(value: string): string {
- if (value.length >= 2 && value.startsWith('"') && value.endsWith('"')) {
- try {
- const parsed = parseJSON(value)
- if (typeof parsed === 'string') {
- return parsed
- }
- } catch {
- // Not valid JSON — treat as a plain string
- }
- }
- return value
-}
-
-/**
- * Inverse of `decodeLogAttributeValue` for values written back onto the record:
- * plain strings are JSON-encoded so the ClickHouse sink's `JSONExtractString`
- * surfaces them; values that are already valid JSON (numbers, booleans, objects,
- * pre-encoded strings) pass through unchanged.
- */
-export function encodeLogAttributeValue(value: string): string {
- try {
- parseJSON(value)
- return value
- } catch {
- return JSON.stringify(value)
- }
-}
-
function decodeAttributeMap(map: Record<string, string> | null | undefined): Record<string, string> {
const out: Record<string, string> = {}
for (const [key, value] of Object.entries(map ?? {})) {
diff --git a/nodejs/src/logs/transformations/logs-transformer.service.ts b/nodejs/src/logs/transformations/logs-transformer.service.ts
index e0bc1b5a3ec0..129ec911c04f 100644
--- a/nodejs/src/logs/transformations/logs-transformer.service.ts
+++ b/nodejs/src/logs/transformations/logs-transformer.service.ts
@@ -9,12 +9,11 @@ import { yieldEventLoopIfNeeded } from '~/common/utils/event-loop-yield'
import { logger } from '~/common/utils/logger'
import { UUIDT } from '~/common/utils/utils'
+import { decodeLogAttributeValue, encodeLogAttributeValue } from '../attribute-value'
import type { LogRecord } from '../log-record-avro'
import {
LogTransformationGlobals,
buildLogRecordGlobals,
- decodeLogAttributeValue,
- encodeLogAttributeValue,
executeLogTransformation,
resolveLogTransformationInputs,
} from './hog-log-exec'