: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
feat(clickhouse): add pooled payload decompression udf (#98226)
Rory Shanks3bfa4904c2c0
diff --git a/.github/scripts/trunk-impacted-targets.js b/.github/scripts/trunk-impacted-targets.jsindex 3dc038420ae1..aa0e8c346a9e 100644--- a/.github/scripts/trunk-impacted-targets.js+++ b/.github/scripts/trunk-impacted-targets.js@@ -388,7 +388,6 @@ const TRIPWIRE_RULES = [['.github/workflows/llm-gateway-cd.yml', DEPLOY],['.github/workflows/publish-quill-npm.yml', DEPLOY],['.github/workflows/publish-symbol-data-crate.yml', DEPLOY],- ['.github/workflows/clickhouse-udfs.yml', DEPLOY],// A scheduled mirror of the upstream Playwright image; no suite runs it.['.github/workflows/ci-playwright-container.yml', DEPLOY],// The dev-environment checks: the flox boot check and the sandboxdiff --git a/.github/workflows/ci-clickhouse-util-udfs.yml b/.github/workflows/ci-clickhouse-util-udfs.ymlindex 771edde11b3d..4d422c712df4 100644--- a/.github/workflows/ci-clickhouse-util-udfs.yml+++ b/.github/workflows/ci-clickhouse-util-udfs.yml@@ -6,6 +6,7 @@ on:- '.github/workflows/ci-clickhouse-util-udfs.yml'- 'clickhouse-udfs/util/**'- 'docker/clickhouse/user_defined_function.xml'+ - 'posthog/user_scripts/decompress_udf*'- '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*'diff --git a/.github/workflows/clickhouse-udfs.yml b/.github/workflows/clickhouse-udfs.ymldeleted file mode 100644index 1f7761605cbd..000000000000--- a/.github/workflows/clickhouse-udfs.yml+++ /dev/null@@ -1,38 +0,0 @@-name: ClickHouse UDFs--on:- push:- branches:- - master- paths:- - 'posthog/user_scripts/**'--permissions:- contents: read--jobs:- trigger_udfs_workflow:- runs-on: ubuntu-24.04- timeout-minutes: 5- steps:- - name: Get app token- id: app-token- # NOTE: This token is very limited in what it can do.- # It can't (and should not) read repo contents or create PRs.- # Do not use for cross-repo dependencies, see thread below for an alternative approach:- # https://posthog.slack.com/archives/C02E3BKC78F/p1769016151167609- uses: actions/create-github-app-token@1b10c78c7865c340bc4f6099eb2f838309f1e8c3 # v3.1.1- with:- client-id: ${{ vars.GH_APP_POSTHOG_CLOUD_INFRA_WORKFLOW_TRIGGER_APP_ID }}- private-key: ${{ secrets.GH_APP_POSTHOG_CLOUD_INFRA_WORKFLOW_TRIGGER_PRIVATE_KEY }}- owner: PostHog- repositories: posthog-cloud-infra-- - name: Trigger UDFs Workflow- shell: bash- env:- GH_TOKEN: ${{ steps.app-token.outputs.token }}- run: |- gh workflow run clickhouse-udfs.yml \- -R posthog/posthog-cloud-infra \- --ref maindiff --git a/clickhouse-udfs/util/README.md b/clickhouse-udfs/util/README.mdindex d603127edfbe..e9e01685866d 100644--- a/clickhouse-udfs/util/README.md+++ b/clickhouse-udfs/util/README.md@@ -7,6 +7,7 @@ This module contains the executable ClickHouse UDFs used by PostHog:- `JSONCleanPostHogPersonProperties`- `JSONCleanPostHogTemporaryProperties`- `JSONStripEmptyStringsAndNulls`+- `decompress(data, codec)`Run `./scripts/build.sh` to test the module and build Linux amd64 and arm64 binaries into`posthog/user_scripts`.@@ -16,5 +17,8 @@ Run `./scripts/integration_test.sh` to execute the stateless fixtures against ClSee [JSONDropKeys benchmarks](../../docs/internal/json-drop-keys-benchmarks.md) for thefile-based workloads and commands to compare throughput and allocations.+See [decompression usage and benchmarks](../../docs/internal/clickhouse-utility-udfs.md#decompressdata-codec)+for supported codecs, Kafka envelope handling, and size limits.+These utility UDFs keep stable, unversioned names. Regenerating the deployment manifest does notchange `UDF_VERSION`, which only switches callers between versioned funnel UDF releases.diff --git a/clickhouse-udfs/util/cmd/decompress_udf/main.go b/clickhouse-udfs/util/cmd/decompress_udf/main.gonew file mode 100644index 000000000000..2b3a1bdfee11--- /dev/null+++ b/clickhouse-udfs/util/cmd/decompress_udf/main.go@@ -0,0 +1,286 @@+package main++import (+ "bufio"+ "bytes"+ "compress/gzip"+ "encoding/binary"+ "errors"+ "fmt"+ "io"+ "os"+ "slices"+ "strconv"+ "strings"++ "github.com/klauspost/compress/zstd"+ "github.com/pierrec/lz4/v4"+)++const maxDecompressedSize = 64 << 20+const maxCompressedSize = 65 << 20++type processor struct {+ maxOutput int+ zstd *zstd.Decoder+ gzip *gzip.Reader+ lz4 *lz4.Reader+ input bytes.Reader+ output bytes.Buffer+ zstdOutput []byte+ lz4Block []byte+}++func newProcessor(maxOutput int) (*processor, error) {+ decoder, err := zstd.NewReader(nil,+ zstd.WithDecoderConcurrency(1),+ zstd.WithDecoderMaxMemory(uint64(maxOutput)),+ )+ if err != nil {+ return nil, fmt.Errorf("create ZSTD decoder: %w", err)+ }+ return &processor{maxOutput: maxOutput, zstd: decoder, lz4: lz4.NewReader(nil)}, nil+}++func (p *processor) close() {+ p.zstd.Close()+}++func (p *processor) decompress(data []byte, codec string) ([]byte, error) {+ if len(data) == 0 {+ return nil, errors.New("empty compressed data: expected a compression frame or block")+ }+ if codec == "" {+ var err error+ codec, err = detectCodec(data)+ if err != nil {+ return nil, err+ }+ }+ p.input.Reset(data)++ switch {+ case strings.EqualFold(codec, "GZIP"):+ var err error+ if p.gzip == nil {+ p.gzip, err = gzip.NewReader(&p.input)+ } else {+ err = p.gzip.Reset(&p.input)+ }+ if err != nil {+ return nil, fmt.Errorf("invalid GZIP stream: %w", err)+ }+ return p.readLimited(p.gzip)+ case strings.EqualFold(codec, "ZSTD"):+ var err error+ p.zstdOutput, err = p.zstd.DecodeAll(data, p.zstdOutput[:0])+ if err != nil {+ return nil, fmt.Errorf("invalid ZSTD stream: %w", err)+ }+ return p.zstdOutput, nil+ case strings.EqualFold(codec, "LZ4"):+ if err := validateLZ4Frames(data); err != nil {+ return nil, fmt.Errorf("invalid LZ4 stream: %w", err)+ }+ p.lz4.Reset(&p.input)+ return p.readLimited(p.lz4)+ case strings.EqualFold(codec, "LZ4SIZEPREFIXED"):+ // Capture's replay envelope is a little-endian size followed by a raw block.+ if len(data) < 5 {+ return nil, errors.New("truncated LZ4SizePrefixed envelope")+ }+ size := uint64(binary.LittleEndian.Uint32(data[:4]))+ if size > uint64(p.maxOutput) {+ return nil, fmt.Errorf("decompressed size exceeds %d bytes", p.maxOutput)+ }+ p.lz4Block = slices.Grow(p.lz4Block[:0], int(size))[:int(size)]+ n, err := lz4.UncompressBlock(data[4:], p.lz4Block)+ if err != nil || n != int(size) {+ return nil, fmt.Errorf("invalid LZ4SizePrefixed block: decoded %d bytes, expected %d (error: %v)", n, size, err)+ }+ return p.lz4Block[:n], nil+ case strings.EqualFold(codec, "LZ4BLOCK"):+ // ponytail: raw blocks omit their size; use the cap, prefer LZ4SizePrefixed for smaller buffers.+ p.lz4Block = slices.Grow(p.lz4Block[:0], p.maxOutput)[:p.maxOutput]+ n, err := lz4.UncompressBlock(data, p.lz4Block)+ if err != nil {+ return nil, fmt.Errorf("invalid LZ4Block or decompressed size exceeds %d bytes: %w", p.maxOutput, err)+ }+ return p.lz4Block[:n], nil+ default:+ return nil, fmt.Errorf("unsupported compression codec %q", codec)+ }+}++func validateLZ4Frames(data []byte) error {+ // The LZ4 reader treats EOF at some header/block boundaries as success, even without an end mark.+ for len(data) > 0 {+ if len(data) < 4 {+ return io.ErrUnexpectedEOF+ }+ magic := binary.LittleEndian.Uint32(data)+ if magic&0xfffffff0 == 0x184d2a50 {+ if len(data) < 8 {+ return io.ErrUnexpectedEOF+ }+ size := uint64(binary.LittleEndian.Uint32(data[4:])) + 8+ if size > uint64(len(data)) {+ return io.ErrUnexpectedEOF+ }+ data = data[int(size):]+ continue+ }+ if magic != 0x184d2204 {+ return errors.New("expected a standard LZ4 frame")+ }+ if len(data) < 7 {+ return io.ErrUnexpectedEOF+ }+ flags := data[4]+ headerSize := 7+ if flags&0x08 != 0 {+ headerSize += 8+ }+ if flags&0x01 != 0 {+ headerSize += 4+ }+ if len(data) < headerSize {+ return io.ErrUnexpectedEOF+ }+ data = data[headerSize:]+ for {+ if len(data) < 4 {+ return io.ErrUnexpectedEOF+ }+ block := binary.LittleEndian.Uint32(data)+ data = data[4:]+ size := uint64(block & 0x7fffffff)+ if (block == 0 && flags&0x04 != 0) || (block != 0 && flags&0x10 != 0) {+ size += 4+ }+ if size > uint64(len(data)) {+ return io.ErrUnexpectedEOF+ }+ data = data[int(size):]+ if block == 0 {+ break+ }+ }+ }+ return nil+}++func (p *processor) readLimited(reader io.Reader) ([]byte, error) {+ p.output.Reset()+ n, err := io.CopyN(&p.output, reader, int64(p.maxOutput)+1)+ if n > int64(p.maxOutput) {+ return nil, fmt.Errorf("decompressed size exceeds %d bytes", p.maxOutput)+ }+ if err != nil && !errors.Is(err, io.EOF) {+ return nil, fmt.Errorf("decompression failed: %w", err)+ }+ return p.output.Bytes(), nil+}++func detectCodec(data []byte) (string, error) {+ remaining := data+ for len(remaining) >= 8 && binary.LittleEndian.Uint32(remaining[:4])&0xfffffff0 == 0x184d2a50 {+ skip := uint64(binary.LittleEndian.Uint32(remaining[4:8])) + 8+ if skip > uint64(len(remaining)) {+ return "", errors.New("truncated skippable compression frame")+ }+ remaining = remaining[int(skip):]+ }++ switch {+ case len(remaining) >= 3 && bytes.Equal(remaining[:3], []byte{0x1f, 0x8b, 0x08}):+ return "GZIP", nil+ case len(remaining) >= 4 && bytes.Equal(remaining[:4], []byte{0x28, 0xb5, 0x2f, 0xfd}):+ return "ZSTD", nil+ case len(remaining) >= 4 && bytes.Equal(remaining[:4], []byte{0x04, 0x22, 0x4d, 0x18}):+ return "LZ4", nil+ default:+ return "", errors.New("cannot detect compression codec from frame header")+ }+}++func readString(reader *bufio.Reader, buf []byte, maxSize int) ([]byte, error) {+ length, err := binary.ReadUvarint(reader)+ if err != nil {+ return nil, err+ }+ if length > uint64(maxSize) {+ return nil, fmt.Errorf("RowBinary string length %d exceeds %d bytes", length, maxSize)+ }+ value := slices.Grow(buf[:0], int(length))[:int(length)]+ if _, err := io.ReadFull(reader, value); err != nil {+ if errors.Is(err, io.EOF) {+ return nil, io.ErrUnexpectedEOF+ }+ return nil, err+ }+ return value, nil+}++func writeString(writer *bufio.Writer, value []byte) error {+ var length [binary.MaxVarintLen64]byte+ n := binary.PutUvarint(length[:], uint64(len(value)))+ if _, err := writer.Write(length[:n]); err != nil {+ return err+ }+ _, err := writer.Write(value)+ return err+}++func run(input io.Reader, output io.Writer, maxOutput int) error {+ proc, err := newProcessor(maxOutput)+ if err != nil {+ return err+ }+ defer proc.close()++ reader := bufio.NewReaderSize(input, 64*1024)+ writer := bufio.NewWriterSize(output, 64*1024)+ var data, codec []byte+ for {+ // ClickHouse sends an ASCII row count even when the rows use RowBinary.+ header, err := reader.ReadSlice('\n')+ if err == io.EOF && len(header) == 0 {+ return nil+ }+ if err != nil {+ return fmt.Errorf("read chunk header: %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 {+ data, err = readString(reader, data, maxCompressedSize)+ if err != nil {+ return fmt.Errorf("read compressed data: %w", err)+ }+ codec, err = readString(reader, codec, 32)+ if err != nil {+ return fmt.Errorf("read codec: %w", err)+ }+ decompressed, err := proc.decompress(data, string(codec))+ if err != nil {+ return err+ }+ if err := writeString(writer, decompressed); err != nil {+ return fmt.Errorf("write decompressed data: %w", err)+ }+ }+ if err := writer.Flush(); err != nil {+ return fmt.Errorf("flush chunk: %w", err)+ }+ }+}++func main() {+ if err := run(os.Stdin, os.Stdout, maxDecompressedSize); err != nil {+ fmt.Fprintln(os.Stderr, err)+ os.Exit(1)+ }+}diff --git a/clickhouse-udfs/util/cmd/decompress_udf/main_test.go b/clickhouse-udfs/util/cmd/decompress_udf/main_test.gonew file mode 100644index 000000000000..f5727eff6248--- /dev/null+++ b/clickhouse-udfs/util/cmd/decompress_udf/main_test.go@@ -0,0 +1,350 @@+package main++import (+ "bufio"+ "bytes"+ "compress/gzip"+ "encoding/binary"+ "encoding/hex"+ "fmt"+ "io"+ "strings"+ "testing"++ "github.com/klauspost/compress/zstd"+ "github.com/pierrec/lz4/v4"+)++func TestDecompress(t *testing.T) {+ input := []byte{'h', 'i', 0, '\n', '\t', 0xff}+ fixtures := compressedFixtures(t, input)+ proc, err := newProcessor(1024)+ if err != nil {+ t.Fatal(err)+ }+ defer proc.close()++ for codec, compressed := range fixtures {+ for _, requested := range []string{codec, strings.ToLower(codec), strings.ToUpper(codec), ""} {+ if (codec == "LZ4Block" || codec == "LZ4SizePrefixed") && requested == "" {+ continue+ }+ got, err := proc.decompress(compressed, requested)+ if err != nil {+ t.Fatalf("decompress(%s, %q): %v", codec, requested, err)+ }+ if !bytes.Equal(got, input) {+ t.Fatalf("decompress(%s, %q) = %x, want %x", codec, requested, got, input)+ }+ }+ }++ for codec, compressed := range compressedFixtures(t, nil) {+ if codec == "LZ4Block" || codec == "LZ4SizePrefixed" {+ continue+ }+ got, err := proc.decompress(compressed, "")+ if err != nil || len(got) != 0 {+ t.Fatalf("decompress empty %s = %x, %v", codec, got, err)+ }+ }+}++func TestDecompressFailsFast(t *testing.T) {+ fixtures := compressedFixtures(t, []byte("hello"))+ proc, err := newProcessor(4)+ if err != nil {+ t.Fatal(err)+ }+ defer proc.close()++ tests := []struct {+ name string+ data []byte+ codec string+ }{+ {"unknown header", []byte("plain"), ""},+ {"raw block detection", fixtures["LZ4Block"], ""},+ {"unsupported codec", fixtures["GZIP"], "SNAPPY"},+ {"codec mismatch", fixtures["GZIP"], "ZSTD"},+ {"output limit", fixtures["GZIP"], "GZIP"},+ {"truncated stream", fixtures["ZSTD"][:5], "ZSTD"},+ }+ for _, test := range tests {+ t.Run(test.name, func(t *testing.T) {+ if _, err := proc.decompress(test.data, test.codec); err == nil {+ t.Fatal("expected an error")+ }+ })+ }+}++func TestRowBinaryTransport(t *testing.T) {+ value := bytes.Repeat([]byte{'a', '\n', 0, 0xff}, 20*1024)+ fixtures := compressedFixtures(t, value)+ var input bytes.Buffer+ writer := bufio.NewWriter(&input)+ for _, codec := range []string{"GZIP", "ZSTD", "LZ4", "LZ4Block", "LZ4SizePrefixed"} {+ fmt.Fprint(writer, "1\n")+ if err := writeString(writer, fixtures[codec]); err != nil {+ t.Fatal(err)+ }+ if err := writeString(writer, []byte(codec)); err != nil {+ t.Fatal(err)+ }+ }+ if err := writer.Flush(); err != nil {+ t.Fatal(err)+ }++ var output bytes.Buffer+ if err := run(&input, &output, len(value)); err != nil {+ t.Fatal(err)+ }+ reader := bufio.NewReader(&output)+ for range 5 {+ got, err := readString(reader, nil, len(value))+ if err != nil {+ t.Fatal(err)+ }+ if !bytes.Equal(got, value) {+ t.Fatalf("got %x, want %x", got, value)+ }+ }+ if _, err := reader.ReadByte(); err != io.EOF {+ t.Fatalf("unexpected output after final row: %v", err)+ }+}++func TestDetectCodecSkipsMetadataFrame(t *testing.T) {+ fixtures := compressedFixtures(t, []byte("hello"))+ proc, err := newProcessor(1024)+ if err != nil {+ t.Fatal(err)+ }+ defer proc.close()+ for _, codec := range []string{"ZSTD", "LZ4"} {+ data := append([]byte{0x50, 0x2a, 0x4d, 0x18, 0x03, 0, 0, 0, 'a', 'b', 'c'}, fixtures[codec]...)+ if got, err := detectCodec(data); err != nil || got != codec {+ t.Fatalf("detectCodec() = %q, %v, want %s", got, err, codec)+ }+ if got, err := proc.decompress(data, ""); err != nil || string(got) != "hello" {+ t.Fatalf("decompress(%s) = %q, %v", codec, got, err)+ }+ }+}++func compressedFixtures(t testing.TB, input []byte) map[string][]byte {+ t.Helper()+ fixtures := make(map[string][]byte)++ var gzipData bytes.Buffer+ gzipWriter := gzip.NewWriter(&gzipData)+ if _, err := gzipWriter.Write(input); err != nil {+ t.Fatal(err)+ }+ if err := gzipWriter.Close(); err != nil {+ t.Fatal(err)+ }+ fixtures["GZIP"] = gzipData.Bytes()++ zstdWriter, err := zstd.NewWriter(nil, zstd.WithEncoderConcurrency(1), zstd.WithZeroFrames(true))+ if err != nil {+ t.Fatal(err)+ }+ fixtures["ZSTD"] = zstdWriter.EncodeAll(input, nil)+ zstdWriter.Close()++ var lz4Data bytes.Buffer+ lz4Writer := lz4.NewWriter(&lz4Data)+ if _, err := lz4Writer.Write(input); err != nil {+ t.Fatal(err)+ }+ if err := lz4Writer.Close(); err != nil {+ t.Fatal(err)+ }+ fixtures["LZ4"] = lz4Data.Bytes()++ block := make([]byte, lz4.CompressBlockBound(len(input)))+ n, err := lz4.CompressBlock(input, block, nil)+ if err != nil {+ t.Fatal(err)+ }+ if n == 0 {+ t.Fatalf("test input is not compressible as an LZ4 block: %s", hex.EncodeToString(input))+ }+ fixtures["LZ4Block"] = block[:n]+ fixtures["LZ4SizePrefixed"] = append(binary.LittleEndian.AppendUint32(nil, uint32(len(input))), block[:n]...)+ return fixtures+}++func TestChunkFlushedBeforeNextInput(t *testing.T) {+ input, send := io.Pipe()+ output, receive := io.Pipe()+ defer input.Close()+ defer send.Close()+ defer output.Close()+ defer receive.Close()+ done := make(chan error, 1)+ go func() { done <- run(input, receive, 1024) }()+ reader := bufio.NewReader(output)+ fixtures := compressedFixtures(t, []byte("hello\x00\n\xff"))+ for _, rows := range []int{1, 3, 2} {+ var chunk bytes.Buffer+ fmt.Fprintf(&chunk, "%d\n", rows)+ writer := bufio.NewWriter(&chunk)+ for range rows {+ if err := writeString(writer, fixtures["GZIP"]); err != nil {+ t.Fatal(err)+ }+ if err := writeString(writer, []byte("gzip")); err != nil {+ t.Fatal(err)+ }+ }+ if err := writer.Flush(); err != nil {+ t.Fatal(err)+ }+ if _, err := send.Write(chunk.Bytes()); err != nil {+ t.Fatal(err)+ }+ for range rows {+ got, err := readString(reader, nil, 1024)+ if err != nil || string(got) != "hello\x00\n\xff" {+ t.Fatalf("got %q, %v", got, err)+ }+ }+ }+ send.Close()+ if err := <-done; err != nil {+ t.Fatal(err)+ }+}++func TestDecompressBoundaries(t *testing.T) {+ value := bytes.Repeat([]byte("abcd"), 1024)+ fixtures := compressedFixtures(t, value)+ for codec, data := range fixtures {+ t.Run(codec, func(t *testing.T) {+ proc, err := newProcessor(len(value))+ if err != nil {+ t.Fatal(err)+ }+ defer proc.close()+ for _, bad := range [][]byte{nil, data[:len(data)-1], []byte("garbage")} {+ if _, err := proc.decompress(bad, codec); err == nil {+ t.Fatalf("accepted invalid input %x", bad)+ }+ }+ if codec == "GZIP" || codec == "ZSTD" || codec == "LZ4" {+ for end := 1; end < len(data); end++ {+ if _, err := proc.decompress(data[:end], codec); err == nil {+ t.Fatalf("accepted truncated frame of length %d", end)+ }+ }+ if _, err := proc.decompress(append(bytes.Clone(data), data...), codec); err == nil {+ t.Fatal("accepted concatenated frames exceeding the output limit")+ }+ }+ for range 2 {+ got, err := proc.decompress(data, codec)+ if err != nil || !bytes.Equal(got, value) {+ t.Fatalf("exact limit: %v", err)+ }+ }+ limited, err := newProcessor(len(value) - 1)+ if err != nil {+ t.Fatal(err)+ }+ defer limited.close()+ if _, err := limited.decompress(data, codec); err == nil {+ t.Fatal("accepted oversized output")+ }+ })+ }+ proc, err := newProcessor(len(value) * 2)+ if err != nil {+ t.Fatal(err)+ }+ defer proc.close()+ for _, codec := range []string{"GZIP", "ZSTD", "LZ4"} {+ data := append(bytes.Clone(fixtures[codec]), fixtures[codec]...)+ got, err := proc.decompress(data, codec)+ if err != nil || !bytes.Equal(got, bytes.Repeat(value, 2)) {+ t.Fatalf("concatenated %s: %v", codec, err)+ }+ data[len(data)-1] ^= 0xff+ if _, err := proc.decompress(data, codec); err == nil {+ t.Fatalf("accepted corrupt %s checksum", codec)+ }+ }+ for _, size := range []uint32{1, uint32(len(value) + 1), uint32(maxDecompressedSize + 1)} {+ data := bytes.Clone(fixtures["LZ4SizePrefixed"])+ binary.LittleEndian.PutUint32(data, size)+ if _, err := proc.decompress(data, "LZ4SizePrefixed"); err == nil {+ t.Fatalf("accepted incorrect size %d", size)+ }+ }+ var frame bytes.Buffer+ writer := lz4.NewWriter(&frame)+ if err := writer.Apply(lz4.ChecksumOption(false), lz4.BlockChecksumOption(true), lz4.SizeOption(uint64(len(value)))); err != nil {+ t.Fatal(err)+ }+ if _, err := writer.Write(value); err != nil {+ t.Fatal(err)+ }+ if err := writer.Close(); err != nil {+ t.Fatal(err)+ }+ if got, err := proc.decompress(frame.Bytes(), "LZ4"); err != nil || !bytes.Equal(got, value) {+ t.Fatalf("LZ4 with size and block checksum: %v", err)+ }+ for end := 0; end < frame.Len(); end++ {+ data := append(bytes.Clone(fixtures["LZ4"]), frame.Bytes()[:end]...)+ if end > 0 {+ if _, err := proc.decompress(data, "LZ4"); err == nil {+ t.Fatalf("accepted truncated second LZ4 frame at %d", end)+ }+ }+ }+}++func TestInvalidChunkTransport(t *testing.T) {+ for _, input := range [][]byte{+ []byte("1"), []byte("-1\n"), []byte("x\n"), []byte("1\n"), []byte("1\n\x80"),+ []byte("1\n\x01"), []byte("1\n\x00"),+ append([]byte("1\n"), binary.AppendUvarint(nil, uint64(maxCompressedSize+1))...),+ append([]byte("1\n\x00"), binary.AppendUvarint(nil, 33)...),+ } {+ if err := run(bytes.NewReader(input), io.Discard, 1024); err == nil {+ t.Fatalf("accepted truncated or invalid transport %x", input)+ }+ }+}++func BenchmarkDecompress(b *testing.B) {+ for _, size := range []int{1024, 64 * 1024} {+ value := bytes.Repeat([]byte(`{"event":"example","properties":{"path":"/example","value":123}}`), size/64+1)[:size]+ fixtures := compressedFixtures(b, value)+ for codec, data := range fixtures {+ b.Run(fmt.Sprintf("%s/%d", codec, size), func(b *testing.B) {+ proc, err := newProcessor(maxDecompressedSize)+ if err != nil {+ b.Fatal(err)+ }+ defer proc.close()+ if _, err := proc.decompress(data, codec); err != nil {+ b.Fatal(err)+ }+ b.SetBytes(int64(len(value)))+ b.ReportAllocs()+ b.ResetTimer()+ for range b.N {+ got, err := proc.decompress(data, codec)+ if err != nil || len(got) != len(value) {+ b.Fatalf("decompress: %v", err)+ }+ }+ })+ }+ }+}diff --git a/clickhouse-udfs/util/go.mod b/clickhouse-udfs/util/go.modindex 31f748118999..0df9551bb979 100644--- a/clickhouse-udfs/util/go.mod+++ b/clickhouse-udfs/util/go.mod@@ -3,6 +3,8 @@ module github.com/PostHog/posthog/clickhouse-udfs/utilgo 1.27.1require (+ github.com/klauspost/compress v1.19.1+ github.com/pierrec/lz4/v4 v4.1.27github.com/stretchr/testify v1.11.1github.com/valyala/fastjson v1.6.7)diff --git a/clickhouse-udfs/util/go.sum b/clickhouse-udfs/util/go.sumindex 6a3bb5ebe723..8d9e808ac187 100644--- a/clickhouse-udfs/util/go.sum+++ b/clickhouse-udfs/util/go.sum@@ -1,5 +1,9 @@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/klauspost/compress v1.19.1 h1:VsB4HPswih7mmZ8WleSFQ75c/Ui1M4trX5oAsJnhSlk=+github.com/klauspost/compress v1.19.1/go.mod h1:cwPg85FWrGar70rWktvGQj8/hthj3wpl0PGDogxkrSQ=+github.com/pierrec/lz4/v4 v4.1.27 h1:+PhzhWDrjRj89TH2sw43nE3+4+W8lSxIuQadEHZyjUk=+github.com/pierrec/lz4/v4 v4.1.27/go.mod h1:EoQMVJgeeEOMsCqCzqFm2O0cJvljX2nGZjcRIPL34O4=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=diff --git a/clickhouse-udfs/util/scripts/build.sh b/clickhouse-udfs/util/scripts/build.shindex 40d65d5df64d..a0c9c197c041 100755--- a/clickhouse-udfs/util/scripts/build.sh+++ b/clickhouse-udfs/util/scripts/build.sh@@ -4,6 +4,7 @@ set -euo pipefailROOT_DIR=$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)OUT_DIR="$ROOT_DIR/../../posthog/user_scripts"UDFS=(+ decompress_udfjson_drop_keys_udfjson_clean_posthog_event_properties_udfjson_strip_empty_strings_and_nulls_udfdiff --git a/clickhouse-udfs/util/scripts/integration_test.sh b/clickhouse-udfs/util/scripts/integration_test.shindex f2613b70c974..6544c267293b 100755--- a/clickhouse-udfs/util/scripts/integration_test.sh+++ b/clickhouse-udfs/util/scripts/integration_test.sh@@ -5,6 +5,7 @@ ROOT_DIR=$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)COMPOSE_FILE="$ROOT_DIR/docker-compose.yml"TEMP_DIR=$(mktemp -d)UDFS=(+ decompressjson_drop_keysjson_clean_posthog_event_propertiesjson_clean_posthog_person_properties@@ -21,6 +22,9 @@ trap cleanup EXITquery_for() {local input="file('$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"+ ;;json_drop_keys)echo "SELECT JSONDropKeys(['a'])(x) FROM $input FORMAT TabSeparated";;@@ -72,6 +76,25 @@ for udf in "${UDFS[@]}"; dodonedone+query=$(cat <<'SQL'+WITH+ number % 2 = 0 AS compressed,+ if(compressed, unhex('170000006068656c6c6f200600d06f2068656c6c6f2068656c6c6f'), 'plain') AS data+SELECT countIf(+ if(compressed, decompress(data, 'LZ4SizePrefixed'), data)+ != if(compressed, 'hello hello hello hello', 'plain')+)+FROM numbers(10000)+SETTINGS short_circuit_function_evaluation = 'force_enable', 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 mixed compressed/plain rows to round-trip across pool chunks, got: $output" >&2+ exit 1+fi+echo "Passed mixed compressed/plain pool chunks."+query=$(cat <<'SQL'WITH concat('{"x":', repeat('[', 24), '[0]', repeat(',null]', 24), '}') AS rawSELECTdiff --git a/clickhouse-udfs/util/testdata/decompress/stateless/README.md b/clickhouse-udfs/util/testdata/decompress/stateless/README.mdnew file mode 100644index 000000000000..3556150b0314--- /dev/null+++ b/clickhouse-udfs/util/testdata/decompress/stateless/README.md@@ -0,0 +1,13 @@+# decompress Stateless Fixtures++The integration script also checks 10,000 mixed compressed/plain rows with short-circuit evaluation and 128-row chunks.++`truncated_frame.fail` rejects an LZ4 magic number without the rest of its frame, which the underlying reader otherwise accepts as empty output.++| Fixture | Coverage |+| --------------------- | ------------------------------------------------------------------------------------------------------------------------- |+| `codecs` | Explicit and automatic GZIP, ZSTD, and framed LZ4 decoding, plus raw and size-prefixed LZ4 blocks, across two-row chunks. |+| `binary` | Every byte value, including NUL, newlines and invalid UTF-8, plus an empty decompressed string. |+| `size_mismatch.fail` | Rejects a replay envelope whose size prefix differs from its decoded block length. |+| `size_limit.fail` | Rejects a replay envelope exceeding the output limit before allocating its output. |+| `unknown_header.fail` | Rejects data without a recognized framed-codec header. |diff --git a/clickhouse-udfs/util/testdata/decompress/stateless/binary.reference b/clickhouse-udfs/util/testdata/decompress/stateless/binary.referencenew file mode 100644index 000000000000..6a7c24d5b1a6--- /dev/null+++ b/clickhouse-udfs/util/testdata/decompress/stateless/binary.reference@@ -0,0 +1,2 @@+000102030405060708090A0B0C0D0E0F101112131415161718191A1B1C1D1E1F202122232425262728292A2B2C2D2E2F303132333435363738393A3B3C3D3E3F404142434445464748494A4B4C4D4E4F505152535455565758595A5B5C5D5E5F606162636465666768696A6B6C6D6E6F707172737475767778797A7B7C7D7E7F808182838485868788898A8B8C8D8E8F909192939495969798999A9B9C9D9E9FA0A1A2A3A4A5A6A7A8A9AAABACADAEAFB0B1B2B3B4B5B6B7B8B9BABBBCBDBEBFC0C1C2C3C4C5C6C7C8C9CACBCCCDCECFD0D1D2D3D4D5D6D7D8D9DADBDCDDDEDFE0E1E2E3E4E5E6E7E8E9EAEBECEDEEEFF0F1F2F3F4F5F6F7F8F9FAFBFCFDFEFF+diff --git a/clickhouse-udfs/util/testdata/decompress/stateless/binary.tsv b/clickhouse-udfs/util/testdata/decompress/stateless/binary.tsvnew file mode 100644index 000000000000..12b99d3e90f4--- /dev/null+++ b/clickhouse-udfs/util/testdata/decompress/stateless/binary.tsv@@ -0,0 +1,2 @@+gzip 1f8b08000000000002ff010001fffe000102030405060708090a0b0c0d0e0f101112131415161718191a1b1c1d1e1f202122232425262728292a2b2c2d2e2f303132333435363738393a3b3c3d3e3f404142434445464748494a4b4c4d4e4f505152535455565758595a5b5c5d5e5f606162636465666768696a6b6c6d6e6f707172737475767778797a7b7c7d7e7f808182838485868788898a8b8c8d8e8f909192939495969798999a9b9c9d9e9fa0a1a2a3a4a5a6a7a8a9aaabacadaeafb0b1b2b3b4b5b6b7b8b9babbbcbdbebfc0c1c2c3c4c5c6c7c8c9cacbcccdcecfd0d1d2d3d4d5d6d7d8d9dadbdcdddedfe0e1e2e3e4e5e6e7e8e9eaebecedeeeff0f1f2f3f4f5f6f7f8f9fafbfcfdfeff738c052900010000+ 1f8b08000000000002ff03000000000000000000diff --git a/clickhouse-udfs/util/testdata/decompress/stateless/codecs.reference b/clickhouse-udfs/util/testdata/decompress/stateless/codecs.referencenew file mode 100644index 000000000000..700feaada23e--- /dev/null+++ b/clickhouse-udfs/util/testdata/decompress/stateless/codecs.reference@@ -0,0 +1,8 @@+68656C6C6F2068656C6C6F2068656C6C6F2068656C6C6F+68656C6C6F2068656C6C6F2068656C6C6F2068656C6C6F+68656C6C6F2068656C6C6F2068656C6C6F2068656C6C6F+68656C6C6F2068656C6C6F2068656C6C6F2068656C6C6F+68656C6C6F2068656C6C6F2068656C6C6F2068656C6C6F+68656C6C6F2068656C6C6F2068656C6C6F2068656C6C6F+68656C6C6F2068656C6C6F2068656C6C6F2068656C6C6F+68656C6C6F2068656C6C6F2068656C6C6F2068656C6C6Fdiff --git a/clickhouse-udfs/util/testdata/decompress/stateless/codecs.tsv b/clickhouse-udfs/util/testdata/decompress/stateless/codecs.tsvnew file mode 100644index 000000000000..5bbd915099a3--- /dev/null+++ b/clickhouse-udfs/util/testdata/decompress/stateless/codecs.tsv@@ -0,0 +1,8 @@+GZIP 1f8b08000000000000ffca48cdc9c957c02001010000ffffe3513d8d17000000+ 1f8b08000000000000ffca48cdc9c957c02001010000ffffe3513d8d17000000+ZSTD 28b52ffd04006d00003068656c6c6f20015406030e09175eae0d+ 28b52ffd04006d00003068656c6c6f20015406030e09175eae0d+LZ4 04224d186470b91700008068656c6c6f2068656c6c6f2068656c6c6f2068656c6c6f00000000f26b940b+ 04224d186470b91700008068656c6c6f2068656c6c6f2068656c6c6f2068656c6c6f00000000f26b940b+LZ4Block 6068656c6c6f200600d06f2068656c6c6f2068656c6c6f+LZ4SizePrefixed 170000006068656c6c6f200600d06f2068656c6c6f2068656c6c6fdiff --git a/clickhouse-udfs/util/testdata/decompress/stateless/size_limit.fail.reference b/clickhouse-udfs/util/testdata/decompress/stateless/size_limit.fail.referencenew file mode 100644index 000000000000..193d4aaeae22--- /dev/null+++ b/clickhouse-udfs/util/testdata/decompress/stateless/size_limit.fail.reference@@ -0,0 +1 @@+decompressed size exceedsdiff --git a/clickhouse-udfs/util/testdata/decompress/stateless/size_limit.fail.tsv b/clickhouse-udfs/util/testdata/decompress/stateless/size_limit.fail.tsvnew file mode 100644index 000000000000..cb1c585f76dc--- /dev/null+++ b/clickhouse-udfs/util/testdata/decompress/stateless/size_limit.fail.tsv@@ -0,0 +1 @@+LZ4SizePrefixed 010000046068656c6c6f200600d06f2068656c6c6f2068656c6c6fdiff --git a/clickhouse-udfs/util/testdata/decompress/stateless/size_mismatch.fail.reference b/clickhouse-udfs/util/testdata/decompress/stateless/size_mismatch.fail.referencenew file mode 100644index 000000000000..54165e168937--- /dev/null+++ b/clickhouse-udfs/util/testdata/decompress/stateless/size_mismatch.fail.reference@@ -0,0 +1 @@+invalid LZ4SizePrefixeddiff --git a/clickhouse-udfs/util/testdata/decompress/stateless/size_mismatch.fail.tsv b/clickhouse-udfs/util/testdata/decompress/stateless/size_mismatch.fail.tsvnew file mode 100644index 000000000000..a9aee853866e--- /dev/null+++ b/clickhouse-udfs/util/testdata/decompress/stateless/size_mismatch.fail.tsv@@ -0,0 +1 @@+LZ4SizePrefixed 180000006068656c6c6f200600d06f2068656c6c6f2068656c6c6fdiff --git a/clickhouse-udfs/util/testdata/decompress/stateless/truncated_frame.fail.reference b/clickhouse-udfs/util/testdata/decompress/stateless/truncated_frame.fail.referencenew file mode 100644index 000000000000..fa55d8c2993b--- /dev/null+++ b/clickhouse-udfs/util/testdata/decompress/stateless/truncated_frame.fail.reference@@ -0,0 +1 @@+invalid LZ4 streamdiff --git a/clickhouse-udfs/util/testdata/decompress/stateless/truncated_frame.fail.tsv b/clickhouse-udfs/util/testdata/decompress/stateless/truncated_frame.fail.tsvnew file mode 100644index 000000000000..feb9d38d482e--- /dev/null+++ b/clickhouse-udfs/util/testdata/decompress/stateless/truncated_frame.fail.tsv@@ -0,0 +1 @@+LZ4 04224d18diff --git a/clickhouse-udfs/util/testdata/decompress/stateless/unknown_header.fail.reference b/clickhouse-udfs/util/testdata/decompress/stateless/unknown_header.fail.referencenew file mode 100644index 000000000000..73f726298873--- /dev/null+++ b/clickhouse-udfs/util/testdata/decompress/stateless/unknown_header.fail.reference@@ -0,0 +1 @@+cannot detect compression codec from frame headerdiff --git a/clickhouse-udfs/util/testdata/decompress/stateless/unknown_header.fail.tsv b/clickhouse-udfs/util/testdata/decompress/stateless/unknown_header.fail.tsvnew file mode 100644index 000000000000..22de71791b92--- /dev/null+++ b/clickhouse-udfs/util/testdata/decompress/stateless/unknown_header.fail.tsv@@ -0,0 +1 @@+ 00diff --git a/docker/clickhouse/user_defined_function.xml b/docker/clickhouse/user_defined_function.xmlindex 194671c40784..aee90f3f582a 100644--- a/docker/clickhouse/user_defined_function.xml+++ b/docker/clickhouse/user_defined_function.xml@@ -644,4 +644,20 @@<command>json_strip_empty_strings_and_nulls_udf --chunked</command><send_chunk_header>true</send_chunk_header></function>+ <function>+ <type>executable_pool</type>+ <name>decompress</name>+ <return_type>String</return_type>+ <argument>+ <type>String</type>+ </argument>+ <argument>+ <type>String</type>+ </argument>+ <format>RowBinary</format>+ <command>decompress_udf</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.mdindex 7c7629e52278..ea993acc3af3 100644--- a/docs/internal/clickhouse-utility-udfs.md+++ b/docs/internal/clickhouse-utility-udfs.md@@ -11,7 +11,8 @@ map values from failing insertion into the typed JSON column while preserving unSee [the utility UDF README](../../clickhouse-udfs/util/README.md) for build and integration-test commands.The utility module and CI use Go 1.27.1, declared in `clickhouse-udfs/util/go.mod`.-Rebuild all three utilities for Linux amd64 and arm64 with `./scripts/build.sh` whenever this version changes; CI verifies the checked-in binaries.+Rebuild all utilities for Linux amd64 and arm64 with `./scripts/build.sh` whenever this version changes; CI verifies the checked-in binaries.+Changes to `posthog/user_scripts` no longer dispatch the separate UDF publishing workflow on pushes to master.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.@@ -160,3 +161,127 @@ Regression tests cover malformed discarded values, duplicate handling in wide obThe 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.++### `decompress(data, codec)`++Returns the exact decompressed bytes as a ClickHouse `String`, including NUL, newlines, and non-UTF-8 bytes.+Both inputs are regular SQL arguments, so the codec can vary between rows in an `executable_pool`.+The worker uses RowBinary transport with row-count headers and flushes after each chunk, allowing ClickHouse to reuse it across blocks and queries.+See [ClickHouse's executable UDF documentation](https://clickhouse.com/docs/reference/functions/regular-functions/udf) for the argument and pool protocol.++| Codec | Input |+| ----------------- | ---------------------------------------------------------------------- |+| `GZIP` | GZIP stream, including concatenated members. |+| `ZSTD` | Zstandard frames, including concatenated frames. |+| `LZ4` | Standard LZ4 frames. |+| `LZ4Block` | Raw LZ4 block without a size prefix. |+| `LZ4SizePrefixed` | Four-byte little-endian uncompressed size followed by a raw LZ4 block. |++Names are case-insensitive. An empty codec auto-detects GZIP, ZSTD, or framed LZ4, including ZSTD/LZ4 streams with leading skippable metadata frames.+Raw and size-prefixed blocks require an explicit codec because they have no identifying magic bytes.+`LZ4` always means the standard frame format; it does not select the replay envelope.++```sql+SELECT decompress(unhex('170000006068656c6c6f200600d06f2068656c6c6f2068656c6c6f'), 'LZ4SizePrefixed');+-- hello hello hello hello++SELECT decompress(compressed_body, 'ZSTD') FROM messages;+SELECT decompress(base64Decode(encoded_body), '') FROM messages;+```++The replay producer in `rust/capture/src/serialization/mod.rs` uses `LZ4SizePrefixed` and marks those Kafka values with `content-encoding: lz4`.+Read the message value into a raw `String`, decompress it, then parse its JSON.+Kafka record-batch compression is handled by the Kafka client separately.+The function does not pass through uncompressed messages: select which rows need decoding using the message's encoding metadata.+When using `if` to mix compressed and plain rows, set `short_circuit_function_evaluation = 'force_enable'` so the UDF only receives the compressed branch.++Each compressed input is limited to 65 MiB and each decoded value to 64 MiB.+The extra input allowance accommodates compression overhead near the output limit.+Invalid frames, unsupported codecs, truncated transport, size-limit violations, and incorrect envelope sizes fail the query.+Framed codec checksums are validated when present; raw LZ4 blocks have no checksum, so a damaged block that still decodes cannot always be detected.+A size-prefixed block must produce exactly the declared number of bytes.++Workers reuse GZIP and LZ4 readers, the ZSTD decoder, and input/output buffers.+ZSTD uses `DecodeAll` to decode directly into a reusable slice.+Input and output transport buffers are 64 KiB each, down from 4 MiB each in the archived implementation.+Buffers retain their high-water capacity for the worker's lifetime, and each codec can retain separate output storage; the value limit is not a total worker-memory limit.+`LZ4Block` reserves the full 64 MiB output capacity because it has no size metadata; `LZ4SizePrefixed` grows its output buffer to the declared size instead.++The build script, architecture launcher, unversioned function configuration, deployment manifests, and existing utility-UDF CI include the decompressor.+Installing those artifacts makes the function available; this change does not alter Kafka table definitions or materialized views.++Run its unit tests and repeat the synthetic decoding benchmarks from `clickhouse-udfs/util`:++```sh+go test ./cmd/decompress_udf -timeout 30s+go test -run '^$' -bench BenchmarkDecompress -benchmem -cpu=1 -count=3 ./cmd/decompress_udf+```++#### Decompression measurements, September 10, 2026++Baseline: archived `PostHog/clickhouse-util-udfs` commit `92a3dd0c0ce81adada0440144acbdf12ef5beec2`.+Both implementations used Go 1.27.1 on an Apple M4 Pro, macOS arm64, with identical compression-library versions.+The microbenchmark repeats synthetic JSON to make 1 KiB and 64 KiB payloads and reuses one processor after warmup.+Results below are medians of three alternating before/after runs with `-cpu=1 -benchtime=200ms`.++| Workload | Before | After | Speedup | Allocated bytes per row, before / after |+| ------------ | --------- | --------- | ------- | --------------------------------------- |+| GZIP, 1 KiB | 2,616 ns | 715 ns | 3.66× | 41,256 / 24 |+| GZIP, 64 KiB | 15,841 ns | 12,764 ns | 1.24× | 41,256 / 24 |+| ZSTD, 1 KiB | 1,489 ns | 1,312 ns | 1.13× | 72 / 0 |+| ZSTD, 64 KiB | 20,234 ns | 19,198 ns | 1.05× | 72 / 0 |++LZ4 reader reuse reduces allocations from 488 to 136 bytes per row.+Raw LZ4 decoding uses the same library primitive as before; its decoding speed is effectively unchanged.+The new size-prefixed variant avoids reserving a full 64 MiB buffer for a small block.++Whole-query GZIP measurements used ClickHouse 26.6.2.158 in Docker on the same host.+The baseline used `executable`; the new function used `executable_pool` with chunk headers.+Each result is the median of five alternating measurements after one warmup, using `max_threads=1` and `max_block_size=8192`.++| Workload | Before | After | Speedup |+| -------------------- | ------ | ------ | ------- |+| 100,000 rows × 1 KiB | 432 ms | 110 ms | 3.93× |+| 10,000 rows × 64 KiB | 714 ms | 464 ms | 1.54× |++Queries summed `length(decompress(materialize(unhex(payload_hex)), materialize('GZIP')))` over `numbers(row_count)` to prevent constant folding.+Separate byte-for-byte comparisons found zero differing rows for both workloads.+These highly compressible, repeated payloads measure decoding and UDF transport, not Kafka ingestion, JSON parsing, or production capacity.++#### Codec dispatch and native Zstandard follow-up++Codec dispatch uses `strings.EqualFold`, avoiding an uppercase-string allocation for mixed-case codec names.+For `LZ4SizePrefixed` on the 1 KiB synthetic workload, median decoding time fell from 92.39 ns to 58.67 ns, a 36.5% reduction.+Allocated bytes fell from 16 to zero per row. These are three-sample medians with `-cpu=1 -benchtime=500ms` on the same macOS arm64 host.+The existing round-trip cases cover original, lowercase, and uppercase codec names.++A separate benchmark compared the Go processor with a direct CGO call to `ZSTD_decompressDCtx`.+It reused a decoder context and a 64 MiB output buffer on both sides, included the CGO call overhead, and verified identical output before timing.+Compression and warmup were excluded; the two decoders received identical frames from the Go encoder at its default compression level.+Payloads contained repeated text, deterministic varied event text, or pseudorandom bytes at 1 KiB, 64 KiB, and 1 MiB.+Text was truncated to the exact benchmark size; no JSON parsing was performed.++Linux results used Go 1.27.1, klauspost/compress v1.19.1, Debian Bookworm libzstd 1.5.4, and glibc 2.36 in an arm64 Docker container on the Apple M4 Pro.+Values below are three-sample medians with `-cpu=1 -benchtime=200ms`.++| Input | Size | Go decoder | Native via CGO | Native throughput / Go |+| ------------------ | ------ | ---------- | -------------- | ---------------------- |+| Varied event text | 1 KiB | 2.437 µs | 2.003 µs | 1.22× |+| Varied event text | 64 KiB | 33.445 µs | 23.549 µs | 1.42× |+| Varied event text | 1 MiB | 472.654 µs | 336.296 µs | 1.41× |+| Repeated text | 64 KiB | 20.042 µs | 5.082 µs | 3.94× |+| Pseudorandom bytes | 64 KiB | 3.656 µs | 4.023 µs | 0.91× |+| Pseudorandom bytes | 1 MiB | 65.406 µs | 68.503 µs | 0.95× |++On macOS arm64 with libzstd 1.5.7, native throughput was 1.18–1.31× Go's for varied event text, and 4.72× for the repeated 64 KiB input.+That repeated input compressed to only 77 bytes; its speedup should not be treated as representative.+The macOS and Linux results use different library versions and execution environments, so they do not isolate a libc or version effect.+Neither run measures production CPUs, ClickHouse transport, Kafka ingestion, or concurrent queries.+Go allocation counters do not include C allocations.++Both implementations passed checks for valid and empty frames, unknown content size, concatenated frames, skippable metadata, checksum errors, truncated frames, and output limits.+This is a bounded compatibility check, not an exhaustive audit; the benchmark's direct native API does not implement every policy of the Go UDF, including its window-size restriction.++Native Zstandard is not integrated into the UDF. Both Linux artifacts still build with `CGO_ENABLED=0` and contain no native Zstandard dependency.+A direct C binding requires CGO and a target C toolchain/library. Disabling CGO excludes files importing `C`; it does not automatically select another decoder.+Dynamic native libraries also introduce target ABI and library-version dependencies. See the [Go CGO documentation](https://pkg.go.dev/cmd/cgo).diff --git a/posthog/udf_versioner.py b/posthog/udf_versioner.pyindex 3d7fe6fd8ee4..cb745676d9bb 100644--- a/posthog/udf_versioner.py+++ b/posthog/udf_versioner.py@@ -15,6 +15,7 @@ UDF_VERSION = 12 # Last modified by: @aspicer, 2026-04-20 (RowBinary default, JEARLIEST_UDF_VERSION = 11UNVERSIONED_FUNCTIONS = {+ "decompress","JSONCleanPostHogEventProperties","JSONCleanPostHogPersonProperties","JSONCleanPostHogTemporaryProperties",diff --git a/posthog/user_scripts/decompress_udf b/posthog/user_scripts/decompress_udfnew file mode 100755index 000000000000..aa4e855d0fb1--- /dev/null+++ b/posthog/user_scripts/decompress_udf@@ -0,0 +1,18 @@+#!/bin/sh++DIR_NAME=$(dirname "$0")+TEMP_DIR=$(mktemp -d -p /tmp "decompress_udf_XXXXXXXXXX")+trap 'rm -rf "$TEMP_DIR"; exit' 0++case $(uname -m) in+aarch64)+ EXECUTABLE_NAME="decompress_udf_aarch64"+ ;;+*)+ EXECUTABLE_NAME="decompress_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/decompress_udf_aarch64 b/posthog/user_scripts/decompress_udf_aarch64new file mode 100755index 000000000000..3af9a059daf7Binary files /dev/null and b/posthog/user_scripts/decompress_udf_aarch64 differdiff --git a/posthog/user_scripts/decompress_udf_x86_64 b/posthog/user_scripts/decompress_udf_x86_64new file mode 100755index 000000000000..56d4d5f1c3e6Binary files /dev/null and b/posthog/user_scripts/decompress_udf_x86_64 differdiff --git a/posthog/user_scripts/latest_user_defined_function.xml b/posthog/user_scripts/latest_user_defined_function.xmlindex d0e39c449745..8b06cc6515d8 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-09-07T07:48:54.700356+00:00+ <!-- Version: v12. Generated at: 2026-09-10T10:15:07.735801+00:00This 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>@@ -963,4 +963,20 @@ This file is autogenerated by udf_versioner.py. Do not edit this, only edit the<command>json_strip_empty_strings_and_nulls_udf --chunked</command><send_chunk_header>true</send_chunk_header></function>+ <function>+ <type>executable_pool</type>+ <name>decompress</name>+ <return_type>String</return_type>+ <argument>+ <type>String</type>+ </argument>+ <argument>+ <type>String</type>+ </argument>+ <format>RowBinary</format>+ <command>decompress_udf</command>+ <send_chunk_header>true</send_chunk_header>+ <stderr_reaction>throw</stderr_reaction>+ <deterministic>true</deterministic>+ </function></functions>\ No newline at end of filediff --git a/posthog/user_scripts/v12/user_defined_function.xml b/posthog/user_scripts/v12/user_defined_function.xmlindex d0e39c449745..8b06cc6515d8 100644--- a/posthog/user_scripts/v12/user_defined_function.xml+++ b/posthog/user_scripts/v12/user_defined_function.xml@@ -1,5 +1,5 @@<functions>- <!-- Version: v12. Generated at: 2026-09-07T07:48:54.700356+00:00+ <!-- Version: v12. Generated at: 2026-09-10T10:15:07.735801+00:00This 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>@@ -963,4 +963,20 @@ This file is autogenerated by udf_versioner.py. Do not edit this, only edit the<command>json_strip_empty_strings_and_nulls_udf --chunked</command><send_chunk_header>true</send_chunk_header></function>+ <function>+ <type>executable_pool</type>+ <name>decompress</name>+ <return_type>String</return_type>+ <argument>+ <type>String</type>+ </argument>+ <argument>+ <type>String</type>+ </argument>+ <format>RowBinary</format>+ <command>decompress_udf</command>+ <send_chunk_header>true</send_chunk_header>+ <stderr_reaction>throw</stderr_reaction>+ <deterministic>true</deterministic>+ </function></functions>\ No newline at end of file