Repository navigation
Conversation
…columns_to_row_data MergeTree setting
…ybrid storage format
…e and Compact formats
…ata for qualifying queries
|
Is there a shortcut for "all columns"? For many observability-based use cases, narrow queries look like |
|
Yeah we could also expose the __row column, right now that is not implemented. |
|
This sounds super exciting to me! Is there anything else needed before this PR is ready to review? |
|
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. |
|
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? |
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]>
|
Thanks but let's keep ClickHouse a columnar-only database. |
|
@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 It does so by a mechanism that is very common already in ClickHouse: an additional virtual Moreover, it's common in other column store databases too, such as Apache Doris's hybrid storage:
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? |
|
There was discussion about introduction of mixed format (between compact/wide), basically storing some columns together. #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: 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. Tuple, currently create many files on disk, so it might need to be something different as type implementation. 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). And make some QueryPlanRule, which would rewrite to use such column. |
|
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! |
|
@UnamedRus I like the idea of having it as an new type and built some query planner optimizations around that 👍 |
|
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).
# 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
`03173_row_binary_and_native_with_binary_encoded_types` spawns four `clickhouse-local` processes per case and already runs close to the 180 s limit on debug and sanitizer builds. The two `Row` cases pushed it over the limit in the flaky check: https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=95071&sha=5f23db1f975777d4eca4fde60c9ddb1ca6816b71&name_0=PR&name_1=Stateless%20tests%20%28amd_debug%2C%20flaky%20check%29 ClickHouse#95071 Co-Authored-By: Claude Fable 5.1 <[email protected]> Claude-Session: https://claude.ai/code/session_01MJVguMRPAmveaPa2dCLxvm
# 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 |
There was a problem hiding this comment.
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 = 1plusoutput_format_csv_header_serialize_tuple_into_separate_columns = 1, aRowcolumn writes multiple data cells throughSerializationTuple::serializeTextCSV, whileCSVWithNames*still emits just one header cell for it. - With
input_format_null_as_default = 1plusinput_format_csv_deserialize_separate_columns_into_tuple = 1, a leading\Non aRowfield is handled bySerializationNullable::deserializeNullAsDefaultOrNestedTextCSVas a whole-row default instead of the first element default, becauseisCSVSeparateColumnsTuplereturnsfalseforRow.
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.
Co-Authored-By: Claude Fable 5.1 <[email protected]>
# Conflicts: # src/Core/SettingsChangesHistory.cpp
| { | ||
| auto & tuple = assert_cast<ColumnTuple &>(column); | ||
| for (size_t i = 0; i < elems.size(); ++i) | ||
| elems[i]->insertDefaultInto(tuple.getColumn(i)); |
There was a problem hiding this comment.
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.
Co-Authored-By: Claude Opus 5.5 <[email protected]>
| MutableColumnPtr createColumn() const override; | ||
|
|
||
| Field getDefault() const override; | ||
| void insertDefaultInto(IColumn & column) const override; |
There was a problem hiding this comment.
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.
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
Changelog category (leave one):
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
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/.mrkpair), in contrast toTuplewhich stores one stream per element. It is typically declared as aMATERIALIZED 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
Workflow [PR]
Sync PR [sync-upstream/pr/95071]