Skip to content

Add a Row(...) data type for bundling columns into one stream - #95071

Closed
raimannma wants to merge 96 commits into
ClickHouse:masterfrom
raimannma:hybrid-storage
Closed

raimannma wants to merge 96 commits into
ClickHouse:masterfrom
raimannma:hybrid-storage

Conversation

@raimannma

@raimannma raimannma commented Jan 25, 2026 •

Copy link
Copy Markdown
Contributor

Changelog category (leave one):

  • New Feature

Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):

Add a Row(name1 T1, name2 T2, ...) data type that bundles several columns into a single row-oriented stream on disk. A query-plan optimization automatically reads covered columns from the wrapper, speeding up narrow and point/scattered lookups over wide schemas while the original columns keep their columnar storage.

Documentation entry for user-facing changes

  • Documentation is written (mandatory for new features)

Motivation

Columnar storage excels at analytical workloads but is inefficient when reading a small subset of rows across many columns: each column lives in its own file, so a scattered point lookup pays one open/seek per column per granule. This reworks the original table-level "hybrid storage" idea into a user-declared, column-scoped construct.

A new Row(...) data type stores its fields together as one binary record per row (one .bin/.mrk pair), in contrast to Tuple which stores one stream per element. It is typically declared as a MATERIALIZED tuple(...) mirror of the bundled columns, so the wrapper is populated automatically on insert and the originals keep their own columnar storage. A query-plan rule (query_plan_use_row_wrappers) rewrites reads that the wrapper covers to read the single wrapper stream and unpack the requested fields.

In benchmarks the biggest win is the target case, a small number of rows scattered across many granules, where bundling ~20 columns into one file cut file opens ~19x and bytes read ~9x. It is most useful for moderate column counts read together; very wide full scans are better left columnar.

Example use

CREATE TABLE events
(
    id UInt64,
    timestamp DateTime,
    user_id UInt32,
    event_type String,
    payload String,
    combined Row(user_id UInt32, event_type String, payload String)
        MATERIALIZED tuple(user_id, event_type, payload)
) ENGINE = MergeTree()
ORDER BY (timestamp, id);

-- Reads user_id, event_type and payload from the single `combined` stream.
SELECT user_id, event_type, payload
FROM events
WHERE id = 12345;

Workflow [PR]
Sync PR [sync-upstream/pr/95071]

@EmeraldShift

Copy link
Copy Markdown
Contributor

Is there a shortcut for "all columns"? For many observability-based use cases, narrow queries look like SELECT * WHERE ..., and having a compact "full-row" store would help in this case. Some databases even expose it as a separate (maybe virtual) column, like _row, so the optimization can be controlled by users.

@raimannma

Copy link
Copy Markdown
Contributor Author

Yeah we could also expose the __row column, right now that is not implemented.

@EmeraldShift

Copy link
Copy Markdown
Contributor

This sounds super exciting to me! Is there anything else needed before this PR is ready to review?

@raimannma

Copy link
Copy Markdown
Contributor Author

One can review it, but I can't say if it works under all circumstances. I tested only few cases and don't know the codebase super well.

@EmeraldShift

Copy link
Copy Markdown
Contributor

Im not sure who is best to review it, cc @rschu1ze (sorry for all the pings!) -- can this PR have tests enabled, and a reviewer assigned?

@raimannma
raimannma marked this pull request as ready for review January 31, 2026 20:32
Resolved conflicts:
- src/Storages/MergeTree/MergeTreeIOSettings.h: Added both `use_hybrid_row_reading` and `read_only_column_sample` fields
- src/Storages/MergeTree/MergeTreeSettings.cpp: Added both hybrid storage settings and distributed_index_analysis settings

Co-Authored-By: Claude Opus 4.5 <[email protected]>
@rschu1ze

rschu1ze commented Feb 2, 2026

Copy link
Copy Markdown
Member

Thanks but let's keep ClickHouse a columnar-only database.

@rschu1ze rschu1ze closed this Feb 2, 2026
@EmeraldShift

Copy link
Copy Markdown
Contributor

