:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
fix(clickhouse): speed up property cleaner with bounded reuse (#97146)
Rory Shanks116875f72210
diff --git a/clickhouse-udfs/util/cmd/json_clean_posthog_event_properties_udf/main.go b/clickhouse-udfs/util/cmd/json_clean_posthog_event_properties_udf/main.goindex da0de1144ab9..c7f44b0f33b7 100644--- a/clickhouse-udfs/util/cmd/json_clean_posthog_event_properties_udf/main.go+++ b/clickhouse-udfs/util/cmd/json_clean_posthog_event_properties_udf/main.go@@ -7,6 +7,7 @@ import ("flag""fmt""io"+ "math/bits""os""runtime/pprof""slices"@@ -43,32 +44,40 @@ const (// Nested arrays can amplify ClickHouse type inference even for small documents.maxJSONArrayDepth = 8unparseablePropertiesKey = "$unparseable_properties"+ maxRecycledValues = 4096)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": {},- "$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": {},- "$transformations_succeeded": {},- "$transformations_skipped": {},- unparseablePropertiesKey: {},+func isDroppedEventProperty(key string) bool {+ switch key {+ case "$ai_input",+ "$ai_output",+ "$ai_output_choices",+ "$ai_input_state",+ "$ai_output_state",+ "$ai_tools",+ "ph_product_tours",+ "$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",+ "$transformations_succeeded",+ "$transformations_skipped",+ unparseablePropertiesKey:+ return true+ }+ return false}func isTemporaryProperty(key string) bool {+ if len(key) == 0 || key[0] != '$' {+ return false+ }root, _, _ := strings.Cut(key, ".")switch root {case "$set", "$set_once", "$unset", "$group_set", "$feature_flag_request_id",@@ -157,16 +166,20 @@ type mergeKey struct {}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+ data []byte+ pos int+ kind propertiesKind+ mutated bool+ rawSafe bool+ free []*value+ info map[string]entryInfo+ index map[mergeKey]*value+ entriesBuf []entry+ entryBuffers [8][]entry+ entryBufferMask uint8+ stringBuf bytes.Buffer+ tooDeepArrays bool+ discard bool}func processLine(rawLine []byte, buf *bytes.Buffer) error {@@ -175,13 +188,27 @@ func processLine(rawLine []byte, buf *bytes.Buffer) error {}func (p *processor) processLine(rawLine []byte, buf *bytes.Buffer) error {+ for p.entryBufferMask != 0 {+ i := bits.Len8(p.entryBufferMask) - 1+ if cap(p.entryBuffers[i]) <= max(16, len(rawLine)) {+ break+ }+ p.entryBuffers[i] = nil+ p.entryBufferMask &^= 1 << i+ }+ if buf.Cap() > max(64*1024, 2*len(rawLine)) {+ *buf = bytes.Buffer{}+ }+ if p.stringBuf.Cap() > max(64*1024, 2*len(rawLine)) {+ p.stringBuf = bytes.Buffer{}+ }p.data = rawLinep.pos = 0p.mutated = falsep.rawSafe = true- p.depth = 0+ p.tooDeepArrays = false- parsed, err := p.parseValue()+ parsed, err := p.parseValue(1, 0)if err != nil {if errors.Is(err, errMaxJSONDepth) {p.writeUnparseableProperties(buf, rawLine)@@ -194,8 +221,8 @@ func (p *processor) processLine(rawLine []byte, buf *bytes.Buffer) error {p.recycle(parsed)return fmt.Errorf("json parse error: trailing data at byte %d", p.pos)}- // Check before filtering so the permanent cleaner preserves rejected temporary properties.- if exceedsJSONArrayDepth(parsed, 0) {+ // Parsing counts arrays inside discarded properties so quarantine preserves rejected inputs.+ if p.tooDeepArrays {p.recycle(parsed)p.writeUnparseableProperties(buf, rawLine)return nil@@ -211,14 +238,13 @@ func (p *processor) processLine(rawLine []byte, buf *bytes.Buffer) error {return fmt.Errorf("json clean error: %w", err)}// Normalization can decode stringified JSON and wrap objects in arrays.- if exceedsJSONArrayDepth(cleaned, 0) {+ if p.mutated && exceedsJSONArrayDepth(cleaned, 0) {p.recycle(cleaned)p.writeUnparseableProperties(buf, rawLine)return nil}buf.Reset()- buf.Grow(len(rawLine))if !p.mutated && p.rawSafe {buf.Write(rawLine)} else {@@ -254,7 +280,7 @@ func (p *processor) cleanProperties(v *value) (*value, error) {return p.cleanTemporaryProperties(v)}if p.kind == personProperties {- return p.cleanNode(nil, v)+ return p.cleanNode(nil, v, 1)}return p.cleanEventProperties(v)}@@ -263,34 +289,31 @@ func (p *processor) cleanTemporaryProperties(v *value) (*value, error) {if v.kind != kindObject {return nil, fmt.Errorf("temporary properties must be a JSON object")}- writeIdx := 0- for _, property := range v.entries {- if !isTemporaryProperty(property.key) {- p.mutated = true- p.recycle(property.value)- continue- }- v.entries[writeIdx] = property- writeIdx++- }- v.entries = v.entries[:writeIdx]- return p.cleanNode(nil, v)+ return p.cleanNode(nil, v, 1)}func (p *processor) cleanEventProperties(v *value) (*value, error) {if v.kind != kindObject {- return p.cleanNode(eventPropertyRules, v)+ return p.cleanNode(eventPropertyRules, v, 1)}var featureFlags *valuehasFeatureProperties := false+ hasFeatureKeys := falsefor _, property := range v.entries {+ if !strings.HasPrefix(property.key, "$feature") {+ continue+ }+ hasFeatureKeys = trueif strings.HasPrefix(property.key, "$feature/") {hasFeatureProperties = true} else if property.key == "$feature_flags" && property.value.kind == kindObject && featureFlags == nil {featureFlags = property.value}}+ if !hasFeatureKeys {+ return p.cleanNode(eventPropertyRules, v, 1)+ }createdFeatureFlags := hasFeatureProperties && featureFlags == nilif createdFeatureFlags {featureFlags = p.newValue(kindObject)@@ -298,8 +321,7 @@ func (p *processor) cleanEventProperties(v *value) (*value, error) {writeIdx := 0for _, property := range v.entries {- _, drop := droppedEventPropertyKeys[property.key]- if drop || isTemporaryProperty(property.key) || hasFeatureProperties && property.key == "$feature_flags" && property.value != featureFlags {+ if hasFeatureProperties && property.key == "$feature_flags" && property.value != featureFlags {p.mutated = truep.recycle(property.value)continue@@ -316,7 +338,7 @@ func (p *processor) cleanEventProperties(v *value) (*value, error) {if createdFeatureFlags {v.entries = append(v.entries, entry{key: "$feature_flags", value: featureFlags})}- cleaned, err := p.cleanNode(eventPropertyRules, v)+ cleaned, err := p.cleanNode(eventPropertyRules, v, 1)if err != nil {return nil, err}@@ -333,17 +355,17 @@ func (p *processor) cleanEventProperties(v *value) (*value, error) {}func (p *processor) newValue(kind valueKind) *value {+ if p.discard {+ return nil+ }n := len(p.free)if n == 0 {return &value{kind: kind}}v := p.free[n-1]+ p.free[n-1] = nilp.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}@@ -351,34 +373,62 @@ func (p *processor) recycle(v *value) {if v == nil {return}+ if v.kind < kindObject && cap(v.entries) <= 16 && cap(v.values) <= 16 {+ if len(p.free) < maxRecycledValues {+ v.s = ""+ v.b = false+ p.free = append(p.free, v)+ }+ return+ }for _, entry := range v.entries {p.recycle(entry.value)}for _, child := range v.values {p.recycle(child)}+ // A single large retained property must not pin its entire tree in an executable pool worker.+ if len(p.free) >= maxRecycledValues {+ return+ }v.s = ""v.b = false// Keep small arrays for reuse; bound clearing work for larger ones by this row's size.if cap(v.entries) > max(16, 2*len(v.entries)) {+ p.cacheEntries(v.entries)v.entries = nil}if cap(v.values) > max(16, 2*len(v.values)) {v.values = nil}// Truncated entries can still hold borrowed keys that retain entire input rows.- clear(v.entries[:cap(v.entries)])- clear(v.values[:cap(v.values)])+ if v.kind == kindObject {+ clear(v.entries[:cap(v.entries)])+ } else if v.kind == kindArray {+ clear(v.values[:cap(v.values)])+ }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+func (p *processor) cacheEntries(entries []entry) {+ if cap(entries) <= 16 || cap(entries) > min(maxRecycledValues, len(p.data)) {+ return+ }+ // One buffer per size class retains fewer than 8,192 entries across all classes.+ i := bits.Len(uint(cap(entries)-1)) - 5+ if cap(entries) > cap(p.entryBuffers[i]) {+ clear(entries[:cap(entries)])+ p.entryBuffers[i] = entries[:0]+ p.entryBufferMask |= 1 << i+ }+}++func (p *processor) parseValue(depth, arrayDepth int) (*value, error) {+ if depth > maxJSONDepth {+ return nil, errMaxJSONDepth}- defer p.leaveJSONDepth()p.skipWS()if p.pos >= len(p.data) {@@ -387,23 +437,27 @@ func (p *processor) parseValue() (*value, error) {switch p.data[p.pos] {case '{':- return p.parseObject()+ return p.parseObject(depth, arrayDepth)case '[':- return p.parseArray()+ return p.parseArray(depth, arrayDepth)case '"':s, err := p.parseString()if err != nil {return nil, err}v := p.newValue(kindString)- v.s = s+ if v != nil {+ v.s = s+ }return v, nilcase 't':if !p.consumeLiteral("true") {return nil, fmt.Errorf("invalid literal at byte %d", p.pos)}v := p.newValue(kindBool)- v.b = true+ if v != nil {+ v.b = true+ }return v, nilcase 'f':if !p.consumeLiteral("false") {@@ -422,6 +476,9 @@ func (p *processor) parseValue() (*value, error) {return nil, err}v := p.newValue(kindNumber)+ if v == nil {+ return nil, nil+ }if shouldStringifyNumber(num) {p.mutated = truev.kind = kindString@@ -433,9 +490,12 @@ func (p *processor) parseValue() (*value, error) {}}-func (p *processor) parseObject() (*value, error) {+func (p *processor) parseObject(depth, arrayDepth int) (*value, error) {p.pos++obj := p.newValue(kindObject)+ if obj != nil && cap(p.entriesBuf) > cap(obj.entries) {+ obj.entries, p.entriesBuf = p.entriesBuf, obj.entries+ }p.skipWS()if p.consumeByte('}') {return obj, nil@@ -457,12 +517,26 @@ func (p *processor) parseObject() (*value, error) {p.recycle(obj)return nil, fmt.Errorf("expected ':' at byte %d", p.pos)}- child, err := p.parseValue()+ discard := p.discard+ if depth == 1 {+ switch p.kind {+ case eventProperties:+ p.discard = isDroppedEventProperty(key) || isTemporaryProperty(key)+ case temporaryProperties:+ p.discard = !isTemporaryProperty(key)+ }+ p.mutated = p.mutated || p.discard+ }+ // Discarded properties still pass the same syntax and depth validation.+ child, err := p.parseValue(depth+1, arrayDepth)+ p.discard = discardif err != nil {p.recycle(obj)return nil, err}- obj.entries = append(obj.entries, entry{key: key, value: child})+ if obj != nil && child != nil {+ obj.entries = append(obj.entries, entry{key: key, value: child})+ }p.skipWS()if p.consumeByte('}') {return obj, nil@@ -474,7 +548,11 @@ func (p *processor) parseObject() (*value, error) {}}-func (p *processor) parseArray() (*value, error) {+func (p *processor) parseArray(depth, arrayDepth int) (*value, error) {+ arrayDepth+++ if arrayDepth > maxJSONArrayDepth {+ p.tooDeepArrays = true+ }p.pos++arr := p.newValue(kindArray)p.skipWS()@@ -483,12 +561,14 @@ func (p *processor) parseArray() (*value, error) {}for {- child, err := p.parseValue()+ child, err := p.parseValue(depth+1, arrayDepth)if err != nil {p.recycle(arr)return nil, err}- arr.values = append(arr.values, child)+ if arr != nil {+ arr.values = append(arr.values, child)+ }p.skipWS()if p.consumeByte(']') {return arr, nil@@ -500,80 +580,101 @@ func (p *processor) parseArray() (*value, error) {}}+var stringSpecialBytes = func() (special [256]bool) {+ for i := range 0x20 {+ special[i] = true+ }+ special['"'], special['\\'] = true, true+ return+}()+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]+ start := quote + 1+ for i, c := range p.data[start:] {+ if !stringSpecialBytes[c] {+ continue+ }switch {case c == '"':- s := borrowedString(p.data[start:p.pos])- p.pos+++ s := borrowedString(p.data[start : start+i])+ p.pos = start + i + 1return s, nilcase c == '\\':+ p.pos = start + ireturn p.parseEscapedString(quote)case c < 0x20:- return "", fmt.Errorf("invalid control character at byte %d", p.pos)- default:- p.pos+++ return "", fmt.Errorf("invalid control character at byte %d", start+i)}}return "", fmt.Errorf("unterminated string at byte %d", quote)}func (p *processor) parseEscapedString(quote int) (string, error) {- p.pos = quote + 1p.stringBuf.Reset()-+ if !p.discard {+ p.stringBuf.Write(p.data[quote+1 : p.pos])+ }for p.pos < len(p.data) {- c := p.data[p.pos]- switch {- case c == '"':+ start := p.pos+ p.pos = len(p.data)+ for i, c := range p.data[start:] {+ if stringSpecialBytes[c] {+ p.pos = start + i+ break+ }+ }+ if !p.discard {+ p.stringBuf.Write(p.data[start:p.pos])+ }+ if p.pos == len(p.data) {+ break+ }+ switch p.data[p.pos] {+ case '"':p.pos++return p.stringBuf.String(), nil- case c == '\\':+ case '\\':p.pos++if p.pos >= len(p.data) {return "", fmt.Errorf("unterminated escape at byte %d", p.pos)}+ var decoded byteswitch p.data[p.pos] {case '"', '\\', '/':- if p.data[p.pos] == '/' {+ decoded = p.data[p.pos]+ if decoded == '/' {p.rawSafe = false}- p.stringBuf.WriteByte(p.data[p.pos])- p.pos++case 'b':- p.stringBuf.WriteByte('\b')- p.pos+++ decoded = '\b'case 'f':- p.stringBuf.WriteByte('\f')- p.pos+++ decoded = '\f'case 'n':- p.stringBuf.WriteByte('\n')- p.pos+++ decoded = '\n'case 'r':- p.stringBuf.WriteByte('\r')- p.pos+++ decoded = '\r'case 't':- p.stringBuf.WriteByte('\t')- p.pos+++ decoded = '\t'case 'u':p.rawSafe = falser, err := p.parseUnicodeEscape()if err != nil {return "", err}- p.stringBuf.WriteRune(r)+ if !p.discard {+ p.stringBuf.WriteRune(r)+ }+ continuedefault: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)+ if !p.discard {+ p.stringBuf.WriteByte(decoded)+ }p.pos+++ default:+ return "", fmt.Errorf("invalid control character at byte %d", p.pos)}}return "", fmt.Errorf("unterminated string at byte %d", quote)@@ -622,48 +723,49 @@ func hexRune(b []byte) (rune, bool) {}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)+ start, pos := p.pos, p.pos+ if pos < len(p.data) && p.data[pos] == '-' {+ pos++}- if p.pos >= len(p.data) {+ if 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+++ if p.data[pos] == '0' {+ pos+++ } else if p.data[pos] >= '1' && p.data[pos] <= '9' {+ for pos < len(p.data) && isDigit(p.data[pos]) {+ 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)+ if pos < len(p.data) && p.data[pos] == '.' {+ pos+++ if pos >= len(p.data) || !isDigit(p.data[pos]) {+ return "", fmt.Errorf("invalid fraction at byte %d", pos)}- for p.pos < len(p.data) && isDigit(p.data[p.pos]) {- p.pos+++ for pos < len(p.data) && isDigit(p.data[pos]) {+ 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 pos < len(p.data) && (p.data[pos] == 'e' || p.data[pos] == 'E') {+ pos+++ if pos < len(p.data) && (p.data[pos] == '+' || p.data[pos] == '-') {+ pos++}- if p.pos >= len(p.data) || !isDigit(p.data[p.pos]) {- return "", fmt.Errorf("invalid exponent at byte %d", p.pos)+ if pos >= len(p.data) || !isDigit(p.data[pos]) {+ return "", fmt.Errorf("invalid exponent at byte %d", pos)}- for p.pos < len(p.data) && isDigit(p.data[p.pos]) {- p.pos+++ for pos < len(p.data) && isDigit(p.data[pos]) {+ pos++}}- return borrowedString(p.data[start:p.pos]), nil+ p.pos = pos+ return borrowedString(p.data[start:pos]), nil}func (p *processor) skipWS() {@@ -699,20 +801,23 @@ func (p *processor) consumeLiteral(s string) bool {return true}-func (p *processor) cleanNode(pathRules *pathRule, v *value) (*value, error) {- if err := p.enterJSONDepth(); err != nil {- return nil, err+func (p *processor) cleanNode(pathRules *pathRule, v *value, depth int) (*value, error) {+ // Scalar children skip recursion, but must still fit below their container's depth.+ if depth > maxJSONDepth || depth == maxJSONDepth && (len(v.entries) != 0 || len(v.values) != 0) {+ return nil, errMaxJSONDepth}- defer p.leaveJSONDepth()switch v.kind {case kindObject:- if err := p.cleanObject(pathRules, v); err != nil {+ if err := p.cleanObject(pathRules, v, depth); err != nil {return nil, err}case kindArray:for i, child := range v.values {- cleaned, err := p.cleanNode(pathRules, child)+ if child.kind < kindObject {+ continue+ }+ cleaned, err := p.cleanNode(pathRules, child, depth+1)if err != nil {return nil, err}@@ -722,8 +827,8 @@ func (p *processor) cleanNode(pathRules *pathRule, v *value) (*value, error) {return v, nil}-func (p *processor) cleanObject(pathRules *pathRule, obj *value) error {- expanded, err := p.expandDottedEntries(obj.entries)+func (p *processor) cleanObject(pathRules *pathRule, obj *value, depth int) error {+ expanded, err := p.expandDottedEntries(obj.entries, depth)if err != nil {return err}@@ -736,15 +841,18 @@ func (p *processor) cleanObject(pathRules *pathRule, obj *value) error {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+ cleaned := entry.value+ if cleaned.kind >= kindObject {+ cleaned, err = p.cleanNode(childPathRules, cleaned, depth+1)+ if err != nil {+ p.retainUnprocessedEntries(obj, writeIdx, readIdx)+ return err+ }}if childPathRules != nil && childPathRules.normalization != normalizationNone {p.mutated = trueoriginal := cleaned- cleaned, err = p.normalizeValue(childPathRules.normalization, cleaned)+ cleaned, err = p.normalizeValue(childPathRules.normalization, cleaned, depth)if err != nil {cleaned = originalif unparsable.Len() == 0 {@@ -763,8 +871,10 @@ func (p *processor) cleanObject(pathRules *pathRule, obj *value) error {p.recycle(cleaned)continue}- obj.entries[writeIdx] = entry- obj.entries[writeIdx].value = cleaned+ if writeIdx != readIdx || cleaned != entry.value {+ obj.entries[writeIdx] = entry+ obj.entries[writeIdx].value = cleaned+ }writeIdx++}obj.entries = obj.entries[:writeIdx]@@ -784,11 +894,11 @@ func (p *processor) retainUnprocessedEntries(obj *value, writeIdx, readIdx int)obj.entries = obj.entries[:writeIdx+remaining]}-func (p *processor) expandDottedEntries(entries []entry) ([]entry, error) {+func (p *processor) expandDottedEntries(entries []entry, depth int) ([]entry, error) {needsExpand := falsefor _, entry := range entries {if strings.IndexByte(entry.key, '.') >= 0 {- if p.depth+strings.Count(entry.key, ".")+1 > maxJSONDepth {+ if depth+strings.Count(entry.key, ".")+1 > maxJSONDepth {return nil, errMaxJSONDepth}needsExpand = true@@ -799,14 +909,10 @@ func (p *processor) expandDottedEntries(entries []entry) ([]entry, error) {}p.mutated = true- expanded := make([]entry, 0, len(entries))+ expanded := p.entriesBuf[:0]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)@@ -815,23 +921,17 @@ func (p *processor) expandDottedEntries(entries []entry) ([]entry, error) {}}- for key := range p.index {- delete(p.index, key)+ if len(p.index) > maxRecycledValues {+ p.index = nil+ } else {+ clear(p.index)}- return expanded, nil-}--func (p *processor) enterJSONDepth() error {- p.depth++- if p.depth > maxJSONDepth {- p.depth--- return errMaxJSONDepth+ clear(entries[:cap(entries)])+ p.entriesBuf = entries[:0]+ if cap(p.entriesBuf) > maxRecycledValues {+ p.entriesBuf = nil}- return nil-}--func (p *processor) leaveJSONDepth() {- p.depth--+ return expanded, nil}func (p *processor) writeUnparseableProperties(buf *bytes.Buffer, raw []byte) {@@ -873,6 +973,13 @@ func (p *processor) insertDottedKey(parent *value, entries *[]entry, key string,target := p.index[mk]if target == nil {target = p.newValue(kindObject)+ if p.entryBufferMask != 0 {+ i := bits.Len8(p.entryBufferMask) - 1+ if cap(p.entryBuffers[i]) > cap(target.entries) {+ target.entries, p.entryBuffers[i] = p.entryBuffers[i], nil+ p.entryBufferMask &^= 1 << i+ }+ }p.appendEntry(parent, entries, head, target)}parent = target@@ -882,16 +989,30 @@ func (p *processor) insertDottedKey(parent *value, entries *[]entry, key string,}func (p *processor) deduplicateEntries(obj *value) {- if len(obj.entries) == 0 {+ if len(obj.entries) < 2 {return}+ // Bound pairwise comparisons to small objects; wide objects use the hash table.+ if len(obj.entries) <= 16 {+ duplicate := false+ for i, entry := range obj.entries {+ for _, previous := range obj.entries[:i] {+ if previous.key == entry.key {+ duplicate = true+ break+ }+ }+ if duplicate {+ break+ }+ }+ if !duplicate {+ 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@@ -910,7 +1031,9 @@ func (p *processor) deduplicateEntries(obj *value) {keep = info.firstNonEmpty == i}if keep {- obj.entries[writeIdx] = entry+ if writeIdx != i {+ obj.entries[writeIdx] = entry+ }writeIdx++} else {p.mutated = true@@ -919,23 +1042,25 @@ func (p *processor) deduplicateEntries(obj *value) {}obj.entries = obj.entries[:writeIdx]- for key := range p.info {- delete(p.info, key)+ if len(p.info) > maxRecycledValues {+ p.info = nil+ } else {+ clear(p.info)}}-func (p *processor) normalizeValue(normalization normalizationKind, v *value) (*value, error) {+func (p *processor) normalizeValue(normalization normalizationKind, v *value, depth int) (*value, error) {switch normalization {case normalizationStringArray:- return p.coerceStringArray(v)+ return p.coerceStringArray(v, depth)case normalizationObjectArray:- return p.coerceObjectArray(v)+ return p.coerceObjectArray(v, depth)default:return v, nil}}-func (p *processor) coerceObjectArray(v *value) (*value, error) {+func (p *processor) coerceObjectArray(v *value, depth int) (*value, error) {switch v.kind {case kindArray:for _, child := range v.values {@@ -955,11 +1080,11 @@ func (p *processor) coerceObjectArray(v *value) (*value, error) {if isNullishString(raw) {return p.reuseAsEmptyArray(v), nil}- parsed, err := p.parseStringifiedJSON(raw)+ parsed, err := p.parseStringifiedJSON(raw, depth)if err != nil {return nil, err}- normalized, err := p.coerceObjectArray(parsed)+ normalized, err := p.coerceObjectArray(parsed, depth)if err != nil {p.recycle(parsed)return nil, err@@ -994,7 +1119,7 @@ func valueKindName(kind valueKind) string {}}-func (p *processor) coerceStringArray(v *value) (*value, error) {+func (p *processor) coerceStringArray(v *value, depth int) (*value, error) {switch v.kind {case kindArray:oldValues := v.values@@ -1020,11 +1145,11 @@ func (p *processor) coerceStringArray(v *value) (*value, error) {if isEmptyArrayString(trimmed) {return p.reuseAsEmptyArray(v), nil}- if parsed, ok, err := p.parseStringifiedJSONArray(trimmed); err != nil {+ if parsed, ok, err := p.parseStringifiedJSONArray(trimmed, depth); err != nil {return nil, err} else if ok {p.recycle(v)- return p.coerceStringArray(parsed)+ return p.coerceStringArray(parsed, depth)}return p.reuseAsStringArray(v, v.s), nildefault:@@ -1039,6 +1164,8 @@ func (p *processor) resetValue(v *value, kind valueKind) {for _, child := range v.values {p.recycle(child)}+ clear(v.entries[:cap(v.entries)])+ clear(v.values[:cap(v.values)])v.kind = kindv.s = ""v.b = false@@ -1059,7 +1186,7 @@ func (p *processor) reuseAsStringArray(v *value, s string) *value {return v}-func (p *processor) parseStringifiedJSON(raw string) (*value, error) {+func (p *processor) parseStringifiedJSON(raw string, depth int) (*value, error) {if raw == "" || (raw[0] != '[' && raw[0] != '{') {return nil, fmt.Errorf("cannot coerce %q to Array(JSON)", raw)}@@ -1067,7 +1194,7 @@ func (p *processor) parseStringifiedJSON(raw string) (*value, error) {oldData, oldPos := p.data, p.posp.data = borrowedBytes(raw)p.pos = 0- parsed, err := p.parseValue()+ parsed, err := p.parseValue(depth+1, 0)if err != nil {p.data, p.pos = oldData, oldPosreturn nil, fmt.Errorf("cannot coerce %q to Array(JSON): %w", raw, err)@@ -1078,7 +1205,7 @@ func (p *processor) parseStringifiedJSON(raw string) (*value, error) {p.data, p.pos = oldData, oldPosreturn nil, fmt.Errorf("cannot coerce %q to Array(JSON): trailing data", raw)}- cleaned, err := p.cleanNode(nil, parsed)+ cleaned, err := p.cleanNode(nil, parsed, depth+1)p.data, p.pos = oldData, oldPosif err != nil {p.recycle(parsed)@@ -1087,7 +1214,7 @@ func (p *processor) parseStringifiedJSON(raw string) (*value, error) {return cleaned, nil}-func (p *processor) parseStringifiedJSONArray(raw string) (*value, bool, error) {+func (p *processor) parseStringifiedJSONArray(raw string, depth int) (*value, bool, error) {if raw == "" || raw[0] != '[' {return nil, false, nil}@@ -1095,7 +1222,7 @@ func (p *processor) parseStringifiedJSONArray(raw string) (*value, bool, error)oldData, oldPos := p.data, p.posp.data = borrowedBytes(raw)p.pos = 0- parsed, err := p.parseValue()+ parsed, err := p.parseValue(depth+1, 0)if err != nil {p.data, p.pos = oldData, oldPosreturn nil, false, nil@@ -1106,7 +1233,7 @@ func (p *processor) parseStringifiedJSONArray(raw string) (*value, bool, error)p.data, p.pos = oldData, oldPosreturn nil, false, nil}- cleaned, err := p.cleanNode(nil, parsed)+ cleaned, err := p.cleanNode(nil, parsed, depth+1)p.data, p.pos = oldData, oldPosif err != nil {return nil, false, err@@ -1237,7 +1364,7 @@ func isEmptyArrayString(s string) bool {}func shouldStringifyNumber(num string) bool {- if len(num) == 0 {+ if len(num) < 19 {return false}@@ -1300,14 +1427,30 @@ func borrowedBytes(s string) []byte {return unsafe.Slice(unsafe.StringData(s), len(s))}+func readLine(reader *bufio.Reader) ([]byte, error) {+ line, err := reader.ReadSlice('\n')+ if err != bufio.ErrBufferFull {+ return line, err+ }+ // Only rows larger than the reader buffer need an owned copy.+ var full []byte+ for {+ full = append(full, line...)+ if err != bufio.ErrBufferFull {+ return full, err+ }+ line, err = reader.ReadSlice('\n')+ }+}+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)+ reader := bufio.NewReaderSize(input, 64*1024)+ writer := bufio.NewWriterSize(output, 64*1024)buf := bytes.NewBuffer(make([]byte, 0, 64*1024))proc := processor{kind: kind}for {- line, err := reader.ReadBytes('\n')+ line, err := readLine(reader)if err != nil && err != io.EOF {return fmt.Errorf("stdin read error: %w", err)}@@ -1336,8 +1479,8 @@ func run(input io.Reader, output io.Writer, kind propertiesKind) error {}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)+ reader := bufio.NewReaderSize(input, 64*1024)+ writer := bufio.NewWriterSize(output, 64*1024)buf := bytes.NewBuffer(make([]byte, 0, 64*1024))proc := processor{kind: kind}@@ -1349,7 +1492,7 @@ func runChunked(input io.Reader, output io.Writer, kind propertiesKind) error {return fmt.Errorf("chunk header read error: %w", err)}for range rows {- line, err := reader.ReadBytes('\n')+ line, err := readLine(reader)if err != nil {return fmt.Errorf("stdin read error: %w", err)}@@ -1358,7 +1501,10 @@ func runChunked(input io.Reader, output io.Writer, kind propertiesKind) error {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 {+ if _, writeErr := writer.Write(buf.Bytes()); writeErr != nil {+ return fmt.Errorf("stdout write error: %w", writeErr)+ }+ if writeErr := writer.WriteByte('\n'); writeErr != nil {return fmt.Errorf("stdout write error: %w", writeErr)}}diff --git a/clickhouse-udfs/util/cmd/json_clean_posthog_event_properties_udf/main_test.go b/clickhouse-udfs/util/cmd/json_clean_posthog_event_properties_udf/main_test.goindex d9b860683247..6698522c47f9 100644--- a/clickhouse-udfs/util/cmd/json_clean_posthog_event_properties_udf/main_test.go+++ b/clickhouse-udfs/util/cmd/json_clean_posthog_event_properties_udf/main_test.go@@ -2,7 +2,9 @@ package mainimport ("bytes"+ "encoding/json""fmt"+ "io""os""path/filepath""runtime"@@ -15,12 +17,19 @@ 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)+ for _, width := range []int{0, 16, 256} {+ var prefix strings.Builder+ prefix.WriteByte('{')+ for i := range width {+ fmt.Fprintf(&prefix, `"key%d":%d,`, i, i)+ }+ var got bytes.Buffer+ if err := processLine([]byte(prefix.String()+string(input[1:])), &got); err != nil {+ t.Fatal(err)+ }+ if expected := prefix.String() + want[1:]; got.String() != expected {+ t.Fatalf("processLine() = %s, want %s", got.String(), expected)+ }}}@@ -53,6 +62,7 @@ func TestProcessLinePreservesPersonProperties(t *testing.T) {func TestProcessLineGroupsFeaturePropertiesAndPreservesExistingFlagValues(t *testing.T) {tests := map[string]string{+ `{"$feature_flags.z":true,"$feature_flags.a":false,"other":1}`: `{"$feature_flags":{"a":false,"z":true},"other":1}`,`{"$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"}`: `{"$feature_flags":{"config":{"nested":{"value":"dropped"}},"enabled":true,"existing":"kept","first-flag":"existing","number":42},"other":"value"}`,`{"$feature/zebra":false,"$feature/alpha":"control","other":1}`: `{"other":1,"$feature_flags":{"alpha":"control","zebra":false}}`,`{"$feature_flags":{"zebra":false,"alpha":"control"}}`: `{"$feature_flags":{"alpha":"control","zebra":false}}`,@@ -183,6 +193,25 @@ func TestProcessLineArrayDepthBoundary(t *testing.T) {}}+func TestProcessLineDottedDepthBoundary(t *testing.T) {+ for _, depth := range []int{maxJSONDepth - 1, maxJSONDepth} {+ for _, leaf := range []string{`1`, `{}`, `{"y":1}`, `[1]`} {+ input := `{"` + strings.Repeat("x.", depth-2) + `x":` + leaf + `}`+ want := strings.Repeat(`{"x":`, depth-1) + leaf + strings.Repeat(`}`, depth-1)+ if depth == maxJSONDepth && (leaf == `{"y":1}` || leaf == `[1]`) {+ want = fmt.Sprintf(`{"$unparseable_properties":%q}`, input)+ }+ var output bytes.Buffer+ if err := processLine([]byte(input), &output); err != nil {+ t.Fatal(err)+ }+ if output.String() != want {+ t.Fatalf("depth=%d leaf=%s: got %s, want %s", depth, leaf, output.String(), want)+ }+ }+ }+}+func TestProcessLineChecksArrayDepthAfterNormalization(t *testing.T) {for _, depth := range []int{7, 8} {object := `{"x":` + strings.Repeat(`[`, depth) + `1` + strings.Repeat(`]`, depth) + `}`@@ -257,11 +286,11 @@ func TestCleanNodeMatchesNestedArrayStringPath(t *testing.T) {var proc processorproc.data = input- parsed, err := proc.parseValue()+ parsed, err := proc.parseValue(1, 0)if err != nil {t.Fatal(err)}- cleaned, err := proc.cleanNode(makePathRules("outer.$exception_sources"), parsed)+ cleaned, err := proc.cleanNode(makePathRules("outer.$exception_sources"), parsed, 1)if err != nil {t.Fatal(err)}@@ -288,9 +317,95 @@ func TestProcessLineHandlesEscapedDottedKeysAndStrings(t *testing.T) {}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")+ for _, invalid := range []string{+ `{"broken"`, `{"x":1,}`, `[1,]`, `01`, `1e`, `true false`,+ `"unterminated`, `"bad\q"`, `"bad\uXYZW"`, `"\ud800"`, `"\ud800\u0041"`,+ "\"control\x01\"", strings.Repeat(`[`, 9) + `1,]` + strings.Repeat(`]`, 8),+ } {+ for _, key := range []string{"keep", "$ai_input", "$set"} {+ for _, kind := range []propertiesKind{eventProperties, personProperties, temporaryProperties} {+ var got bytes.Buffer+ proc := processor{kind: kind}+ input := fmt.Sprintf(`{%q:%s}`, key, invalid)+ if err := proc.processLine([]byte(input), &got); err == nil {+ t.Fatalf("expected error for malformed JSON (%d): %s", kind, input)+ }+ if err := proc.processLine([]byte(`{"$set":1,"keep":2}`), &got); err != nil {+ t.Fatal(err)+ }+ want := `{"keep":2}`+ if kind == personProperties {+ want = `{"$set":1,"keep":2}`+ } else if kind == temporaryProperties {+ want = `{"$set":1}`+ }+ if got.String() != want {+ t.Fatalf("row after parse error = %s, want %s", got.String(), want)+ }+ }+ }+ }+}++func TestRunReusesInputBuffer(t *testing.T) {+ for _, size := range []int{31, 4*1024*1024 + 17} {+ text := strings.Repeat("x", size) + "\n\t\"\\😀"+ encoded, err := json.Marshal(text)+ if err != nil {+ t.Fatal(err)+ }+ row := `{"keep":` + string(encoded) + `,"$ai_input":` + string(encoded) + `}`+ cleaned := `{"keep":` + string(encoded) + `}`+ for _, newline := range []string{"\n", "\r\n"} {+ for _, chunked := range []bool{false, true} {+ input := row + newline + `{"keep":1}` + newline+ runner := run+ if chunked {+ input = "1\n" + row + newline + "1\n" + `{"keep":1}` + newline+ runner = runChunked+ }+ var got bytes.Buffer+ if err := runner(strings.NewReader(input), &got, eventProperties); err != nil {+ t.Fatal(err)+ }+ if got.String() != cleaned+"\n"+`{"keep":1}`+"\n" {+ t.Fatalf("incorrect output (size=%d, chunked=%t)", size, chunked)+ }+ }+ }+ var got bytes.Buffer+ if err := run(strings.NewReader(row), &got, eventProperties); err != nil || got.String() != cleaned {+ t.Fatalf("final row without newline: %v", err)+ }+ if err := runChunked(strings.NewReader("1\n"+row), io.Discard, eventProperties); err == nil {+ t.Fatal("expected truncated chunk to fail")+ }+ }+}++func TestProcessLineStringBytes(t *testing.T) {+ for _, offset := range []int{0, 7, 8, 15, 16, 31, 32} {+ for c := range 256 {+ input := []byte(`{"keep":"` + strings.Repeat("a", offset) + string([]byte{byte(c)}) + `x"}`)+ valid := c >= 0x20 && c != '"' && c != '\\'+ for _, kind := range []propertiesKind{eventProperties, personProperties, temporaryProperties} {+ var output bytes.Buffer+ proc := processor{kind: kind}+ err := proc.processLine(input, &output)+ if (err == nil) != valid {+ t.Fatalf("offset=%d byte=%d kind=%d: error=%v, valid=%t", offset, c, kind, err, valid)+ }+ if valid {+ want := input+ if kind == temporaryProperties {+ want = []byte(`{}`)+ }+ if !bytes.Equal(output.Bytes(), want) {+ t.Fatalf("offset=%d byte=%d kind=%d: got %q, want %q", offset, c, kind, output.Bytes(), want)+ }+ }+ }+ }}}@@ -338,7 +453,7 @@ func TestProcessLineReleasesPreviousInput(t *testing.T) {t.Run(fmt.Sprint(kind), func(t *testing.T) {proc := processor{kind: kind}var output bytes.Buffer- input := []byte(`{"$set":1,"discard":null}`)+ input := []byte(`{"$set":1,"discard":null,"nested.path":2,"$sdk_debug_probe.path":3,"escaped\u002ekey":"line\n"}`)previousInput := weak.Make(&input[0])if err := proc.processLine(input, &output); err != nil {t.Fatal(err)@@ -404,6 +519,71 @@ func TestProcessLineReleasesOversizedContainers(t *testing.T) {}}+func TestProcessLineBoundsRetainedMemory(t *testing.T) {+ input := []byte(`{"keep":[` + strings.Repeat(`{"x":1},`, 8192) + `{}]}`)+ var proc processor+ var output bytes.Buffer+ if err := proc.processLine(input, &output); err != nil {+ t.Fatal(err)+ }+ if !bytes.Equal(output.Bytes(), input) {+ t.Fatal("large retained property changed")+ }+ if len(proc.free) > maxRecycledValues {+ t.Fatalf("retained %d parser nodes after a large row", len(proc.free))+ }+ if err := proc.processLine([]byte(`{}`), &output); err != nil {+ t.Fatal(err)+ }+ if output.String() != "{}" || output.Cap() > 64*1024 {+ t.Fatalf("small row output length=%d capacity=%d", output.Len(), output.Cap())+ }+}++func TestProcessLineReusesDottedBuffers(t *testing.T) {+ var proc processor+ var output bytes.Buffer+ for _, width := range []int{32, 256, 4096, 17, 512, 32, 256, 1} {+ var input, expected strings.Builder+ input.WriteByte('{')+ expected.WriteString(`{"group":{`)+ for i := range width {+ if i > 0 {+ input.WriteByte(',')+ expected.WriteByte(',')+ }+ fmt.Fprintf(&input, `"group.key%d":%d`, i, i)+ fmt.Fprintf(&expected, `"key%d":%d`, i, i)+ }+ input.WriteByte('}')+ expected.WriteString("}}")+ if err := proc.processLine([]byte(input.String()), &output); err != nil {+ t.Fatal(err)+ }+ if output.String() != expected.String() {+ t.Fatalf("dotted expansion changed after buffer reuse at width %d", width)+ }+ retained := 0+ for _, entries := range proc.entryBuffers {+ retained += cap(entries)+ for _, entry := range entries[:cap(entries)] {+ if entry.key != "" || entry.value != nil {+ t.Fatal("cached entry retains input or a recycled value")+ }+ }+ }+ if retained >= 8192 {+ t.Fatalf("cached %d entries", retained)+ }+ }+ if err := proc.processLine([]byte(`{}`), &output); err != nil {+ t.Fatal(err)+ }+ if proc.entryBufferMask != 0 {+ t.Fatal("small row retains oversized cached buffers")+ }+}+func TestShouldStringifyNumber(t *testing.T) {tests := map[string]bool{"18446744073709551615": false,diff --git a/docs/internal/clickhouse-utility-udfs.md b/docs/internal/clickhouse-utility-udfs.mdindex ff6176f09fc8..14b0850e052a 100644--- a/docs/internal/clickhouse-utility-udfs.md+++ b/docs/internal/clickhouse-utility-udfs.md@@ -7,9 +7,16 @@ Flag values and person-property ordering follow the existing cleanup rules.See [the utility UDF README](../../clickhouse-udfs/util/README.md) for build and integration-test commands.-The event, person, and temporary cleaners reuse parser nodes across rows.+The event, person, and temporary cleaners reuse at most 4,096 parser nodes across rows.Recycled nodes keep small backing arrays for reuse and release larger arrays whose capacity exceeds twice their used length, so a wide row does not make later small rows repeatedly clear oversized arrays.They clear references across the remaining backing arrays, including entries removed during cleanup, so borrowed property keys do not retain previously processed input rows.+The parser validates discarded properties without allocating their value trees or decoding their strings into buffers.+Dotted-key expansion reuses a scratch entry slice and up to eight cleared backing arrays, one per size class, totaling less than 192 KiB.+The backing-array cache releases buffers larger than the next input row; scratch slices and lookup maps exceeding 4,096 entries are released.+Output and decoded-string buffers larger than 64 KiB are released when their capacity exceeds twice the next input row's length.+Each worker uses 64 KiB input and output buffers and borrows ordinary input rows directly from the reader.+Rows exceeding the reader buffer are assembled into an owned slice without imposing a new row-size limit.+These limits bound reuse, not the size of an accepted property: a large retained document still needs memory proportional to its contents.### Array nesting limit@@ -18,7 +25,7 @@ This limit is separate from the general JSON depth limit of 300.Small documents with deeply nested arrays and nulls can cause excessive memory allocation during ClickHouse JSON type inference.The eight-array limit is a conservative input policy, not a guarantee against every possible inference failure.-The cleaners check the parsed document before filtering properties and check the normalized result before emitting it.+The parser counts array nesting even inside discarded properties and checks the normalized result before emitting it.The second check covers arrays decoded from strings or introduced by schema normalization.Event and person cleaners preserve a rejected document verbatim as an escaped JSON string under `$unparseable_properties`.The rejected document's original properties are no longer available as individually queryable JSON paths.@@ -55,3 +62,95 @@ SELECTBoth functions use the same executable. The temporary entry point uses `--temporary-properties` with the existing chunk protocol.Documents exceeding the shared depth limit produce `{}` in the temporary output; the permanent cleaner quarantines the original document.++### Benchmarking the cleaner++`BenchmarkProcessFixture` measures cleaning with a reused processor and output buffer.+One fixture operation processes the entire supplied file, so divide allocations and elapsed time by its row count for per-row figures.++To use the public [JSONBench Bluesky dataset](https://github.com/ClickHouse/JSONBench), run these commands from `clickhouse-udfs/util`:++```sh+mkdir -p /tmp/cleaner-bench+curl -fL https://clickhouse-public-datasets.s3.amazonaws.com/bluesky/file_0001.json.gz -o /tmp/cleaner-bench/bluesky.json.gz+gzip -dk /tmp/cleaner-bench/bluesky.json.gz+head -n 10000 /tmp/cleaner-bench/bluesky.json > /tmp/cleaner-bench/sample.json+BENCH_FILE=/tmp/cleaner-bench/sample.json go test -run '^$' -bench Fixture -benchmem -cpu=1 -count=5 ./cmd/json_clean_posthog_event_properties_udf+go test -run '^$' -bench Process -benchmem -cpu=1 -count=5 ./cmd/json_clean_posthog_event_properties_udf+```++For whole-file throughput and process memory, build the executable and process the decompressed file directly.+Keep decompression outside the timed command and compare output hashes before interpreting timings.+On macOS, `/usr/bin/time -l` reports peak RSS in bytes; on Linux, `/usr/bin/time -v` reports it in KiB.++```sh+go build -o /tmp/cleaner-bench/cleaner ./cmd/json_clean_posthog_event_properties_udf+GOMAXPROCS=1 /usr/bin/time -l /tmp/cleaner-bench/cleaner < /tmp/cleaner-bench/bluesky.json > /dev/null+```++#### Results recorded September 8, 2026++Baseline: commit `8044a57049952b3423b5e26a8d85ddb1bb8e6953`.+Host: Apple M4 Pro, macOS arm64, Go 1.25.5.+The Bluesky file contains 1,000,000 rows and 480,778,277 bytes, including newlines.+Its decompressed SHA-256 is `7beb29f6c036fe784754ff34d68d1f216c6cc89de12155da06f725bdf5c8536e`.+Native executable results are medians of seven runs with `GOMAXPROCS=1`, alternating baseline, first-pass, and final binaries, with cached file input and output sent to `/dev/null`.+RSS is the median of each run's maximum resident set size, not live heap size.++| Workload | Before | First pass | Final | Speedup | Peak RSS before / final |+| ------------------------------------------ | ------: | ---------: | ------: | ------: | ----------------------: |+| Bluesky, event executable | 2.04 s | 0.86 s | 0.57 s | 3.58× | 24.50 / 8.62 MiB |+| Bluesky, person executable | 1.87 s | 0.77 s | 0.52 s | 3.60× | 23.48 / 8.62 MiB |+| Bluesky, temporary executable | 1.34 s | 0.52 s | 0.32 s | 4.19× | 23.83 / 3.72 MiB |+| Large discarded payloads, event executable | 0.58 s | 0.30 s | 0.15 s | 3.87× | 30.36 / 8.55 MiB |+| Bluesky, event UDF inside ClickHouse | 2.080 s | 0.952 s | 0.710 s | 2.93× | Not measured |++The discarded-payload file repeats the synthetic `BenchmarkProcessWorkloads/dropped` row 1,000 times, totaling 172,018,000 bytes.+Its repeated shape exercises disposal of large object arrays; it is not representative of every event distribution.+All four executable comparisons produced identical SHA-256 output hashes for all three versions.+A further 10,000 generated objects containing duplicate and dotted keys, exceptional values, large integers, and PostHog-specific properties produced identical output hashes in all three modes.+Bluesky exercises real nested JSON and strings, but does not contain PostHog's special property names, so synthetic workloads cover those transformations separately.++ClickHouse measurements used version 26.6.2.158 in Docker on the same host, with the dataset copied into the container.+All three executable-pool functions used the repository's `Raw` format and chunk headers.+Results are medians of seven alternating query runs after one warmup for each of the three binaries:++```sql+SELECT sum(length(CleanBefore(json)))+FROM file('bluesky.json', 'JSONAsString', 'json String')+SETTINGS max_threads = 1, max_block_size = 65536;+-- Repeat with CleanAfter, backed by the optimized executable.+```++All three versions returned `479709047`.+A separate `countIf(CleanBefore(json) != CleanAfter(json))` comparison across the million rows returned zero.+These timings include file parsing and UDF transport; they do not measure inserts, JSON-column type inference, or production concurrency.++Microbenchmark results are medians of five alternating runs with `-cpu=1 -benchtime=500ms`.+They measure parser work separately from whole-process memory.++| Workload | Before | First pass | Final | Allocations before / final |+| ----------------------------------------- | -------: | ---------: | -------: | -------------------------: |+| Bluesky, 10,000 rows | 16.10 ms | 7.30 ms | 4.76 ms | 301 / 268 |+| Transformation fixture, 256 rows | 396.8 µs | 247.3 µs | 205.0 µs | 1,024 / 0 |+| Clean object | 378.4 ns | 229.3 ns | 138.7 ns | 0 / 0 |+| Wide object, 256 keys | 17.96 µs | 17.36 µs | 13.86 µs | 0 / 0 |+| Dotted object, 256 keys | 42.55 µs | 40.72 µs | 25.63 µs | 19 / 0 |+| Escaped string | 27.23 µs | 16.24 µs | 15.70 µs | 1 / 1 |+| Large discarded payload | 581.7 µs | 244.2 µs | 127.7 µs | 4,139 / 0 |+| Temporary payload filtered from event | 10.27 µs | 5.30 µs | 2.90 µs | 9 / 0 |+| Feature flags and exception normalization | 707.0 ns | 512.7 ns | 417.5 ns | 1 / 1 |++The first pass removed discarded-value allocations, per-row input copies, redundant traversals, and oversized I/O buffers.+Repeated CPU profiles then identified depth-counter updates, scalar recursion, string classification, recycling, and root-key hashing as remaining costs.+The final version passes depth explicitly, skips no-op scalar cleanup while preserving depth checks, classifies string bytes with a 256-byte table, avoids redundant copies, and replaces the fixed discard map with a string switch.+A bounded entry-buffer cache removes repeated dotted-expansion allocations: allocated bytes for the dotted workload fell from 37,972 to approximately 5 per row, amortizing initial buffer allocation, with zero allocations after warmup.+The final Bluesky CPU profile attributes approximately 31% of samples to string parsing, 10% to recycling, and 7% to duplicate checking, including callees.+Two portable eight-byte string-scanning experiments were rejected because they did not improve Bluesky and slowed escaped strings or small objects.++Validation covered the module's unit tests, race detector, `go vet`, both Linux architecture builds, and the ClickHouse stateless fixtures, including quarantine-to-JSON casts.+Temporary differential fuzzing against the baseline compared output bytes and error acceptance across all three modes for approximately 12 million inputs during the first pass, then 988,086 additional generated inputs on the final implementation.+Regression tests cover malformed discarded values, duplicate handling in wide objects, every string byte at multiple offsets, dotted expansion at the depth boundary, escaped rows exceeding the I/O buffer, truncated chunks, processor recovery, and retained-memory limits.+The buffer-reuse test alternates dotted-object widths and verifies exact output, cleared references, the cache bound, and release after a small row.++These local measurements should be repeated on deployment hardware before estimating fleet capacity.diff --git a/posthog/user_scripts/json_clean_posthog_event_properties_udf_aarch64 b/posthog/user_scripts/json_clean_posthog_event_properties_udf_aarch64index 1b242fb807c6..0b9ff0ed4eb5 100755Binary files a/posthog/user_scripts/json_clean_posthog_event_properties_udf_aarch64 and b/posthog/user_scripts/json_clean_posthog_event_properties_udf_aarch64 differdiff --git a/posthog/user_scripts/json_clean_posthog_event_properties_udf_x86_64 b/posthog/user_scripts/json_clean_posthog_event_properties_udf_x86_64index d444917054c2..84ac366feef8 100755Binary files a/posthog/user_scripts/json_clean_posthog_event_properties_udf_x86_64 and b/posthog/user_scripts/json_clean_posthog_event_properties_udf_x86_64 differ