Repository navigation
Add a bucketed schema for system.metric_log: a single Map column with Enum keys and 128 buckets - #115380
Conversation
…keys Instead of a separate column for every profile event and current metric (about 1900 columns), the table now stores them in 128 bucket columns metrics_0 ... metrics_127 of type Map(Enum16(...), Int64). Each metric belongs to one bucket (contiguous ranges of the combined metric index space), the Enum16 value is the global metric index, and zero values are not stored: a lookup of a missing key in a Map returns 0. Every metric is still accessible under its old name through an ALIAS column, e.g. ProfileEvent_Query UInt64 ALIAS metrics_0['ProfileEvent_Query'], so existing queries, dashboards, and tests keep working, while reading a single metric only reads the one bucket that contains it. To support these aliases (and direct queries against the map columns), the arrayElement function now allows indexing a Map with Enum keys by the string name of the enum value: the index is cast to the key type, so an unknown name throws UNKNOWN_ELEMENT_OF_ENUM, while a name that is in the Enum but absent from the map returns the default value. On an idle server, the new structure takes about 320 bytes per row of compressed data versus about 1240 bytes per row for the wide structure, and a part now consists of a few hundred files instead of several thousands. On upgrade, the old wide table is renamed to metric_log_0 as usual for system log tables. The transposed schema (schema_type = 'transposed') is unaffected. Co-Authored-By: Claude Fable 5 <[email protected]>
…kets Per review: instead of changing the default (wide) schema of system.metric_log, add a new schema_type option 'bucketed'. The wide and transposed schemas are unchanged. With <schema_type>bucketed</schema_type>, the table stores all profile events and current metrics in a single `metrics` column of type Map(Enum16(...), Int64), where the Enum16 value is the global metric index and zero values are not stored. The default table definition uses the bucketed Map serialization with a constant number of 128 buckets (map_serialization_version = 'with_buckets', max_buckets_in_map = 128, map_buckets_strategy = 'constant', map_buckets_min_avg_size = 0), while parts created by inserts keep the basic serialization (map_serialization_version_for_zero_level_parts = 'basic') to avoid creating many small files on every flush. Every metric is exposed through an ALIAS column, e.g. ProfileEvent_Query UInt64 ALIAS metrics['ProfileEvent_Query'], so all queries written for the wide schema continue to work. Reading a single metric goes through the Map key subcolumn (metrics.key_<name>), which reads only the bucket that contains the key: on a test table it reads about 100 times less data than reading the whole map. To make this work, the optimization of `arrayElement` to a key subcolumn in `FunctionToSubcolumnsPass` now supports maps with Enum keys indexed by the string name of the enum value (in addition to the `arrayElement` runtime support for Enum-keyed maps from the previous commit). System logs can now declare additional default engine settings via `getDefaultEngineSettings`, which are merged with the `settings` from the server configuration when no custom engine is specified. Co-Authored-By: Claude Fable 5 <[email protected]>
system.metric_log to bucketed Maps with Enum keysbucketed schema for system.metric_log: a single Map column with Enum keys and 128 buckets
# Conflicts: # docs/en/operations/system-tables/metric_log.md # src/Interpreters/MetricLog.cpp
|
Workflow [PR], commit [f306dce] Summary: ✅
AI ReviewSummaryThis PR adds a Findings
Tests
Final VerdictChanges requested. LLVM Coverage Report
Changed lines: Changed C/C++ lines covered: 234/240 (97.50%) · Uncovered code |
After merging master, SystemLogBase::add only accepts a callback that fills the element in place (so its allocations are charged to the global memory tracker), and the old add(std::move(elem)) call in BucketedMetricLog::stepFunction no longer compiled, failing the Fast test and Build (arm_tidy) jobs: https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=115380&sha=49ef1e3b05571c8c0ec583e0d27e1eb9c831825e&name_0=PR&name_1=Fast%20test Build the element inside the add callback, following the same idiom as `MetricLog::stepFunction`. Co-Authored-By: Claude Fable 5 <[email protected]>
Build profile diff (arm_release)Comparing ✅ No significant changes. Binary sizes
Only the stripped binary is compared: the official master build keeps debug symbols while PR builds strip them, so the other binaries differ by construction. Object file sizes73 object files changed (+453.39 KiB total), 1 added.
737 more object files are built by the master warmup baseline only (it builds every object-file target, a pull request build only Compile time of recompiled translation units720 translation units recompiled, 5438 s compile time in total, 719 of them have a recent master baseline. |
…mode Two issues found in review: - `SystemLogs::flushImpl` built the name lookup map from an initializer list, so the first entry for a duplicated key won. Several logs share the public table name `system.metric_log` (`metric_log`, `transposed_metric_log`, `bucketed_metric_log`), and only the one matching the configured `schema_type` is instantiated, so `SYSTEM FLUSH LOGS metric_log` resolved to the empty `metric_log` slot and silently did nothing. Now an empty slot never replaces a live log. - The whole per-metric interface of the `bucketed` schema consists of ALIAS columns over the `metrics` Map. When alias columns are skipped (an S3-backed engine, or `default_system_log_flush_policy.skip_alias_columns` in the configuration), the table would silently lose all `ProfileEvent_*` / `CurrentMetric_*` columns. This combination is now rejected at startup. The integration test used a configuration with an explicit `engine`, which overrides the default table definition, so the engine settings of the `bucketed` schema were not applied. Use a configuration without `engine` and cover both fixes.
`SYSTEM FLUSH LOGS <name>` looks the name up without the database, so only the member name of the log was ever matched. Register every instantiated log under the name of the table it writes to as well, so that the name of the public table resolves to whichever of `metric_log` / `transposed_metric_log` / `bucketed_metric_log` is instantiated. Also read `SHOW CREATE TABLE` in the test as `TSVRaw`: the default format escapes the quotes inside the query text, so the assertions on the engine settings never matched.
|
🕵 Addressed both AI-review Majors and the failing own test in f306dce:
Remaining failures on the previous run are unrelated to this change:
@groeneai, please take a look at the |
| **Schema** | ||
| This table can be configured with different schema types using the XML tag `<schema_type>`. The default schema type is `wide`, where each metric or profile event is stored as a separate column. This schema is the most performant and efficient for single-column reads. | ||
|
|
||
| The `bucketed` schema stores all profile events and current metrics in a single `metrics` column of type [Map](/reference/data-types/map)([Enum16](/reference/data-types/enum), [Int64](/reference/data-types/int-uint)), so the table consists of a few columns instead of thousands. The `Map` uses the bucketed serialization (`map_serialization_version = 'with_buckets'`) with a constant number of 128 buckets, so reading a single metric reads only one of the 128 buckets. Zero values are not stored: reading a missing key returns `0`. Every metric is also exposed through an `ALIAS` column named as the metric itself (for example, `ProfileEvent_Query UInt64 ALIAS metrics['ProfileEvent_Query']`), so all queries written for the `wide` schema continue to work. Profile events are stored as increments during the collection interval, and current metrics are stored as values at the moment of collection. |
There was a problem hiding this comment.
The docs overstate the runtime contract here. BucketedMetricLog::getDefaultEngineSettings() sets map_serialization_version_for_zero_level_parts = 'basic', so fresh system.metric_log parts still require whole-Map reads until they merge; and those defaults are only injected when no custom <engine> is configured. As written, this paragraph promises immediate/universal 128-bucket pruning after schema_type = bucketed, which is not what the implementation does. Please document the zero-level/custom-engine caveat or weaken the selective-read claim.
| SELECT va FROM t_map_enum_buckets ORDER BY id; | ||
| SELECT m.key_a FROM t_map_enum_buckets ORDER BY id; | ||
|
|
||
| -- The element access by a constant name reads a key subcolumn instead of the whole map. |
There was a problem hiding this comment.
This is still weaker than the compatibility contract the PR is selling. system.metric_log exposes metrics through ALIAS metrics['ProfileEvent_*'], but the only EXPLAIN here checks the raw m['a'] expression, not the alias path. If alias expansion ever stops feeding FunctionToSubcolumnsPass, SELECT ProfileEvent_Query will silently fall back to whole-Map reads while this test still passes. Please add a focused assertion for SELECT va (or an equivalent system.metric_log alias query), ideally on data that has actually been merged into the with_buckets layout.
There was a problem hiding this comment.
It's already overdone.
|
Looked into the What happened: the Azurite container crashed mid-module. From Exit 139 is SIGSEGV in the Node process. So the ordering is: Azurite crashes -> Persistence: it does not. CIDB, 30 days:
One crash, one job, never before and not since. Nothing to reproduce and nothing in ClickHouse to fix, so I am not opening a fix PR: the fault is in the emulator, and a harness-side timeout bump would only hide it. Two things I noticed while measuring, neither raised as work:
|
|
📊 Cloud Performance Report ✅ AI verdict: no significant changes detected. K_source=6 K_base=30 flagged=0/65 clickbench🟢 No significant changes tpch_adapted_1_official🟢 No significant changes Debug info
|
|
Preview deployment for your docs. Learn more about Mintlify Previews.
|
alexey-milovidov
left a comment
There was a problem hiding this comment.
This is very good. A lot of tech-debt was solved along the way.
We need a follow-up PR to enable this by default. We may want to make the number of buckets configurable.
|
@alexey-milovidov @Avogar — ClickGap found the following in this PR:
Close anything that's wrong or already addressed. |
`has`, `notHas`, `indexOf`, `countEqual` and `mapContains` silently returned
"not found" for a constant array of `Enum` values searched for a `String`:
```
WITH CAST(map('a', 10, 'c', 30), 'Map(Enum8(\'a\' = 1, \'c\' = 3), Int64)') AS m
SELECT mapContains(m, 'a'); -- 0, must be 1
```
`FunctionArrayIndex::executeConst` compares the raw `Field`s of the constant
array with `accurateEquals`, and the field of an `Enum` element is its numeric
value while the field of the argument is the name, so nothing ever matched.
The non-constant code path (`executeGeneric`) casts both arguments to their
common type, which for `Enum` and `String` is `String`, and therefore compares
by the name of the enum value. Every other way of writing the same predicate -
`equals`, `arrayFilter`, `arrayMap`, and all of the above over a materialized
array - already compared by name, so only the constant path was wrong.
Replace the values of the constant array by their names when the argument is a
`String`, which makes the constant and the non-constant paths agree. For
`indexOfAssumeSorted` the binary search is skipped in that case, because the
array is sorted by the numeric values of the enum and not by the names.
This also fixes `arrayExists(x -> x = 'name', constant_enum_array)`, which is
rewritten to `has` and returned `0` while `arrayFilter` with the same lambda
returned the element.
`04509_not_has_function` asserted the old result of the constant path, with a
comment stating that an `Enum` element only matches a needle of the `Enum`
type. That was a description of this bug: the same expression over a
materialized array returned the opposite. The assertion and the comment are
updated.
Follow-up to ClickHouse#115380, which made
`Map`s with `Enum` keys indexable by the name of the enum value and thereby
made these functions reachable for `system.metric_log` with the `bucketed`
schema.
Co-Authored-By: Claude Fable 5 <[email protected]>
… the `Enum`
Indexing a `Map` with `Enum` keys by a numeric value that is not in the `Enum`
threw during query analysis instead of reading the default value:
```
SELECT m[toInt8(4)] FROM t; -- m Map(Enum8('a' = 1, 'b' = 2, 'c' = 3), Int64)
Code: 691. DB::Exception: Unexpected value 4 in enum. (UNKNOWN_ELEMENT_OF_ENUM)
```
`optimizeFunctionArrayElementForMap` inserts the constant into a column of the
key type and serializes it to build the name of the key subcolumn. For an
`Enum` key type `tryInsert` only range-checks the number, so a value outside
the `Enum` was accepted and `serializeText` then threw looking up its name. At
runtime the same expression returns the default value, like any key that is
missing from the map.
Convert the constant through `tryConvertFieldToType` first: it accepts both the
name and the numeric value of an enum value and rejects anything that is not in
the `Enum`, in which case the optimization is skipped and the whole map is read.
As a side effect `m[1]` is now rewritten to the same key subcolumn as `m['a']`;
before, a `UInt64` literal never inserted into the `Int8`/`Int16` column of the
enum, so the rewrite was silently declined for the numeric form.
Follow-up to ClickHouse#115380.
Co-Authored-By: Claude Fable 5 <[email protected]>
Two properties of the schema are only visible in the code: the server refuses to start when alias columns are skipped in system log tables, because the whole per-metric interface of the schema consists of `ALIAS` columns; and the engine settings of the bucketed `Map` serialization belong to the default table definition, so a configuration with an explicit `<engine>` does not get them. Follow-up to ClickHouse#115380. Co-Authored-By: Claude Fable 5 <[email protected]>
|
🕵️ A server whose config has a This PR added The fix is one line, adding |
Adds a new
schema_typeoptionbucketedforsystem.metric_log(the defaultwideand thetransposedschemas are unchanged):With this schema, all profile events and current metrics are stored in a single
metricscolumn of typeMap(Enum16(...), Int64), where theEnum16value is the global metric index and zero values are not stored (a lookup of a missing key in aMapreturns0). The default table definition uses the bucketedMapserialization with a constant number of 128 buckets:Parts created by inserts keep the basic serialization to avoid creating many small files on every flush; merged parts are always split into 128 buckets.
Every metric is also exposed through an
ALIAScolumn, e.g.ProfileEvent_Query UInt64 ALIAS metrics['ProfileEvent_Query'], so all queries, dashboards, and tests written for thewideschema continue to work. Reading a single metric goes through theMapkey subcolumn (metrics.key_ProfileEvent_Query), which reads only the bucket containing the key: in a local test it reads ~100 times less data than reading the whole map (616 vs 60716 bytes on the same rows).Supporting changes:
arrayElementon aMapwithEnumkeys now accepts the string name of the enum value (m['name']): the index is cast to the key type, so an unknown name throws theUNKNOWN_ELEMENT_OF_ENUMexception, while a name that is in theEnumbut absent from the map returns the default value. This previously threwILLEGAL_TYPE_OF_ARGUMENT.m['key']to a key subcolumn inFunctionToSubcolumnsPassnow supportsEnum-keyed maps indexed by the name of the enum value, so both the aliases and ad-hoc queries prune buckets.getDefaultEngineSettings, merged with thesettingsfrom the server configuration when no customengineis specified.metric_log.schema_typevalue is now rejected with an error instead of silently disabling the table.Changelog category (leave one):
Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):
Add a new
bucketedschema type forsystem.metric_log, which stores all metrics in a singleMap(Enum16(...), Int64)column using the bucketedMapserialization with 128 buckets, plus a per-metricALIAScolumn for compatibility: the table consists of a few columns instead of thousands, zero values are not stored, and reading a single metric reads only one of the 128 buckets. In addition, aMapwithEnumkeys can now be indexed by the string name of the enum value, e.g.map['name'].Documentation entry for user-facing changes
🤖 Generated with Claude Code
Workflow [PR]
Sync PR [sync-upstream/pr/115380]
Version info
26.8.1.1976(included in26.8and later)