:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
fix(clickhouse): cap null-key path bytes in the event cleaner udf (#109128)
Rory Shanks8329f05c9651
diff --git a/clickhouse-udfs/util/cmd/json_clean_posthog_event_properties_udf/main.go b/clickhouse-udfs/util/cmd/json_clean_posthog_event_properties_udf/main.goindex 2fad8dc2303d..072a216c8249 100644--- a/clickhouse-udfs/util/cmd/json_clean_posthog_event_properties_udf/main.go+++ b/clickhouse-udfs/util/cmd/json_clean_posthog_event_properties_udf/main.go@@ -54,6 +54,9 @@ const (maxJSONArrayDepth = 8unparseablePropertiesKey = "$unparseable_properties"maxRecycledValues = 4096+ // Each null path repeats its ancestor keys, so a small document with a long key and many null+ // children can expand to gigabytes of paths. The budget bounds that expansion per document.+ maxNullKeyBytes = 256 * 1024)var errMaxJSONDepth = errors.New("maximum JSON depth exceeded")@@ -192,6 +195,8 @@ type processor struct {docs [envelopeDocs]bytes.BufferdocNullKeys [envelopeDocs][]stringnullKeySeen map[string]struct{}+ nullKeyBytes int+ nullKeysOver bool}func processLine(rawLine []byte, buf *bytes.Buffer) error {@@ -1512,7 +1517,7 @@ func (p *processor) cleanEventDocument(raw []byte) {p.collectNulls = truedefer func() { p.collectNulls = false }()- p.nullKeys = p.nullKeys[:0]+ p.resetNullKeys()cleaned, err := p.cleanEventProperties(parsed)if err != nil || (p.mutated && exceedsJSONArrayDepth(cleaned, 0)) {if err != nil {@@ -1528,7 +1533,7 @@ func (p *processor) cleanEventDocument(raw []byte) {p.writeValue(permanent, cleaned)p.recycle(cleaned)- p.nullKeys = p.nullKeys[:0]+ p.resetNullKeys()cleanedTemporary, err := p.cleanNode(nil, temporaryObject, 1)if err != nil || (p.mutated && exceedsJSONArrayDepth(cleanedTemporary, 0)) {// The permanent output already quarantines the raw document; do not duplicate it outside the allowlist.@@ -1566,7 +1571,7 @@ func (p *processor) cleanPersonDocument(raw []byte) {p.collectNulls = truedefer func() { p.collectNulls = false }()- p.nullKeys = p.nullKeys[:0]+ p.resetNullKeys()cleaned, err := p.cleanNode(nil, parsed, 1)if err != nil || (p.mutated && exceedsJSONArrayDepth(cleaned, 0)) {if err != nil {@@ -1591,8 +1596,27 @@ func isBlank(raw []byte) bool {return true}+func (p *processor) resetNullKeys() {+ p.nullKeys = p.nullKeys[:0]+ p.nullKeyBytes = 0+ p.nullKeysOver = false+}+// %2E is the json_type_escape_dots_in_keys spelling, which tells the flat key `a.b` from the path `a` > `b`.func (p *processor) recordNullKey(key string) {+ if p.nullKeysOver {+ return+ }+ // Measure the path before building it, so an oversized path is never allocated.+ size := encodedNullKeySegmentLen(key)+ for _, segment := range p.path {+ size += encodedNullKeySegmentLen(segment) + 1+ }+ p.nullKeyBytes += size+ if p.nullKeyBytes > maxNullKeyBytes {+ p.nullKeysOver = true+ return+ }if len(p.path) == 0 && strings.IndexByte(key, '.') < 0 {p.nullKeys = append(p.nullKeys, key)return@@ -1606,6 +1630,10 @@ func (p *processor) recordNullKey(key string) {p.nullKeys = append(p.nullKeys, p.pathBuf.String())}+func encodedNullKeySegmentLen(segment string) int {+ return len(segment) + 2*strings.Count(segment, ".")+}+func writeNullKeySegment(buf *bytes.Buffer, segment string) {for {dot := strings.IndexByte(segment, '.')@@ -1622,7 +1650,8 @@ func writeNullKeySegment(buf *bytes.Buffer, segment string) {// A duplicate key can leave a non-null value under a recorded path after cleaning.// The seen set keeps deduplication linear, because one event can carry thousands of null fields.func (p *processor) finishNullKeys(root *value, out []string) []string {- if len(p.nullKeys) == 0 {+ // A partial list would claim that the unlisted fields were never sent, so record none.+ if p.nullKeysOver || len(p.nullKeys) == 0 {return out}if p.nullKeySeen == nil {diff --git a/clickhouse-udfs/util/cmd/json_clean_posthog_event_properties_udf/main_test.go b/clickhouse-udfs/util/cmd/json_clean_posthog_event_properties_udf/main_test.goindex 344cf7c98f44..59d83431f8ae 100644--- a/clickhouse-udfs/util/cmd/json_clean_posthog_event_properties_udf/main_test.go+++ b/clickhouse-udfs/util/cmd/json_clean_posthog_event_properties_udf/main_test.go@@ -728,6 +728,15 @@ func TestProcessEnvelopeLineSplitsEveryOutput(t *testing.T) {func TestProcessEnvelopeLineNullKeysIgnoreSurvivingValues(t *testing.T) {proc := processor{kind: eventEnvelope}+ var amplified strings.Builder+ amplified.WriteString(`{"keep":1,"` + strings.Repeat("k", 1024) + `":{`)+ for i := range 300 {+ if i > 0 {+ amplified.WriteByte(',')+ }+ fmt.Fprintf(&lified, `"%d":null`, i)+ }+ amplified.WriteString(`}}`)tests := []struct {name, properties stringwant []string@@ -736,6 +745,7 @@ func TestProcessEnvelopeLineNullKeysIgnoreSurvivingValues(t *testing.T) {{"duplicate keeps later value", `{"a":1,"a":null}`, nil},{"dotted key keeps nested null", `{"Account.client_id":"abc","Account":{"client_id":null}}`, []string{"Account.client_id"}},{"duplicate dotted key keeps value", `{"a.b":null,"a.b":1}`, nil},+ {"paths over the byte budget record none", amplified.String(), nil},{"repeated null once", `{"x":null,"x":null}`, []string{"x"}},{"dropped list never recorded", `{"$ai_input":null,"$feature_flag_payload":null,"kept":null}`, []string{"kept"}},{"null flags map", `{"$feature_flags":null}`, []string{"$feature_flags"}},diff --git a/docs/internal/clickhouse-utility-udfs.md b/docs/internal/clickhouse-utility-udfs.mdindex a5b91e520117..d3986cfaa869 100644--- a/docs/internal/clickhouse-utility-udfs.md+++ b/docs/internal/clickhouse-utility-udfs.md@@ -54,7 +54,7 @@ One call per event row for the native JSON events table. It takes the raw event| `temporary_properties_null_keys` | `Array(String)` | The same for `temporary_properties` || `person_properties_null_keys` | `Array(String)` | The same for `person_properties` |-The typed JSON column cannot store `null`, so the cleaners drop null fields. The null-key arrays keep the difference between a property sent as `null` and one never sent. No reader uses them yet: queries, filters and exports treat a null property the same as a missing one, and the arrays keep the data so that a later change can restore the nulls. A path joins the object keys with `.` and writes array positions as numbers: `{"items":[{"a":null}]}` records `items.0.a`. A dot inside one key is written as `%2E`, the spelling `json_type_escape_dots_in_keys` uses, so `{"user":{"plan":null},"a.b":null}` records `user.plan` and `a%2Eb`. A path that still holds a value after duplicate handling is not recorded, so `{"a":null,"a":1}` records nothing. Nulls inside arrays are not object fields; they stay in the array.+The typed JSON column cannot store `null`, so the cleaners drop null fields. The null-key arrays keep the difference between a property sent as `null` and one never sent. No reader uses them yet: queries, filters and exports treat a null property the same as a missing one, and the arrays keep the data so that a later change can restore the nulls. A path joins the object keys with `.` and writes array positions as numbers: `{"items":[{"a":null}]}` records `items.0.a`. A dot inside one key is written as `%2E`, the spelling `json_type_escape_dots_in_keys` uses, so `{"user":{"plan":null},"a.b":null}` records `user.plan` and `a%2Eb`. A path that still holds a value after duplicate handling is not recorded, so `{"a":null,"a":1}` records nothing. Nulls inside arrays are not object fields; they stay in the array. The paths of one document can use at most 256 KiB. If they need more, that document records no null keys, and its cleaned properties are unchanged. A path repeats every key above it, so without this limit a small document with a long key and many null children could produce gigabytes of paths.The function never fails. Blank input becomes `{}`. Malformed, non-object, or too-deep input comes back quarantined under `$unparseable_properties` in that document, with `{}` temporary properties and no null keys, so the calling SQL needs no `isValidJSON` guards. Rows travel as `JSONEachRow` in both directions and the executable pool reads a chunk header before each batch.diff --git a/posthog/user_scripts/json_clean_posthog_event_properties_udf_aarch64 b/posthog/user_scripts/json_clean_posthog_event_properties_udf_aarch64index 62821e37405b..2abcf3b62b8e 100755Binary files a/posthog/user_scripts/json_clean_posthog_event_properties_udf_aarch64 and b/posthog/user_scripts/json_clean_posthog_event_properties_udf_aarch64 differdiff --git a/posthog/user_scripts/json_clean_posthog_event_properties_udf_x86_64 b/posthog/user_scripts/json_clean_posthog_event_properties_udf_x86_64index ca0e63b823d2..e7eb1fb54e0f 100755Binary files a/posthog/user_scripts/json_clean_posthog_event_properties_udf_x86_64 and b/posthog/user_scripts/json_clean_posthog_event_properties_udf_x86_64 differ