From 9f373e7180bbe6463218b688c1a0e1e284cd65e7 Mon Sep 17 00:00:00 2001 From: Yuzhong Zhang Date: Fri, 4 Sep 2026 01:41:49 +0000 Subject: [PATCH 1/3] fix(json): consume v0 SharedData to keep native stream aligned JSON deprecated object decoding only skipped SharedData offsets and left the Array(Tuple(String, String)) payload in the wire stream, which desynced later columns (#1854). Decode the full array and merge overflow paths into the scanned JSON object. --- lib/column/json.go | 12 ++ lib/column/json_deprecated.go | 225 ++++++++++++++++++++++++++++- lib/column/json_deprecated_test.go | 176 ++++++++++++++++++++++ 3 files changed, 410 insertions(+), 3 deletions(-) create mode 100644 lib/column/json_deprecated_test.go diff --git a/lib/column/json.go b/lib/column/json.go index d6064c55b5..bd0b681a7d 100644 --- a/lib/column/json.go +++ b/lib/column/json.go @@ -55,6 +55,11 @@ type JSON struct { maxDynamicPaths int maxDynamicTypes int + + // sharedData is JSON v0 overflow storage: Array(Tuple(String, String)). + // Populated only by decodeObjectData_v1. Each tuple is (path, Dynamic + // serializeBinary payload) for paths that exceeded max_dynamic_paths. + sharedData Interface } // jsonMode is the mode preference a value carries when offered to a JSON @@ -245,6 +250,8 @@ func (c *JSON) rowAsJSON(row int) *chcol.JSON { obj.SetValueAtPath(path, col.Row(row, false)) } + c.mergeSharedDataRow(obj, row) + return obj } @@ -942,6 +949,11 @@ func (c *JSON) Reset() { c.jsonStrings.Reset() } + if c.sharedData != nil { + c.sharedData.Reset() + c.sharedData = nil + } + // Clear the latched mode so the next batch starts unbiased. An all-null // batch only latches String at WriteStatePrefix; without this reset, a // subsequent batch of structs/maps would fail reconcileMode with a diff --git a/lib/column/json_deprecated.go b/lib/column/json_deprecated.go index bf9ba21886..119cf122a9 100644 --- a/lib/column/json_deprecated.go +++ b/lib/column/json_deprecated.go @@ -1,9 +1,12 @@ package column import ( + "bytes" "fmt" "github.com/ClickHouse/ch-go/proto" + + "github.com/ClickHouse/clickhouse-go/v2/lib/chcol" ) func (c *JSON) encodeObjectHeader_v1(buffer *proto.Buffer) error { @@ -114,11 +117,227 @@ func (c *JSON) decodeObjectData_v1(reader *proto.Reader, rows int) error { } } - // SharedData per row, ignored for now. May cause stream offset issues if present - _, err := reader.ReadRaw(8 * rows) // one UInt64 per row + if err := c.decodeSharedData_v1(reader, rows); err != nil { + return err + } + + return nil +} + +func (c *JSON) decodeSharedData_v1(reader *proto.Reader, rows int) error { + // ClickHouse stores overflow JSON paths as Array(Tuple(String, String)): + // UInt64 offsets followed by the flattened Tuple columns. Reading only the + // offsets leaves the Tuple payload in the stream and desyncs every later + // column (issue #1854). + col, err := Type("Array(Tuple(String, String))").Column("", c.sc) if err != nil { + return fmt.Errorf("failed to init shared data for json column: %w", err) + } + if err := col.Decode(reader, rows); err != nil { return fmt.Errorf("failed to read shared data for json column: %w", err) } - + c.sharedData = col return nil } + +func (c *JSON) mergeSharedDataRow(obj *chcol.JSON, row int) { + if c.sharedData == nil || row >= c.sharedData.Rows() { + return + } + for _, pair := range sharedDataPairs(c.sharedData.Row(row, false)) { + value, chType := decodeSharedDataValue(pair[1]) + obj.SetValueAtPath(pair[0], chcol.NewDynamicWithType(value, chType)) + } +} + +func sharedDataPairs(raw any) [][2]string { + switch rows := raw.(type) { + case [][]any: + out := make([][2]string, 0, len(rows)) + for _, p := range rows { + if len(p) < 2 { + continue + } + path, _ := p[0].(string) + val, _ := p[1].(string) + if path != "" { + out = append(out, [2]string{path, val}) + } + } + return out + case []any: + out := make([][2]string, 0, len(rows)) + for _, item := range rows { + p, ok := item.([]any) + if !ok || len(p) < 2 { + continue + } + path, _ := p[0].(string) + val, _ := p[1].(string) + if path != "" { + out = append(out, [2]string{path, val}) + } + } + return out + default: + return nil + } +} + +// Binary type indexes from ClickHouse src/DataTypes/DataTypesBinaryEncoding.cpp. +const ( + binNothing = 0x00 + binUInt8 = 0x01 + binUInt16 = 0x02 + binUInt32 = 0x03 + binUInt64 = 0x04 + binInt8 = 0x07 + binInt16 = 0x08 + binInt32 = 0x09 + binInt64 = 0x0A + binFloat32 = 0x0D + binFloat64 = 0x0E + binString = 0x15 + binArray = 0x1E + binNullable = 0x23 + binBool = 0x2D + binDynamic = 0x2B +) + +type sharedBinType struct { + kind byte + child *sharedBinType + name string +} + +func decodeSharedDataValue(raw string) (any, string) { + if raw == "" { + return nil, "" + } + r := proto.NewReader(bytes.NewReader([]byte(raw))) + t, err := readSharedBinType(r) + if err != nil { + return raw, "String" + } + v, err := readSharedBinValue(r, t) + if err != nil { + return raw, "String" + } + return v, t.name +} + +func readSharedBinType(r *proto.Reader) (sharedBinType, error) { + idx, err := r.ReadByte() + if err != nil { + return sharedBinType{}, err + } + switch idx { + case binNothing: + return sharedBinType{kind: idx, name: "Nothing"}, nil + case binUInt8: + return sharedBinType{kind: idx, name: "UInt8"}, nil + case binUInt16: + return sharedBinType{kind: idx, name: "UInt16"}, nil + case binUInt32: + return sharedBinType{kind: idx, name: "UInt32"}, nil + case binUInt64: + return sharedBinType{kind: idx, name: "UInt64"}, nil + case binInt8: + return sharedBinType{kind: idx, name: "Int8"}, nil + case binInt16: + return sharedBinType{kind: idx, name: "Int16"}, nil + case binInt32: + return sharedBinType{kind: idx, name: "Int32"}, nil + case binInt64: + return sharedBinType{kind: idx, name: "Int64"}, nil + case binFloat32: + return sharedBinType{kind: idx, name: "Float32"}, nil + case binFloat64: + return sharedBinType{kind: idx, name: "Float64"}, nil + case binString: + return sharedBinType{kind: idx, name: "String"}, nil + case binBool: + return sharedBinType{kind: idx, name: "Bool"}, nil + case binArray: + child, err := readSharedBinType(r) + if err != nil { + return sharedBinType{}, err + } + return sharedBinType{kind: idx, child: &child, name: "Array(" + child.name + ")"}, nil + case binNullable: + child, err := readSharedBinType(r) + if err != nil { + return sharedBinType{}, err + } + return sharedBinType{kind: idx, child: &child, name: "Nullable(" + child.name + ")"}, nil + case binDynamic: + if _, err := r.ReadByte(); err != nil { // uint8 max_types + return sharedBinType{}, err + } + return sharedBinType{kind: idx, name: "Dynamic"}, nil + default: + return sharedBinType{}, fmt.Errorf("unsupported shared-data type index 0x%02x", idx) + } +} + +func readSharedBinValue(r *proto.Reader, t sharedBinType) (any, error) { + switch t.kind { + case binNothing: + return nil, nil + case binUInt8: + return r.UInt8() + case binUInt16: + return r.UInt16() + case binUInt32: + return r.UInt32() + case binUInt64: + return r.UInt64() + case binInt8: + return r.Int8() + case binInt16: + return r.Int16() + case binInt32: + return r.Int32() + case binInt64: + return r.Int64() + case binFloat32: + return r.Float32() + case binFloat64: + return r.Float64() + case binString: + return r.Str() + case binBool: + return r.Bool() + case binArray: + n, err := r.UVarInt() + if err != nil { + return nil, err + } + out := make([]any, 0, n) + for i := uint64(0); i < n; i++ { + v, err := readSharedBinValue(r, *t.child) + if err != nil { + return nil, err + } + out = append(out, v) + } + return out, nil + case binNullable: + flag, err := r.ReadByte() + if err != nil { + return nil, err + } + if flag != 0 { + return nil, nil + } + return readSharedBinValue(r, *t.child) + case binDynamic: + inner, err := readSharedBinType(r) + if err != nil { + return nil, err + } + return readSharedBinValue(r, inner) + default: + return nil, fmt.Errorf("unsupported shared-data type index 0x%02x", t.kind) + } +} diff --git a/lib/column/json_deprecated_test.go b/lib/column/json_deprecated_test.go new file mode 100644 index 0000000000..6627965761 --- /dev/null +++ b/lib/column/json_deprecated_test.go @@ -0,0 +1,176 @@ +package column + +import ( + "bytes" + "encoding/binary" + "math" + "testing" + + "github.com/ClickHouse/ch-go/proto" + "github.com/stretchr/testify/require" + + "github.com/ClickHouse/clickhouse-go/v2/lib/chcol" +) + +// encodeDynamicBinary is ClickHouse ISerialization::serializeBinary for Dynamic: +// . Used to build JSON shared-data payloads the way +// the server writes them into Array(Tuple(String, String)). +func encodeDynamicInt64(v int64) string { + b := make([]byte, 9) + b[0] = 0x0A // BinaryTypeIndex::Int64 + binary.LittleEndian.PutUint64(b[1:], uint64(v)) + return string(b) +} + +func encodeDynamicFloat64(v float64) string { + b := make([]byte, 9) + b[0] = 0x0E // BinaryTypeIndex::Float64 + binary.LittleEndian.PutUint64(b[1:], math.Float64bits(v)) + return string(b) +} + +func encodeDynamicString(s string) string { + var buf proto.Buffer + buf.PutUInt8(0x15) // BinaryTypeIndex::String + buf.PutString(s) + return string(buf.Buf) +} + +func encodeDynamicBool(v bool) string { + b := []byte{0x2D, 0} // BinaryTypeIndex::Bool + if v { + b[1] = 1 + } + return string(b) +} + +func encodeDynamicEmptyArrayInt64() string { + // Array + Int64 + varuint count 0 + return string([]byte{0x1E, 0x0A, 0x00}) +} + +func encodeSharedData(t *testing.T, rows [][][2]string) []byte { + t.Helper() + col, err := Type("Array(Tuple(String, String))").Column("", nil) + require.NoError(t, err) + for _, row := range rows { + pairs := make([][]any, len(row)) + for i, p := range row { + pairs[i] = []any{p[0], p[1]} + } + require.NoError(t, col.AppendRow(pairs)) + } + var buf proto.Buffer + col.Encode(&buf) + return buf.Buf +} + +// TestJSONDeprecatedSharedDataConsumedAndMerged is the #1854 repro at the +// native-protocol layer: ClickHouse JSON v0 (deprecated object) stores overflow +// paths in SharedData as Array(Tuple(String, String)). The decoder used to +// skip only the UInt64 offsets and leave the Tuple payload in the stream, +// which desyncs every later column (makeslice panics, "unexpected value N +// for boolean", "unexpected packet N"). +func TestJSONDeprecatedSharedDataConsumedAndMerged(t *testing.T) { + shared := encodeSharedData(t, [][][2]string{ + { + {"k08", encodeDynamicInt64(8)}, + {"satellites", encodeDynamicInt64(11)}, + {"region", encodeDynamicString("us-east")}, + {"ok", encodeDynamicBool(true)}, + {"ratio", encodeDynamicFloat64(12.5)}, + {"latency_ms", encodeDynamicEmptyArrayInt64()}, + }, + }) + + const sentinel byte = 0xAB + payload := append(append([]byte{}, shared...), sentinel) + + col := newTestJSONColumn(t) + col.serializationVersion = JSONDeprecatedObjectSerializationVersion + + reader := proto.NewReader(bytes.NewReader(payload)) + require.NoError(t, col.Decode(reader, 1)) + + got, err := reader.ReadByte() + require.NoError(t, err, "shared-data payload must be fully consumed") + require.Equal(t, sentinel, got, "bytes after the JSON column must stay aligned for the next column") + + obj, ok := col.Row(0, false).(*chcol.JSON) + require.True(t, ok) + + k08, ok := chcol.ExtractJSONPathAs[int64](obj, "k08") + require.True(t, ok, "overflow path k08 must be merged from shared data") + require.Equal(t, int64(8), k08) + + sat, ok := chcol.ExtractJSONPathAs[int64](obj, "satellites") + require.True(t, ok) + require.Equal(t, int64(11), sat) + + region, ok := chcol.ExtractJSONPathAs[string](obj, "region") + require.True(t, ok) + require.Equal(t, "us-east", region) + + flag, ok := chcol.ExtractJSONPathAs[bool](obj, "ok") + require.True(t, ok) + require.Equal(t, true, flag) + + ratio, ok := chcol.ExtractJSONPathAs[float64](obj, "ratio") + require.True(t, ok) + require.Equal(t, 12.5, ratio) + + latency, ok := chcol.ExtractJSONPathAs[[]any](obj, "latency_ms") + require.True(t, ok) + require.Empty(t, latency) +} + +func TestJSONDeprecatedSharedDataEmptyRoundtrip(t *testing.T) { + src := newTestJSONColumn(t) + require.NoError(t, src.AppendRow(map[string]any{"kept": int64(7)})) + + var buf proto.Buffer + require.NoError(t, src.WriteStatePrefix(&buf)) + src.Encode(&buf) + + dst := newTestJSONColumn(t) + reader := proto.NewReader(bytes.NewReader(buf.Buf)) + require.NoError(t, dst.ReadStatePrefix(reader)) + require.NoError(t, dst.Decode(reader, 1)) + + obj, ok := dst.Row(0, false).(*chcol.JSON) + require.True(t, ok) + kept, ok := chcol.ExtractJSONPathAs[int64](obj, "kept") + require.True(t, ok) + require.Equal(t, int64(7), kept) +} + +func TestJSONDeprecatedSharedDataSecondRowOnly(t *testing.T) { + shared := encodeSharedData(t, [][][2]string{ + {}, + {{"overflow", encodeDynamicInt64(42)}}, + }) + + const sentinel byte = 0xCD + payload := append(append([]byte{}, shared...), sentinel) + + col := newTestJSONColumn(t) + col.serializationVersion = JSONDeprecatedObjectSerializationVersion + + reader := proto.NewReader(bytes.NewReader(payload)) + require.NoError(t, col.Decode(reader, 2)) + + got, err := reader.ReadByte() + require.NoError(t, err) + require.Equal(t, sentinel, got) + + row0, ok := col.Row(0, false).(*chcol.JSON) + require.True(t, ok) + _, present := row0.ValueAtPath("overflow") + require.False(t, present, "row 0 has empty shared data") + + row1, ok := col.Row(1, false).(*chcol.JSON) + require.True(t, ok) + v, ok := chcol.ExtractJSONPathAs[int64](row1, "overflow") + require.True(t, ok) + require.Equal(t, int64(42), v) +} From 40a6e7ea012e5e3b16e0e439e99586b82872404b Mon Sep 17 00:00:00 2001 From: Joe S Date: Fri, 20 Nov 2026 16:31:40 -0800 Subject: [PATCH 2/3] fix: reject unsupported JSON and Dynamic shared data --- docs/data-types.mdx | 6 + lib/column/dynamic_deprecated.go | 3 + lib/column/json.go | 12 -- lib/column/json_deprecated.go | 227 +++-------------------------- lib/column/json_deprecated_test.go | 155 +++++--------------- tests/issues/issue_1854_test.go | 96 ++++++++++++ 6 files changed, 156 insertions(+), 343 deletions(-) create mode 100644 tests/issues/issue_1854_test.go diff --git a/docs/data-types.mdx b/docs/data-types.mdx index ea1d5c3c6b..5cf3e48135 100644 --- a/docs/data-types.mdx +++ b/docs/data-types.mdx @@ -786,6 +786,12 @@ fmt.Printf("Col1: %v, Col2: %v\n", col1, col2) [Full Example](https://github.com/ClickHouse/clickhouse-go/blob/main/examples/clickhouse_api/bfloat16.go) +### JSON and Dynamic {#json-dynamic} + +With the legacy V1 Native format, the driver returns a decode error if `JSON` paths exceed `max_dynamic_paths` and use shared storage, or if a `Dynamic` value uses `SharedVariant` storage. This includes `Dynamic` values inside `JSON` columns. The error can occur on either the Native or HTTP transport. + +On ClickHouse 25.6 and later, set `output_format_native_use_flattened_dynamic_and_json_serialization=1` in `Options.Settings` or for the query to read these values. For a `readonly=1` user, an administrator can enable the setting in the user's settings profile. On earlier servers, read `JSON` into a Go `string` with `output_format_native_write_json_as_string=1`, or cast `Dynamic` values to a concrete type in the query. + ### QBit {#qbit} `QBit` is an experimental column type for storing vector embeddings in bit-sliced format, optimized for vector similarity search. It requires the `allow_experimental_qbit_type` setting to be enabled. diff --git a/lib/column/dynamic_deprecated.go b/lib/column/dynamic_deprecated.go index b22c9d4158..5126c44b92 100644 --- a/lib/column/dynamic_deprecated.go +++ b/lib/column/dynamic_deprecated.go @@ -176,5 +176,8 @@ func (c *Dynamic) decodeData_v1(reader *proto.Reader, rows int) error { } } + if sharedIndex, ok := c.columnIndexByType["SharedVariant"]; ok && rowCountByType[sharedIndex] != 0 { + return unsupportedSharedDataError("Dynamic SharedVariant") + } return nil } diff --git a/lib/column/json.go b/lib/column/json.go index bd0b681a7d..d6064c55b5 100644 --- a/lib/column/json.go +++ b/lib/column/json.go @@ -55,11 +55,6 @@ type JSON struct { maxDynamicPaths int maxDynamicTypes int - - // sharedData is JSON v0 overflow storage: Array(Tuple(String, String)). - // Populated only by decodeObjectData_v1. Each tuple is (path, Dynamic - // serializeBinary payload) for paths that exceeded max_dynamic_paths. - sharedData Interface } // jsonMode is the mode preference a value carries when offered to a JSON @@ -250,8 +245,6 @@ func (c *JSON) rowAsJSON(row int) *chcol.JSON { obj.SetValueAtPath(path, col.Row(row, false)) } - c.mergeSharedDataRow(obj, row) - return obj } @@ -949,11 +942,6 @@ func (c *JSON) Reset() { c.jsonStrings.Reset() } - if c.sharedData != nil { - c.sharedData.Reset() - c.sharedData = nil - } - // Clear the latched mode so the next batch starts unbiased. An all-null // batch only latches String at WriteStatePrefix; without this reset, a // subsequent batch of structs/maps would fail reconcileMode with a diff --git a/lib/column/json_deprecated.go b/lib/column/json_deprecated.go index 119cf122a9..3db2d51b91 100644 --- a/lib/column/json_deprecated.go +++ b/lib/column/json_deprecated.go @@ -1,12 +1,10 @@ package column import ( - "bytes" + "encoding/binary" "fmt" "github.com/ClickHouse/ch-go/proto" - - "github.com/ClickHouse/clickhouse-go/v2/lib/chcol" ) func (c *JSON) encodeObjectHeader_v1(buffer *proto.Buffer) error { @@ -125,219 +123,30 @@ func (c *JSON) decodeObjectData_v1(reader *proto.Reader, rows int) error { } func (c *JSON) decodeSharedData_v1(reader *proto.Reader, rows int) error { - // ClickHouse stores overflow JSON paths as Array(Tuple(String, String)): - // UInt64 offsets followed by the flattened Tuple columns. Reading only the - // offsets leaves the Tuple payload in the stream and desyncs every later - // column (issue #1854). - col, err := Type("Array(Tuple(String, String))").Column("", c.sc) - if err != nil { - return fmt.Errorf("failed to init shared data for json column: %w", err) - } - if err := col.Decode(reader, rows); err != nil { - return fmt.Errorf("failed to read shared data for json column: %w", err) - } - c.sharedData = col - return nil -} - -func (c *JSON) mergeSharedDataRow(obj *chcol.JSON, row int) { - if c.sharedData == nil || row >= c.sharedData.Rows() { - return - } - for _, pair := range sharedDataPairs(c.sharedData.Row(row, false)) { - value, chType := decodeSharedDataValue(pair[1]) - obj.SetValueAtPath(pair[0], chcol.NewDynamicWithType(value, chType)) - } -} - -func sharedDataPairs(raw any) [][2]string { - switch rows := raw.(type) { - case [][]any: - out := make([][2]string, 0, len(rows)) - for _, p := range rows { - if len(p) < 2 { - continue - } - path, _ := p[0].(string) - val, _ := p[1].(string) - if path != "" { - out = append(out, [2]string{path, val}) - } - } - return out - case []any: - out := make([][2]string, 0, len(rows)) - for _, item := range rows { - p, ok := item.([]any) - if !ok || len(p) < 2 { - continue - } - path, _ := p[0].(string) - val, _ := p[1].(string) - if path != "" { - out = append(out, [2]string{path, val}) - } - } - return out - default: + if rows == 0 { return nil } -} - -// Binary type indexes from ClickHouse src/DataTypes/DataTypesBinaryEncoding.cpp. -const ( - binNothing = 0x00 - binUInt8 = 0x01 - binUInt16 = 0x02 - binUInt32 = 0x03 - binUInt64 = 0x04 - binInt8 = 0x07 - binInt16 = 0x08 - binInt32 = 0x09 - binInt64 = 0x0A - binFloat32 = 0x0D - binFloat64 = 0x0E - binString = 0x15 - binArray = 0x1E - binNullable = 0x23 - binBool = 0x2D - binDynamic = 0x2B -) - -type sharedBinType struct { - kind byte - child *sharedBinType - name string -} - -func decodeSharedDataValue(raw string) (any, string) { - if raw == "" { - return nil, "" + if rows < 0 || rows > int(^uint(0)>>1)/8 { + return fmt.Errorf("invalid json row count %d", rows) } - r := proto.NewReader(bytes.NewReader([]byte(raw))) - t, err := readSharedBinType(r) + offsets, err := reader.ReadRaw(8 * rows) if err != nil { - return raw, "String" + return fmt.Errorf("failed to read shared data offsets for json column: %w", err) } - v, err := readSharedBinValue(r, t) - if err != nil { - return raw, "String" - } - return v, t.name -} - -func readSharedBinType(r *proto.Reader) (sharedBinType, error) { - idx, err := r.ReadByte() - if err != nil { - return sharedBinType{}, err - } - switch idx { - case binNothing: - return sharedBinType{kind: idx, name: "Nothing"}, nil - case binUInt8: - return sharedBinType{kind: idx, name: "UInt8"}, nil - case binUInt16: - return sharedBinType{kind: idx, name: "UInt16"}, nil - case binUInt32: - return sharedBinType{kind: idx, name: "UInt32"}, nil - case binUInt64: - return sharedBinType{kind: idx, name: "UInt64"}, nil - case binInt8: - return sharedBinType{kind: idx, name: "Int8"}, nil - case binInt16: - return sharedBinType{kind: idx, name: "Int16"}, nil - case binInt32: - return sharedBinType{kind: idx, name: "Int32"}, nil - case binInt64: - return sharedBinType{kind: idx, name: "Int64"}, nil - case binFloat32: - return sharedBinType{kind: idx, name: "Float32"}, nil - case binFloat64: - return sharedBinType{kind: idx, name: "Float64"}, nil - case binString: - return sharedBinType{kind: idx, name: "String"}, nil - case binBool: - return sharedBinType{kind: idx, name: "Bool"}, nil - case binArray: - child, err := readSharedBinType(r) - if err != nil { - return sharedBinType{}, err - } - return sharedBinType{kind: idx, child: &child, name: "Array(" + child.name + ")"}, nil - case binNullable: - child, err := readSharedBinType(r) - if err != nil { - return sharedBinType{}, err + var total uint64 + for i := 0; i < rows; i++ { + offset := binary.LittleEndian.Uint64(offsets[8*i:]) + if offset < total { + return fmt.Errorf("invalid shared data offsets for json column") } - return sharedBinType{kind: idx, child: &child, name: "Nullable(" + child.name + ")"}, nil - case binDynamic: - if _, err := r.ReadByte(); err != nil { // uint8 max_types - return sharedBinType{}, err - } - return sharedBinType{kind: idx, name: "Dynamic"}, nil - default: - return sharedBinType{}, fmt.Errorf("unsupported shared-data type index 0x%02x", idx) + total = offset + } + if total == 0 { + return nil } + return unsupportedSharedDataError("JSON shared data") } -func readSharedBinValue(r *proto.Reader, t sharedBinType) (any, error) { - switch t.kind { - case binNothing: - return nil, nil - case binUInt8: - return r.UInt8() - case binUInt16: - return r.UInt16() - case binUInt32: - return r.UInt32() - case binUInt64: - return r.UInt64() - case binInt8: - return r.Int8() - case binInt16: - return r.Int16() - case binInt32: - return r.Int32() - case binInt64: - return r.Int64() - case binFloat32: - return r.Float32() - case binFloat64: - return r.Float64() - case binString: - return r.Str() - case binBool: - return r.Bool() - case binArray: - n, err := r.UVarInt() - if err != nil { - return nil, err - } - out := make([]any, 0, n) - for i := uint64(0); i < n; i++ { - v, err := readSharedBinValue(r, *t.child) - if err != nil { - return nil, err - } - out = append(out, v) - } - return out, nil - case binNullable: - flag, err := r.ReadByte() - if err != nil { - return nil, err - } - if flag != 0 { - return nil, nil - } - return readSharedBinValue(r, *t.child) - case binDynamic: - inner, err := readSharedBinType(r) - if err != nil { - return nil, err - } - return readSharedBinValue(r, inner) - default: - return nil, fmt.Errorf("unsupported shared-data type index 0x%02x", t.kind) - } +func unsupportedSharedDataError(storage string) error { + return fmt.Errorf("cannot decode %s: on ClickHouse 25.6 or later, enable output_format_native_use_flattened_dynamic_and_json_serialization=1; for readonly=1, an administrator must set it to 1 in the settings profile or mark it changeable_in_readonly; on earlier servers, upgrade to ClickHouse 25.6 or later, or read JSON as a string with output_format_native_write_json_as_string=1, or cast Dynamic values to a concrete type in the query", storage) } diff --git a/lib/column/json_deprecated_test.go b/lib/column/json_deprecated_test.go index 6627965761..c4f8849853 100644 --- a/lib/column/json_deprecated_test.go +++ b/lib/column/json_deprecated_test.go @@ -3,7 +3,6 @@ package column import ( "bytes" "encoding/binary" - "math" "testing" "github.com/ClickHouse/ch-go/proto" @@ -12,43 +11,6 @@ import ( "github.com/ClickHouse/clickhouse-go/v2/lib/chcol" ) -// encodeDynamicBinary is ClickHouse ISerialization::serializeBinary for Dynamic: -// . Used to build JSON shared-data payloads the way -// the server writes them into Array(Tuple(String, String)). -func encodeDynamicInt64(v int64) string { - b := make([]byte, 9) - b[0] = 0x0A // BinaryTypeIndex::Int64 - binary.LittleEndian.PutUint64(b[1:], uint64(v)) - return string(b) -} - -func encodeDynamicFloat64(v float64) string { - b := make([]byte, 9) - b[0] = 0x0E // BinaryTypeIndex::Float64 - binary.LittleEndian.PutUint64(b[1:], math.Float64bits(v)) - return string(b) -} - -func encodeDynamicString(s string) string { - var buf proto.Buffer - buf.PutUInt8(0x15) // BinaryTypeIndex::String - buf.PutString(s) - return string(buf.Buf) -} - -func encodeDynamicBool(v bool) string { - b := []byte{0x2D, 0} // BinaryTypeIndex::Bool - if v { - b[1] = 1 - } - return string(b) -} - -func encodeDynamicEmptyArrayInt64() string { - // Array + Int64 + varuint count 0 - return string([]byte{0x1E, 0x0A, 0x00}) -} - func encodeSharedData(t *testing.T, rows [][][2]string) []byte { t.Helper() col, err := Type("Array(Tuple(String, String))").Column("", nil) @@ -65,63 +27,21 @@ func encodeSharedData(t *testing.T, rows [][][2]string) []byte { return buf.Buf } -// TestJSONDeprecatedSharedDataConsumedAndMerged is the #1854 repro at the -// native-protocol layer: ClickHouse JSON v0 (deprecated object) stores overflow -// paths in SharedData as Array(Tuple(String, String)). The decoder used to -// skip only the UInt64 offsets and leave the Tuple payload in the stream, -// which desyncs every later column (makeslice panics, "unexpected value N -// for boolean", "unexpected packet N"). -func TestJSONDeprecatedSharedDataConsumedAndMerged(t *testing.T) { - shared := encodeSharedData(t, [][][2]string{ - { - {"k08", encodeDynamicInt64(8)}, - {"satellites", encodeDynamicInt64(11)}, - {"region", encodeDynamicString("us-east")}, - {"ok", encodeDynamicBool(true)}, - {"ratio", encodeDynamicFloat64(12.5)}, - {"latency_ms", encodeDynamicEmptyArrayInt64()}, - }, - }) - - const sentinel byte = 0xAB - payload := append(append([]byte{}, shared...), sentinel) - - col := newTestJSONColumn(t) - col.serializationVersion = JSONDeprecatedObjectSerializationVersion - - reader := proto.NewReader(bytes.NewReader(payload)) - require.NoError(t, col.Decode(reader, 1)) - - got, err := reader.ReadByte() - require.NoError(t, err, "shared-data payload must be fully consumed") - require.Equal(t, sentinel, got, "bytes after the JSON column must stay aligned for the next column") - - obj, ok := col.Row(0, false).(*chcol.JSON) - require.True(t, ok) - - k08, ok := chcol.ExtractJSONPathAs[int64](obj, "k08") - require.True(t, ok, "overflow path k08 must be merged from shared data") - require.Equal(t, int64(8), k08) - - sat, ok := chcol.ExtractJSONPathAs[int64](obj, "satellites") - require.True(t, ok) - require.Equal(t, int64(11), sat) - - region, ok := chcol.ExtractJSONPathAs[string](obj, "region") - require.True(t, ok) - require.Equal(t, "us-east", region) - - flag, ok := chcol.ExtractJSONPathAs[bool](obj, "ok") - require.True(t, ok) - require.Equal(t, true, flag) - - ratio, ok := chcol.ExtractJSONPathAs[float64](obj, "ratio") - require.True(t, ok) - require.Equal(t, 12.5, ratio) - - latency, ok := chcol.ExtractJSONPathAs[[]any](obj, "latency_ms") - require.True(t, ok) - require.Empty(t, latency) +func TestJSONDeprecatedSharedDataError(t *testing.T) { + for _, rows := range [][][][2]string{ + {{{"overflow", "\x0a\x0d\x00\x00\x00\x00\x00\x00\x00"}, {"other", "unreadable"}}}, + {{}, {{"overflow", "unreadable"}}}, + } { + payload := encodeSharedData(t, rows) + col := newTestJSONColumn(t) + col.serializationVersion = JSONDeprecatedObjectSerializationVersion + reader := proto.NewReader(bytes.NewReader(payload)) + err := col.Decode(reader, len(rows)) + require.ErrorContains(t, err, "cannot decode JSON shared data") + require.ErrorContains(t, err, "25.6") + require.ErrorContains(t, err, "output_format_native_use_flattened_dynamic_and_json_serialization=1") + require.ErrorContains(t, err, "changeable_in_readonly") + } } func TestJSONDeprecatedSharedDataEmptyRoundtrip(t *testing.T) { @@ -144,33 +64,24 @@ func TestJSONDeprecatedSharedDataEmptyRoundtrip(t *testing.T) { require.Equal(t, int64(7), kept) } -func TestJSONDeprecatedSharedDataSecondRowOnly(t *testing.T) { - shared := encodeSharedData(t, [][][2]string{ - {}, - {{"overflow", encodeDynamicInt64(42)}}, - }) - - const sentinel byte = 0xCD - payload := append(append([]byte{}, shared...), sentinel) - +func TestJSONDeprecatedSharedDataMalformed(t *testing.T) { + var offsets [16]byte + binary.LittleEndian.PutUint64(offsets[:], 2) + binary.LittleEndian.PutUint64(offsets[8:], 1) col := newTestJSONColumn(t) - col.serializationVersion = JSONDeprecatedObjectSerializationVersion - - reader := proto.NewReader(bytes.NewReader(payload)) - require.NoError(t, col.Decode(reader, 2)) - - got, err := reader.ReadByte() - require.NoError(t, err) - require.Equal(t, sentinel, got) - - row0, ok := col.Row(0, false).(*chcol.JSON) - require.True(t, ok) - _, present := row0.ValueAtPath("overflow") - require.False(t, present, "row 0 has empty shared data") + require.ErrorContains(t, col.decodeSharedData_v1(proto.NewReader(bytes.NewReader(offsets[:])), 2), "invalid shared data offsets") + for _, payload := range [][]byte{{}, {1}, encodeSharedData(t, [][][2]string{{{"path", "value"}}})[:10]} { + require.Error(t, col.decodeSharedData_v1(proto.NewReader(bytes.NewReader(payload)), 1)) + } +} - row1, ok := col.Row(1, false).(*chcol.JSON) - require.True(t, ok) - v, ok := chcol.ExtractJSONPathAs[int64](row1, "overflow") - require.True(t, ok) - require.Equal(t, int64(42), v) +func TestDynamicDeprecatedSharedVariantError(t *testing.T) { + for _, raw := range []string{"", "unreadable", "\x0a\x0d\x00\x00\x00\x00\x00\x00\x00"} { + var buf proto.Buffer + buf.PutByte(0) + buf.PutString(raw) + col := &Dynamic{columns: []Interface{&SharedVariant{}}, columnIndexByType: map[string]int{"SharedVariant": 0}} + reader := proto.NewReader(bytes.NewReader(buf.Buf)) + require.ErrorContains(t, col.decodeData_v1(reader, 1), "cannot decode Dynamic SharedVariant") + } } diff --git a/tests/issues/issue_1854_test.go b/tests/issues/issue_1854_test.go new file mode 100644 index 0000000000..5fa51570a2 --- /dev/null +++ b/tests/issues/issue_1854_test.go @@ -0,0 +1,96 @@ +package issues + +import ( + "context" + "testing" + + "github.com/stretchr/testify/require" + + "github.com/ClickHouse/clickhouse-go/v2" + "github.com/ClickHouse/clickhouse-go/v2/lib/chcol" + clickhouse_tests "github.com/ClickHouse/clickhouse-go/v2/tests" + clickhouse_std_tests "github.com/ClickHouse/clickhouse-go/v2/tests/std" +) + +func TestIssue1854(t *testing.T) { + env, err := GetIssuesTestEnvironment() + require.NoError(t, err) + clickhouse_tests.TestProtocols(t, func(t *testing.T, protocol clickhouse.Protocol) { + settings := clickhouse.Settings{ + "allow_experimental_json_type": 1, + "allow_experimental_dynamic_type": 1, + "allow_experimental_variant_type": 1, + } + opts := clickhouse_tests.ClientOptionsFromEnv(env, settings, protocol == clickhouse.HTTP) + opts.MaxOpenConns, opts.MaxIdleConns = 1, 1 + t.Run("ClickHouse", func(t *testing.T) { + conn, err := clickhouse.Open(&opts) + require.NoError(t, err) + t.Cleanup(func() { require.NoError(t, conn.Close()) }) + if !clickhouse_tests.CheckMinServerServerVersion(conn, 24, 8, 0) { + t.Skip("JSON requires ClickHouse 24.8") + } + checkIssue1854(t, clickhouse_tests.CheckMinServerServerVersion(conn, 25, 6, 0), func(ctx context.Context, q string, dest ...any) error { + return conn.QueryRow(ctx, q).Scan(dest...) + }) + }) + t.Run("database_sql", func(t *testing.T) { + db := clickhouse.OpenDB(&opts) + db.SetMaxOpenConns(1) + t.Cleanup(func() { require.NoError(t, db.Close()) }) + if !clickhouse_std_tests.CheckMinServerVersion(db, 24, 8, 0) { + t.Skip("JSON requires ClickHouse 24.8") + } + checkIssue1854(t, clickhouse_std_tests.CheckMinServerVersion(db, 25, 6, 0), func(ctx context.Context, q string, dest ...any) error { + return db.QueryRowContext(ctx, q).Scan(dest...) + }) + }) + }) +} + +func checkIssue1854(t *testing.T, supportsFlattened bool, scan func(context.Context, string, ...any) error) { + t.Helper() + const setting = "output_format_native_use_flattened_dynamic_and_json_serialization" + legacy := context.Background() + if supportsFlattened { + legacy = clickhouse.Context(legacy, clickhouse.WithSettings(clickhouse.Settings{setting: 0})) + } + for _, tc := range []struct{ name, expr, storage string }{ + {"JSON", `'{"x":13,"y":"east"}'::JSON(max_dynamic_paths=0)`, "JSON shared data"}, + {"JSON_Dynamic", `'{"x":13,"y":"east"}'::JSON(max_dynamic_types=0)`, "Dynamic SharedVariant"}, + {"Dynamic", `toInt64(13)::Dynamic(max_types=0)`, "Dynamic SharedVariant"}, + } { + t.Run(tc.name, func(t *testing.T) { + query := "SELECT " + tc.expr + ", 'tail'" + var doc chcol.JSON + var value chcol.Dynamic + var dest any = &doc + if tc.name == "Dynamic" { + dest = &value + } + var tail string + err := scan(legacy, query, dest, &tail) + require.ErrorContains(t, err, "cannot decode "+tc.storage) + require.ErrorContains(t, err, setting+"=1") + var one uint8 + require.NoError(t, scan(context.Background(), "SELECT toUInt8(1)", &one)) + require.Equal(t, uint8(1), one) + if !supportsFlattened { + return + } + flattened := clickhouse.Context(context.Background(), clickhouse.WithSettings(clickhouse.Settings{setting: 1})) + require.NoError(t, scan(flattened, query, dest, &tail)) + require.Equal(t, "tail", tail) + if tc.name == "Dynamic" { + require.Equal(t, int64(13), value.Any()) + return + } + x, ok := chcol.ExtractJSONPathAs[int64](&doc, "x") + require.True(t, ok) + require.Equal(t, int64(13), x) + y, ok := chcol.ExtractJSONPathAs[string](&doc, "y") + require.True(t, ok) + require.Equal(t, "east", y) + }) + } +} From a348b54a7b6c2d66cc71c7d7e5889d793bf32dfe Mon Sep 17 00:00:00 2001 From: Joe S Date: Fri, 20 Nov 2026 17:00:49 -0800 Subject: [PATCH 3/3] fix: clarify legacy JSON workaround and test truncated offsets --- docs/data-types.mdx | 2 +- lib/column/json_deprecated.go | 2 +- lib/column/json_deprecated_test.go | 4 ++-- 3 files changed, 4 insertions(+), 4 deletions(-) diff --git a/docs/data-types.mdx b/docs/data-types.mdx index 5cf3e48135..eec46667ee 100644 --- a/docs/data-types.mdx +++ b/docs/data-types.mdx @@ -790,7 +790,7 @@ fmt.Printf("Col1: %v, Col2: %v\n", col1, col2) With the legacy V1 Native format, the driver returns a decode error if `JSON` paths exceed `max_dynamic_paths` and use shared storage, or if a `Dynamic` value uses `SharedVariant` storage. This includes `Dynamic` values inside `JSON` columns. The error can occur on either the Native or HTTP transport. -On ClickHouse 25.6 and later, set `output_format_native_use_flattened_dynamic_and_json_serialization=1` in `Options.Settings` or for the query to read these values. For a `readonly=1` user, an administrator can enable the setting in the user's settings profile. On earlier servers, read `JSON` into a Go `string` with `output_format_native_write_json_as_string=1`, or cast `Dynamic` values to a concrete type in the query. +On ClickHouse 25.6 and later, set `output_format_native_use_flattened_dynamic_and_json_serialization=1` in `Options.Settings` or for the query to read these values. For a `readonly=1` user, an administrator can enable the setting in the user's settings profile. On earlier servers, use `CAST(json_column AS String)` to read `JSON` as a Go `string`, or cast `Dynamic` values to a concrete type in the query. ClickHouse 24.10 and later also supports `output_format_native_write_json_as_string=1` for `JSON` columns. ### QBit {#qbit} diff --git a/lib/column/json_deprecated.go b/lib/column/json_deprecated.go index 3db2d51b91..9ee422408b 100644 --- a/lib/column/json_deprecated.go +++ b/lib/column/json_deprecated.go @@ -148,5 +148,5 @@ func (c *JSON) decodeSharedData_v1(reader *proto.Reader, rows int) error { } func unsupportedSharedDataError(storage string) error { - return fmt.Errorf("cannot decode %s: on ClickHouse 25.6 or later, enable output_format_native_use_flattened_dynamic_and_json_serialization=1; for readonly=1, an administrator must set it to 1 in the settings profile or mark it changeable_in_readonly; on earlier servers, upgrade to ClickHouse 25.6 or later, or read JSON as a string with output_format_native_write_json_as_string=1, or cast Dynamic values to a concrete type in the query", storage) + return fmt.Errorf("cannot decode %s: on ClickHouse 25.6 or later, enable output_format_native_use_flattened_dynamic_and_json_serialization=1; for readonly=1, an administrator must set it to 1 in the settings profile or mark it changeable_in_readonly; on earlier servers, use CAST(json_column AS String) for JSON or cast Dynamic values to a concrete type in the query", storage) } diff --git a/lib/column/json_deprecated_test.go b/lib/column/json_deprecated_test.go index c4f8849853..5484c3e401 100644 --- a/lib/column/json_deprecated_test.go +++ b/lib/column/json_deprecated_test.go @@ -70,8 +70,8 @@ func TestJSONDeprecatedSharedDataMalformed(t *testing.T) { binary.LittleEndian.PutUint64(offsets[8:], 1) col := newTestJSONColumn(t) require.ErrorContains(t, col.decodeSharedData_v1(proto.NewReader(bytes.NewReader(offsets[:])), 2), "invalid shared data offsets") - for _, payload := range [][]byte{{}, {1}, encodeSharedData(t, [][][2]string{{{"path", "value"}}})[:10]} { - require.Error(t, col.decodeSharedData_v1(proto.NewReader(bytes.NewReader(payload)), 1)) + for _, payload := range [][]byte{nil, offsets[:7]} { + require.ErrorContains(t, col.decodeSharedData_v1(proto.NewReader(bytes.NewReader(payload)), 1), "failed to read shared data offsets") } }