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.

fix(clickhouse): quarantine deeply nested property arrays (#96738)

Rory Shanks577cc787b7e5
diff --git a/clickhouse-udfs/util/cmd/json_clean_posthog_event_properties_udf/main.go b/clickhouse-udfs/util/cmd/json_clean_posthog_event_properties_udf/main.go
index b39e38085872..da0de1144ab9 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
@@ -39,7 +39,9 @@ var eventPropertyRules = makeEventPropertyRules()
const (
// Match fastjson's parser ceiling so every stored document remains readable by the blob-cleanup UDF.
- maxJSONDepth = 300
+ maxJSONDepth = 300
+ // Nested arrays can amplify ClickHouse type inference even for small documents.
+ maxJSONArrayDepth = 8
unparseablePropertiesKey = "$unparseable_properties"
)
@@ -192,6 +194,12 @@ 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) {
+ p.recycle(parsed)
+ p.writeUnparseableProperties(buf, rawLine)
+ return nil
+ }
cleaned, err := p.cleanProperties(parsed)
if err != nil {
@@ -202,6 +210,12 @@ 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) {
+ p.recycle(cleaned)
+ p.writeUnparseableProperties(buf, rawLine)
+ return nil
+ }
buf.Reset()
buf.Grow(len(rawLine))
@@ -214,6 +228,27 @@ func (p *processor) processLine(rawLine []byte, buf *bytes.Buffer) error {
return nil
}
+func exceedsJSONArrayDepth(v *value, depth int) bool {
+ if v.kind == kindArray {
+ depth++
+ if depth > maxJSONArrayDepth {
+ return true
+ }
+ for _, child := range v.values {
+ if exceedsJSONArrayDepth(child, depth) {
+ return true
+ }
+ }
+ } else if v.kind == kindObject {
+ for _, entry := range v.entries {
+ if exceedsJSONArrayDepth(entry.value, depth) {
+ return true
+ }
+ }
+ }
+ return false
+}
+
func (p *processor) cleanProperties(v *value) (*value, error) {
if p.kind == temporaryProperties {
return p.cleanTemporaryProperties(v)
diff --git a/clickhouse-udfs/util/cmd/json_clean_posthog_event_properties_udf/main_test.go b/clickhouse-udfs/util/cmd/json_clean_posthog_event_properties_udf/main_test.go
index 11eea0ee65e8..d9b860683247 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
@@ -131,21 +131,73 @@ func TestProcessLineQuarantinesInvalidExceptionList(t *testing.T) {
func TestProcessLineQuarantinesExcessiveDepth(t *testing.T) {
tests := map[string]string{
- "nested JSON": strings.Repeat(`{"x":`, maxJSONDepth) + `1` + strings.Repeat(`}`, maxJSONDepth),
- "dotted key": `{"` + strings.Repeat("x.", maxJSONDepth) + `x":1}`,
+ "nested JSON": strings.Repeat(`{"x":`, maxJSONDepth) + `1` + strings.Repeat(`}`, maxJSONDepth),
+ "dotted key": `{"` + strings.Repeat("x.", maxJSONDepth) + `x":1}`,
+ "nested arrays": `{"x":` + strings.Repeat(`[`, 9) + `1` + strings.Repeat(`]`, 9) + `}`,
+ "arrays through objects": `{"x":` + strings.Repeat(`[{"x":`, 9) + `1` + strings.Repeat(`}]`, 9) + `}`,
+ "temporary property": `{"$set":` + strings.Repeat(`[`, 9) + `1` + strings.Repeat(`]`, 9) + `}`,
+ "arrays with nulls": `{"x":` + strings.Repeat(`[`, 24) + `[0]` + strings.Repeat(`,null]`, 24) + `}`,
}
-
for name, input := range tests {
- t.Run(name, func(t *testing.T) {
- var got bytes.Buffer
- if err := processLine([]byte(input), &got); err != nil {
- t.Fatal(err)
- }
- want := fmt.Sprintf(`{"$unparseable_properties":%q}`, input)
- if got.String() != want {
- t.Fatalf("processLine() = %s, want %s", got.String(), want)
- }
- })
+ for _, kind := range []propertiesKind{eventProperties, personProperties, temporaryProperties} {
+ t.Run(fmt.Sprintf("%s/%d", name, kind), func(t *testing.T) {
+ var got bytes.Buffer
+ proc := processor{kind: kind}
+ if err := proc.processLine([]byte(input), &got); err != nil {
+ t.Fatal(err)
+ }
+ want := fmt.Sprintf(`{"$unparseable_properties":%q}`, input)
+ if kind == temporaryProperties {
+ want = `{}`
+ }
+ if got.String() != want {
+ t.Fatalf("processLine() = %s, want %s", got.String(), want)
+ }
+ })
+ }
+ }
+}
+
+func TestProcessLineArrayDepthBoundary(t *testing.T) {
+ for _, depth := range []int{7, 8} {
+ arrays := strings.Repeat(`[`, depth) + `1` + strings.Repeat(`]`, depth)
+ input := `{"x":` + arrays + `,"$set":` + arrays + `}`
+ for _, kind := range []propertiesKind{eventProperties, personProperties, temporaryProperties} {
+ t.Run(fmt.Sprintf("%d/%d", depth, kind), func(t *testing.T) {
+ var got bytes.Buffer
+ proc := processor{kind: kind}
+ if err := proc.processLine([]byte(input), &got); err != nil {
+ t.Fatal(err)
+ }
+ want := input
+ if kind == eventProperties {
+ want = `{"x":` + arrays + `}`
+ } else if kind == temporaryProperties {
+ want = `{"$set":` + arrays + `}`
+ }
+ if got.String() != want {
+ t.Fatalf("processLine() = %s, want %s", got.String(), want)
+ }
+ })
+ }
+ }
+}
+
+func TestProcessLineChecksArrayDepthAfterNormalization(t *testing.T) {
+ for _, depth := range []int{7, 8} {
+ object := `{"x":` + strings.Repeat(`[`, depth) + `1` + strings.Repeat(`]`, depth) + `}`
+ input := fmt.Sprintf(`{"$exception_list":%q}`, object)
+ var got bytes.Buffer
+ if err := processLine([]byte(input), &got); err != nil {
+ t.Fatal(err)
+ }
+ want := `{"$exception_list":[` + object + `]}`
+ if depth == 8 {
+ want = fmt.Sprintf(`{"$unparseable_properties":%q}`, input)
+ }
+ if got.String() != want {
+ t.Fatalf("processLine() = %s, want %s", got.String(), want)
+ }
}
}
@@ -255,6 +307,32 @@ func TestRunChunked(t *testing.T) {
}
}
+func TestRunChunkedAfterArrayQuarantine(t *testing.T) {
+ poison := `{"$set":` + strings.Repeat(`[`, 9) + `1` + strings.Repeat(`]`, 9) + `}`
+ good := `{"keep":1,"$set":2}`
+ input := "2\n" + poison + "\n" + good + "\n1\n" + good + "\n"
+ for _, kind := range []propertiesKind{eventProperties, personProperties, temporaryProperties} {
+ t.Run(fmt.Sprint(kind), func(t *testing.T) {
+ quarantine := fmt.Sprintf(`{"$unparseable_properties":%q}`, poison)
+ cleaned := good
+ if kind == eventProperties {
+ cleaned = `{"keep":1}`
+ } else if kind == temporaryProperties {
+ quarantine = `{}`
+ cleaned = `{"$set":2}`
+ }
+ var output bytes.Buffer
+ if err := runChunked(strings.NewReader(input), &output, kind); err != nil {
+ t.Fatal(err)
+ }
+ want := quarantine + "\n" + cleaned + "\n" + cleaned + "\n"
+ if output.String() != want {
+ t.Fatalf("runChunked() = %q, want %q", output.String(), want)
+ }
+ })
+ }
+}
+
func TestProcessLineReleasesPreviousInput(t *testing.T) {
for _, kind := range []propertiesKind{eventProperties, personProperties, temporaryProperties} {
t.Run(fmt.Sprint(kind), func(t *testing.T) {
diff --git a/clickhouse-udfs/util/scripts/integration_test.sh b/clickhouse-udfs/util/scripts/integration_test.sh
index 160941a79a29..f2613b70c974 100755
--- a/clickhouse-udfs/util/scripts/integration_test.sh
+++ b/clickhouse-udfs/util/scripts/integration_test.sh
@@ -71,3 +71,20 @@ for udf in "${UDFS[@]}"; do
echo "Passed $udf/$test_name."
done
done
+
+query=$(cat <<'SQL'
+WITH concat('{"x":', repeat('[', 24), '[0]', repeat(',null]', 24), '}') AS raw
+SELECT
+ JSONExtractString(toJSONString(CAST(JSONCleanPostHogEventProperties(raw) AS JSON(max_dynamic_paths=0))), '$unparseable_properties') = raw,
+ JSONExtractString(toJSONString(CAST(JSONCleanPostHogPersonProperties(raw) AS JSON(max_dynamic_paths=0))), '$unparseable_properties') = raw,
+ toJSONString(CAST(JSONCleanPostHogTemporaryProperties(raw) AS JSON(max_dynamic_paths=0))) = '{}'
+SETTINGS max_threads = 1, max_memory_usage = 268435456
+FORMAT TabSeparated
+SQL
+)
+output=$(docker compose -f "$COMPOSE_FILE" exec -T clickhouse clickhouse-client --query "$query")
+if [[ "$output" != $'1\t1\t1' ]]; then
+ echo "Expected array quarantine to preserve the input and produce castable JSON, got: $output" >&2
+ exit 1
+fi
+echo "Passed nested-array quarantine JSON casts."
diff --git a/docs/internal/clickhouse-utility-udfs.md b/docs/internal/clickhouse-utility-udfs.md
index e17d0f1fea0d..ff6176f09fc8 100644
--- a/docs/internal/clickhouse-utility-udfs.md
+++ b/docs/internal/clickhouse-utility-udfs.md
@@ -11,6 +11,21 @@ The event, person, and temporary cleaners reuse 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.
+### Array nesting limit
+
+The event, person, and temporary cleaners accept at most eight nested arrays along any path, including arrays separated by objects.
+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 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.
+The temporary cleaner emits `{}` because the permanent cleaner preserves the original input, including temporary properties.
+Run both event cleaners on the original document to retain that guarantee.
+Malformed JSON still fails instead of entering this quarantine path.
+
### `JSONCleanPostHogTemporaryProperties(json)`
Accepts a JSON object and retains only the following top-level properties, including their dotted descendants. It uses the event cleaner's dotted-key expansion, null-object-field removal, duplicate handling, and integer protection, without coercing values to declared schema types. Non-object input fails.
diff --git a/posthog/user_scripts/json_clean_posthog_event_properties_udf_aarch64 b/posthog/user_scripts/json_clean_posthog_event_properties_udf_aarch64
index cf46caa7ebdb..1b242fb807c6 100755
Binary files a/posthog/user_scripts/json_clean_posthog_event_properties_udf_aarch64 and b/posthog/user_scripts/json_clean_posthog_event_properties_udf_aarch64 differ
diff --git a/posthog/user_scripts/json_clean_posthog_event_properties_udf_x86_64 b/posthog/user_scripts/json_clean_posthog_event_properties_udf_x86_64
index c15af701705e..d444917054c2 100755
Binary 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