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 pooled json drop keys udf (#105844)

Rory Shanksb2bc2750b3a1
diff --git a/clickhouse-udfs/util/README.md b/clickhouse-udfs/util/README.md
index e9e01685866d..239ba9bc7412 100644
--- a/clickhouse-udfs/util/README.md
+++ b/clickhouse-udfs/util/README.md
@@ -2,7 +2,7 @@
This module contains the executable ClickHouse UDFs used by PostHog:
-- `JSONDropKeys`
+- `JSONDropKeys` and `JSONDropKeysPool`
- `JSONCleanPostHogEventProperties`
- `JSONCleanPostHogPersonProperties`
- `JSONCleanPostHogTemporaryProperties`
diff --git a/clickhouse-udfs/util/cmd/json_drop_keys_udf/main.go b/clickhouse-udfs/util/cmd/json_drop_keys_udf/main.go
index 2d349242d017..eda74b08476b 100644
--- a/clickhouse-udfs/util/cmd/json_drop_keys_udf/main.go
+++ b/clickhouse-udfs/util/cmd/json_drop_keys_udf/main.go
@@ -3,12 +3,16 @@ package main
import (
"bufio"
"bytes"
+ "encoding/binary"
+ "errors"
"flag"
"fmt"
"io"
"log"
"os"
"runtime/pprof"
+ "slices"
+ "strconv"
"strings"
"sync"
@@ -491,6 +495,7 @@ func makeKeyDict(keys []string) jsonKey {
func main() {
cpuProfile := flag.String("cpuprofile", "", "write CPU profile to file")
debugLog := flag.Bool("debug", false, "enable debug logging")
+ rowBinary := flag.Bool("row-binary", false, "read (json String, keys Array(String)) RowBinary rows after a row-count header")
flag.Parse()
keysArg := flag.Arg(0)
@@ -508,12 +513,24 @@ func main() {
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)
+ var runner func(io.Reader, io.Writer) error
+ if *rowBinary {
+ if flag.NArg() > 0 {
+ fmt.Fprintln(stdErr, "keys are a per-row argument in RowBinary mode, not a command-line argument")
+ os.Exit(1)
+ }
+ runner = runRowBinary
+ } else {
+ keys, err := parseSingleQuotedArray(keysArg)
+ if err != nil {
+ fmt.Fprintf(stdErr, "keysToDrop parse error: %v\n", err)
+ os.Exit(1)
+ }
+ keysToDrop := makeKeyDict(keys)
+ runner = func(input io.Reader, output io.Writer) error {
+ return run(input, output, keysToDrop)
+ }
}
- keysToDrop := makeKeyDict(keys)
if *cpuProfile != "" {
f, err := os.Create(*cpuProfile)
@@ -532,7 +549,7 @@ func main() {
}()
}
- if err := run(os.Stdin, os.Stdout, keysToDrop); err != nil {
+ if err := runner(os.Stdin, os.Stdout); err != nil {
fmt.Fprintln(stdErr, err)
os.Exit(1)
}
@@ -584,3 +601,134 @@ func run(input io.Reader, output io.Writer, keys jsonKey) error {
}
}
}
+
+const (
+ // Matches ClickHouse's default format_binary_max_string_size, so the limit only rejects corrupt lengths.
+ maxRowBinaryJSONSize = 1 << 30
+ maxRowBinaryKeyCount = 1 << 16
+ maxRowBinaryKeySize = 64 * 1024
+)
+
+// rowBinaryKeys keeps the filter for the most recent key array. A query sends the same array on every row,
+// so the filter is rebuilt only when the encoded array changes.
+type rowBinaryKeys struct {
+ encoded []byte
+ scratch []byte
+ filter jsonKey
+}
+
+func (k *rowBinaryKeys) read(reader *bufio.Reader) (jsonKey, error) {
+ count, err := readRowBinaryLength(reader, maxRowBinaryKeyCount, "key array")
+ if err != nil {
+ return nil, err
+ }
+ k.scratch = binary.AppendUvarint(k.scratch[:0], uint64(count))
+ for range count {
+ size, err := readRowBinaryLength(reader, maxRowBinaryKeySize, "key")
+ if err != nil {
+ return nil, err
+ }
+ k.scratch = binary.AppendUvarint(k.scratch, uint64(size))
+ if k.scratch, err = appendRowBinaryBytes(reader, k.scratch, size); err != nil {
+ return nil, err
+ }
+ }
+ if k.filter != nil && bytes.Equal(k.scratch, k.encoded) {
+ return k.filter, nil
+ }
+
+ keys := make([]string, 0, count)
+ _, offset := binary.Uvarint(k.scratch)
+ for range count {
+ size, n := binary.Uvarint(k.scratch[offset:])
+ offset += n
+ keys = append(keys, string(k.scratch[offset:offset+int(size)]))
+ offset += int(size)
+ }
+ k.filter = makeKeyDict(keys)
+ k.encoded, k.scratch = k.scratch, k.encoded
+ return k.filter, nil
+}
+
+func readRowBinaryLength(reader *bufio.Reader, maxSize int, name string) (int, error) {
+ length, err := binary.ReadUvarint(reader)
+ if err != nil {
+ return 0, fmt.Errorf("read %s length: %w", name, truncated(err))
+ }
+ if length > uint64(maxSize) {
+ return 0, fmt.Errorf("%s length %d exceeds %d", name, length, maxSize)
+ }
+ return int(length), nil
+}
+
+func appendRowBinaryBytes(reader *bufio.Reader, dst []byte, size int) ([]byte, error) {
+ start := len(dst)
+ dst = slices.Grow(dst, size)[:start+size]
+ if _, err := io.ReadFull(reader, dst[start:]); err != nil {
+ return nil, fmt.Errorf("read RowBinary string: %w", truncated(err))
+ }
+ return dst, nil
+}
+
+// truncated reports a clean EOF inside a chunk as truncation, because the chunk header promised more rows.
+func truncated(err error) error {
+ if errors.Is(err, io.EOF) {
+ return io.ErrUnexpectedEOF
+ }
+ return err
+}
+
+// runRowBinary serves the executable_pool function. ClickHouse keeps one process per pool slot across blocks and
+// queries, and sends an ASCII row count before each chunk so the process knows when to flush its answer.
+func runRowBinary(input io.Reader, output io.Writer) error {
+ reader := bufio.NewReaderSize(input, 64*1024)
+ writer := bufio.NewWriterSize(output, 64*1024)
+ buf := bytes.NewBuffer(make([]byte, 0, 64*1024))
+ var (
+ row []byte
+ keys rowBinaryKeys
+ length [binary.MaxVarintLen64]byte
+ )
+ for {
+ header, err := reader.ReadSlice('\n')
+ if err == io.EOF && len(header) == 0 {
+ return nil
+ }
+ if err != nil {
+ return fmt.Errorf("chunk header read error: %w", err)
+ }
+ rows, err := strconv.ParseUint(string(header[:len(header)-1]), 10, 64)
+ if err != nil {
+ return fmt.Errorf("invalid chunk header: %w", err)
+ }
+ for range rows {
+ size, err := readRowBinaryLength(reader, maxRowBinaryJSONSize, "JSON")
+ if err != nil {
+ return err
+ }
+ if cap(row) > max(64*1024, 2*size) {
+ row = nil
+ }
+ if row, err = appendRowBinaryBytes(reader, row[:0], size); err != nil {
+ return err
+ }
+ filter, err := keys.read(reader)
+ if err != nil {
+ return err
+ }
+ if err := processLine(filter, row, buf); err != nil {
+ return fmt.Errorf("row processing error: %w", err)
+ }
+ n := binary.PutUvarint(length[:], uint64(buf.Len()))
+ if _, err := writer.Write(length[:n]); err != nil {
+ return fmt.Errorf("stdout write error: %w", err)
+ }
+ if _, err := writer.Write(buf.Bytes()); err != nil {
+ return fmt.Errorf("stdout write error: %w", err)
+ }
+ }
+ if err := writer.Flush(); err != nil {
+ return fmt.Errorf("stdout flush error: %w", err)
+ }
+ }
+}
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
index 09426a468649..06127ce92937 100644
--- a/clickhouse-udfs/util/cmd/json_drop_keys_udf/main_test.go
+++ b/clickhouse-udfs/util/cmd/json_drop_keys_udf/main_test.go
@@ -1,8 +1,11 @@
package main
import (
+ "bufio"
"bytes"
+ "encoding/binary"
"errors"
+ "fmt"
"io"
"os"
"path/filepath"
@@ -183,6 +186,100 @@ func TestDropKeysStreamErrors(t *testing.T) {
}
}
+type rowBinaryRow struct {
+ json string
+ keys []string
+}
+
+func encodeRowBinaryChunks(chunks ...[]rowBinaryRow) []byte {
+ var out []byte
+ appendString := func(value string) {
+ out = binary.AppendUvarint(out, uint64(len(value)))
+ out = append(out, value...)
+ }
+ for _, chunk := range chunks {
+ out = fmt.Appendf(out, "%d\n", len(chunk))
+ for _, row := range chunk {
+ appendString(row.json)
+ out = binary.AppendUvarint(out, uint64(len(row.keys)))
+ for _, key := range row.keys {
+ appendString(key)
+ }
+ }
+ }
+ return out
+}
+
+func decodeRowBinaryStrings(t *testing.T, data []byte) []string {
+ t.Helper()
+ reader := bufio.NewReader(bytes.NewReader(data))
+ var values []string
+ for {
+ size, err := binary.ReadUvarint(reader)
+ if err == io.EOF {
+ return values
+ }
+ if err != nil {
+ t.Fatal(err)
+ }
+ value := make([]byte, size)
+ if _, err := io.ReadFull(reader, value); err != nil {
+ t.Fatal(err)
+ }
+ values = append(values, string(value))
+ }
+}
+
+func TestRunRowBinary(t *testing.T) {
+ input := encodeRowBinaryChunks(
+ []rowBinaryRow{
+ {json: `{"a":1,"b":2}`, keys: []string{"a"}},
+ {json: `{"a":1,"b":2}`, keys: []string{"a"}},
+ {json: `{"a":1,"b":2}`, keys: []string{"b"}},
+ {json: "{\n\"a\":1,\t\"b\":\"x\\ny\"}", keys: []string{"a"}},
+ {json: `{"a":{"s":1,"k":2}}`, keys: []string{"a.s", "missing"}},
+ {json: `{"a":1}`, keys: nil},
+ },
+ []rowBinaryRow{
+ {json: `{"a":1,"b":2}`, keys: []string{"a"}},
+ },
+ )
+ var output bytes.Buffer
+ if err := runRowBinary(bytes.NewReader(input), &output); err != nil {
+ t.Fatal(err)
+ }
+ assert.Equal(t, []string{
+ `{"b":2}`,
+ `{"b":2}`,
+ `{"a":1}`,
+ `{"b":"x\ny"}`,
+ `{"a":{"k":2}}`,
+ `{"a":1}`,
+ `{"b":2}`,
+ }, decodeRowBinaryStrings(t, output.Bytes()))
+}
+
+func TestRunRowBinaryErrors(t *testing.T) {
+ valid := encodeRowBinaryChunks([]rowBinaryRow{{json: `{"a":1}`, keys: []string{"a"}}})
+ cases := []struct {
+ name string
+ input []byte
+ want string
+ }{
+ {"missing row", append([]byte("2\n"), valid[2:]...), "unexpected EOF"},
+ {"truncated keys", valid[:len(valid)-1], "unexpected EOF"},
+ {"malformed JSON", encodeRowBinaryChunks([]rowBinaryRow{{json: `{"a":`, keys: nil}}), "json parse error"},
+ {"invalid header", []byte("x\n"), "invalid chunk header"},
+ {"oversized key array", binary.AppendUvarint([]byte("1\n\x02{}"), maxRowBinaryKeyCount+1), "key array length"},
+ }
+ for _, tc := range cases {
+ t.Run(tc.name, func(t *testing.T) {
+ err := runRowBinary(bytes.NewReader(tc.input), io.Discard)
+ assert.ErrorContains(t, err, tc.want)
+ })
+ }
+}
+
func TestParseSingleQuotedArray(t *testing.T) {
cases := []struct {
name string
diff --git a/clickhouse-udfs/util/scripts/integration_test.sh b/clickhouse-udfs/util/scripts/integration_test.sh
index 6544c267293b..e22bb70fd871 100755
--- a/clickhouse-udfs/util/scripts/integration_test.sh
+++ b/clickhouse-udfs/util/scripts/integration_test.sh
@@ -1,12 +1,17 @@
#!/usr/bin/env bash
set -euo pipefail
+# The repository .envrc exports COMPOSE_PROJECT_NAME=posthog. Without an override, this script's cleanup
+# (down -v --remove-orphans) removes every container of the local development stack.
+export COMPOSE_PROJECT_NAME=clickhouse-util-udfs-test
+
ROOT_DIR=$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)
COMPOSE_FILE="$ROOT_DIR/docker-compose.yml"
TEMP_DIR=$(mktemp -d)
UDFS=(
decompress
json_drop_keys
+ json_drop_keys_pool
json_clean_posthog_event_properties
json_clean_posthog_person_properties
json_clean_posthog_temporary_properties
@@ -19,8 +24,16 @@ cleanup() {
}
trap cleanup EXIT
+# JSONDropKeysPool must match JSONDropKeys, so both run against the same fixtures.
+fixtures_for() {
+ case "$1" in
+ json_drop_keys_pool) echo json_drop_keys ;;
+ *) echo "$1" ;;
+ esac
+}
+
query_for() {
- local input="file('$1/stateless/$2', 'TabSeparated', 'x String')"
+ local input="file('$(fixtures_for "$1")/stateless/$2', 'TabSeparated', 'x String')"
case "$1" in
decompress)
echo "SELECT hex(decompress(unhex(data), codec)) FROM file('$1/stateless/$2', 'TabSeparated', 'codec String, data String') SETTINGS max_block_size = 2, max_threads = 1 FORMAT TabSeparated"
@@ -28,6 +41,9 @@ query_for() {
json_drop_keys)
echo "SELECT JSONDropKeys(['a'])(x) FROM $input FORMAT TabSeparated"
;;
+ json_drop_keys_pool)
+ echo "SELECT JSONDropKeysPool(x, ['a']) FROM $input SETTINGS max_block_size = 2, max_threads = 1 FORMAT TabSeparated"
+ ;;
json_clean_posthog_event_properties)
echo "SELECT JSONCleanPostHogEventProperties(x) FROM $input FORMAT TabSeparated"
;;
@@ -47,7 +63,7 @@ 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"
+ stateless_dir="$ROOT_DIR/testdata/$(fixtures_for "$udf")/stateless"
for test_file in "$stateless_dir"/*.tsv; do
test_name=$(basename "$test_file")
@@ -95,6 +111,22 @@ if [[ "$output" != "0" ]]; then
fi
echo "Passed mixed compressed/plain pool chunks."
+query=$(cat <<'SQL'
+SELECT countIf(
+ JSONDropKeysPool(concat('{"a":', toString(number), ',"b":', toString(number), '}'), if(number % 2 = 0, ['a'], ['b']))
+ != concat('{"', if(number % 2 = 0, 'b', 'a'), '":', toString(number), '}')
+)
+FROM numbers(10000)
+SETTINGS max_block_size = 128, max_threads = 2
+SQL
+)
+output=$(docker compose -f "$COMPOSE_FILE" exec -T clickhouse clickhouse-client --query "$query")
+if [[ "$output" != "0" ]]; then
+ echo "Expected per-row JSONDropKeysPool keys to apply across pool chunks, got: $output" >&2
+ exit 1
+fi
+echo "Passed per-row JSONDropKeysPool keys."
+
query=$(cat <<'SQL'
WITH concat('{"x":', repeat('[', 24), '[0]', repeat(',null]', 24), '}') AS raw
SELECT
diff --git a/docker/clickhouse/user_defined_function.xml b/docker/clickhouse/user_defined_function.xml
index aee90f3f582a..ea70fe74d986 100644
--- a/docker/clickhouse/user_defined_function.xml
+++ b/docker/clickhouse/user_defined_function.xml
@@ -660,4 +660,23 @@
<stderr_reaction>throw</stderr_reaction>
<deterministic>true</deterministic>
</function>
+
+ <function>
+ <type>executable_pool</type>
+ <name>JSONDropKeysPool</name>
+ <return_type>String</return_type>
+ <argument>
+ <type>String</type>
+ <name>json</name>
+ </argument>
+ <argument>
+ <type>Array(String)</type>
+ <name>keys</name>
+ </argument>
+ <format>RowBinary</format>
+ <command>json_drop_keys_udf --row-binary</command>
+ <send_chunk_header>true</send_chunk_header>
+ <stderr_reaction>throw</stderr_reaction>
+ <deterministic>true</deterministic>
+ </function>
</functions>
diff --git a/docs/internal/clickhouse-utility-udfs.md b/docs/internal/clickhouse-utility-udfs.md
index fac1e759dbd4..03001ec6e930 100644
--- a/docs/internal/clickhouse-utility-udfs.md
+++ b/docs/internal/clickhouse-utility-udfs.md
@@ -165,6 +165,38 @@ The buffer-reuse test alternates dotted-object widths and verifies exact output,
These local measurements should be repeated on deployment hardware before estimating fleet capacity.
+### `JSONDropKeysPool(json, keys)`
+
+Removes the given keys from a JSON document and returns the result as a `String`.
+It produces the same output as `JSONDropKeys(keys)(json)`, including dotted-key expansion.
+Each key is a dot-separated path, such as `properties.secret`.
+
+```sql
+SELECT JSONDropKeysPool('{"a":1,"b":{"c":2,"d":3}}', ['a', 'b.c']);
+-- {"b":{"d":3}}
+```
+
+`JSONDropKeys` receives its keys as a query parameter in the command line.
+ClickHouse accepts parameters only for the `executable` type, which starts a new process for every block.
+`JSONDropKeysPool` receives the keys as a regular argument, so it can use `executable_pool`.
+The worker stays alive across blocks and queries, and the keys can differ between rows.
+The worker keeps the parsed filter for the most recent key array and parses it again only when the array changes.
+
+Both functions use the `json_drop_keys_udf` executable. The pool entry point uses `--row-binary` with chunk headers.
+RowBinary transport lets the JSON contain raw newlines and tabs.
+Malformed JSON, truncated chunks, a JSON value above 1 GiB, more than 65,536 keys, and a key above 64 KiB fail the query.
+
+With 1,000,000 small synthetic rows, `max_threads = 1`, and ClickHouse 26.6.2.158 on an Apple M4 Pro, best of three runs, recorded September 24, 2026:
+
+| `max_block_size` | `JSONDropKeys` | `JSONDropKeysPool` |
+| ---------------- | -------------: | -----------------: |
+| 65,536 | 0.346 s | 0.26 s |
+| 8,192 | 0.873 s | 0.30 s |
+| 1,024 | 4.885 s | 0.504 s |
+
+A `countIf` comparison of both functions over the same rows returned zero differences.
+These timings measure process startup and transport, not production block sizes or concurrent load.
+
### `decompress(data, codec)`
Returns the exact decompressed bytes as a ClickHouse `String`, including NUL, newlines, and non-UTF-8 bytes.
diff --git a/posthog/udf_versioner.py b/posthog/udf_versioner.py
index cb745676d9bb..a9f7e5a795f5 100644
--- a/posthog/udf_versioner.py
+++ b/posthog/udf_versioner.py
@@ -19,6 +19,7 @@ UNVERSIONED_FUNCTIONS = {
"JSONCleanPostHogEventProperties",
"JSONCleanPostHogPersonProperties",
"JSONCleanPostHogTemporaryProperties",
+ "JSONDropKeysPool",
"JSONStripEmptyStringsAndNulls",
}
diff --git a/posthog/user_scripts/json_drop_keys_udf_aarch64 b/posthog/user_scripts/json_drop_keys_udf_aarch64
index 58cddd6d9062..4f7d00caa7be 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 c350273b2379..c200e236941a 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/latest_user_defined_function.xml b/posthog/user_scripts/latest_user_defined_function.xml
index 8b06cc6515d8..6aa505aa8b57 100644
--- a/posthog/user_scripts/latest_user_defined_function.xml
+++ b/posthog/user_scripts/latest_user_defined_function.xml
@@ -979,4 +979,22 @@ This file is autogenerated by udf_versioner.py. Do not edit this, only edit the
<stderr_reaction>throw</stderr_reaction>
<deterministic>true</deterministic>
</function>
+ <function>
+ <type>executable_pool</type>
+ <name>JSONDropKeysPool</name>
+ <return_type>String</return_type>
+ <argument>
+ <type>String</type>
+ <name>json</name>
+ </argument>
+ <argument>
+ <type>Array(String)</type>
+ <name>keys</name>
+ </argument>
+ <format>RowBinary</format>
+ <command>json_drop_keys_udf --row-binary</command>
+ <send_chunk_header>true</send_chunk_header>
+ <stderr_reaction>throw</stderr_reaction>
+ <deterministic>true</deterministic>
+ </function>
</functions>
\ No newline at end of file
diff --git a/posthog/user_scripts/v12/user_defined_function.xml b/posthog/user_scripts/v12/user_defined_function.xml
index 8b06cc6515d8..6aa505aa8b57 100644
--- a/posthog/user_scripts/v12/user_defined_function.xml
+++ b/posthog/user_scripts/v12/user_defined_function.xml
@@ -979,4 +979,22 @@ This file is autogenerated by udf_versioner.py. Do not edit this, only edit the
<stderr_reaction>throw</stderr_reaction>
<deterministic>true</deterministic>
</function>
+ <function>
+ <type>executable_pool</type>
+ <name>JSONDropKeysPool</name>
+ <return_type>String</return_type>
+ <argument>
+ <type>String</type>
+ <name>json</name>
+ </argument>
+ <argument>
+ <type>Array(String)</type>
+ <name>keys</name>
+ </argument>
+ <format>RowBinary</format>
+ <command>json_drop_keys_udf --row-binary</command>
+ <send_chunk_header>true</send_chunk_header>
+ <stderr_reaction>throw</stderr_reaction>
+ <deterministic>true</deterministic>
+ </function>
</functions>
\ No newline at end of file