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(clickhouse): add utility UDFs to local stack (#91718)

Rory Shanks3f1b1362710a
diff --git a/.github/workflows/ci-clickhouse-util-udfs.yml b/.github/workflows/ci-clickhouse-util-udfs.yml
new file mode 100644
index 000000000000..771edde11b3d
--- /dev/null
+++ b/.github/workflows/ci-clickhouse-util-udfs.yml
@@ -0,0 +1,47 @@
+name: ClickHouse utility UDF tests
+
+on:
+ pull_request:
+ paths:
+ - '.github/workflows/ci-clickhouse-util-udfs.yml'
+ - 'clickhouse-udfs/util/**'
+ - 'docker/clickhouse/user_defined_function.xml'
+ - 'posthog/user_scripts/json_clean_posthog_event_properties_udf*'
+ - 'posthog/user_scripts/json_drop_keys_udf*'
+ - 'posthog/user_scripts/json_strip_empty_strings_and_nulls_udf*'
+
+concurrency:
+ group: ${{ github.workflow }}-${{ github.head_ref || github.ref }}
+ cancel-in-progress: ${{ github.event_name == 'pull_request' }}
+
+permissions:
+ contents: read
+
+jobs:
+ test:
+ name: Test ClickHouse utility UDFs
+ runs-on: ubuntu-24.04
+ timeout-minutes: 10
+ defaults:
+ run:
+ working-directory: clickhouse-udfs/util
+ steps:
+ - uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2
+ with:
+ sparse-checkout: |
+ clickhouse-udfs/util
+ docker/clickhouse/user_defined_function.xml
+ posthog/user_scripts
+ sparse-checkout-cone-mode: false
+ - uses: actions/setup-go@4a3601121dd01d1626a1e23e37211e3254c1c06c # v6.4.0
+ with:
+ go-version-file: clickhouse-udfs/util/go.mod
+ cache: false
+ - name: Build and test
+ run: ./scripts/build.sh
+ - name: Verify checked binaries
+ run: git diff --exit-code -- ../../posthog/user_scripts
+ - name: Smoke benchmarks
+ run: go test -run '^$' -bench=. -benchtime=1x ./...
+ - name: Run ClickHouse integration tests
+ run: ./scripts/integration_test.sh
diff --git a/clickhouse-udfs/util/README.md b/clickhouse-udfs/util/README.md
new file mode 100644
index 000000000000..e7499bb619ed
--- /dev/null
+++ b/clickhouse-udfs/util/README.md
@@ -0,0 +1,16 @@
+# ClickHouse utility UDFs
+
+This module contains the executable ClickHouse UDFs used by PostHog:
+
+- `JSONDropKeys`
+- `JSONCleanPostHogEventProperties`
+- `JSONCleanPostHogPersonProperties`
+- `JSONStripEmptyStringsAndNulls`
+
+Run `./scripts/build.sh` to test the module and build Linux amd64 and arm64 binaries into
+`posthog/user_scripts`.
+
+Run `./scripts/integration_test.sh` to execute the stateless fixtures against ClickHouse.
+
+These utility UDFs keep stable, unversioned names. Regenerating the deployment manifest does not
+change `UDF_VERSION`, which only switches callers between versioned funnel UDF releases.
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.go
new file mode 100644
index 000000000000..fd0ccfbe0d90
--- /dev/null
+++ b/clickhouse-udfs/util/cmd/json_clean_posthog_event_properties_udf/main.go
@@ -0,0 +1,1311 @@
+package main
+
+import (
+ "bufio"
+ "bytes"
+ "errors"
+ "flag"
+ "fmt"
+ "io"
+ "os"
+ "runtime/pprof"
+ "strings"
+ "unsafe"
+)
+
+type normalizationKind byte
+
+const (
+ normalizationNone normalizationKind = iota
+ normalizationStringArray
+ normalizationObjectArray
+)
+
+type propertiesKind byte
+
+const (
+ eventProperties propertiesKind = iota
+ personProperties
+)
+
+type pathRule struct {
+ normalization normalizationKind
+ children map[string]*pathRule
+}
+
+var eventPropertyRules = makeEventPropertyRules()
+
+const (
+ // Leave headroom below ClickHouse's 1024-level JSON parser ceiling so destination casts cannot poison a Kafka block.
+ maxJSONDepth = 1000
+ unparseablePropertiesKey = "$unparseable_properties"
+)
+
+var errMaxJSONDepth = errors.New("maximum JSON depth exceeded")
+
+var droppedEventPropertyKeys = map[string]struct{}{
+ "$ai_input": {},
+ "$ai_output": {},
+ "$ai_output_choices": {},
+ "$ai_input_state": {},
+ "$ai_output_state": {},
+ "$ai_tools": {},
+ "ph_product_tours": {},
+ "$session_recording_remote_config": {},
+ "$product_tours_activated": {},
+ "$product_tours_enabled_server_side": {},
+ "$surveys_activated": {},
+ "$active_feature_flags": {},
+ "$feature_flag_payload": {},
+ "$feature_flag_bootstrapped_payload": {},
+ "$feature_flag_original_payload": {},
+ "$feature_flag_payloads": {},
+ "$set": {},
+ "$set_once": {},
+ "$unset": {},
+ "$transformations_succeeded": {},
+ "$transformations_skipped": {},
+ unparseablePropertiesKey: {},
+}
+
+func makePathRules(paths ...string) *pathRule {
+ root := &pathRule{children: make(map[string]*pathRule, len(paths))}
+ addPathRules(root, normalizationStringArray, paths...)
+ return root
+}
+
+func addPathRules(root *pathRule, normalization normalizationKind, paths ...string) {
+ for _, path := range paths {
+ node := root
+ for {
+ part, rest, ok := strings.Cut(path, ".")
+ child := node.children[part]
+ if child == nil {
+ child = &pathRule{children: make(map[string]*pathRule)}
+ node.children[part] = child
+ }
+ if !ok {
+ child.normalization = normalization
+ break
+ }
+ node = child
+ path = rest
+ }
+ }
+}
+
+func makeEventPropertyRules() *pathRule {
+ root := makePathRules(
+ "$exception_functions",
+ "$exception_sources",
+ "$exception_types",
+ "$exception_values",
+ "$mcp_listed_tool_names",
+ )
+ addPathRules(root, normalizationObjectArray,
+ "$exception_list",
+ )
+ return root
+}
+
+type valueKind byte
+
+const (
+ kindString valueKind = iota
+ kindNumber
+ kindBool
+ kindNull
+ kindObject
+ kindArray
+)
+
+type value struct {
+ kind valueKind
+ s string
+ b bool
+ entries []entry
+ values []*value
+}
+
+type entry struct {
+ key string
+ value *value
+}
+
+type entryInfo struct {
+ firstNonEmpty int
+ last int
+ hasNonEmpty bool
+}
+
+type mergeKey struct {
+ parent *value
+ key string
+}
+
+type processor struct {
+ data []byte
+ pos int
+ kind propertiesKind
+ mutated bool
+ rawSafe bool
+ free []*value
+ info map[string]entryInfo
+ index map[mergeKey]*value
+ stringBuf bytes.Buffer
+ depth int
+}
+
+func processLine(rawLine []byte, buf *bytes.Buffer) error {
+ var proc processor
+ return proc.processLine(rawLine, buf)
+}
+
+func (p *processor) processLine(rawLine []byte, buf *bytes.Buffer) error {
+ p.data = rawLine
+ p.pos = 0
+ p.mutated = false
+ p.rawSafe = true
+ p.depth = 0
+
+ parsed, err := p.parseValue()
+ if err != nil {
+ if errors.Is(err, errMaxJSONDepth) {
+ writeUnparseableProperties(buf, rawLine)
+ return nil
+ }
+ return fmt.Errorf("json parse error: %w", err)
+ }
+ p.skipWS()
+ if p.pos != len(p.data) {
+ p.recycle(parsed)
+ return fmt.Errorf("json parse error: trailing data at byte %d", p.pos)
+ }
+
+ cleaned, err := p.cleanProperties(parsed)
+ if err != nil {
+ p.recycle(parsed)
+ if errors.Is(err, errMaxJSONDepth) {
+ writeUnparseableProperties(buf, rawLine)
+ return nil
+ }
+ return fmt.Errorf("json clean error: %w", err)
+ }
+
+ buf.Reset()
+ buf.Grow(len(rawLine))
+ if !p.mutated && p.rawSafe {
+ buf.Write(rawLine)
+ } else {
+ p.writeValue(buf, cleaned)
+ }
+ p.recycle(cleaned)
+ return nil
+}
+
+func (p *processor) cleanProperties(v *value) (*value, error) {
+ if p.kind == personProperties {
+ return p.cleanNode(nil, v)
+ }
+ return p.cleanEventProperties(v)
+}
+
+func (p *processor) cleanEventProperties(v *value) (*value, error) {
+ if v.kind != kindObject {
+ return p.cleanNode(eventPropertyRules, v)
+ }
+
+ var featureFlags *value
+ hasFeatureProperties := false
+ for _, property := range v.entries {
+ if strings.HasPrefix(property.key, "$feature/") {
+ hasFeatureProperties = true
+ } else if property.key == "$feature_flags" && property.value.kind == kindObject && featureFlags == nil {
+ featureFlags = property.value
+ }
+ }
+ createdFeatureFlags := hasFeatureProperties && featureFlags == nil
+ if createdFeatureFlags {
+ featureFlags = p.newValue(kindObject)
+ }
+
+ writeIdx := 0
+ for _, property := range v.entries {
+ _, drop := droppedEventPropertyKeys[property.key]
+ if drop || hasFeatureProperties && property.key == "$feature_flags" && property.value != featureFlags {
+ p.mutated = true
+ p.recycle(property.value)
+ continue
+ }
+ if name, ok := strings.CutPrefix(property.key, "$feature/"); ok {
+ featureFlags.entries = append(featureFlags.entries, entry{key: name, value: property.value})
+ p.mutated = true
+ continue
+ }
+ v.entries[writeIdx] = property
+ writeIdx++
+ }
+ v.entries = v.entries[:writeIdx]
+ if createdFeatureFlags {
+ v.entries = append(v.entries, entry{key: "$feature_flags", value: featureFlags})
+ }
+ return p.cleanNode(eventPropertyRules, v)
+}
+
+func (p *processor) newValue(kind valueKind) *value {
+ n := len(p.free)
+ if n == 0 {
+ return &value{kind: kind}
+ }
+ v := p.free[n-1]
+ p.free = p.free[:n-1]
+ v.kind = kind
+ v.s = ""
+ v.b = false
+ v.entries = v.entries[:0]
+ v.values = v.values[:0]
+ return v
+}
+
+func (p *processor) recycle(v *value) {
+ if v == nil {
+ return
+ }
+ for _, entry := range v.entries {
+ p.recycle(entry.value)
+ }
+ for _, child := range v.values {
+ p.recycle(child)
+ }
+ v.s = ""
+ v.b = false
+ v.entries = v.entries[:0]
+ v.values = v.values[:0]
+ p.free = append(p.free, v)
+}
+
+func (p *processor) parseValue() (*value, error) {
+ if err := p.enterJSONDepth(); err != nil {
+ return nil, err
+ }
+ defer p.leaveJSONDepth()
+
+ p.skipWS()
+ if p.pos >= len(p.data) {
+ return nil, fmt.Errorf("unexpected end of input")
+ }
+
+ switch p.data[p.pos] {
+ case '{':
+ return p.parseObject()
+ case '[':
+ return p.parseArray()
+ case '"':
+ s, err := p.parseString()
+ if err != nil {
+ return nil, err
+ }
+ v := p.newValue(kindString)
+ v.s = s
+ return v, nil
+ case 't':
+ if !p.consumeLiteral("true") {
+ return nil, fmt.Errorf("invalid literal at byte %d", p.pos)
+ }
+ v := p.newValue(kindBool)
+ v.b = true
+ return v, nil
+ case 'f':
+ if !p.consumeLiteral("false") {
+ return nil, fmt.Errorf("invalid literal at byte %d", p.pos)
+ }
+ return p.newValue(kindBool), nil
+ case 'n':
+ if !p.consumeLiteral("null") {
+ return nil, fmt.Errorf("invalid literal at byte %d", p.pos)
+ }
+ return p.newValue(kindNull), nil
+ default:
+ if p.data[p.pos] == '-' || isDigit(p.data[p.pos]) {
+ num, err := p.parseNumber()
+ if err != nil {
+ return nil, err
+ }
+ v := p.newValue(kindNumber)
+ if shouldStringifyNumber(num) {
+ p.mutated = true
+ v.kind = kindString
+ }
+ v.s = num
+ return v, nil
+ }
+ return nil, fmt.Errorf("unexpected byte %q at byte %d", p.data[p.pos], p.pos)
+ }
+}
+
+func (p *processor) parseObject() (*value, error) {
+ p.pos++
+ obj := p.newValue(kindObject)
+ p.skipWS()
+ if p.consumeByte('}') {
+ return obj, nil
+ }
+
+ for {
+ p.skipWS()
+ if p.pos >= len(p.data) || p.data[p.pos] != '"' {
+ p.recycle(obj)
+ return nil, fmt.Errorf("expected object key at byte %d", p.pos)
+ }
+ key, err := p.parseString()
+ if err != nil {
+ p.recycle(obj)
+ return nil, err
+ }
+ p.skipWS()
+ if !p.consumeByte(':') {
+ p.recycle(obj)
+ return nil, fmt.Errorf("expected ':' at byte %d", p.pos)
+ }
+ child, err := p.parseValue()
+ if err != nil {
+ p.recycle(obj)
+ return nil, err
+ }
+ obj.entries = append(obj.entries, entry{key: key, value: child})
+ p.skipWS()
+ if p.consumeByte('}') {
+ return obj, nil
+ }
+ if !p.consumeByte(',') {
+ p.recycle(obj)
+ return nil, fmt.Errorf("expected ',' or '}' at byte %d", p.pos)
+ }
+ }
+}
+
+func (p *processor) parseArray() (*value, error) {
+ p.pos++
+ arr := p.newValue(kindArray)
+ p.skipWS()
+ if p.consumeByte(']') {
+ return arr, nil
+ }
+
+ for {
+ child, err := p.parseValue()
+ if err != nil {
+ p.recycle(arr)
+ return nil, err
+ }
+ arr.values = append(arr.values, child)
+ p.skipWS()
+ if p.consumeByte(']') {
+ return arr, nil
+ }
+ if !p.consumeByte(',') {
+ p.recycle(arr)
+ return nil, fmt.Errorf("expected ',' or ']' at byte %d", p.pos)
+ }
+ }
+}
+
+func (p *processor) parseString() (string, error) {
+ quote := p.pos
+ p.pos++
+ start := p.pos
+ for p.pos < len(p.data) {
+ c := p.data[p.pos]
+ switch {
+ case c == '"':
+ s := borrowedString(p.data[start:p.pos])
+ p.pos++
+ return s, nil
+ case c == '\\':
+ return p.parseEscapedString(quote)
+ case c < 0x20:
+ return "", fmt.Errorf("invalid control character at byte %d", p.pos)
+ default:
+ p.pos++
+ }
+ }
+ return "", fmt.Errorf("unterminated string at byte %d", quote)
+}
+
+func (p *processor) parseEscapedString(quote int) (string, error) {
+ p.pos = quote + 1
+ p.stringBuf.Reset()
+
+ for p.pos < len(p.data) {
+ c := p.data[p.pos]
+ switch {
+ case c == '"':
+ p.pos++
+ return p.stringBuf.String(), nil
+ case c == '\\':
+ p.pos++
+ if p.pos >= len(p.data) {
+ return "", fmt.Errorf("unterminated escape at byte %d", p.pos)
+ }
+ switch p.data[p.pos] {
+ case '"', '\\', '/':
+ if p.data[p.pos] == '/' {
+ p.rawSafe = false
+ }
+ p.stringBuf.WriteByte(p.data[p.pos])
+ p.pos++
+ case 'b':
+ p.stringBuf.WriteByte('\b')
+ p.pos++
+ case 'f':
+ p.stringBuf.WriteByte('\f')
+ p.pos++
+ case 'n':
+ p.stringBuf.WriteByte('\n')
+ p.pos++
+ case 'r':
+ p.stringBuf.WriteByte('\r')
+ p.pos++
+ case 't':
+ p.stringBuf.WriteByte('\t')
+ p.pos++
+ case 'u':
+ p.rawSafe = false
+ r, err := p.parseUnicodeEscape()
+ if err != nil {
+ return "", err
+ }
+ p.stringBuf.WriteRune(r)
+ default:
+ return "", fmt.Errorf("invalid escape at byte %d", p.pos)
+ }
+ case c < 0x20:
+ return "", fmt.Errorf("invalid control character at byte %d", p.pos)
+ default:
+ p.stringBuf.WriteByte(c)
+ p.pos++
+ }
+ }
+ return "", fmt.Errorf("unterminated string at byte %d", quote)
+}
+
+func (p *processor) parseUnicodeEscape() (rune, error) {
+ if p.pos+5 > len(p.data) {
+ return 0, fmt.Errorf("short unicode escape at byte %d", p.pos)
+ }
+ r, ok := hexRune(p.data[p.pos+1 : p.pos+5])
+ if !ok {
+ return 0, fmt.Errorf("invalid unicode escape at byte %d", p.pos)
+ }
+ p.pos += 5
+
+ if r < 0xd800 || r > 0xdbff {
+ return r, nil
+ }
+ if p.pos+6 > len(p.data) || p.data[p.pos] != '\\' || p.data[p.pos+1] != 'u' {
+ return 0, fmt.Errorf("missing low surrogate at byte %d", p.pos)
+ }
+ low, ok := hexRune(p.data[p.pos+2 : p.pos+6])
+ if !ok || low < 0xdc00 || low > 0xdfff {
+ return 0, fmt.Errorf("invalid low surrogate at byte %d", p.pos)
+ }
+ p.pos += 6
+ return 0x10000 + ((r - 0xd800) << 10) + (low - 0xdc00), nil
+}
+
+func hexRune(b []byte) (rune, bool) {
+ var r rune
+ for _, c := range b {
+ r <<= 4
+ switch {
+ case c >= '0' && c <= '9':
+ r += rune(c - '0')
+ case c >= 'a' && c <= 'f':
+ r += rune(c-'a') + 10
+ case c >= 'A' && c <= 'F':
+ r += rune(c-'A') + 10
+ default:
+ return 0, false
+ }
+ }
+ return r, true
+}
+
+func (p *processor) parseNumber() (string, error) {
+ start := p.pos
+ if p.consumeByte('-') && p.pos >= len(p.data) {
+ return "", fmt.Errorf("short number at byte %d", start)
+ }
+ if p.pos >= len(p.data) {
+ return "", fmt.Errorf("short number at byte %d", start)
+ }
+
+ if p.data[p.pos] == '0' {
+ p.pos++
+ } else if p.data[p.pos] >= '1' && p.data[p.pos] <= '9' {
+ for p.pos < len(p.data) && isDigit(p.data[p.pos]) {
+ p.pos++
+ }
+ } else {
+ return "", fmt.Errorf("invalid number at byte %d", start)
+ }
+
+ if p.pos < len(p.data) && p.data[p.pos] == '.' {
+ p.pos++
+ if p.pos >= len(p.data) || !isDigit(p.data[p.pos]) {
+ return "", fmt.Errorf("invalid fraction at byte %d", p.pos)
+ }
+ for p.pos < len(p.data) && isDigit(p.data[p.pos]) {
+ p.pos++
+ }
+ }
+
+ if p.pos < len(p.data) && (p.data[p.pos] == 'e' || p.data[p.pos] == 'E') {
+ p.pos++
+ if p.pos < len(p.data) && (p.data[p.pos] == '+' || p.data[p.pos] == '-') {
+ p.pos++
+ }
+ if p.pos >= len(p.data) || !isDigit(p.data[p.pos]) {
+ return "", fmt.Errorf("invalid exponent at byte %d", p.pos)
+ }
+ for p.pos < len(p.data) && isDigit(p.data[p.pos]) {
+ p.pos++
+ }
+ }
+
+ return borrowedString(p.data[start:p.pos]), nil
+}
+
+func (p *processor) skipWS() {
+ for p.pos < len(p.data) {
+ switch p.data[p.pos] {
+ case ' ', '\n', '\r', '\t':
+ p.rawSafe = false
+ p.pos++
+ default:
+ return
+ }
+ }
+}
+
+func (p *processor) consumeByte(c byte) bool {
+ if p.pos < len(p.data) && p.data[p.pos] == c {
+ p.pos++
+ return true
+ }
+ return false
+}
+
+func (p *processor) consumeLiteral(s string) bool {
+ if len(p.data)-p.pos < len(s) {
+ return false
+ }
+ for i := 0; i < len(s); i++ {
+ if p.data[p.pos+i] != s[i] {
+ return false
+ }
+ }
+ p.pos += len(s)
+ return true
+}
+
+func (p *processor) cleanNode(pathRules *pathRule, v *value) (*value, error) {
+ if err := p.enterJSONDepth(); err != nil {
+ return nil, err
+ }
+ defer p.leaveJSONDepth()
+
+ switch v.kind {
+ case kindObject:
+ if err := p.cleanObject(pathRules, v); err != nil {
+ return nil, err
+ }
+ case kindArray:
+ for i, child := range v.values {
+ cleaned, err := p.cleanNode(pathRules, child)
+ if err != nil {
+ return nil, err
+ }
+ v.values[i] = cleaned
+ }
+ }
+ return v, nil
+}
+
+func (p *processor) cleanObject(pathRules *pathRule, obj *value) error {
+ expanded, err := p.expandDottedEntries(obj.entries)
+ if err != nil {
+ return err
+ }
+ obj.entries = expanded
+
+ var unparsable bytes.Buffer
+ writeIdx := 0
+ for readIdx, entry := range obj.entries {
+ var childPathRules *pathRule
+ if pathRules != nil {
+ childPathRules = pathRules.children[entry.key]
+ }
+ cleaned, err := p.cleanNode(childPathRules, entry.value)
+ if err != nil {
+ p.retainUnprocessedEntries(obj, writeIdx, readIdx)
+ return err
+ }
+ if childPathRules != nil && childPathRules.normalization != normalizationNone {
+ p.mutated = true
+ original := cleaned
+ cleaned, err = p.normalizeValue(childPathRules.normalization, cleaned)
+ if err != nil {
+ cleaned = original
+ if unparsable.Len() == 0 {
+ unparsable.WriteByte('{')
+ } else {
+ unparsable.WriteByte(',')
+ }
+ writeJSONString(&unparsable, entry.key)
+ unparsable.WriteByte(':')
+ p.writeValue(&unparsable, cleaned)
+ cleaned = p.reuseAsEmptyArray(cleaned)
+ }
+ }
+ if cleaned.kind == kindNull {
+ p.mutated = true
+ p.recycle(cleaned)
+ continue
+ }
+ obj.entries[writeIdx] = entry
+ obj.entries[writeIdx].value = cleaned
+ writeIdx++
+ }
+ obj.entries = obj.entries[:writeIdx]
+ if unparsable.Len() > 0 {
+ unparsable.WriteByte('}')
+ marker := p.newValue(kindString)
+ marker.s = unparsable.String()
+ obj.entries = append(obj.entries, entry{key: unparseablePropertiesKey, value: marker})
+ }
+ p.deduplicateEntries(obj)
+ return nil
+}
+
+func (p *processor) retainUnprocessedEntries(obj *value, writeIdx, readIdx int) {
+ remaining := len(obj.entries) - readIdx
+ copy(obj.entries[writeIdx:writeIdx+remaining], obj.entries[readIdx:])
+ obj.entries = obj.entries[:writeIdx+remaining]
+}
+
+func (p *processor) expandDottedEntries(entries []entry) ([]entry, error) {
+ needsExpand := false
+ for _, entry := range entries {
+ if strings.IndexByte(entry.key, '.') >= 0 {
+ if p.depth+strings.Count(entry.key, ".")+1 > maxJSONDepth {
+ return nil, errMaxJSONDepth
+ }
+ needsExpand = true
+ }
+ }
+ if !needsExpand {
+ return entries, nil
+ }
+ p.mutated = true
+
+ expanded := make([]entry, 0, len(entries))
+ if p.index == nil {
+ p.index = make(map[mergeKey]*value, len(entries))
+ }
+ for key := range p.index {
+ delete(p.index, key)
+ }
+
+ for _, entry := range entries {
+ if strings.IndexByte(entry.key, '.') < 0 {
+ p.appendEntry(nil, &expanded, entry.key, entry.value)
+ } else {
+ p.insertDottedKey(nil, &expanded, entry.key, entry.value)
+ }
+ }
+
+ for key := range p.index {
+ delete(p.index, key)
+ }
+ return expanded, nil
+}
+
+func (p *processor) enterJSONDepth() error {
+ p.depth++
+ if p.depth > maxJSONDepth {
+ p.depth--
+ return errMaxJSONDepth
+ }
+ return nil
+}
+
+func (p *processor) leaveJSONDepth() {
+ p.depth--
+}
+
+func writeUnparseableProperties(buf *bytes.Buffer, raw []byte) {
+ buf.Reset()
+ buf.Grow(len(raw) + len(unparseablePropertiesKey) + 8)
+ buf.WriteByte('{')
+ writeJSONString(buf, unparseablePropertiesKey)
+ buf.WriteByte(':')
+ writeJSONString(buf, borrowedString(raw))
+ buf.WriteByte('}')
+}
+
+func (p *processor) appendEntry(parent *value, entries *[]entry, key string, child *value) {
+ *entries = append(*entries, entry{key: key, value: child})
+ mk := mergeKey{parent: parent, key: key}
+ if child.kind == kindObject {
+ p.index[mk] = child
+ } else {
+ delete(p.index, mk)
+ }
+}
+
+func (p *processor) insertDottedKey(parent *value, entries *[]entry, key string, child *value) {
+ for {
+ dot := strings.IndexByte(key, '.')
+ if dot < 0 {
+ p.appendEntry(parent, entries, key, child)
+ return
+ }
+
+ head := key[:dot]
+ rest := key[dot+1:]
+ mk := mergeKey{parent: parent, key: head}
+ target := p.index[mk]
+ if target == nil {
+ target = p.newValue(kindObject)
+ p.appendEntry(parent, entries, head, target)
+ }
+ parent = target
+ entries = &parent.entries
+ key = rest
+ }
+}
+
+func (p *processor) deduplicateEntries(obj *value) {
+ if len(obj.entries) == 0 {
+ return
+ }
+ if p.info == nil {
+ p.info = make(map[string]entryInfo, len(obj.entries))
+ }
+ for key := range p.info {
+ delete(p.info, key)
+ }
+
+ for i, entry := range obj.entries {
+ info := p.info[entry.key]
+ info.last = i
+ if !info.hasNonEmpty && isNonEmptyValue(entry.value) {
+ info.hasNonEmpty = true
+ info.firstNonEmpty = i
+ }
+ p.info[entry.key] = info
+ }
+
+ writeIdx := 0
+ for i, entry := range obj.entries {
+ info := p.info[entry.key]
+ keep := info.last == i
+ if info.hasNonEmpty {
+ keep = info.firstNonEmpty == i
+ }
+ if keep {
+ obj.entries[writeIdx] = entry
+ writeIdx++
+ } else {
+ p.mutated = true
+ p.recycle(entry.value)
+ }
+ }
+ obj.entries = obj.entries[:writeIdx]
+
+ for key := range p.info {
+ delete(p.info, key)
+ }
+}
+
+func (p *processor) normalizeValue(normalization normalizationKind, v *value) (*value, error) {
+ switch normalization {
+ case normalizationStringArray:
+ return p.coerceStringArray(v)
+ case normalizationObjectArray:
+ return p.coerceObjectArray(v)
+ default:
+ return v, nil
+ }
+}
+
+func (p *processor) coerceObjectArray(v *value) (*value, error) {
+ switch v.kind {
+ case kindArray:
+ for _, child := range v.values {
+ if child.kind != kindObject {
+ return nil, fmt.Errorf("cannot coerce array containing %s to Array(JSON)", valueKindName(child.kind))
+ }
+ }
+ return v, nil
+ case kindObject:
+ arr := p.newValue(kindArray)
+ arr.values = append(arr.values, v)
+ return arr, nil
+ case kindNull:
+ return p.reuseAsEmptyArray(v), nil
+ case kindString:
+ raw := strings.TrimSpace(v.s)
+ if isNullishString(raw) {
+ return p.reuseAsEmptyArray(v), nil
+ }
+ parsed, err := p.parseStringifiedJSON(raw)
+ if err != nil {
+ return nil, err
+ }
+ normalized, err := p.coerceObjectArray(parsed)
+ if err != nil {
+ p.recycle(parsed)
+ return nil, err
+ }
+ p.recycle(v)
+ return normalized, nil
+ default:
+ return nil, fmt.Errorf("cannot coerce %s to Array(JSON)", valueKindName(v.kind))
+ }
+}
+
+func isNullishString(s string) bool {
+ return s == "" || strings.EqualFold(s, "null") || strings.EqualFold(s, "undefined")
+}
+
+func valueKindName(kind valueKind) string {
+ switch kind {
+ case kindString:
+ return "String"
+ case kindNumber:
+ return "Number"
+ case kindBool:
+ return "Bool"
+ case kindNull:
+ return "Null"
+ case kindObject:
+ return "Object"
+ case kindArray:
+ return "Array"
+ default:
+ return "unknown value"
+ }
+}
+
+func (p *processor) coerceStringArray(v *value) (*value, error) {
+ switch v.kind {
+ case kindArray:
+ oldValues := v.values
+ v.values = v.values[:0]
+ for _, child := range oldValues {
+ s := p.nodeString(child)
+ p.recycle(child)
+ str := p.newValue(kindString)
+ str.s = s
+ v.values = append(v.values, str)
+ }
+ return v, nil
+ case kindObject:
+ if len(v.entries) == 0 {
+ return p.reuseAsEmptyArray(v), nil
+ }
+ s := p.nodeString(v)
+ return p.reuseAsStringArray(v, s), nil
+ case kindNull:
+ return p.reuseAsEmptyArray(v), nil
+ case kindString:
+ trimmed := strings.TrimSpace(v.s)
+ if isEmptyArrayString(trimmed) {
+ return p.reuseAsEmptyArray(v), nil
+ }
+ if parsed, ok, err := p.parseStringifiedJSONArray(trimmed); err != nil {
+ return nil, err
+ } else if ok {
+ p.recycle(v)
+ return p.coerceStringArray(parsed)
+ }
+ return p.reuseAsStringArray(v, v.s), nil
+ default:
+ return p.reuseAsStringArray(v, p.nodeString(v)), nil
+ }
+}
+
+func (p *processor) resetValue(v *value, kind valueKind) {
+ for _, entry := range v.entries {
+ p.recycle(entry.value)
+ }
+ for _, child := range v.values {
+ p.recycle(child)
+ }
+ v.kind = kind
+ v.s = ""
+ v.b = false
+ v.entries = v.entries[:0]
+ v.values = v.values[:0]
+}
+
+func (p *processor) reuseAsEmptyArray(v *value) *value {
+ p.resetValue(v, kindArray)
+ return v
+}
+
+func (p *processor) reuseAsStringArray(v *value, s string) *value {
+ p.reuseAsEmptyArray(v)
+ child := p.newValue(kindString)
+ child.s = s
+ v.values = append(v.values, child)
+ return v
+}
+
+func (p *processor) parseStringifiedJSON(raw string) (*value, error) {
+ if raw == "" || (raw[0] != '[' && raw[0] != '{') {
+ return nil, fmt.Errorf("cannot coerce %q to Array(JSON)", raw)
+ }
+
+ oldData, oldPos := p.data, p.pos
+ p.data = borrowedBytes(raw)
+ p.pos = 0
+ parsed, err := p.parseValue()
+ if err != nil {
+ p.data, p.pos = oldData, oldPos
+ return nil, fmt.Errorf("cannot coerce %q to Array(JSON): %w", raw, err)
+ }
+ p.skipWS()
+ if p.pos != len(p.data) {
+ p.recycle(parsed)
+ p.data, p.pos = oldData, oldPos
+ return nil, fmt.Errorf("cannot coerce %q to Array(JSON): trailing data", raw)
+ }
+ cleaned, err := p.cleanNode(nil, parsed)
+ p.data, p.pos = oldData, oldPos
+ if err != nil {
+ p.recycle(parsed)
+ return nil, err
+ }
+ return cleaned, nil
+}
+
+func (p *processor) parseStringifiedJSONArray(raw string) (*value, bool, error) {
+ if raw == "" || raw[0] != '[' {
+ return nil, false, nil
+ }
+
+ oldData, oldPos := p.data, p.pos
+ p.data = borrowedBytes(raw)
+ p.pos = 0
+ parsed, err := p.parseValue()
+ if err != nil {
+ p.data, p.pos = oldData, oldPos
+ return nil, false, nil
+ }
+ p.skipWS()
+ if p.pos != len(p.data) || parsed.kind != kindArray {
+ p.recycle(parsed)
+ p.data, p.pos = oldData, oldPos
+ return nil, false, nil
+ }
+ cleaned, err := p.cleanNode(nil, parsed)
+ p.data, p.pos = oldData, oldPos
+ if err != nil {
+ return nil, false, err
+ }
+ return cleaned, true, nil
+}
+
+func (p *processor) nodeString(v *value) string {
+ switch v.kind {
+ case kindString, kindNumber:
+ return v.s
+ case kindBool:
+ if v.b {
+ return "true"
+ }
+ return "false"
+ case kindNull:
+ return ""
+ default:
+ p.stringBuf.Reset()
+ p.writeValue(&p.stringBuf, v)
+ return p.stringBuf.String()
+ }
+}
+
+func (p *processor) writeValue(buf *bytes.Buffer, v *value) {
+ switch v.kind {
+ case kindString:
+ writeJSONString(buf, v.s)
+ case kindNumber:
+ buf.WriteString(v.s)
+ case kindBool:
+ if v.b {
+ buf.WriteString("true")
+ } else {
+ buf.WriteString("false")
+ }
+ case kindNull:
+ buf.WriteString("null")
+ case kindObject:
+ buf.WriteByte('{')
+ for i, entry := range v.entries {
+ if i > 0 {
+ buf.WriteByte(',')
+ }
+ writeJSONString(buf, entry.key)
+ buf.WriteByte(':')
+ p.writeValue(buf, entry.value)
+ }
+ buf.WriteByte('}')
+ case kindArray:
+ buf.WriteByte('[')
+ for i, child := range v.values {
+ if i > 0 {
+ buf.WriteByte(',')
+ }
+ p.writeValue(buf, child)
+ }
+ buf.WriteByte(']')
+ }
+}
+
+func writeJSONString(buf *bytes.Buffer, s string) {
+ buf.WriteByte('"')
+ start := 0
+ for i := 0; i < len(s); i++ {
+ ch := s[i]
+ if ch >= 0x20 && ch != '\\' && ch != '"' {
+ continue
+ }
+ if start < i {
+ buf.WriteString(s[start:i])
+ }
+ switch ch {
+ case '\\', '"':
+ buf.WriteByte('\\')
+ buf.WriteByte(ch)
+ case '\b':
+ buf.WriteString("\\b")
+ case '\f':
+ buf.WriteString("\\f")
+ case '\n':
+ buf.WriteString("\\n")
+ case '\r':
+ buf.WriteString("\\r")
+ case '\t':
+ buf.WriteString("\\t")
+ default:
+ buf.WriteString("\\u00")
+ const hex = "0123456789abcdef"
+ buf.WriteByte(hex[ch>>4])
+ buf.WriteByte(hex[ch&0x0f])
+ }
+ start = i + 1
+ }
+ if start < len(s) {
+ buf.WriteString(s[start:])
+ }
+ buf.WriteByte('"')
+}
+
+func isNonEmptyValue(v *value) bool {
+ switch v.kind {
+ case kindNull:
+ return false
+ case kindString:
+ return v.s != ""
+ case kindArray:
+ return len(v.values) > 0
+ case kindObject:
+ return len(v.entries) > 0
+ default:
+ return true
+ }
+}
+
+func isEmptyArrayString(s string) bool {
+ switch len(s) {
+ case 0:
+ return true
+ case 4:
+ return strings.EqualFold(s, "null")
+ case 9:
+ return strings.EqualFold(s, "undefined")
+ default:
+ return false
+ }
+}
+
+func shouldStringifyNumber(num string) bool {
+ if len(num) == 0 {
+ return false
+ }
+
+ for i := 0; i < len(num); i++ {
+ switch num[i] {
+ case '.', 'e', 'E':
+ return false
+ }
+ }
+
+ start := 0
+ neg := num[0] == '-'
+ if neg {
+ start = 1
+ }
+ for start < len(num) && num[start] == '0' {
+ start++
+ }
+
+ digitLen := len(num) - start
+ if digitLen == 0 {
+ return false
+ }
+ if digitLen > 20 {
+ return true
+ }
+ if neg {
+ if digitLen < 19 {
+ return false
+ }
+ if digitLen > 19 {
+ return true
+ }
+ return num[start:] > "9223372036854775808"
+ }
+ if digitLen < 20 {
+ return false
+ }
+ return num[start:] > "18446744073709551615"
+}
+
+func isDigit(c byte) bool {
+ return c >= '0' && c <= '9'
+}
+
+// ponytail: borrowed strings never leave processLine; copy here if values escape.
+func borrowedString(b []byte) string {
+ if len(b) == 0 {
+ return ""
+ }
+ // nosemgrep: go.lang.security.audit.unsafe.use-of-unsafe-block -- b owns the bytes for every use of the borrowed string.
+ return unsafe.String(unsafe.SliceData(b), len(b))
+}
+
+func borrowedBytes(s string) []byte {
+ if len(s) == 0 {
+ return nil
+ }
+ // nosemgrep: go.lang.security.audit.unsafe.use-of-unsafe-block -- callers only read the slice while s remains live.
+ return unsafe.Slice(unsafe.StringData(s), len(s))
+}
+
+func run(input io.Reader, output io.Writer, kind propertiesKind) error {
+ reader := bufio.NewReaderSize(input, 4*1024*1024)
+ writer := bufio.NewWriterSize(output, 4*1024*1024)
+ buf := bytes.NewBuffer(make([]byte, 0, 64*1024))
+ proc := processor{kind: kind}
+
+ for {
+ line, err := reader.ReadBytes('\n')
+ if err != nil && err != io.EOF {
+ return fmt.Errorf("stdin read error: %w", err)
+ }
+ if len(line) == 0 && err == io.EOF {
+ return writer.Flush()
+ }
+
+ hadNewline := len(line) > 0 && line[len(line)-1] == '\n'
+ line = bytes.TrimSuffix(line, []byte{'\n'})
+ line = bytes.TrimSuffix(line, []byte{'\r'})
+ if processErr := proc.processLine(line, buf); processErr != nil {
+ return fmt.Errorf("line processing error: %w", processErr)
+ }
+ if _, writeErr := writer.Write(buf.Bytes()); writeErr != nil {
+ return fmt.Errorf("stdout write error: %w", writeErr)
+ }
+ if hadNewline {
+ if writeErr := writer.WriteByte('\n'); writeErr != nil {
+ return fmt.Errorf("stdout write error: %w", writeErr)
+ }
+ }
+ if err == io.EOF {
+ return writer.Flush()
+ }
+ }
+}
+
+func runChunked(input io.Reader, output io.Writer, kind propertiesKind) error {
+ reader := bufio.NewReaderSize(input, 4*1024*1024)
+ writer := bufio.NewWriterSize(output, 4*1024*1024)
+ buf := bytes.NewBuffer(make([]byte, 0, 64*1024))
+ proc := processor{kind: kind}
+
+ for {
+ var rows int
+ if _, err := fmt.Fscanln(reader, &rows); err == io.EOF {
+ return writer.Flush()
+ } else if err != nil {
+ return fmt.Errorf("chunk header read error: %w", err)
+ }
+ for range rows {
+ line, err := reader.ReadBytes('\n')
+ if err != nil {
+ return fmt.Errorf("stdin read error: %w", err)
+ }
+ line = bytes.TrimSuffix(line, []byte{'\n'})
+ line = bytes.TrimSuffix(line, []byte{'\r'})
+ if processErr := proc.processLine(line, buf); processErr != nil {
+ return fmt.Errorf("line processing error: %w", processErr)
+ }
+ if _, writeErr := writer.Write(append(buf.Bytes(), '\n')); writeErr != nil {
+ return fmt.Errorf("stdout write error: %w", writeErr)
+ }
+ }
+ if err := writer.Flush(); err != nil {
+ return fmt.Errorf("stdout flush error: %w", err)
+ }
+ }
+}
+
+func main() {
+ cpuProfile := flag.String("cpuprofile", "", "write CPU profile to file")
+ chunked := flag.Bool("chunked", false, "read a row-count header before each input chunk")
+ cleanPersonProperties := flag.Bool("person-properties", false, "clean person properties without event-specific transformations")
+ flag.Parse()
+
+ if *cpuProfile != "" {
+ f, err := os.Create(*cpuProfile)
+ if err != nil {
+ fmt.Fprintf(os.Stderr, "cpuprofile create error: %v\n", err)
+ os.Exit(1)
+ }
+ if err := pprof.StartCPUProfile(f); err != nil {
+ _ = f.Close()
+ fmt.Fprintf(os.Stderr, "cpuprofile start error: %v\n", err)
+ os.Exit(1)
+ }
+ defer func() {
+ pprof.StopCPUProfile()
+ _ = f.Close()
+ }()
+ }
+
+ runner := run
+ if *chunked {
+ runner = runChunked
+ }
+ kind := eventProperties
+ if *cleanPersonProperties {
+ kind = personProperties
+ }
+ if err := runner(os.Stdin, os.Stdout, kind); err != nil {
+ fmt.Fprintln(os.Stderr, err)
+ os.Exit(1)
+ }
+}
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.go
new file mode 100644
index 000000000000..8de651923466
--- /dev/null
+++ b/clickhouse-udfs/util/cmd/json_clean_posthog_event_properties_udf/main_test.go
@@ -0,0 +1,331 @@
+package main
+
+import (
+ "bytes"
+ "fmt"
+ "os"
+ "path/filepath"
+ "strings"
+ "testing"
+)
+
+func TestProcessLineCleansEventProperties(t *testing.T) {
+ input := []byte(`{"$active_feature_flags":"undefined","$active_feature_flags":["beta",42,null,{"a.b":1}],"Account.client_id":"abc","Account":{"client_id":null},"huge":18446744073709551616,"max_uint":18446744073709551615,"too_negative":-9223372036854775809,"min_int":-9223372036854775808,"null_field":null,"dupe":"","dupe":"kept","emptydupe":"","emptydupe":null}`)
+ want := `{"Account":{"client_id":"abc"},"huge":"18446744073709551616","max_uint":18446744073709551615,"too_negative":"-9223372036854775809","min_int":-9223372036854775808,"dupe":"kept","emptydupe":""}`
+
+ var got bytes.Buffer
+ if err := processLine(input, &got); err != nil {
+ t.Fatal(err)
+ }
+ if got.String() != want {
+ t.Fatalf("processLine() = %s, want %s", got.String(), want)
+ }
+}
+
+func TestProcessLineDropsHighVolumeEventProperties(t *testing.T) {
+ input := []byte(`{"$ai_input":"input","$ai_output":"output","$ai_output_choices":["choice"],"$ai_input_state":{"state":1},"$ai_output_state":{"state":2},"$ai_tools":["tool"],"ph_product_tours":true,"$session_recording_remote_config":{"enabled":true},"$product_tours_activated":true,"$product_tours_enabled_server_side":true,"$surveys_activated":true,"$active_feature_flags":["flag"],"$feature_flag_payload":"payload","$feature_flag_bootstrapped_payload":true,"$feature_flag_original_payload":{"key":"value"},"$feature_flag_payloads":{"flag":"payload"},"$set":{"name":"value"},"$set_once":{"initial":"value"},"$unset":["old_property"],"$transformations_succeeded":["one"],"$transformations_skipped":["two"],"kept":"value"}`)
+ want := `{"kept":"value"}`
+
+ var got bytes.Buffer
+ if err := processLine(input, &got); err != nil {
+ t.Fatal(err)
+ }
+ if got.String() != want {
+ t.Fatalf("processLine() = %s, want %s", got.String(), want)
+ }
+}
+
+func TestProcessLinePreservesPersonProperties(t *testing.T) {
+ input := []byte(`{"$active_feature_flags":["flag"],"$feature/test":true,"$set":{"name":"value"},"nested.key":"value","drop":null}`)
+ want := `{"$active_feature_flags":["flag"],"$feature/test":true,"$set":{"name":"value"},"nested":{"key":"value"}}`
+
+ var got bytes.Buffer
+ proc := processor{kind: personProperties}
+ if err := proc.processLine(input, &got); err != nil {
+ t.Fatal(err)
+ }
+ if got.String() != want {
+ t.Fatalf("processLine() = %s, want %s", got.String(), want)
+ }
+}
+
+func TestProcessLineGroupsFeaturePropertiesAndPreservesExistingFlagValues(t *testing.T) {
+ input := []byte(`{"$feature/first-flag":"fresh","$feature/number":42,"$feature/enabled":true,"$feature/config":{"nested.value":"dropped"},"$feature_flags":"invalid","$feature_flags":{"existing":"kept","first-flag":"existing"},"$feature_flag_payloads":{"flag":"dropped"},"other":"value"}`)
+ want := `{"$feature_flags":{"existing":"kept","first-flag":"existing","number":42,"enabled":true,"config":{"nested":{"value":"dropped"}}},"other":"value"}`
+
+ var got bytes.Buffer
+ if err := processLine(input, &got); err != nil {
+ t.Fatal(err)
+ }
+ if got.String() != want {
+ t.Fatalf("processLine() = %s, want %s", got.String(), want)
+ }
+}
+
+func TestEventPropertyRulesCoverComplexSchemaPaths(t *testing.T) {
+ tests := map[normalizationKind][]string{
+ normalizationStringArray: {
+ "$exception_functions",
+ "$exception_sources",
+ "$exception_types",
+ "$exception_values",
+ "$mcp_listed_tool_names",
+ },
+ normalizationObjectArray: {
+ "$exception_list",
+ },
+ }
+
+ for want, paths := range tests {
+ for _, path := range paths {
+ rule := eventPropertyRules.children[path]
+ if rule == nil {
+ t.Errorf("missing normalization rule for %s", path)
+ continue
+ }
+ if rule.normalization != want {
+ t.Errorf("normalization rule for %s = %v, want %v", path, rule.normalization, want)
+ }
+ }
+ }
+}
+
+func TestProcessLinePreservesScalarPropertiesAndNormalizesComplexProperties(t *testing.T) {
+ input := []byte(`{"$agent_turn":"42.0","$ai_total_cost_usd":{"currency":"USD"},"$is_identified":"yes","created_by_system":"scheduler","$mcp_listed_tool_names":"search","$exception_list":"{\"type\":\"TypeError\",\"value\":null}"}`)
+ want := `{"$agent_turn":"42.0","$ai_total_cost_usd":{"currency":"USD"},"$is_identified":"yes","created_by_system":"scheduler","$mcp_listed_tool_names":["search"],"$exception_list":[{"type":"TypeError"}]}`
+
+ var got bytes.Buffer
+ if err := processLine(input, &got); err != nil {
+ t.Fatal(err)
+ }
+ if got.String() != want {
+ t.Fatalf("processLine() = %s, want %s", got.String(), want)
+ }
+}
+
+func TestProcessLineQuarantinesInvalidExceptionList(t *testing.T) {
+ tests := map[string]string{
+ `{"$unparseable_properties":"spoofed","$exception_list":"[redacted]","kept":"value"}`: `{"$exception_list":[],"kept":"value","$unparseable_properties":"{\"$exception_list\":\"[redacted]\"}"}`,
+ `{"$exception_list":[1]}`: `{"$exception_list":[],"$unparseable_properties":"{\"$exception_list\":[1]}"}`,
+ `{"$exception_list":true}`: `{"$exception_list":[],"$unparseable_properties":"{\"$exception_list\":true}"}`,
+ }
+
+ for input, want := range tests {
+ var got bytes.Buffer
+ if err := processLine([]byte(input), &got); err != nil {
+ t.Fatalf("processLine(%s) returned error: %v", input, err)
+ }
+ if got.String() != want {
+ t.Fatalf("processLine(%s) = %s, want %s", input, got.String(), want)
+ }
+ }
+}
+
+func TestProcessLineQuarantinesExcessiveDepth(t *testing.T) {
+ tests := map[string]string{
+ "nested JSON": strings.Repeat(`{"x":`, maxJSONDepth) + `1` + strings.Repeat(`}`, maxJSONDepth),
+ "dotted key": `{"` + strings.Repeat("x.", maxJSONDepth) + `x":1}`,
+ }
+
+ for name, input := range tests {
+ t.Run(name, func(t *testing.T) {
+ var got bytes.Buffer
+ if err := processLine([]byte(input), &got); err != nil {
+ t.Fatal(err)
+ }
+ want := fmt.Sprintf(`{"$unparseable_properties":%q}`, input)
+ if got.String() != want {
+ t.Fatalf("processLine() = %s, want %s", got.String(), want)
+ }
+ })
+ }
+}
+
+func TestProcessLineParsesStringifiedArrayPath(t *testing.T) {
+ input := []byte(`{"$exception_types":"[\"TypeError\",7,null,{\"x.y\":\"z\"}]"}`)
+ want := `{"$exception_types":["TypeError","7","","{\"x\":{\"y\":\"z\"}}"]}`
+
+ var got bytes.Buffer
+ if err := processLine(input, &got); err != nil {
+ t.Fatal(err)
+ }
+ if got.String() != want {
+ t.Fatalf("processLine() = %s, want %s", got.String(), want)
+ }
+}
+
+func TestProcessLineCoercesArrayPathScalars(t *testing.T) {
+ tests := map[string]string{
+ `{"$exception_sources":"undefined"}`: `{"$exception_sources":[]}`,
+ `{"$exception_sources":"worker"}`: `{"$exception_sources":["worker"]}`,
+ `{"$exception_sources":false}`: `{"$exception_sources":["false"]}`,
+ `{"$exception_sources":{}}`: `{"$exception_sources":[]}`,
+ `{"$exception_sources":{"worker.id":3}}`: `{"$exception_sources":["{\"worker\":{\"id\":3}}"]}`,
+ `{"nested":{"$exception_sources":"worker"}}`: `{"nested":{"$exception_sources":"worker"}}`,
+ }
+
+ for input, want := range tests {
+ var got bytes.Buffer
+ if err := processLine([]byte(input), &got); err != nil {
+ t.Fatalf("processLine(%s) returned error: %v", input, err)
+ }
+ if got.String() != want {
+ t.Fatalf("processLine(%s) = %s, want %s", input, got.String(), want)
+ }
+ }
+}
+
+func TestCleanNodeMatchesNestedArrayStringPath(t *testing.T) {
+ input := []byte(`{"outer":[{"$exception_sources":"undefined"},{"$exception_sources":"worker"}],"nested":{"$exception_sources":"worker"}}`)
+ want := `{"outer":[{"$exception_sources":[]},{"$exception_sources":["worker"]}],"nested":{"$exception_sources":"worker"}}`
+
+ var proc processor
+ proc.data = input
+ parsed, err := proc.parseValue()
+ if err != nil {
+ t.Fatal(err)
+ }
+ cleaned, err := proc.cleanNode(makePathRules("outer.$exception_sources"), parsed)
+ if err != nil {
+ t.Fatal(err)
+ }
+ defer proc.recycle(cleaned)
+
+ var got bytes.Buffer
+ proc.writeValue(&got, cleaned)
+ if got.String() != want {
+ t.Fatalf("cleanNode() = %s, want %s", got.String(), want)
+ }
+}
+
+func TestProcessLineHandlesEscapedDottedKeysAndStrings(t *testing.T) {
+ input := []byte("{\"a\\u002eb\":\"line\\nquote\\\"\",\"emoji\":\"\\ud83d\\ude00\"}")
+ want := "{\"a\":{\"b\":\"line\\nquote\\\"\"},\"emoji\":\"\U0001F600\"}"
+
+ var got bytes.Buffer
+ if err := processLine(input, &got); err != nil {
+ t.Fatal(err)
+ }
+ if got.String() != want {
+ t.Fatalf("processLine() = %s, want %s", got.String(), want)
+ }
+}
+
+func TestProcessLineErrorsOnMalformedJSON(t *testing.T) {
+ var got bytes.Buffer
+ if err := processLine([]byte(`{"broken"`), &got); err == nil {
+ t.Fatal("expected error for malformed JSON, got nil")
+ }
+}
+
+func TestRunChunked(t *testing.T) {
+ input := "2\n{\"drop\":null,\"keep\":1}\n{\"$feature/enabled\":true}\n1\n{\"drop\":null}\n"
+ want := "{\"keep\":1}\n{\"$feature_flags\":{\"enabled\":true}}\n{}\n"
+ var output bytes.Buffer
+
+ if err := runChunked(strings.NewReader(input), &output, eventProperties); err != nil {
+ t.Fatal(err)
+ }
+ if output.String() != want {
+ t.Fatalf("runChunked() = %q, want %q", output.String(), want)
+ }
+}
+
+func TestShouldStringifyNumber(t *testing.T) {
+ tests := map[string]bool{
+ "18446744073709551615": false,
+ "18446744073709551616": true,
+ "9223372036854775808": false,
+ "-9223372036854775808": false,
+ "-9223372036854775809": true,
+ "1.8446744073709552e19": false,
+ "42": false,
+ }
+
+ for input, want := range tests {
+ if got := shouldStringifyNumber(input); got != want {
+ t.Fatalf("shouldStringifyNumber(%q) = %v, want %v", input, got, want)
+ }
+ }
+}
+
+func BenchmarkProcessLine(b *testing.B) {
+ input := []byte(`{"$active_feature_flags":"[\"beta\", \"new-ui\"]","$exception_types":"undefined","Account.client_id":"client_123","huge":18446744073709551616,"small":123,"dotted.key":"value","duplicate":"","duplicate":"kept","null_field":null,"nested":{"a.b":{"c":1}}}`)
+ var buf bytes.Buffer
+ proc := processor{}
+
+ b.ReportAllocs()
+ b.SetBytes(int64(len(input)))
+
+ for i := 0; i < b.N; i++ {
+ if err := proc.processLine(input, &buf); err != nil {
+ b.Fatal(err)
+ }
+ }
+}
+
+func BenchmarkProcessFixture(b *testing.B) {
+ lines, totalBytes := loadBenchmarkLines(b)
+ var buf bytes.Buffer
+ proc := processor{}
+
+ b.ReportAllocs()
+ b.SetBytes(int64(totalBytes))
+ b.ResetTimer()
+
+ for i := 0; i < b.N; i++ {
+ for _, line := range lines {
+ if err := proc.processLine(line, &buf); err != nil {
+ b.Fatal(err)
+ }
+ }
+ }
+}
+
+func loadBenchmarkLines(b *testing.B) ([][]byte, int) {
+ b.Helper()
+
+ path := os.Getenv("BENCH_FILE")
+ if path == "" {
+ return generatedBenchmarkLines()
+ } else if !filepath.IsAbs(path) {
+ path = filepath.Join("../..", path)
+ }
+
+ data, err := os.ReadFile(path)
+ if err != nil {
+ b.Fatal(err)
+ }
+
+ rawLines := bytes.Split(bytes.TrimSpace(data), []byte("\n"))
+ lines := make([][]byte, 0, len(rawLines))
+ totalBytes := 0
+ for _, line := range rawLines {
+ line = bytes.TrimSpace(line)
+ if len(line) == 0 {
+ continue
+ }
+ lines = append(lines, line)
+ totalBytes += len(line)
+ }
+ if len(lines) == 0 {
+ b.Fatalf("benchmark file has no JSON lines: %s", path)
+ }
+ return lines, totalBytes
+}
+
+func generatedBenchmarkLines() ([][]byte, int) {
+ lines := make([][]byte, 0, 256)
+ totalBytes := 0
+ for i := 0; i < 256; i++ {
+ line := []byte(fmt.Sprintf(
+ `{"$active_feature_flags":"[\"beta-%d\"]","$exception_types":"undefined","Account.client_id":"client_%d","huge":18446744073709551616,"duplicate":"","duplicate":"kept","nested":{"a.b":{"c":%d}}}`,
+ i,
+ i,
+ i,
+ ))
+ lines = append(lines, line)
+ totalBytes += len(line)
+ }
+ return lines, totalBytes
+}
diff --git a/clickhouse-udfs/util/cmd/json_drop_keys_udf/main.go b/clickhouse-udfs/util/cmd/json_drop_keys_udf/main.go
new file mode 100644
index 000000000000..2dba8d147753
--- /dev/null
+++ b/clickhouse-udfs/util/cmd/json_drop_keys_udf/main.go
@@ -0,0 +1,564 @@
+package main
+
+import (
+ "bufio"
+ "bytes"
+ "flag"
+ "fmt"
+ "io"
+ "log"
+ "os"
+ "runtime/pprof"
+ "strings"
+ "sync"
+
+ "github.com/valyala/fastjson"
+)
+
+type emptyT struct{}
+
+// a struct for hierarchical keys, e.g. if someone wants to drop "properties.foo.bar", works only for objects
+type jsonKey map[string]jsonKey
+
+type node interface {
+ Write(*bytes.Buffer)
+ DropKeys(keys jsonKey) node
+}
+
+type valueKind int
+
+const (
+ kindString valueKind = iota
+ kindNumber
+ kindBool
+ kindNull
+)
+
+type valueNode struct {
+ kind valueKind
+ str string
+ num string
+ b bool
+}
+
+func (v *valueNode) Write(buf *bytes.Buffer) {
+ switch v.kind {
+ case kindString:
+ writeJSONString(buf, v.str)
+ case kindNumber:
+ buf.WriteString(v.num)
+ case kindBool:
+ if v.b {
+ buf.WriteString("true")
+ } else {
+ buf.WriteString("false")
+ }
+ case kindNull:
+ buf.WriteString("null")
+ }
+}
+
+func (v *valueNode) DropKeys(jsonKey) node {
+ return v
+}
+
+type objectEntry struct {
+ key string
+ value node
+}
+
+type objectNode struct {
+ entries []objectEntry
+}
+
+func (o *objectNode) Write(buf *bytes.Buffer) {
+ buf.WriteByte('{')
+ for i, entry := range o.entries {
+ if i > 0 {
+ buf.WriteByte(',')
+ }
+ writeJSONString(buf, entry.key)
+ buf.WriteByte(':')
+ entry.value.Write(buf)
+ }
+ buf.WriteByte('}')
+}
+
+func (o *objectNode) DropKeys(keysToDrop jsonKey) node {
+ if len(o.entries) == 0 {
+ return o
+ }
+
+ o.entries = expandDottedEntries(o.entries)
+
+ for i, e := range o.entries {
+ if val, ok := keysToDrop[e.key]; ok && val != nil {
+ o.entries[i].value = o.entries[i].value.DropKeys(val)
+ }
+ }
+
+ writeIdx := 0
+ for _, entry := range o.entries {
+ if val, toDrop := keysToDrop[entry.key]; toDrop && val == nil {
+ continue
+ }
+ o.entries[writeIdx] = entry
+ writeIdx++
+ }
+ o.entries = o.entries[:writeIdx]
+
+ return o
+}
+
+type mergeKey struct {
+ parent *objectNode
+ key string
+}
+
+var dottedIndexPool = sync.Pool{
+ New: func() interface{} {
+ return make(map[mergeKey]*objectNode)
+ },
+}
+
+func expandDottedEntries(entries []objectEntry) []objectEntry {
+ needsExpand := false
+ for _, entry := range entries {
+ if indexByte(entry.key, '.') >= 0 {
+ needsExpand = true
+ break
+ }
+ }
+ if !needsExpand {
+ return entries
+ }
+
+ expanded := make([]objectEntry, 0, len(entries))
+ index := dottedIndexPool.Get().(map[mergeKey]*objectNode)
+ for _, entry := range entries {
+ if indexByte(entry.key, '.') < 0 {
+ appendEntry(nil, &expanded, entry.key, entry.value, index)
+ continue
+ }
+ insertDottedKey(nil, &expanded, entry.key, entry.value, index)
+ }
+
+ for key := range index {
+ delete(index, key)
+ }
+ dottedIndexPool.Put(index)
+
+ return expanded
+}
+
+func appendEntry(parent *objectNode, entries *[]objectEntry, key string, value node, index map[mergeKey]*objectNode) {
+ *entries = append(*entries, objectEntry{key: key, value: value})
+ mk := mergeKey{parent: parent, key: key}
+ if obj, ok := value.(*objectNode); ok {
+ index[mk] = obj
+ } else {
+ delete(index, mk)
+ }
+}
+
+func insertDottedKey(parent *objectNode, entries *[]objectEntry, key string, value node, index map[mergeKey]*objectNode) {
+ for {
+ dot := indexByte(key, '.')
+ if dot < 0 {
+ appendEntry(parent, entries, key, value, index)
+ return
+ }
+ head := key[:dot]
+ rest := key[dot+1:]
+ mk := mergeKey{parent: parent, key: head}
+ target := index[mk]
+ if target == nil {
+ target = objectNodePool.Get().(*objectNode)
+ target.entries = target.entries[:0]
+ appendEntry(parent, entries, head, target, index)
+ }
+ parent = target
+ entries = &parent.entries
+ key = rest
+ }
+}
+
+func indexByte(s string, c byte) int {
+ for i := 0; i < len(s); i++ {
+ if s[i] == c {
+ return i
+ }
+ }
+ return -1
+}
+
+type arrayNode struct {
+ values []node
+}
+
+func (a *arrayNode) Write(buf *bytes.Buffer) {
+ buf.WriteByte('[')
+ for i, value := range a.values {
+ if i > 0 {
+ buf.WriteByte(',')
+ }
+ value.Write(buf)
+ }
+ buf.WriteByte(']')
+}
+
+func (a *arrayNode) DropKeys(keys jsonKey) node {
+ for i := range a.values {
+ a.values[i] = a.values[i].DropKeys(keys)
+ }
+ return a
+}
+
+func writeJSONString(buf *bytes.Buffer, s string) {
+ buf.WriteByte('"')
+ start := 0
+ for i := 0; i < len(s); i++ {
+ ch := s[i]
+ if ch >= 0x20 && ch != '\\' && ch != '"' {
+ continue
+ }
+ if start < i {
+ buf.WriteString(s[start:i])
+ }
+ switch ch {
+ case '\\', '"':
+ buf.WriteByte('\\')
+ buf.WriteByte(ch)
+ case '\b':
+ buf.WriteString("\\b")
+ case '\f':
+ buf.WriteString("\\f")
+ case '\n':
+ buf.WriteString("\\n")
+ case '\r':
+ buf.WriteString("\\r")
+ case '\t':
+ buf.WriteString("\\t")
+ default:
+ buf.WriteString("\\u00")
+ const hex = "0123456789abcdef"
+ buf.WriteByte(hex[ch>>4])
+ buf.WriteByte(hex[ch&0x0f])
+ }
+ start = i + 1
+ }
+ if start < len(s) {
+ buf.WriteString(s[start:])
+ }
+ buf.WriteByte('"')
+}
+
+var parserPool = sync.Pool{
+ New: func() interface{} {
+ return &fastjson.Parser{}
+ },
+}
+
+var valueNodePool = sync.Pool{
+ New: func() interface{} {
+ return &valueNode{}
+ },
+}
+
+var objectNodePool = sync.Pool{
+ New: func() interface{} {
+ return &objectNode{}
+ },
+}
+
+var arrayNodePool = sync.Pool{
+ New: func() interface{} {
+ return &arrayNode{}
+ },
+}
+
+func recycleNode(n node) {
+ switch v := n.(type) {
+ case *valueNode:
+ v.str = ""
+ v.num = ""
+ valueNodePool.Put(v)
+ case *objectNode:
+ for _, entry := range v.entries {
+ recycleNode(entry.value)
+ }
+ v.entries = v.entries[:0]
+ objectNodePool.Put(v)
+ case *arrayNode:
+ for _, child := range v.values {
+ recycleNode(child)
+ }
+ v.values = v.values[:0]
+ arrayNodePool.Put(v)
+ }
+}
+
+func convertFastJSON(value *fastjson.Value) (node, error) {
+ switch value.Type() {
+ case fastjson.TypeObject:
+ obj, err := value.Object()
+ if err != nil {
+ return nil, err
+ }
+
+ objNode := objectNodePool.Get().(*objectNode)
+ if cap(objNode.entries) >= obj.Len() {
+ objNode.entries = objNode.entries[:0]
+ } else {
+ objNode.entries = make([]objectEntry, 0, obj.Len())
+ }
+ obj.Visit(func(key []byte, v *fastjson.Value) {
+ child, convErr := convertFastJSON(v)
+ if convErr != nil {
+ err = convErr
+ return
+ }
+ objNode.entries = append(objNode.entries, objectEntry{key: string(key), value: child})
+ })
+ if err != nil {
+ return nil, err
+ }
+
+ return objNode, nil
+ case fastjson.TypeArray:
+ values, err := value.Array()
+ if err != nil {
+ return nil, err
+ }
+
+ arrNode := arrayNodePool.Get().(*arrayNode)
+ if cap(arrNode.values) >= len(values) {
+ arrNode.values = arrNode.values[:0]
+ } else {
+ arrNode.values = make([]node, 0, len(values))
+ }
+ for _, item := range values {
+ child, convErr := convertFastJSON(item)
+ if convErr != nil {
+ return nil, convErr
+ }
+ arrNode.values = append(arrNode.values, child)
+ }
+
+ return arrNode, nil
+ case fastjson.TypeString:
+ vn := valueNodePool.Get().(*valueNode)
+ vn.kind = kindString
+ vn.str = string(value.GetStringBytes())
+ vn.num = ""
+ return vn, nil
+ case fastjson.TypeNumber:
+ num := value.String()
+ vn := valueNodePool.Get().(*valueNode)
+ vn.kind = kindNumber
+ vn.num = num
+ vn.str = ""
+ return vn, nil
+ case fastjson.TypeTrue:
+ vn := valueNodePool.Get().(*valueNode)
+ vn.kind = kindBool
+ vn.b = true
+ vn.str = ""
+ vn.num = ""
+ return vn, nil
+ case fastjson.TypeFalse:
+ vn := valueNodePool.Get().(*valueNode)
+ vn.kind = kindBool
+ vn.b = false
+ vn.str = ""
+ vn.num = ""
+ return vn, nil
+ case fastjson.TypeNull:
+ vn := valueNodePool.Get().(*valueNode)
+ vn.kind = kindNull
+ vn.str = ""
+ vn.num = ""
+ return vn, nil
+ default:
+ return nil, fmt.Errorf("unexpected fastjson type %v", value.Type())
+ }
+}
+
+func processLine(keys jsonKey, rawLine []byte, buf *bytes.Buffer) error {
+ parser := parserPool.Get().(*fastjson.Parser)
+ defer parserPool.Put(parser)
+
+ value, err := parser.ParseBytes(rawLine)
+ if err != nil {
+ return fmt.Errorf("json parse error: %w", err)
+ }
+
+ parsed, err := convertFastJSON(value)
+ if err != nil {
+ return fmt.Errorf("json parse error: %w", err)
+ }
+ result := parsed.DropKeys(keys)
+ buf.Reset()
+ buf.Grow(len(rawLine))
+ result.Write(buf)
+ recycleNode(result)
+ return nil
+}
+
+// parseSingleQuotedArray parses a Python-style array like ['a', 'b\'c']
+func parseSingleQuotedArray(s string) ([]string, error) {
+ s = strings.TrimSpace(s)
+ if len(s) < 2 || s[0] != '[' || s[len(s)-1] != ']' {
+ return nil, fmt.Errorf("expected array wrapped in []")
+ }
+ s = s[1 : len(s)-1] // strip [ ]
+
+ var result []string
+ for len(s) > 0 {
+ s = strings.TrimLeft(s, " \t")
+ if len(s) == 0 {
+ break
+ }
+ if s[0] != '\'' {
+ return nil, fmt.Errorf("expected single quote at start of string, got %q", s)
+ }
+ s = s[1:] // skip opening '
+
+ var sb strings.Builder
+ for {
+ if len(s) == 0 {
+ return nil, fmt.Errorf("unterminated string")
+ }
+ if s[0] == '\\' && len(s) > 1 && s[1] == '\'' {
+ sb.WriteByte('\'')
+ s = s[2:]
+ continue
+ }
+ if s[0] == '\'' {
+ s = s[1:] // skip closing '
+ break
+ }
+ sb.WriteByte(s[0])
+ s = s[1:]
+ }
+ result = append(result, sb.String())
+
+ s = strings.TrimLeft(s, " \t")
+ if len(s) > 0 && s[0] == ',' {
+ s = s[1:]
+ }
+ }
+ return result, nil
+}
+
+func makeKeyDict(keys []string) jsonKey {
+ dict := make(jsonKey)
+ for _, key := range keys {
+ parts := strings.Split(key, ".")
+ current := dict
+ for i, part := range parts {
+ child, exists := current[part]
+ if exists && child == nil {
+ break
+ }
+ if i == len(parts)-1 {
+ current[part] = nil
+ } else {
+ if !exists {
+ child = make(jsonKey)
+ current[part] = child
+ }
+ current = child
+ }
+ }
+ }
+ return dict
+}
+
+func main() {
+ cpuProfile := flag.String("cpuprofile", "", "write CPU profile to file")
+ debugLog := flag.Bool("debug", false, "enable debug logging")
+ flag.Parse()
+
+ keysArg := flag.Arg(0)
+
+ stdErr := os.Stderr
+ if *debugLog {
+ logFile, err := os.OpenFile("/tmp/json_drop_keys_udf.log", os.O_CREATE|os.O_APPEND|os.O_WRONLY, 0644)
+ if err != nil {
+ fmt.Fprintf(os.Stderr, "open log file error: %v\n", err)
+ os.Exit(1)
+ }
+ defer logFile.Close()
+ stdErr = logFile
+ log.SetOutput(logFile)
+ fmt.Fprintf(logFile, "keysToDrop: %s\n", keysArg)
+ }
+
+ keys, err := parseSingleQuotedArray(keysArg)
+ if err != nil {
+ fmt.Fprintf(stdErr, "keysToDrop parse error: %v\n", err)
+ os.Exit(1)
+ }
+ keysToDrop := makeKeyDict(keys)
+
+ if *cpuProfile != "" {
+ f, err := os.Create(*cpuProfile)
+ if err != nil {
+ fmt.Fprintf(stdErr, "cpuprofile create error: %v\n", err)
+ os.Exit(1)
+ }
+ if err := pprof.StartCPUProfile(f); err != nil {
+ _ = f.Close()
+ fmt.Fprintf(stdErr, "cpuprofile start error: %v\n", err)
+ os.Exit(1)
+ }
+ defer func() {
+ pprof.StopCPUProfile()
+ _ = f.Close()
+ }()
+ }
+
+ reader := bufio.NewReaderSize(os.Stdin, 4*1024*1024)
+ writer := bufio.NewWriterSize(os.Stdout, 4*1024*1024)
+ defer writer.Flush()
+ buf := bytes.NewBuffer(make([]byte, 0, 64*1024))
+
+ for {
+ line, err := reader.ReadBytes('\n')
+ if err != nil && err != io.EOF {
+ fmt.Fprintf(stdErr, "stdin read error: %v\n", err)
+ return
+ }
+
+ if len(line) == 0 && err == io.EOF {
+ return
+ }
+
+ hadNewline := false
+ n := len(line)
+ if n > 0 && line[n-1] == '\n' {
+ hadNewline = true
+ n--
+ }
+ if n > 0 && line[n-1] == '\r' {
+ n--
+ }
+ line = line[:n]
+
+ procErr := processLine(keysToDrop, line, buf)
+ if procErr != nil {
+ fmt.Fprintf(stdErr, "line processing error: %v\n", procErr)
+ os.Exit(1)
+ }
+
+ _, _ = writer.Write(buf.Bytes())
+ if hadNewline {
+ _, _ = writer.WriteString("\n")
+ }
+
+ if err == io.EOF {
+ return
+ }
+ }
+}
diff --git a/clickhouse-udfs/util/cmd/json_drop_keys_udf/main_test.go b/clickhouse-udfs/util/cmd/json_drop_keys_udf/main_test.go
new file mode 100644
index 000000000000..ab428aefe656
--- /dev/null
+++ b/clickhouse-udfs/util/cmd/json_drop_keys_udf/main_test.go
@@ -0,0 +1,285 @@
+package main
+
+import (
+ "bytes"
+ "fmt"
+ "os"
+ "path/filepath"
+ "testing"
+
+ "github.com/stretchr/testify/assert"
+)
+
+func TestProcessLineErrorsOnMalformedJSON(t *testing.T) {
+ var buf bytes.Buffer
+ err := processLine(nil, []byte("{\"a\":"), &buf)
+ assert.Error(t, err, "expected error for malformed JSON, got nil")
+}
+
+func TestDropKeysJSON(t *testing.T) {
+ cases := []struct {
+ name, input, want string
+ keys []string
+ }{
+ {
+ "empty",
+ "{}",
+ "{}",
+ nil,
+ },
+ {
+ "empty2",
+ "{}",
+ "{}",
+ []string{"jeden"},
+ },
+ {
+ "one one key to be dropped",
+ `{"jeden": 1}`,
+ `{}`,
+ []string{"jeden"},
+ },
+ {
+ name: "one key to be dropped, one to be kept",
+ input: `{"jeden": 1, "dwa": 2}`,
+ want: `{"dwa":2}`,
+ keys: []string{"jeden"},
+ },
+ {
+ name: "one key to be dropped one to be kept (order doesnt matter)",
+ input: `{"dwa": 2, "jeden": 1}`,
+ want: `{"dwa":2}`,
+ keys: []string{"jeden"},
+ },
+ {
+ name: "multiple keys to be dropped one to be kept (order doesnt matter)",
+ input: `{"dwa": 2, "jeden": 1, "trzy": 3, "cztery": 4, "piec": {"dwa": 1}}`,
+ want: `{"jeden":1,"cztery":4,"piec":{"dwa":1}}`,
+ keys: []string{"dwa", "trzy"},
+ },
+ {
+ name: "drop nested key with dot notation",
+ input: `{"id":1,"props":{"secret":"xxx","public":"yyy"}}`,
+ want: `{"id":1,"props":{"public":"yyy"}}`,
+ keys: []string{"props.secret"},
+ },
+ {
+ name: "drop deeply nested key",
+ input: `{"a":{"b":{"c":1,"d":2}}}`,
+ want: `{"a":{"b":{"d":2}}}`,
+ keys: []string{"a.b.c"},
+ },
+ {
+ name: "drop entire nested object",
+ input: `{"a":{"b":1},"c":2}`,
+ want: `{"c":2}`,
+ keys: []string{"a"},
+ },
+ {
+ name: "drop parent when it precedes a nested key",
+ input: `{"a":{"b":1,"c":2}}`,
+ want: `{}`,
+ keys: []string{"a", "a.b"},
+ },
+ {
+ name: "drop keys from root array objects",
+ input: `[{"a":1,"b":2},{"a":3}]`,
+ want: `[{"b":2},{}]`,
+ keys: []string{"a"},
+ },
+ {
+ name: "drop nested path through array objects",
+ input: `{"events":[{"a":1,"b":2},{"a":3}]}`,
+ want: `{"events":[{"b":2},{}]}`,
+ keys: []string{"events.a"},
+ },
+ }
+
+ for _, c := range cases {
+ t.Run(c.name, func(t *testing.T) {
+ var buf bytes.Buffer
+ err := processLine(makeKeyDict(c.keys), []byte(c.input), &buf)
+ assert.NoError(t, err, "unexpected error processing line")
+ assert.Equal(t, c.want, buf.String(), "unexpected output")
+ })
+ }
+}
+
+func TestParseSingleQuotedArray(t *testing.T) {
+ cases := []struct {
+ name string
+ input string
+ want []string
+ wantErr bool
+ }{
+ {"empty array", "[]", nil, false},
+ {"single element", "['foo']", []string{"foo"}, false},
+ {"two elements", "['foo', 'bar']", []string{"foo", "bar"}, false},
+ {"escaped single quote", `['some other \'string']`, []string{"some other 'string"}, false},
+ {"mixed", `['some string', 'some other \'string']`, []string{"some string", "some other 'string"}, false},
+ {"with spaces", "[ 'a' , 'b' ]", []string{"a", "b"}, false},
+ {"no brackets", "foo", nil, true},
+ {"unterminated string", "['foo", nil, true},
+ {"missing quote", "[foo]", nil, true},
+ }
+
+ for _, c := range cases {
+ t.Run(c.name, func(t *testing.T) {
+ got, err := parseSingleQuotedArray(c.input)
+ if c.wantErr {
+ assert.Error(t, err)
+ } else {
+ assert.NoError(t, err)
+ assert.Equal(t, c.want, got)
+ }
+ })
+ }
+}
+
+func TestMakeKeyDict(t *testing.T) {
+ cases := []struct {
+ name string
+ keys []string
+ want jsonKey
+ }{
+ {
+ name: "nil input",
+ keys: nil,
+ want: jsonKey{},
+ },
+ {
+ name: "empty input",
+ keys: []string{},
+ want: jsonKey{},
+ },
+ {
+ name: "single top-level key",
+ keys: []string{"a"},
+ want: jsonKey{"a": nil},
+ },
+ {
+ name: "multiple top-level keys",
+ keys: []string{"a", "b", "c"},
+ want: jsonKey{"a": nil, "b": nil, "c": nil},
+ },
+ {
+ name: "single nested key",
+ keys: []string{"a.b"},
+ want: jsonKey{"a": jsonKey{"b": nil}},
+ },
+ {
+ name: "deeply nested key",
+ keys: []string{"a.b.c.d"},
+ want: jsonKey{"a": jsonKey{"b": jsonKey{"c": jsonKey{"d": nil}}}},
+ },
+ {
+ name: "mixed top-level and nested keys",
+ keys: []string{"x", "a.b"},
+ want: jsonKey{"x": nil, "a": jsonKey{"b": nil}},
+ },
+ {
+ name: "multiple nested keys under same parent",
+ keys: []string{"a.b", "a.c"},
+ want: jsonKey{"a": jsonKey{"b": nil, "c": nil}},
+ },
+ {
+ name: "nested key and parent key both specified",
+ keys: []string{"a.b", "a"},
+ want: jsonKey{"a": nil},
+ },
+ }
+
+ for _, c := range cases {
+ t.Run(c.name, func(t *testing.T) {
+ got := makeKeyDict(c.keys)
+ assert.Equal(t, c.want, got)
+ })
+ }
+}
+
+func BenchmarkProcessLine(b *testing.B) {
+ input := []byte(`{"id":1,"identity":"abc","properties":{"secret":"drop","public":"keep"},"events":[{"identity":"nested","value":1}],"amount":934504962295726700000}`)
+ keys := makeKeyDict([]string{"identity", "properties.secret"})
+ var buf bytes.Buffer
+
+ b.ReportAllocs()
+ b.SetBytes(int64(len(input)))
+
+ for i := 0; i < b.N; i++ {
+ if err := processLine(keys, input, &buf); err != nil {
+ b.Fatal(err)
+ }
+ }
+}
+
+func BenchmarkProcessFixture(b *testing.B) {
+ lines, totalBytes := loadBenchmarkLines(b)
+ keys := makeKeyDict([]string{"identity", "properties.secret"})
+ var buf bytes.Buffer
+
+ b.ReportAllocs()
+ b.SetBytes(int64(totalBytes))
+ b.ResetTimer()
+
+ for i := 0; i < b.N; i++ {
+ for _, line := range lines {
+ if err := processLine(keys, line, &buf); err != nil {
+ b.Fatal(err)
+ }
+ }
+ }
+}
+
+func loadBenchmarkLines(b *testing.B) ([][]byte, int) {
+ b.Helper()
+
+ path := os.Getenv("BENCH_FILE")
+ if path == "" {
+ return generatedBenchmarkLines()
+ } else if !filepath.IsAbs(path) {
+ path = filepath.Join("../..", path)
+ }
+
+ data, err := os.ReadFile(path)
+ if err != nil {
+ b.Fatal(err)
+ }
+
+ rawLines := bytes.Split(bytes.TrimSpace(data), []byte("\n"))
+ lines := make([][]byte, 0, len(rawLines))
+ totalBytes := 0
+ for _, line := range rawLines {
+ line = bytes.TrimSpace(line)
+ if len(line) == 0 {
+ continue
+ }
+ lines = append(lines, line)
+ totalBytes += len(line)
+ }
+
+ if len(lines) == 0 {
+ b.Fatalf("benchmark file has no JSON lines: %s", path)
+ }
+
+ return lines, totalBytes
+}
+
+func generatedBenchmarkLines() ([][]byte, int) {
+ lines := make([][]byte, 0, 256)
+ totalBytes := 0
+ for i := 0; i < 256; i++ {
+ line := []byte(fmt.Sprintf(
+ `{"id":%d,"identity":"user-%d","properties":{"secret":"s%d","public":"p%d"},"events":[{"identity":"nested-%d","value":%d}],"amount":934504962295726700000}`,
+ i,
+ i,
+ i,
+ i,
+ i,
+ i,
+ ))
+ lines = append(lines, line)
+ totalBytes += len(line)
+ }
+
+ return lines, totalBytes
+}
diff --git a/clickhouse-udfs/util/cmd/json_strip_empty_strings_and_nulls_udf/main.go b/clickhouse-udfs/util/cmd/json_strip_empty_strings_and_nulls_udf/main.go
new file mode 100644
index 000000000000..b514291bd13b
--- /dev/null
+++ b/clickhouse-udfs/util/cmd/json_strip_empty_strings_and_nulls_udf/main.go
@@ -0,0 +1,235 @@
+package main
+
+import (
+ "bufio"
+ "bytes"
+ "flag"
+ "fmt"
+ "io"
+ "os"
+ "strconv"
+
+ "github.com/valyala/fastjson"
+)
+
+type processor struct {
+ parser fastjson.Parser
+}
+
+func appendCleanJSON(dst []byte, value *fastjson.Value) ([]byte, bool) {
+ start := len(dst)
+ switch value.Type() {
+ case fastjson.TypeNull:
+ return dst, false
+ case fastjson.TypeString:
+ if len(value.GetStringBytes()) == 0 {
+ return dst, false
+ }
+ return value.MarshalTo(dst), true
+ case fastjson.TypeObject:
+ obj, _ := value.Object()
+ dst = append(dst, '{')
+ kept := 0
+ obj.Visit(func(key []byte, child *fastjson.Value) {
+ entryStart := len(dst)
+ if kept > 0 {
+ dst = append(dst, ',')
+ }
+ dst = appendJSONString(dst, string(key))
+ dst = append(dst, ':')
+ var keep bool
+ dst, keep = appendCleanJSON(dst, child)
+ if keep {
+ kept++
+ } else {
+ dst = dst[:entryStart]
+ }
+ })
+ if kept == 0 {
+ return dst[:start], false
+ }
+ return append(dst, '}'), true
+ case fastjson.TypeArray:
+ values, _ := value.Array()
+ dst = append(dst, '[')
+ kept := 0
+ for _, child := range values {
+ itemStart := len(dst)
+ if kept > 0 {
+ dst = append(dst, ',')
+ }
+ var keep bool
+ dst, keep = appendCleanJSON(dst, child)
+ if keep {
+ kept++
+ } else {
+ dst = dst[:itemStart]
+ }
+ }
+ if kept == 0 {
+ return dst[:start], false
+ }
+ return append(dst, ']'), true
+ case fastjson.TypeNumber:
+ dst = value.MarshalTo(dst)
+ if shouldStringifyNumberBytes(dst[start:]) {
+ dst = strconv.AppendQuote(dst[:start], string(dst[start:]))
+ }
+ return dst, true
+ default:
+ return value.MarshalTo(dst), true
+ }
+}
+
+func appendJSONString(dst []byte, s string) []byte {
+ dst = append(dst, '"')
+ start := 0
+ for i := 0; i < len(s); i++ {
+ ch := s[i]
+ if ch >= 0x20 && ch != '\\' && ch != '"' {
+ continue
+ }
+ dst = append(dst, s[start:i]...)
+ switch ch {
+ case '\\', '"':
+ dst = append(dst, '\\', ch)
+ case '\b':
+ dst = append(dst, "\\b"...)
+ case '\f':
+ dst = append(dst, "\\f"...)
+ case '\n':
+ dst = append(dst, "\\n"...)
+ case '\r':
+ dst = append(dst, "\\r"...)
+ case '\t':
+ dst = append(dst, "\\t"...)
+ default:
+ const hex = "0123456789abcdef"
+ dst = append(dst, "\\u00"...)
+ dst = append(dst, hex[ch>>4], hex[ch&0x0f])
+ }
+ start = i + 1
+ }
+ dst = append(dst, s[start:]...)
+ return append(dst, '"')
+}
+
+func shouldStringifyNumberBytes(num []byte) bool {
+ if bytes.IndexAny(num, ".eE") >= 0 {
+ return false
+ }
+
+ start := 0
+ negative := len(num) > 0 && num[0] == '-'
+ if negative {
+ start++
+ }
+ for start < len(num) && num[start] == '0' {
+ start++
+ }
+ digits := num[start:]
+ if len(digits) != 19 {
+ return len(digits) > 19
+ }
+ limit := "9223372036854775807"
+ if negative {
+ limit = "9223372036854775808"
+ }
+ return bytes.Compare(digits, []byte(limit)) > 0
+}
+
+func processLine(rawLine []byte, buf *bytes.Buffer) error {
+ var p processor
+ return p.processLine(rawLine, buf)
+}
+
+func (p *processor) processLine(rawLine []byte, buf *bytes.Buffer) error {
+ value, err := p.parser.ParseBytes(rawLine)
+ if err != nil {
+ return fmt.Errorf("json parse error: %w", err)
+ }
+
+ buf.Reset()
+ buf.Grow(len(rawLine))
+ output, keep := appendCleanJSON(buf.AvailableBuffer(), value)
+ if !keep {
+ output = append(output, "{}"...)
+ }
+ _, _ = buf.Write(output)
+ return nil
+}
+
+func run(input io.Reader, output io.Writer) error {
+ reader := bufio.NewReaderSize(input, 4*1024*1024)
+ writer := bufio.NewWriterSize(output, 4*1024*1024)
+ buf := bytes.NewBuffer(make([]byte, 0, 64*1024))
+ var proc processor
+
+ for {
+ line, err := reader.ReadBytes('\n')
+ if err != nil && err != io.EOF {
+ return fmt.Errorf("stdin read error: %w", err)
+ }
+ if len(line) == 0 && err == io.EOF {
+ return writer.Flush()
+ }
+
+ line = bytes.TrimSuffix(line, []byte{'\n'})
+ line = bytes.TrimSuffix(line, []byte{'\r'})
+ if processErr := proc.processLine(line, buf); processErr != nil {
+ return fmt.Errorf("line processing error: %w", processErr)
+ }
+ if _, writeErr := writer.Write(append(buf.Bytes(), '\n')); writeErr != nil {
+ return fmt.Errorf("stdout write error: %w", writeErr)
+ }
+ if err == io.EOF {
+ return writer.Flush()
+ }
+ }
+}
+
+func runChunked(input io.Reader, output io.Writer) error {
+ reader := bufio.NewReaderSize(input, 4*1024*1024)
+ writer := bufio.NewWriterSize(output, 4*1024*1024)
+ buf := bytes.NewBuffer(make([]byte, 0, 64*1024))
+ var proc processor
+
+ for {
+ var rows int
+ if _, err := fmt.Fscanln(reader, &rows); err == io.EOF {
+ return writer.Flush()
+ } else if err != nil {
+ return fmt.Errorf("chunk header read error: %w", err)
+ }
+ for range rows {
+ line, err := reader.ReadBytes('\n')
+ if err != nil {
+ return fmt.Errorf("stdin read error: %w", err)
+ }
+ line = bytes.TrimSuffix(line, []byte{'\n'})
+ line = bytes.TrimSuffix(line, []byte{'\r'})
+ if err := proc.processLine(line, buf); err != nil {
+ return fmt.Errorf("line processing error: %w", err)
+ }
+ if _, err := writer.Write(append(buf.Bytes(), '\n')); err != nil {
+ return fmt.Errorf("stdout write error: %w", err)
+ }
+ }
+ if err := writer.Flush(); err != nil {
+ return fmt.Errorf("stdout flush error: %w", err)
+ }
+ }
+}
+
+func main() {
+ chunked := flag.Bool("chunked", false, "read a row-count header before each input chunk")
+ flag.Parse()
+ runner := run
+ if *chunked {
+ runner = runChunked
+ }
+ if err := runner(os.Stdin, os.Stdout); err != nil {
+ fmt.Fprintln(os.Stderr, err)
+ os.Exit(1)
+ }
+}
diff --git a/clickhouse-udfs/util/cmd/json_strip_empty_strings_and_nulls_udf/main_test.go b/clickhouse-udfs/util/cmd/json_strip_empty_strings_and_nulls_udf/main_test.go
new file mode 100644
index 000000000000..e2089ec3f248
--- /dev/null
+++ b/clickhouse-udfs/util/cmd/json_strip_empty_strings_and_nulls_udf/main_test.go
@@ -0,0 +1,68 @@
+package main
+
+import (
+ "bytes"
+ "strings"
+ "testing"
+)
+
+func TestProcessLine(t *testing.T) {
+ tests := map[string]string{
+ `{"empty":"","null":null,"object":{"nested":null},"array":[null,"",{},[]]}`: `{}`,
+ `{"keep":0,"false":false,"text":" ","nested":{"drop":null,"keep":"x"},"array":[null,"",{},[],{"drop":null,"keep":1}]}`: `{"keep":0,"false":false,"text":" ","nested":{"keep":"x"},"array":[{"keep":1}]}`,
+ `{"\u000b":"x"}`: `{"\u000b":"x"}`,
+ `{"a":1,"a":null,"a":2}`: `{"a":1,"a":2}`,
+ `[null,"",[],{},0,false,"x"]`: `[0,false,"x"]`,
+ `934504962295726700000`: `"934504962295726700000"`,
+ }
+
+ for input, want := range tests {
+ var buf bytes.Buffer
+ if err := processLine([]byte(input), &buf); err != nil {
+ t.Fatalf("processLine(%s) returned error: %v", input, err)
+ }
+ if got := buf.String(); got != want {
+ t.Fatalf("processLine(%s) = %s, want %s", input, got, want)
+ }
+ }
+}
+
+func TestRunMultipleChunks(t *testing.T) {
+ var output bytes.Buffer
+ if err := run(strings.NewReader("{\"a\":null}\n{\"a\":1}\n"), &output); err != nil {
+ t.Fatal(err)
+ }
+ if got, want := output.String(), "{}\n{\"a\":1}\n"; got != want {
+ t.Fatalf("run output = %q, want %q", got, want)
+ }
+}
+
+func TestRunChunked(t *testing.T) {
+ var output bytes.Buffer
+ input := "2\n{\"a\":null}\n{\"a\":1}\n1\n[null,2]\n"
+ if err := runChunked(strings.NewReader(input), &output); err != nil {
+ t.Fatal(err)
+ }
+ if got, want := output.String(), "{}\n{\"a\":1}\n[2]\n"; got != want {
+ t.Fatalf("runChunked output = %q, want %q", got, want)
+ }
+}
+
+func TestMalformedJSONFails(t *testing.T) {
+ var buf bytes.Buffer
+ if err := processLine([]byte(`{"a":`), &buf); err == nil {
+ t.Fatal("expected malformed JSON to fail")
+ }
+}
+
+func BenchmarkProcessLine(b *testing.B) {
+ input := []byte(`{"empty":"","null":null,"nested":{"empty":"","value":"x"},"arr":[null,"",{},[],{"value":1}],"amount":934504962295726700000}`)
+ var buf bytes.Buffer
+ b.ReportAllocs()
+ b.SetBytes(int64(len(input)))
+ for i := 0; i < b.N; i++ {
+ if err := processLine(input, &buf); err != nil {
+ b.Fatal(err)
+ }
+ }
+}
diff --git a/clickhouse-udfs/util/docker-compose.yml b/clickhouse-udfs/util/docker-compose.yml
new file mode 100644
index 000000000000..765a015e6348
--- /dev/null
+++ b/clickhouse-udfs/util/docker-compose.yml
@@ -0,0 +1,15 @@
+services:
+ clickhouse:
+ image: clickhouse/clickhouse-server:26.6.2.158
+ ulimits:
+ nofile:
+ soft: 262144
+ hard: 262144
+ volumes:
+ - ../../docker/clickhouse/user_defined_function.xml:/etc/clickhouse-server/user_defined_function.xml:ro
+ - ../../posthog/user_scripts:/var/lib/clickhouse/user_scripts:ro
+ healthcheck:
+ test: ['CMD', 'clickhouse-client', '--query', 'SELECT 1']
+ interval: 2s
+ timeout: 5s
+ retries: 15
diff --git a/clickhouse-udfs/util/go.mod b/clickhouse-udfs/util/go.mod
new file mode 100644
index 000000000000..4921e1699e11
--- /dev/null
+++ b/clickhouse-udfs/util/go.mod
@@ -0,0 +1,14 @@
+module github.com/PostHog/posthog/clickhouse-udfs/util
+
+go 1.25.5
+
+require (
+ github.com/stretchr/testify v1.11.1
+ github.com/valyala/fastjson v1.6.7
+)
+
+require (
+ github.com/davecgh/go-spew v1.1.1 // indirect
+ github.com/pmezard/go-difflib v1.0.0 // indirect
+ gopkg.in/yaml.v3 v3.0.1 // indirect
+)
diff --git a/clickhouse-udfs/util/go.sum b/clickhouse-udfs/util/go.sum
new file mode 100644
index 000000000000..6a3bb5ebe723
--- /dev/null
+++ b/clickhouse-udfs/util/go.sum
@@ -0,0 +1,12 @@
+github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c=
+github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
+github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM=
+github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
+github.com/stretchr/testify v1.11.1 h1:7s2iGBzp5EwR7/aIZr8ao5+dra3wiQyKjjFuvgVKu7U=
+github.com/stretchr/testify v1.11.1/go.mod h1:wZwfW3scLgRK+23gO65QZefKpKQRnfz6sD981Nm4B6U=
+github.com/valyala/fastjson v1.6.7 h1:ZE4tRy0CIkh+qDc5McjatheGX2czdn8slQjomexVpBM=
+github.com/valyala/fastjson v1.6.7/go.mod h1:CLCAqky6SMuOcxStkYQvblddUtoRxhYMGLrsQns1aXY=
+gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405 h1:yhCVgyC4o1eVCa2tZl7eS0r+SDo693bJlVdllGtEeKM=
+gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
+gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA=
+gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
diff --git a/clickhouse-udfs/util/scripts/build.sh b/clickhouse-udfs/util/scripts/build.sh
new file mode 100755
index 000000000000..40d65d5df64d
--- /dev/null
+++ b/clickhouse-udfs/util/scripts/build.sh
@@ -0,0 +1,25 @@
+#!/usr/bin/env bash
+set -euo pipefail
+
+ROOT_DIR=$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)
+OUT_DIR="$ROOT_DIR/../../posthog/user_scripts"
+UDFS=(
+ json_drop_keys_udf
+ json_clean_posthog_event_properties_udf
+ json_strip_empty_strings_and_nulls_udf
+)
+
+cd "$ROOT_DIR"
+go test ./...
+
+for goarch in amd64 arm64; do
+ case "$goarch" in
+ amd64) suffix=x86_64 ;;
+ arm64) suffix=aarch64 ;;
+ esac
+
+ for udf in "${UDFS[@]}"; do
+ CGO_ENABLED=0 GOOS=linux GOARCH="$goarch" \
+ go build -buildvcs=false -trimpath -ldflags "-s -w" -o "$OUT_DIR/${udf}_${suffix}" "./cmd/$udf"
+ done
+done
diff --git a/clickhouse-udfs/util/scripts/integration_test.sh b/clickhouse-udfs/util/scripts/integration_test.sh
new file mode 100755
index 000000000000..bae2949deb69
--- /dev/null
+++ b/clickhouse-udfs/util/scripts/integration_test.sh
@@ -0,0 +1,69 @@
+#!/usr/bin/env bash
+set -euo pipefail
+
+ROOT_DIR=$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)
+COMPOSE_FILE="$ROOT_DIR/docker-compose.yml"
+TEMP_DIR=$(mktemp -d)
+UDFS=(
+ json_drop_keys
+ json_clean_posthog_event_properties
+ json_clean_posthog_person_properties
+ json_strip_empty_strings_and_nulls
+)
+
+cleanup() {
+ docker compose -f "$COMPOSE_FILE" down -v --remove-orphans >/dev/null 2>&1 || true
+ rm -rf "$TEMP_DIR"
+}
+trap cleanup EXIT
+
+query_for() {
+ local input="file('$1/stateless/$2', 'TabSeparated', 'x String')"
+ case "$1" in
+ json_drop_keys)
+ echo "SELECT JSONDropKeys(['a'])(x) FROM $input FORMAT TabSeparated"
+ ;;
+ json_clean_posthog_event_properties)
+ echo "SELECT JSONCleanPostHogEventProperties(x) FROM $input FORMAT TabSeparated"
+ ;;
+ json_clean_posthog_person_properties)
+ echo "SELECT JSONCleanPostHogPersonProperties(x) FROM $input FORMAT TabSeparated"
+ ;;
+ json_strip_empty_strings_and_nulls)
+ echo "SELECT JSONStripEmptyStringsAndNulls(x) FROM $input FORMAT TabSeparated"
+ ;;
+ esac
+}
+
+docker compose -f "$COMPOSE_FILE" up -d --wait
+docker compose -f "$COMPOSE_FILE" cp "$ROOT_DIR/testdata/." clickhouse:/var/lib/clickhouse/user_files/
+
+for udf in "${UDFS[@]}"; do
+ stateless_dir="$ROOT_DIR/testdata/$udf/stateless"
+
+ for test_file in "$stateless_dir"/*.tsv; do
+ test_name=$(basename "$test_file")
+ reference="${test_file%.tsv}.reference"
+ output_file="$TEMP_DIR/$udf-$test_name.output"
+ query=$(query_for "$udf" "$test_name")
+
+ if [[ "$test_name" == *.fail.tsv ]]; then
+ if docker compose -f "$COMPOSE_FILE" exec -T clickhouse clickhouse-client --query "$query" \
+ >/dev/null 2> "$output_file"; then
+ echo "Expected $udf $test_name to fail, but the query succeeded." >&2
+ exit 1
+ fi
+ expected_error=$(<"$reference")
+ if [[ -n "$expected_error" ]] && ! grep -Fq "$expected_error" "$output_file"; then
+ echo "Expected $udf $test_name error to contain: $expected_error" >&2
+ cat "$output_file" >&2
+ exit 1
+ fi
+ else
+ docker compose -f "$COMPOSE_FILE" exec -T clickhouse clickhouse-client --query "$query" > "$output_file"
+ diff -u "$reference" "$output_file"
+ fi
+
+ echo "Passed $udf/$test_name."
+ done
+done
diff --git a/clickhouse-udfs/util/testdata/json_clean_posthog_event_properties/stateless/README.md b/clickhouse-udfs/util/testdata/json_clean_posthog_event_properties/stateless/README.md
new file mode 100644
index 000000000000..884387010f4c
--- /dev/null
+++ b/clickhouse-udfs/util/testdata/json_clean_posthog_event_properties/stateless/README.md
@@ -0,0 +1,3 @@
+# JSONCleanPostHogEventProperties Stateless Fixtures
+
+These fixtures cover PostHog event property cleanup and complex-property coercion before casting to typed ClickHouse JSON. Scalar values are preserved for ClickHouse to cast to `Nullable(String)`. Malformed JSON must fail processing; incompatible complex properties use empty arrays and are recorded as stringified JSON in `$unparseable_properties`.
diff --git a/clickhouse-udfs/util/testdata/json_clean_posthog_event_properties/stateless/clean_event_properties.reference b/clickhouse-udfs/util/testdata/json_clean_posthog_event_properties/stateless/clean_event_properties.reference
new file mode 100644
index 000000000000..125f40c24cfd
--- /dev/null
+++ b/clickhouse-udfs/util/testdata/json_clean_posthog_event_properties/stateless/clean_event_properties.reference
@@ -0,0 +1 @@
+{"$agent_turn":"3.0","$ai_total_cost_usd":"1.5","$is_identified":"true","$mcp_listed_tool_names":["search"],"$exception_list":[{"type":"TypeError"}],"Account":{"client_id":"abc"},"huge":"18446744073709551616","max_uint":18446744073709551615,"dupe":"kept","$feature_flags":{"beta":"control"}}
diff --git a/clickhouse-udfs/util/testdata/json_clean_posthog_event_properties/stateless/clean_event_properties.tsv b/clickhouse-udfs/util/testdata/json_clean_posthog_event_properties/stateless/clean_event_properties.tsv
new file mode 100644
index 000000000000..3df51e89b50e
--- /dev/null
+++ b/clickhouse-udfs/util/testdata/json_clean_posthog_event_properties/stateless/clean_event_properties.tsv
@@ -0,0 +1 @@
+{"$active_feature_flags":"undefined","$active_feature_flags":["beta",42,null,{"a.b":1}],"$feature/beta":"control","$ai_input":"secret","$set":{"name":"value"},"$set_once":{"initial":"value"},"$unset":["old_property"],"$agent_turn":"3.0","$ai_total_cost_usd":"1.5","$is_identified":"true","$mcp_listed_tool_names":"search","$exception_list":{"type":"TypeError","value":null},"Account.client_id":"abc","Account":{"client_id":null},"huge":18446744073709551616,"max_uint":18446744073709551615,"null_field":null,"dupe":"","dupe":"kept"}
diff --git a/clickhouse-udfs/util/testdata/json_clean_posthog_event_properties/stateless/invalid_complex_property.reference b/clickhouse-udfs/util/testdata/json_clean_posthog_event_properties/stateless/invalid_complex_property.reference
new file mode 100644
index 000000000000..128f0b24999b
--- /dev/null
+++ b/clickhouse-udfs/util/testdata/json_clean_posthog_event_properties/stateless/invalid_complex_property.reference
@@ -0,0 +1 @@
+{"$exception_list":[],"$unparseable_properties":"{\\"$exception_list\\":\\"[redacted]\\"}"}
diff --git a/clickhouse-udfs/util/testdata/json_clean_posthog_event_properties/stateless/invalid_complex_property.tsv b/clickhouse-udfs/util/testdata/json_clean_posthog_event_properties/stateless/invalid_complex_property.tsv
new file mode 100644
index 000000000000..2cf1f5c39f3b
--- /dev/null
+++ b/clickhouse-udfs/util/testdata/json_clean_posthog_event_properties/stateless/invalid_complex_property.tsv
@@ -0,0 +1 @@
+{"$exception_list":"[redacted]"}
diff --git a/clickhouse-udfs/util/testdata/json_clean_posthog_event_properties/stateless/malformed_json.fail.reference b/clickhouse-udfs/util/testdata/json_clean_posthog_event_properties/stateless/malformed_json.fail.reference
new file mode 100644
index 000000000000..bda0c41a558e
--- /dev/null
+++ b/clickhouse-udfs/util/testdata/json_clean_posthog_event_properties/stateless/malformed_json.fail.reference
@@ -0,0 +1 @@
+line processing error
diff --git a/clickhouse-udfs/util/testdata/json_clean_posthog_event_properties/stateless/malformed_json.fail.tsv b/clickhouse-udfs/util/testdata/json_clean_posthog_event_properties/stateless/malformed_json.fail.tsv
new file mode 100644
index 000000000000..55cbaf72caf2
--- /dev/null
+++ b/clickhouse-udfs/util/testdata/json_clean_posthog_event_properties/stateless/malformed_json.fail.tsv
@@ -0,0 +1 @@
+{"broken"
diff --git a/clickhouse-udfs/util/testdata/json_clean_posthog_person_properties/stateless/README.md b/clickhouse-udfs/util/testdata/json_clean_posthog_person_properties/stateless/README.md
new file mode 100644
index 000000000000..5f72d77ab8fd
--- /dev/null
+++ b/clickhouse-udfs/util/testdata/json_clean_posthog_person_properties/stateless/README.md
@@ -0,0 +1,3 @@
+# JSONCleanPostHogPersonProperties stateless fixtures
+
+These fixtures verify that person-property cleanup preserves event-specific property names while applying common JSON normalization.
diff --git a/clickhouse-udfs/util/testdata/json_clean_posthog_person_properties/stateless/clean_person_properties.reference b/clickhouse-udfs/util/testdata/json_clean_posthog_person_properties/stateless/clean_person_properties.reference
new file mode 100644
index 000000000000..f20e1ab164f4
--- /dev/null
+++ b/clickhouse-udfs/util/testdata/json_clean_posthog_person_properties/stateless/clean_person_properties.reference
@@ -0,0 +1 @@
+{"$active_feature_flags":["flag"],"$feature/test":true,"$set":{"name":"value"},"nested":{"key":"value"},"huge":"18446744073709551616"}
diff --git a/clickhouse-udfs/util/testdata/json_clean_posthog_person_properties/stateless/clean_person_properties.tsv b/clickhouse-udfs/util/testdata/json_clean_posthog_person_properties/stateless/clean_person_properties.tsv
new file mode 100644
index 000000000000..ee14c45e0cff
--- /dev/null
+++ b/clickhouse-udfs/util/testdata/json_clean_posthog_person_properties/stateless/clean_person_properties.tsv
@@ -0,0 +1 @@
+{"$active_feature_flags":["flag"],"$feature/test":true,"$set":{"name":"value"},"nested.key":"value","huge":18446744073709551616,"drop":null}
diff --git a/clickhouse-udfs/util/testdata/json_drop_keys/stateless/README.md b/clickhouse-udfs/util/testdata/json_drop_keys/stateless/README.md
new file mode 100644
index 000000000000..60d3a8d69892
--- /dev/null
+++ b/clickhouse-udfs/util/testdata/json_drop_keys/stateless/README.md
@@ -0,0 +1,11 @@
+# JSONDropKeys Stateless Fixtures
+
+Each test has a `<name>.tsv` input and a matching `<name>.reference` expected output. These integration fixtures run `JSONDropKeys(['a'])`. Files ending in `.fail.tsv` are expected to fail, and their `.reference` file contains the required stderr substring.
+
+| Test | Purpose |
+| -------------------------------------- | --------------------------------------------------------------------------------------------- |
+| `drop_top_level_a` | Removes every top-level `a` key while preserving unrelated keys and duplicate unrelated keys. |
+| `drop_nested_a_and_expand_dotted_keys` | Drops top-level `a` values and verifies dotted non-dropped keys are expanded consistently. |
+| `large_integer` | Preserves large integer values while dropping only requested keys. |
+| `root_array` | Drops keys from objects when the root JSON value is an array. |
+| `malformed_json.fail` | Verifies malformed JSON fails instead of being hidden. |
diff --git a/clickhouse-udfs/util/testdata/json_drop_keys/stateless/drop_nested_a_and_expand_dotted_keys.reference b/clickhouse-udfs/util/testdata/json_drop_keys/stateless/drop_nested_a_and_expand_dotted_keys.reference
new file mode 100644
index 000000000000..c9a00d3e95b5
--- /dev/null
+++ b/clickhouse-udfs/util/testdata/json_drop_keys/stateless/drop_nested_a_and_expand_dotted_keys.reference
@@ -0,0 +1,4 @@
+{"id":6}
+{"id":7}
+{"id":8,"obj":{"x":"","x":"y"}}
+{"id":9,"obj":{"x":"y"},"obj":{"x":""}}
diff --git a/clickhouse-udfs/util/testdata/json_drop_keys/stateless/drop_nested_a_and_expand_dotted_keys.tsv b/clickhouse-udfs/util/testdata/json_drop_keys/stateless/drop_nested_a_and_expand_dotted_keys.tsv
new file mode 100644
index 000000000000..f977b5ae137a
--- /dev/null
+++ b/clickhouse-udfs/util/testdata/json_drop_keys/stateless/drop_nested_a_and_expand_dotted_keys.tsv
@@ -0,0 +1,4 @@
+{"id":6,"a":{"k":"","k":"v"}}
+{"id":7,"a":[{"k":"","k":"x"},{"k":"","k":""}]}
+{"id":8,"obj":{"x":""},"obj.x":"y"}
+{"id":9,"obj.x":"y","obj":{"x":""}}
diff --git a/clickhouse-udfs/util/testdata/json_drop_keys/stateless/drop_top_level_a.reference b/clickhouse-udfs/util/testdata/json_drop_keys/stateless/drop_top_level_a.reference
new file mode 100644
index 000000000000..57ee95be7853
--- /dev/null
+++ b/clickhouse-udfs/util/testdata/json_drop_keys/stateless/drop_top_level_a.reference
@@ -0,0 +1,5 @@
+{"id":1,"b":""}
+{"id":2}
+{"id":3}
+{"id":4}
+{"id":5,"b":true,"b":false}
diff --git a/clickhouse-udfs/util/testdata/json_drop_keys/stateless/drop_top_level_a.tsv b/clickhouse-udfs/util/testdata/json_drop_keys/stateless/drop_top_level_a.tsv
new file mode 100644
index 000000000000..d7d3c63d0544
--- /dev/null
+++ b/clickhouse-udfs/util/testdata/json_drop_keys/stateless/drop_top_level_a.tsv
@@ -0,0 +1,5 @@
+{"id":1,"a":null,"a":"x","b":""}
+{"id":2,"a":"","a":""}
+{"id":3,"a":null,"a":null}
+{"id":4,"a":"","a":"y","a":""}
+{"id":5,"a":1,"a":2,"b":true,"b":false}
diff --git a/clickhouse-udfs/util/testdata/json_drop_keys/stateless/large_integer.reference b/clickhouse-udfs/util/testdata/json_drop_keys/stateless/large_integer.reference
new file mode 100644
index 000000000000..b1331c780a34
--- /dev/null
+++ b/clickhouse-udfs/util/testdata/json_drop_keys/stateless/large_integer.reference
@@ -0,0 +1 @@
+{"id":10,"amount":934504962295726700000}
diff --git a/clickhouse-udfs/util/testdata/json_drop_keys/stateless/large_integer.tsv b/clickhouse-udfs/util/testdata/json_drop_keys/stateless/large_integer.tsv
new file mode 100644
index 000000000000..b1331c780a34
--- /dev/null
+++ b/clickhouse-udfs/util/testdata/json_drop_keys/stateless/large_integer.tsv
@@ -0,0 +1 @@
+{"id":10,"amount":934504962295726700000}
diff --git a/clickhouse-udfs/util/testdata/json_drop_keys/stateless/malformed_json.fail.reference b/clickhouse-udfs/util/testdata/json_drop_keys/stateless/malformed_json.fail.reference
new file mode 100644
index 000000000000..c3d632d6a9d2
--- /dev/null
+++ b/clickhouse-udfs/util/testdata/json_drop_keys/stateless/malformed_json.fail.reference
@@ -0,0 +1 @@
+UDF_EXECUTION_FAILED
diff --git a/clickhouse-udfs/util/testdata/json_drop_keys/stateless/malformed_json.fail.tsv b/clickhouse-udfs/util/testdata/json_drop_keys/stateless/malformed_json.fail.tsv
new file mode 100644
index 000000000000..8f4bc8310d1a
--- /dev/null
+++ b/clickhouse-udfs/util/testdata/json_drop_keys/stateless/malformed_json.fail.tsv
@@ -0,0 +1 @@
+{"id":9999,"a":
diff --git a/clickhouse-udfs/util/testdata/json_drop_keys/stateless/root_array.reference b/clickhouse-udfs/util/testdata/json_drop_keys/stateless/root_array.reference
new file mode 100644
index 000000000000..fceb5889b6f6
--- /dev/null
+++ b/clickhouse-udfs/util/testdata/json_drop_keys/stateless/root_array.reference
@@ -0,0 +1 @@
+[{"b":2},{}]
diff --git a/clickhouse-udfs/util/testdata/json_drop_keys/stateless/root_array.tsv b/clickhouse-udfs/util/testdata/json_drop_keys/stateless/root_array.tsv
new file mode 100644
index 000000000000..2233abd37ab8
--- /dev/null
+++ b/clickhouse-udfs/util/testdata/json_drop_keys/stateless/root_array.tsv
@@ -0,0 +1 @@
+[{"a":1,"b":2},{"a":3}]
diff --git a/clickhouse-udfs/util/testdata/json_strip_empty_strings_and_nulls/stateless/README.md b/clickhouse-udfs/util/testdata/json_strip_empty_strings_and_nulls/stateless/README.md
new file mode 100644
index 000000000000..ea6a76c360f9
--- /dev/null
+++ b/clickhouse-udfs/util/testdata/json_strip_empty_strings_and_nulls/stateless/README.md
@@ -0,0 +1,3 @@
+# JSONStripEmptyStringsAndNulls Stateless Fixtures
+
+These cases cover recursive removal from objects and arrays, useless roots becoming `{}`, retained zero/false/whitespace values, and malformed JSON failure.
diff --git a/clickhouse-udfs/util/testdata/json_strip_empty_strings_and_nulls/stateless/cleanup.reference b/clickhouse-udfs/util/testdata/json_strip_empty_strings_and_nulls/stateless/cleanup.reference
new file mode 100644
index 000000000000..3ad5f952bb11
--- /dev/null
+++ b/clickhouse-udfs/util/testdata/json_strip_empty_strings_and_nulls/stateless/cleanup.reference
@@ -0,0 +1,3 @@
+{}
+{"keep":0,"false":false,"text":" ","nested":{"keep":"x"},"array":[{"keep":1}]}
+[{"a":1},false]
diff --git a/clickhouse-udfs/util/testdata/json_strip_empty_strings_and_nulls/stateless/cleanup.tsv b/clickhouse-udfs/util/testdata/json_strip_empty_strings_and_nulls/stateless/cleanup.tsv
new file mode 100644
index 000000000000..d7be1ff04e02
--- /dev/null
+++ b/clickhouse-udfs/util/testdata/json_strip_empty_strings_and_nulls/stateless/cleanup.tsv
@@ -0,0 +1,3 @@
+{"empty":"","null":null,"object":{"nested":null},"array":[null,"",{},[]]}
+{"keep":0,"false":false,"text":" ","nested":{"drop":null,"keep":"x"},"array":[null,"",{},[],{"drop":null,"keep":1}]}
+[{"a":null},{"a":1},[],null,"",false]
diff --git a/clickhouse-udfs/util/testdata/json_strip_empty_strings_and_nulls/stateless/malformed_json.fail.reference b/clickhouse-udfs/util/testdata/json_strip_empty_strings_and_nulls/stateless/malformed_json.fail.reference
new file mode 100644
index 000000000000..894ff78766df
--- /dev/null
+++ b/clickhouse-udfs/util/testdata/json_strip_empty_strings_and_nulls/stateless/malformed_json.fail.reference
@@ -0,0 +1 @@
+json parse error
diff --git a/clickhouse-udfs/util/testdata/json_strip_empty_strings_and_nulls/stateless/malformed_json.fail.tsv b/clickhouse-udfs/util/testdata/json_strip_empty_strings_and_nulls/stateless/malformed_json.fail.tsv
new file mode 100644
index 000000000000..f68f26269605
--- /dev/null
+++ b/clickhouse-udfs/util/testdata/json_strip_empty_strings_and_nulls/stateless/malformed_json.fail.tsv
@@ -0,0 +1 @@
+{"a":
diff --git a/docker/clickhouse/user_defined_function.xml b/docker/clickhouse/user_defined_function.xml
index 939c86e431de..f651cff9d30c 100644
--- a/docker/clickhouse/user_defined_function.xml
+++ b/docker/clickhouse/user_defined_function.xml
@@ -596,4 +596,40 @@
<format>Raw</format>
<command>json_drop_keys_udf {keys_parameter:Array(String)}</command>
</function>
+
+ <function>
+ <type>executable_pool</type>
+ <name>JSONCleanPostHogEventProperties</name>
+ <return_type>String</return_type>
+ <argument>
+ <type>String</type>
+ </argument>
+ <format>Raw</format>
+ <command>json_clean_posthog_event_properties_udf --chunked</command>
+ <send_chunk_header>true</send_chunk_header>
+ </function>
+
+ <function>
+ <type>executable_pool</type>
+ <name>JSONCleanPostHogPersonProperties</name>
+ <return_type>String</return_type>
+ <argument>
+ <type>String</type>
+ </argument>
+ <format>Raw</format>
+ <command>json_clean_posthog_event_properties_udf --chunked --person-properties</command>
+ <send_chunk_header>true</send_chunk_header>
+ </function>
+
+ <function>
+ <type>executable_pool</type>
+ <name>JSONStripEmptyStringsAndNulls</name>
+ <return_type>String</return_type>
+ <argument>
+ <type>String</type>
+ </argument>
+ <format>Raw</format>
+ <command>json_strip_empty_strings_and_nulls_udf --chunked</command>
+ <send_chunk_header>true</send_chunk_header>
+ </function>
</functions>
diff --git a/posthog/udf_versioner.py b/posthog/udf_versioner.py
index 3f858d654687..30decae8e9f9 100644
--- a/posthog/udf_versioner.py
+++ b/posthog/udf_versioner.py
@@ -14,6 +14,12 @@ UDF_VERSION = 12 # Last modified by: @aspicer, 2026-04-20 (RowBinary default, J
# Clean up all versions less than this
EARLIEST_UDF_VERSION = 11
+UNVERSIONED_FUNCTIONS = {
+ "JSONCleanPostHogEventProperties",
+ "JSONCleanPostHogPersonProperties",
+ "JSONStripEmptyStringsAndNulls",
+}
+
CLICKHOUSE_XML_FILENAME = "user_defined_function.xml"
ACTIVE_XML_CONFIG = "../../docker/clickhouse/user_defined_function.xml"
@@ -54,15 +60,16 @@ def prepare_version(force=False):
for function in list(last_version_root):
name = function.find("name")
match = re.search(r"_v(\d+)$", name.text)
- if match is None or int(match.group(1)) < EARLIEST_UDF_VERSION:
+ if name.text in UNVERSIONED_FUNCTIONS or match is None or int(match.group(1)) < EARLIEST_UDF_VERSION:
last_version_root.remove(function)
# We want to update the name and the command to include the version, and add it to last version
for function in list(base_xml.getroot()):
name = function.find("name")
- name.text = augment_function_name(name.text)
- command = function.find("command")
- command.text = f"{VERSION_STR}/{command.text}"
+ if name.text not in UNVERSIONED_FUNCTIONS:
+ name.text = augment_function_name(name.text)
+ command = function.find("command")
+ command.text = f"{VERSION_STR}/{command.text}"
last_version_root.append(function)
comment = Comment(
diff --git a/posthog/user_scripts/json_clean_posthog_event_properties_udf b/posthog/user_scripts/json_clean_posthog_event_properties_udf
new file mode 100755
index 000000000000..692968133500
--- /dev/null
+++ b/posthog/user_scripts/json_clean_posthog_event_properties_udf
@@ -0,0 +1,18 @@
+#!/bin/sh
+
+DIR_NAME=$(dirname "$0")
+TEMP_DIR=$(mktemp -d -p /tmp "json_clean_posthog_event_properties_udf_XXXXXXXXXX")
+trap 'rm -rf "$TEMP_DIR"; exit' 0
+
+case $(uname -m) in
+aarch64)
+ EXECUTABLE_NAME="json_clean_posthog_event_properties_udf_aarch64"
+ ;;
+*)
+ EXECUTABLE_NAME="json_clean_posthog_event_properties_udf_x86_64"
+ ;;
+esac
+
+cp "$DIR_NAME/$EXECUTABLE_NAME" "$TEMP_DIR/$EXECUTABLE_NAME"
+chmod +x "$TEMP_DIR/$EXECUTABLE_NAME"
+"$TEMP_DIR/$EXECUTABLE_NAME" "$@"
diff --git a/posthog/user_scripts/json_clean_posthog_event_properties_udf_aarch64 b/posthog/user_scripts/json_clean_posthog_event_properties_udf_aarch64
new file mode 100755
index 000000000000..72cb0bf18a52
Binary files /dev/null and b/posthog/user_scripts/json_clean_posthog_event_properties_udf_aarch64 differ
diff --git a/posthog/user_scripts/json_clean_posthog_event_properties_udf_x86_64 b/posthog/user_scripts/json_clean_posthog_event_properties_udf_x86_64
new file mode 100755
index 000000000000..ebc6730a7c4a
Binary files /dev/null and b/posthog/user_scripts/json_clean_posthog_event_properties_udf_x86_64 differ
diff --git a/posthog/user_scripts/json_drop_keys_udf_aarch64 b/posthog/user_scripts/json_drop_keys_udf_aarch64
index b0b044631717..3f78fc1a70b3 100755
Binary files a/posthog/user_scripts/json_drop_keys_udf_aarch64 and b/posthog/user_scripts/json_drop_keys_udf_aarch64 differ
diff --git a/posthog/user_scripts/json_drop_keys_udf_x86_64 b/posthog/user_scripts/json_drop_keys_udf_x86_64
index c4659c2400a5..bfc3e7b6769a 100755
Binary files a/posthog/user_scripts/json_drop_keys_udf_x86_64 and b/posthog/user_scripts/json_drop_keys_udf_x86_64 differ
diff --git a/posthog/user_scripts/json_strip_empty_strings_and_nulls_udf b/posthog/user_scripts/json_strip_empty_strings_and_nulls_udf
new file mode 100755
index 000000000000..549585fca0b3
--- /dev/null
+++ b/posthog/user_scripts/json_strip_empty_strings_and_nulls_udf
@@ -0,0 +1,18 @@
+#!/bin/sh
+
+DIR_NAME=$(dirname "$0")
+TEMP_DIR=$(mktemp -d -p /tmp "json_strip_empty_strings_and_nulls_udf_XXXXXXXXXX")
+trap 'rm -rf "$TEMP_DIR"; exit' 0
+
+case $(uname -m) in
+aarch64)
+ EXECUTABLE_NAME="json_strip_empty_strings_and_nulls_udf_aarch64"
+ ;;
+*)
+ EXECUTABLE_NAME="json_strip_empty_strings_and_nulls_udf_x86_64"
+ ;;
+esac
+
+cp "$DIR_NAME/$EXECUTABLE_NAME" "$TEMP_DIR/$EXECUTABLE_NAME"
+chmod +x "$TEMP_DIR/$EXECUTABLE_NAME"
+"$TEMP_DIR/$EXECUTABLE_NAME" "$@"
diff --git a/posthog/user_scripts/json_strip_empty_strings_and_nulls_udf_aarch64 b/posthog/user_scripts/json_strip_empty_strings_and_nulls_udf_aarch64
new file mode 100755
index 000000000000..c61a43fdf7fe
Binary files /dev/null and b/posthog/user_scripts/json_strip_empty_strings_and_nulls_udf_aarch64 differ
diff --git a/posthog/user_scripts/json_strip_empty_strings_and_nulls_udf_x86_64 b/posthog/user_scripts/json_strip_empty_strings_and_nulls_udf_x86_64
new file mode 100755
index 000000000000..9f1065a14dec
Binary files /dev/null and b/posthog/user_scripts/json_strip_empty_strings_and_nulls_udf_x86_64 differ
diff --git a/posthog/user_scripts/latest_user_defined_function.xml b/posthog/user_scripts/latest_user_defined_function.xml
index 9d3e01189664..2f95af231174 100644
--- a/posthog/user_scripts/latest_user_defined_function.xml
+++ b/posthog/user_scripts/latest_user_defined_function.xml
@@ -1,5 +1,5 @@
<functions>
- <!-- Version: v12. Generated at: 2026-04-23T05:29:22.648565+00:00
+ <!-- Version: v12. Generated at: 2026-09-01T08:45:22.183570+00:00
This file is autogenerated by udf_versioner.py. Do not edit this, only edit the version at docker/clickhouse/user_defined_function.xml--><function>
<type>executable_pool</type>
<name>aggregate_funnel_v11</name>
@@ -915,4 +915,40 @@ This file is autogenerated by udf_versioner.py. Do not edit this, only edit the
<format>Raw</format>
<command>v12/json_drop_keys_udf {keys_parameter:Array(String)}</command>
</function>
-</functions>
\ No newline at end of file
+
+ <function>
+ <type>executable_pool</type>
+ <name>JSONCleanPostHogEventProperties</name>
+ <return_type>String</return_type>
+ <argument>
+ <type>String</type>
+ </argument>
+ <format>Raw</format>
+ <command>json_clean_posthog_event_properties_udf --chunked</command>
+ <send_chunk_header>true</send_chunk_header>
+ </function>
+
+ <function>
+ <type>executable_pool</type>
+ <name>JSONCleanPostHogPersonProperties</name>
+ <return_type>String</return_type>
+ <argument>
+ <type>String</type>
+ </argument>
+ <format>Raw</format>
+ <command>json_clean_posthog_event_properties_udf --chunked --person-properties</command>
+ <send_chunk_header>true</send_chunk_header>
+ </function>
+
+ <function>
+ <type>executable_pool</type>
+ <name>JSONStripEmptyStringsAndNulls</name>
+ <return_type>String</return_type>
+ <argument>
+ <type>String</type>
+ </argument>
+ <format>Raw</format>
+ <command>json_strip_empty_strings_and_nulls_udf --chunked</command>
+ <send_chunk_header>true</send_chunk_header>
+ </function>
+</functions>