ClickHouse (native TCP and HTTP): implementation reference
How the two ClickHouse listeners are built. For status, scores, how to connect and known gaps see the wire page ClickHouse. Shared authentication rules are in Security.
1. Source layout
| File | Role |
|---|---|
src/protocol/clickhouse/mod.rs |
ClickHouseHandler: native TCP listener, packets, Hello, Query, Data, Ping, native INSERT |
src/protocol/clickhouse/http.rs |
ClickHouseHttpHandler: HTTP interface, auth, request routing, output formats, RowBinary and Native decoding; also the shared statement pipeline the native wire calls |
src/protocol/clickhouse/translate.rs |
ClickHouse SQL dialect to SynergyDB (PostgreSQL-flavoured) SQL |
src/protocol/clickhouse/native.rs |
Native block format (typed columns), compressed frames |
src/protocol/clickhouse/format.rs |
Text output formats (TSV family, CSV, JSON family, Values) |
src/protocol/clickhouse/mergetree.rs |
Table engine metadata, FINAL, Buffer tables, materialized views, sort-key index |
One pipeline serves both wires: the native handler builds an internal HTTP request and calls ClickHouseHttpHandler::run_for_native_wire, which runs route with a marker header (x-synergydb-native-wire) so results come back as Native blocks. (source: src/protocol/clickhouse/mod.rs, execute_query; src/protocol/clickhouse/http.rs, run_for_native_wire, NATIVE_WIRE_HEADER; docs/status/2026-11-24-clickhouse-native-tcp-go-clients-uptrace.md)
The module doc of http.rs still says the native protocol has "a Settings-parser desync at protocol rev 54429". That text is stale: the server now advertises revision 54440 and the 2026-11-24 status entry records Go clients and Uptrace working over native TCP.
2. Native TCP
2.1 Framing
Packets start with a LEB128 varint packet type. Strings are varint length plus bytes. The listener ([server] clickhouse_port, default 9000) reads into a 64 KiB BytesMut, waits until a whole Hello or Query is buffered, and dispatches. Unknown packet types clear the buffer and are logged. (source: src/protocol/clickhouse/mod.rs, handle_connection, decode_varint, can_parse_query, has_full_hello)
Client packets:
| Packet | Code | Handling |
|---|---|---|
| Hello | 0 | Client name, version (skipped), database, user, password. Authenticates (section 4) and replies server Hello |
| Query | 1 | Query id, client info (skipped), settings (skipped), stage, compression flag, query text, then the external-tables Data block. Executes and replies |
| Data | 2 | A stray Data packet between queries is consumed (skip_data_block) |
| Cancel | 3 | Ignored |
| Ping | 4 | Pong |
Server packets used: Hello 0, Data 1, Exception 2, Pong 4, EndOfStream 5. The enum also defines Progress, ProfileInfo, Totals, Extremes, TablesStatusResponse, Log and TableColumns. (source: src/protocol/clickhouse/mod.rs, ClientPacket, ServerPacket)
Server Hello: name SynergyDB, version 23.8, revision 54440, timezone UTC, display name SynergyDB ClickHouse, patch 0. The revision is 54440 because uptrace go-clickhouse sends settings in an older binary form at exactly 54429. (source: src/protocol/clickhouse/mod.rs, handle_hello; docs/status/2026-11-24-clickhouse-native-tcp-go-clients-uptrace.md)
2.2 Results
A result set is sent as a header block (column names and types, no rows), then the data block, then EndOfStream, as ClickHouse does. Errors become an Exception packet with the ClickHouse code from the pipeline. system.tables queries are answered from SynergyDB's catalog plus the stored ClickHouse table metadata. (source: src/protocol/clickhouse/mod.rs, encode_wire_result, serve_system_tables)
2.3 Compression
When the Query's compression flag is set, client Data blocks arrive as compressed frames and server Data, Totals and Extremes blocks are sent compressed. A frame is a 16-byte CityHash128 (v1.0.2, crate cityhash-rs) checksum, a method byte, sizes and the payload. Methods read: 0x82 LZ4 (crate lz4_flex), 0x90 ZSTD (crate zstd), and none; written: LZ4, at most 1 MiB of uncompressed data per frame. A checksum mismatch or unknown method is an error. (source: src/protocol/clickhouse/native.rs, compress_frames, read_frame, frame_checksum, compress_server_packets) Tested by compresses_data_packets_only and the round-trip tests in native.rs.
2.4 Native INSERT
An INSERT with no inline VALUES data and no SELECT is a native insert (is_native_insert): the server resolves the table's columns and ClickHouse types, sends a sample block with those types, reads the client's Data blocks until an empty block, writes them as INSERT ... FORMAT Native through the shared pipeline (so declared types, database routing and materialized views apply), then sends EndOfStream. A block may span several compressed frames. LowCardinality with several granules per column is decoded. (source: src/protocol/clickhouse/mod.rs, handle_native_insert, is_native_insert; docs/status/2026-11-28-clickhouse-multiframe-insert.md) Tested by test_is_native_insert, test_parse_insert_table_and_columns (unit).
3. HTTP interface
3.1 Listener and request handling
ClickHouseHttpHandler listens on [server] clickhouse_http_port, default 8124 (real ClickHouse uses 8123). It accepts Content-Length and Transfer-Encoding: chunked bodies, decodes Content-Encoding: lz4|zstd|gzip|deflate, keeps connections alive, and sends X-ClickHouse-Format and related result headers. (source: src/protocol/clickhouse/http.rs, parse_request, decompress_body, add_clickhouse_result_headers; src/config.rs)
Endpoints:
| Request | Result |
|---|---|
GET / with no query string |
200 Ok.\n (no auth) |
GET /ping, GET /replicas_status
|
200 Ok.\n (no auth) |
GET /?query=<sql> |
Run the statement |
POST / with body |
Run the body |
POST /?query=<sql> with body |
URL query, newline, then body (how INSERT data is sent) |
?database=<db> |
Session database |
?param_<name>=<value> |
Binds {name:Type} placeholders |
?user=&password=, X-ClickHouse-User / X-ClickHouse-Key, Authorization: Basic
|
Credentials |
X-ClickHouse-Format header |
Overrides the output format |
(source: src/protocol/clickhouse/http.rs, module doc, route, substitute_query_params, extract_credentials)
3.2 Output formats
Selected by a trailing FORMAT <name> or the X-ClickHouse-Format header; unknown names fall back to TabSeparated.
| Format | Aliases | Content type |
|---|---|---|
| TabSeparated (default) | TSV | text/tab-separated-values |
| TabSeparatedRaw | TSVRaw, Raw | text/tab-separated-values |
| TabSeparatedWithNames | TSVWithNames | text/tab-separated-values |
| TabSeparatedWithNamesAndTypes | TSVWithNamesAndTypes | text/tab-separated-values |
| CSV, CSVWithNames | text/csv | |
| JSONEachRow, JSONCompactEachRow | application/x-ndjson | |
| JSON, JSONCompact | application/json | |
| Values | text/tab-separated-values | |
| Native | application/octet-stream | |
| RowBinary, RowBinaryWithNames, RowBinaryWithNamesAndTypes | application/octet-stream |
Text formats convert the engine's PostgreSQL text cells (t/f, {1,2}, 2024-01-01T00:00:00Z) to ClickHouse text forms, including ClickHouse's quoting of 64-bit integers in JSON. (source: src/protocol/clickhouse/http.rs, OutputFormat; src/protocol/clickhouse/format.rs) Tested by format_parsing (unit) and the format probes in the differential.
Input: INSERT ... VALUES, INSERT ... FORMAT Native (binary body), INSERT ... FORMAT RowBinary[WithNames[AndTypes]] (decoded before text conversion). (source: src/protocol/clickhouse/http.rs, try_decode_rowbinary_insert, decode_rb_insert_body; src/protocol/clickhouse/native.rs, decode_insert)
4. Authentication
Native: the Hello's user and password are checked with auth::wire_auth::verify_credential against the catalog. Empty user and password pass only with SYNERGYDB_DEV_INSECURE_AUTH. Failure sends Exception code 516 AUTHENTICATION_FAILED and closes. Query or Data before a successful Hello gets an Exception and the connection closes. (source: src/protocol/clickhouse/mod.rs, handle_hello, handle_connection)
HTTP: every request except the health endpoints is authenticated the same way. Wrong credentials or none give HTTP 403 with code 516. A body over PREAUTH_BODY_LIMIT (1 MiB), or any chunked body, is read only after the URL and headers authenticate; the overall body cap is 256 MiB. The authenticated user is attached to the engine so RLS and column masking apply on HTTP as on native. (source: src/protocol/clickhouse/http.rs, authenticate, parse_request; src/protocol/buffer_limits.rs, PREAUTH_BODY_LIMIT)
ClickHouse uses the SQL-wire rule: no synergy_wire_* role membership is needed. ClickHouseAuthConfig (a protocol-local user map) still exists and is exercised by tests/protocol_clickhouse.rs, but the server path verifies against the catalog. (source: src/protocol/clickhouse/mod.rs, ClickHouseAuthConfig; Security)
5. Statements
ChPlan::from_sql handles three statements itself and translates everything else:
| Statement | Handling |
|---|---|
EXISTS [TEMPORARY] [TABLE] t |
Wire answers 0/1 |
DESCRIBE/DESC [TABLE] t
|
Wire answers with declared ClickHouse types |
SHOW TABLES [LIKE 'p'] |
Wire answers from the catalog |
SELECT ... |
translate::translate, then the engine; LIMIT n BY, WITH TOTALS and default-filling finished by the wire |
INSERT ... VALUES / FORMAT ... |
Decoded, translated, engine INSERT; materialized views fed |
CREATE TABLE ... ENGINE = ... |
ENGINE, ORDER BY, PARTITION BY, SAMPLE BY, SETTINGS, TTL, PRIMARY KEY clauses stripped; engine, keys and declared column types stored; non-Nullable columns get type defaults; a plain first sort-key column gets a non-unique index <table>_ch_sort_key
|
CREATE TABLE t AS src ENGINE = ... |
Lowered to CTAS, keeping the source's declared types |
CREATE TABLE b AS t ENGINE = Buffer(...) |
Writes go through to the destination |
CREATE MATERIALIZED VIEW (TO t and own-table forms, POPULATE) |
Fed on every INSERT into the source |
CREATE DATABASE, DROP DATABASE, USE
|
Database registry and storage namespace (section 6) |
DROP TABLE\|VIEW [IF EXISTS] [db.]t |
Engine drop plus wire metadata cleanup |
TRUNCATE TABLE [IF EXISTS] t |
Lowered to DELETE; absent table with IF EXISTS succeeds |
ALTER TABLE t UPDATE ... WHERE, ALTER TABLE t DELETE WHERE
|
Lowered to UPDATE / DELETE |
ALTER TABLE structural forms with no SynergyDB equivalent (MODIFY TTL/ORDER BY/SAMPLE BY/SETTING/QUERY/COMMENT, index and projection ops, codec-only MODIFY COLUMN) |
Accepted as no-ops |
CREATE [OR REPLACE] DICTIONARY, DROP DICTIONARY, EXCHANGE TABLES
|
Accepted as no-ops |
SELECT version(), timezone(), system.settings, system.databases, system.clusters, system.columns, system.tables
|
Stubs or catalog-backed virtual tables |
(source: src/protocol/clickhouse/http.rs, ChPlan, route, handle_database_ddl, is_ch_noop_alter, ctas_copy_names, parse_drop_table_or_view, select_from_virtual_table; src/protocol/clickhouse/mergetree.rs; src/protocol/clickhouse/translate.rs, translate_mutation)
Clause-level lowering in translate.rs: WITH <expr> AS <name>, inline expr AS name inside expressions, LIMIT n BY, WITH TOTALS, FINAL (marker /*CH_FINAL*/, resolved for ReplacingMergeTree version and is_deleted columns and SummingMergeTree), PREWHERE, SETTINGS, ARRAY JOIN and LEFT ARRAY JOIN (lateral unnest), GROUP BY ... WITH ROLLUP/CUBE with default-filled keys, LEFT JOIN default-filling (join_use_nulls = 0), cluster table functions (clusterAllReplicas(c, t) reads t), and numbers(N). (source: src/protocol/clickhouse/translate.rs, module doc, Translated, rewrite_array_join; src/protocol/clickhouse/mergetree.rs, FINAL_MARKER)
6. Functions
translate::rewrite_call rewrites these functions (case-insensitive) into engine SQL. Aggregates also accept the -If combinator (countIf, sumIf, …) and parameters (quantile(0.9)(x)).
| Group | Functions |
|---|---|
| Aggregates |
count, sum, avg, min, max, any, anyHeavy, anyLast, argMax, argMin, uniq, uniqExact, uniqCombined, uniqCombined64, uniqHLL12, uniqTheta, groupArray, groupUniqArray, quantile, quantileExact, quantileTiming, quantileTDigest, quantiles, median, medianExact, stddevPop, stddevSamp, varPop, varSamp (and stddev_pop, stddev_samp, var_pop) |
| Date and time |
now, now64, today, yesterday, toDate, toDate32, toDateTime, toDateTime64, fromUnixTimestamp, toUnixTimestamp, parseDateTimeBestEffort, formatDateTime, formatDateTimeInJodaSyntax, toYear, toQuarter, toMonth, toDayOfMonth, toDayOfYear, toDayOfWeek, toHour, toMinute, toSecond, toYYYYMM, toYYYYMMDD, toStartOfDay, toStartOfHour, toStartOfMinute, toStartOfSecond, toStartOfFiveMinute(s), toStartOfTenMinutes, toStartOfFifteenMinutes, toStartOfWeek, toMonday, toStartOfMonth, toStartOfQuarter, toStartOfYear, toStartOfInterval/time_bucket, addSeconds … addYears, subtractSeconds … subtractMonths, dateDiff/date_diff/timestampDiff, age, year, quarter, month, day, hour, minute, second, doy, isodow, extract
|
| String |
length, lengthUTF8, char_length, empty, notEmpty, lower, upper, lowerUTF8, upperUTF8, substring, substringUTF8, substr, mid, leftPad, rightPad (and UTF8 forms), lpad, rpad, trimBoth, trimLeft, trimRight, reverse, concat, concatWithSeparator/concat_ws, position, positionUTF8, positionCaseInsensitive(UTF8), locate, startsWith, endsWith, like, notLike, ilike, match, replaceOne, replaceAll, replaceRegexpOne, replaceRegexpAll, splitByChar, splitByString, toString
|
| Arrays |
array, arrayJoin, has, hasAny, hasAll, indexOf, arrayElement, arrayConcat, arrayStringConcat, arraySlice, arraySort, arrayReverseSort, arrayDistinct, arraySum, range, arrayMap, arrayFilter, arrayCount, arrayExists, arrayAll (lambdas x -> expr) |
| Numeric and logic |
round, modulo, isNaN, isInfinite, isFinite, multiIf, toDecimal32/64/128/256
|
| Other |
generateUUIDv4, currentDatabase/database, assumeNotNull, toNullable, identity, toTypeName
|
Any other function is passed through by name to the SQL engine. Whether it exists there decides the result; the README states that unknown functions return NULL instead of ClickHouse error 46, and that xxHash64, cityHash64 and sipHash64 are missing. (source: src/protocol/clickhouse/translate.rs, rewrite_call, is_ch_aggregate, split_if_combinator; README.md, Known gaps)
toTypeName(x) is implemented: static types become a literal, a bare column becomes a marker resolved from declared types, other expressions use the engine's runtime type. The README and the wire page still list toTypeName as unsupported. (source: src/protocol/clickhouse/translate.rs, totypename, TYPE_MARKER) Not verified: no toTypeName probe was found in the proof logs read for this page.
Result types follow ClickHouse: integer literals take the smallest fitting type (SELECT 1 is UInt8), count(), uniq* and length are UInt64, sum of UInt* is UInt64, avg is Float64, argMax/argMin take the argument's type. (source: src/protocol/clickhouse/translate.rs, ch_num_literal_type, ch_static_type; src/protocol/clickhouse/http.rs, aggregate_type; status entries of 2026-11-24 and 2026-11-30)
7. Storage mapping
- Tables are ordinary engine tables in a storage namespace. The ClickHouse database
defaultmaps to thepostgresnamespace; a database created withCREATE DATABASE xmaps to its own namespace, registered persistently (NamespacedStorage::register_database) and also in an in-process registry thatsystem.databasesreads.db.tablequalifiers are routed byroute_ch_database; an unknown database is error 81 (HTTP 404).DROP DATABASEdrops the namespace and the wire's metadata. Tested byqualified_tables_route_to_their_database(unit). - Wire metadata lives in the KV store under
__catalog__:keys:ch_coltypes:<ns>:<table>(declared ClickHouse column types),ch_engine:<ns>:<table>(engine, args, sort keys),ch_buffer:...,ch_mv:<ns>:<source>andch_mvname:...(materialized views),ch_tablemeta:<table>(native wire CREATE metadata). - Columns are stored as engine types;
Array(T)columns are stored as bracket text and read as arrays in= ANY,unnestandcardinalitycontexts.
(source: src/protocol/clickhouse/http.rs, database_registry, handle_database_ddl, ch_coltypes_key, forget_namespace_catalog; src/protocol/clickhouse/mergetree.rs; src/protocol/clickhouse/mod.rs, execute_query; docs/status/2026-11-30-clickhouse-arrays-rollup.md)
8. Type mapping
Native block types parsed and written (native::ChType): Int8..Int256, UInt8..UInt256 (values are carried as i128 when written, so 256-bit values outside that range are not represented), Float32, Float64, Bool, String, FixedString(n), Date, Date32, DateTime, DateTime64(p), Decimal(p, s), UUID, IPv4, IPv6, Enum8, Enum16, Nullable(T), LowCardinality(T), Array(T), Map(K, V), Tuple(...), Nothing; SimpleAggregateFunction(f, T) is read as T and AggregateFunction(quantile[s]BFloat16(...), T) states are kept as text. (source: src/protocol/clickhouse/native.rs, ChType, parse_type; status 2026-11-24)
Engine type to ClickHouse name, for columns that are not plain references to declared columns, comes from ch_type_from_pg (OID based). The README notes that LowCardinality columns used to go out as their dictionary type; the 2026-11-24 entry says they are now sent as LowCardinality. (source: src/protocol/clickhouse/http.rs, ch_type_from_pg)
9. Error codes
Engine errors map to ClickHouse codes, returned as X-ClickHouse-Exception-Code and in the body as Code: N. DB::Exception: ... (HTTP) or an Exception packet (native):
| Engine error | Code |
|---|---|
| TableNotFound, IndexNotFound | 60 UNKNOWN_TABLE |
| ColumnNotFound | 47 UNKNOWN_IDENTIFIER |
| Parse | 62 SYNTAX_ERROR |
| Schema "already exists" | 57 TABLE_ALREADY_EXISTS |
| other Schema | 36 BAD_ARGUMENTS |
| Constraint | 469 VIOLATED_CONSTRAINT |
| "Unknown function …" | 46 UNKNOWN_FUNCTION |
| DivisionByZero | 153 ILLEGAL_DIVISION |
| anything else | 50 |
Wire-level codes: 516 authentication failed, 81 unknown database, 432 bad Content-Encoding, 62 bad RowBinary body. (source: src/protocol/clickhouse/http.rs, error_code, route, authenticate)
10. Limits and configuration
| Item | Value | Source |
|---|---|---|
| Native port |
[server] clickhouse_port, default 9000 |
src/config.rs |
| HTTP port |
[server] clickhouse_http_port, default 8124 |
src/config.rs |
| TLS | Both listeners wrap in TLS when [tls] is configured |
ClickHouseHandler::with_tls, ClickHouseHttpHandler::with_tls
|
| HTTP body before auth | 1 MiB | PREAUTH_BODY_LIMIT |
| HTTP body after auth | 256 MiB | parse_request |
| Compressed frame out | 1 MiB uncompressed per frame | compress_frames |
11. Test coverage
| Suite | What it covers |
|---|---|
tests/protocol_clickhouse.rs (30 tests) |
ClickHouseAuthConfig, handler construction, SQL through the query engine (create, insert, where, order, limit, group by, delete) |
Unit tests in src/protocol/clickhouse/ (37) |
Varints, strings, packets, Ping, date round trips, native insert detection, decompression of multi-frame bodies, database routing, parameter substitution, format parsing, engine-clause rewrite, Native frames |
test-scripts/diff-clickhouse/diff_clickhouse.py against ClickHouse 24.8 |
248/248 on 2026-11-30 (query 230, second connection 12, restart 6) |
test-scripts/wire-matrix/clickhouse_matrix.py |
44/44 |
(source: tests/protocol_clickhouse.rs; docs/proof/2026-11-30/proof-pack-a3232c9/logs/clickhouse-query-second-connection-restart.txt, clickhouse-feature-matrix.txt)
Both proof-pack runs target the HTTP listener (SynergyDB http://127.0.0.1:8124/ against ClickHouse 8123). Not verified: the native TCP listener is not in the proof pack; its evidence is the 2026-11-24 status entry (clickhouse-go, uptrace go-clickhouse, clickhouse-driver) and the unit tests.