@rschu1ze Thank you for your reply,

My understanding of this PR is not that it changes ClickHouse into any other kind of data store, but rather optimizes (and optionally so) a common shape of query, like SELECT *, so that ClickHouse can read fewer files and respond with lower latency.

It does so by a mechanism that is very common already in ClickHouse: an additional virtual __row column. It strikes me as similar to Compact parts: a more efficiently serialized copy of the same data.

Moreover, it's common in other column store databases too, such as Apache Doris's hybrid storage:

The principle of row storage is that an additional column is added during storage. This column concatenates all the columns of the corresponding row and stores them using a special binary format.

This optimization is important for many critical use cases for ClickHouse, like Observability: selecting e.g. the most recent 500 logs, or a single distributed trace to serve in Grafana (that's why I'm personally so excited for this feature). Especially for low latency queries with high concurrency, it sounds like a straightforward efficiency win. I'd be curious to see how well this PR can improve performance in ClickHouse :)

I thought this feature would fit right in, alongside Projections and MVs, as a way users could tune their preference for fast queries by storing some additional data on disk. I'm somewhat disappointed to hear it not being considered. Maybe I'm missing something context, or some deeper reason this sort of change is not going to be accepted?

@rschu1ze rschu1ze reopened this Feb 2, 2026
@UnamedRus

UnamedRus commented Feb 12, 2026 •

Copy link
Copy Markdown
Contributor

There was discussion about introduction of mixed format (between compact/wide), basically storing some columns together.
It was proposed to be done using some "simple" bucketing based on hash, but it not preventing from making it user configurable.
Your proposed layout is still somewhat different from it, as it's truly row based, and not write column by column (like in compact)
Also storing same data twice, sounds for me what projections currently do in ClickHouse.
Does this code share some parts of implementation with them?

#23516 (comment)
#23516 (comment)

Just thinking about options, it's likely that introduction of new "truly" row based part type is bit of stretch and a lot of work, but may be have some notation(kind of JSON/Dynamic, but simpler/more optimized as keys/columns are the same), which would allow to "compose" multiple columns in "single" column (and automatically deserialize them as subcolumns) (so we can use "compact/wide" layouts without changes on disk) and define it as projection.

Ie, what we can kinda mimic today already:

CREATE TABLE events
(
    id UInt64,
    timestamp DateTime,
    user_id UInt32,
    event_type String,
    payload String,
    PROJECTION row_layout (
    SELECT _part_offset, concat(event_type, payload) as combined ORDER BY _part_offset)
) ENGINE =
MergeTree()
ORDER BY (timestamp, id);

Or, even without using projections(minus of that, it will be forced to have the same granularity as in original part, which can be undesirable), but have it's as real column object in schema, instead of settings based.
(It allow to have codecs / settings being put in more "limited" scope)

CREATE TABLE events_2
(
    id UInt64,
    timestamp DateTime,
    user_id UInt32,
    event_type String,
    payload String,
    combined Tuple(String, String) MATERIALIZED tuple(event_type, payload) CODEC(ZSTD(3)) SETTINGS (min_compress_block_size = 10000)
) ENGINE =
MergeTree()
ORDER BY (timestamp, id

Tuple, currently create many files on disk, so it might need to be something different as type implementation.

-rw-r-----  1 clickhouse clickhouse 4.5M Feb 12 18:50 combined%2E1.bin
-rw-r-----  1 clickhouse clickhouse 1.9K Feb 12 18:50 combined%2E1.cmrk2
-rw-r-----  1 clickhouse clickhouse  41K Feb 12 18:50 combined%2E1.size.bin
-rw-r-----  1 clickhouse clickhouse 1.2K Feb 12 18:50 combined%2E1.size.cmrk2
-rw-r-----  1 clickhouse clickhouse 4.5M Feb 12 18:50 combined%2E2.bin
-rw-r-----  1 clickhouse clickhouse 1.9K Feb 12 18:50 combined%2E2.cmrk2
-rw-r-----  1 clickhouse clickhouse  41K Feb 12 18:50 combined%2E2.size.bin
-rw-r-----  1 clickhouse clickhouse 1.2K Feb 12 18:50 combined%2E2.size.cmrk2

MATERIALIZED currently have some small "issues" (you can directly write to this column, if you override particular setting, which may make values mismatch from it's default definition, and this is bad).
So, more strict/tuned keyword could be introduced. (HYBRID?, it may be materialized if match some limits, otherwise will act like ALIAS)

    combined Tuple(String, String) HYBRID combined(event_type, payload) CODEC(ZSTD(3)) SETTINGS (min_compress_block_size = 10000, hybrid_column_materialize_part_max_bytes = ...)

And make some QueryPlanRule, which would rewrite to use such column.

@alexey-milovidov

Copy link
Copy Markdown
Member

Hi @raimannma! Thanks for the contribution. The PR description is missing the Changelog category and entry sections from the PR template. Could you please add them? Thank you!

@raimannma

Copy link
Copy Markdown
Contributor Author

@UnamedRus I like the idea of having it as an new type and built some query planner optimizations around that 👍

@filimonov

Copy link
Copy Markdown
Contributor

Name 'Hybrid' becomes popular :) (we have another bigger increment in developement with the same name, it's still not finished, early alpha is here: https://github.com/Altinity/ClickHouse/pull/1071/changes)

Resolve conflicts with post-refactor upstream:
- Drop eager addStreams loop from Wide/Compact writer constructors
  (master now lazy-inits via initStreamsIfNeeded); keep explicit
  addStreams call for __row since it's not in columns_list.
- Remove redundant initColumnsSubstreamsIfNeeded(Block&) override;
  the base class initColumnsSubstreamsIfNeeded() covers it.
- Rename WrittenOffsetColumns to WrittenOffsetSubstreams to match
  upstream; reuse offset_substreams in writeHybridRowData.
- Update getEnumerateSettings callsites to the new static signature
  getEnumerateSettings(settings); use findByName for block_sample
  lookups so __row doesn't throw.
- Move __row state-suffix and final-mark handling inside
  finalizeIndexGranularity; keep master's new fillDataChecksums.
- Adapt reader Wide for isColumnDroppedByPendingMutation guard and
  place new getAllColumnsSubstreams before initHybridStorage.
- writeColumnSingleGranule now takes a sample_column; pass the data
  column itself since __row has no per-granule stats.
- getInMemoryMetadataPtr now requires (context, bypass_cache).
- Add explicit Float64 cast on size_t divisor in
  shouldUseHybridRowReading to satisfy -Wimplicit-int-float-conversion.
Resolved conflicts:
- src/Processors/QueryPlan/Optimizations/Optimizations.h: kept both
  tryOptimizeHybridStorage and tryTopKThroughJoin entries; bumped
  optimizations array size from 19 to 20.
- src/Storages/MergeTree/MergeTreeDataPartWriterCompact.cpp: kept both
  MergeTreeVirtualColumns.h and ParallelSyncFiles.h includes.
- src/Storages/MergeTree/MergeTreeDataPartWriterWide.cpp: kept both
  MergeTreeVirtualColumns.h and ParallelSyncFiles.h includes.
This reworks the hybrid storage idea into a user-declared, column-scoped
construct instead of a table-level setting, following the review feedback
on the original PR.

A new `Row(name1 T1, name2 T2, ...)` data type bundles several columns into
a single physical stream on disk (one binary record per row), in contrast to
`Tuple` which stores one stream per element. It is typically declared as a
`MATERIALIZED tuple(a, b, ...)` mirror of the bundled columns, so the wrapper
is populated automatically on insert and the originals keep their own columnar
storage.

A query-plan rule (`optimizeUseRowWrappers`, setting
`query_plan_use_row_wrappers`) detects when a `Row(...)` wrapper covers
columns a query needs and reads them from the single wrapper stream, unpacking
individual fields via the internal `__rowElement` function. This reduces file
opens and seeks for narrow/scattered reads over wide schemas (e.g. recent-logs
or single-trace lookups), where it is the biggest win.

Removes the previous table-level implementation (`__row` virtual column,
`RowDataSerializer`, `enable_hybrid_storage` and related MergeTree settings,
the old optimizer pass, profile events and query-log columns).
@raimannma raimannma changed the title Hybrid storage Add a Row(...) data type for bundling columns into one stream May 24, 2026
raimannma and others added 4 commits September 12, 2026 13:50
# Conflicts:
#	src/Core/SettingsChangesHistory.cpp
#	src/Storages/MergeTree/KeyCondition.cpp
`readRowPayload` only checked `format_binary_max_string_size`, so with that
setting at `0` an absurd `row_size` from a corrupted part or an untrusted
`RowBinary`/`Native` stream still reached `payload.resize`. Mirror
`SerializationString::checkStringSize` and reject anything above the
unconditional `SerializationString::MAX_STRING_SIZE` as well.

Co-Authored-By: Claude Fable 5.1 <[email protected]>
Claude-Session: https://claude.ai/code/session_014m2Q6bpWH9Ut8isMPmaKpt
…ypes` and `Native`

The `BinaryTypeIndex::Row` tag had no round-trip test: `03173` never used a
`Row(...)` value, so neither `output_format_binary_encode_types_in_binary_format`
nor `output_format_native_encode_types_in_binary_format` exercised it. Add a flat
and a nested `Row` case.

Co-Authored-By: Claude Fable 5.1 <[email protected]>
Claude-Session: https://claude.ai/code/session_014m2Q6bpWH9Ut8isMPmaKpt
…alf cover

`pickWrappers` used any wrapper covering two or more requested columns, so a
query reading two fields of a twenty-field wrapper replaced two narrow column
reads with a read of the whole wrapper stream and decompressed far more bytes
than the columnar baseline. Require the overlap to cover at least half of the
wrapper's fields in addition to the existing two-column minimum.

Co-Authored-By: Claude Fable 5.1 <[email protected]>
Claude-Session: https://claude.ai/code/session_014m2Q6bpWH9Ut8isMPmaKpt
Comment thread src/Functions/array/arrayElement.cpp Resolved
Comment thread src/Analyzer/SetUtils.cpp Resolved
Comment thread src/DataTypes/DataTypeRow.h Resolved
raimannma and others added 7 commits September 13, 2026 07:09
# Conflicts:
#	src/Core/SettingsChangesHistory.cpp
# Conflicts:
#	src/Interpreters/InterpreterCreateQuery.cpp
#	src/Interpreters/parseColumnsListForTableFunction.cpp
#	src/Interpreters/parseColumnsListForTableFunction.h
# Conflicts:
#	src/Core/SettingsChangesHistory.cpp
#	src/Databases/enableAllExperimentalSettings.cpp
…` in the `26.10` settings history block

Master moved to version 26.10, and the style check requires every setting added by a change to be recorded in the block of the current version in `SettingsChangesHistory.cpp`.

Co-Authored-By: Claude Fable 5.1 <[email protected]>
The old query analysis was removed on master, and `enable_analyzer = 0` now
throws `SETTING_CONSTRAINT_VIOLATION`, which failed
`05058_row_data_type_primary_key_pruning` in the Fast test. Remove the
`enable_analyzer = 0` queries from that test, delete
`05056_row_data_type_in_membership_old_analyzer`, which only exercised the old
analyzer, and drop the stale old-analyzer note from
`05054_row_data_type_in_membership`.

https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=95071&sha=126493be5b046fffc1208527fa88c3d30ecb4574&name_0=PR&name_1=Fast%20test
ClickHouse#95071

Co-Authored-By: Claude Fable 5.1 <[email protected]>
`DataTypeRow` inherited `IDataType::hasDynamicStructure`, which returns
`false`, although its elements can be `Dynamic`. The expression fallback of the
`VALUES` parser then inserted a bare `Field` instead of taking the typed cast
path, so with `input_format_values_deduce_templates_of_expressions = 0` a
`Row(x Dynamic, y UInt8)` column stored `1::UInt32` as `UInt8`,
`'a'::FixedString(1)` as `String`, and `toDate('2020-01-01')` as the `UInt8`
value `86`. Recurse through the elements like `DataTypeTuple` does.

Address review: ClickHouse#95071 (comment)

Co-Authored-By: Claude Fable 5.1 <[email protected]>
void serializeBinary(const IColumn & column, size_t row_num, WriteBuffer & ostr, const FormatSettings & settings) const override;
void deserializeBinary(IColumn & column, ReadBuffer & istr, const FormatSettings & settings) const override;

/// In memory a `Row` is the equivalent named `Tuple`, so every text format delegates to a

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This overstates the current coverage. SerializationRow does delegate the per-value CSV serializer to SerializationTuple, but the CSV plumbing outside the serialization layer still recognizes only DataTypeTuple as a split tuple (Formats/FlattenTupleForCSVHeader.cpp and Formats/EscapingRuleUtils.cpp). Two user-visible mismatches fall out of that:

  • With format_csv_serialize_tuple_into_separate_columns = 1 plus output_format_csv_header_serialize_tuple_into_separate_columns = 1, a Row column writes multiple data cells through SerializationTuple::serializeTextCSV, while CSVWithNames* still emits just one header cell for it.
  • With input_format_null_as_default = 1 plus input_format_csv_deserialize_separate_columns_into_tuple = 1, a leading \N on a Row field is handled by SerializationNullable::deserializeNullAsDefaultOrNestedTextCSV as a whole-row default instead of the first element default, because isCSVSeparateColumnsTuple returns false for Row.

So Row is not yet behaviorally identical to named Tuple in every text format. Please thread DataTypeRow through the same CSV tuple-like helpers (or share a common predicate) before documenting the stronger contract.

{
auto & tuple = assert_cast<ColumnTuple &>(column);
for (size_t i = 0; i < elems.size(); ++i)
elems[i]->insertDefaultInto(tuple.getColumn(i));

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Row reuses ColumnTuple, but this default-insert path is missing the rollback/consistency guard that DataTypeTuple::insertDefaultInto uses for the same storage. If any nested insertDefaultInto throws (for example on allocation failure or a nested type's exceptional path), the earlier children stay one row longer and the tuple column is left internally inconsistent.

Please wrap this in the same addElementSafe pattern that Tuple uses, or otherwise roll every child back to the pre-call size when one element insert fails.

MutableColumnPtr createColumn() const override;

Field getDefault() const override;
void insertDefaultInto(IColumn & column) const override;

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

DataTypeRow still inherits IDataType::isDefaultInsertTrivial() == true, unlike DataTypeTuple. That lets callers such as ActionsDAG::isFilterAlwaysFalseForDefaultValueInputs and filterResultForNotMatchedRows probe a Row with createColumnConstWithDefaultValue() and assume it matches the row that an unmatched join side would actually produce.

For nested types with non-trivial default insertion that assumption is false. A concrete example is Row(d Date32): getDefault() yields 1900-01-01, while the real column default inserted into ColumnDate32 is 1970-01-01 (see the comments in ActionsDAG.cpp:3408-3413 and Utils.cpp:176-179). A predicate like r.d > toDate32('1960-01-01') can therefore look false on the probe and let convertOuterJoinToInnerJoin collapse an outer join even though the real unmatched row would pass it.

Row needs the same recursive isDefaultInsertTrivial override as Tuple, so these optimizations skip the probe whenever any field has non-trivial default-insertion semantics.

alexey-milovidov and others added 2 commits September 26, 2026 23:32
Resolve the conflict with the move of the settings changes history into the setting declarations
(ee6b44f): the history records this PR added to `SettingsChangesHistory.cpp` now live as
trailing arguments of the `DECLARE` of each setting.

Also resolved conflicts in:
- `src/Interpreters/InterpreterCreateQuery.h`

Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
# Conflicts:
#	src/Core/Settings.cpp
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

can be tested Allows running workflows for external contributors comp-data-types Type system & core datatypes used across query planning/execution. manual approve Manual approve required to run CI pr-feature Pull request with new product feature

Projects

None yet

Development

Successfully merging this pull request may close these issues.

7 participants