Repository navigation
Reject AggregatingMergeTree dimensions outside the sorting key - #108087
alexey-milovidov merged 17 commits into
Conversation
In AggregatingMergeTree, background merges collapse all rows that share the same value of the sorting key into a single row, combining their aggregate states. A column that is neither part of the sorting key nor an aggregate-state measure (`AggregateFunction` or `SimpleAggregateFunction`) is a dimension: after a merge it keeps an arbitrary value of one of the collapsed rows, which silently produces wrong results for queries that `GROUP BY` or filter on it. Before the first merge the data looks correct, and after a merge it is quietly corrupted, with no error or warning. This is a long-standing usability trap (issue #751, open since 2017): a materialized view whose `GROUP BY` includes a column that was not added to the target table's `ORDER BY`. Reject such a schema at table creation. The check: - runs only on `CREATE` (not on attach/load), so existing tables keep loading; - fires only when the table actually aggregates (has at least one aggregate-state column); a table without measures is out of scope and left alone; - is skipped when `allow_tuple_element_aggregation` is enabled, because there a plain column can be an aggregated measure; - treats partition-key columns as covered (they are constant within a part). The new `MergeTree` setting `allow_dimensions_outside_sorting_key` (default `0`) restores the previous behavior for the legitimate case where the off-key column is functionally dependent on the sorting key. The check is limited to AggregatingMergeTree. For SummingMergeTree and CoalescingMergeTree, an explicit list of columns to sum/coalesce that leaves other columns off-key is documented behavior, so those engines are unaffected. A few existing tests intentionally use such schemas; they now either add the missing dimension to `ORDER BY` or set `allow_dimensions_outside_sorting_key = 1`. Closes: #751 Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
…ensions-outside-sorting-key-751
|
Workflow [PR], commit [7c7d7ed] Summary: ✅
AI ReviewSummaryThis PR adds a create-time guard for Findings❌ Blockers
Final VerdictRequest changes. The new validation is directionally correct, but the remaining exceptions still admit silent wrong-result cases in |
…ensions-outside-sorting-key-751 # Conflicts: # src/Storages/MergeTree/MergeTreeSettings.cpp
…ting_key The new setting `allow_dimensions_outside_sorting_key` changes `CREATE` behavior compared with older releases (such schemas were previously accepted), so it must be recorded in `getMergeTreeSettingsChangesHistory`. Record the change in `26.7` with previous value `true` and new value `false`, so that `compatibility = '26.6'` or older restores the old permissive behavior, as documented for the setting. This also fixes the `02995_new_settings_history` test, which requires every new merge tree setting to be present in the settings changes history.
…e tags table When `aggregate_min_time_and_max_time` is enabled (the default), the inner `tags` table of a `TimeSeries` table uses `AggregatingMergeTree`. Its tag columns and the `tags` Map are not part of the sorting key, but they are functionally dependent on `id` (which is part of the sorting key), so all rows that collapse together during a background merge share the same values. Set `allow_dimensions_outside_sorting_key = 1` on that inner engine so the new `AggregatingMergeTree` validation accepts it. This fixes the creation of every `TimeSeries` table (`03222_create_timeseries_table`, `04146_timeseries_attach_detach`, `04238_attach_timeseries_external_metrics`, `04340_timeseries_rename_digest_mismatch`).
…ating tags tables The new `AggregatingMergeTree` validation rejects schemas where a column is neither part of the sorting key nor an aggregate measure. A TimeSeries `tags` inner table keeps the tag columns (and the `tags`/`all_tags` Maps) outside the sorting key, so it needs `allow_dimensions_outside_sorting_key = 1`. The previous commit only set this on the generated default tags engine. When the inner tags engine is specified explicitly (`TAGS ENGINE=AggregatingMergeTree ...`), `generateInnerEngine` is not called, so the setting was missing and the inner table `CREATE` was rejected. Move the injection into a helper `allowOffKeyDimensionsForAggregatingTagsEngine` and apply it to both the generated and the explicit inner tags engine. For manually created external/standalone aggregating tags tables there is no TimeSeries normalization, so the setting must be added by the user. Update the integration tests `test_different_table_engines.py` and `test_upgrade_from_prealpha.py` and the docs to set it, mirroring what the stateless tests `04337` and `04202` already do. Fixes the consistently failing `test_prometheus_protocols` integration tests (`test_inner_engines`, `test_external_tables`, `test_data_keyword`, `test_upgrade_from_prealpha`, `test_upgrade_from_prealpha_ordinary_db`), and addresses the review feedback on the documented explicit inner-engine form. CI report: #108087 Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
…ensions-outside-sorting-key-751
…ensions-outside-sorting-key-751
After merging master, three other tests now use the 04407 prefix (datalake getcatalog guard, geojson output value errors, quantize bfloat16). Move this test to the next free number. Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
…_sorting_key` setting The `docs/en` `TimeSeries` page was updated to show the inner/explicit aggregating tags table with `SETTINGS allow_dimensions_outside_sorting_key = 1`, but the identical documentation embedded in `StorageTimeSeries.cpp` (exposed via `system.documentation` and the in-server `/docs` UI) still advertised the old shape, which `AggregatingMergeTree` now rejects by default. Apply the same three edits to the source documentation so the in-server docs stay in sync and do not advertise a schema that fails to create. Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
…ensions-outside-sorting-key-751
|
Picked this up to merge Changes pushed
CI status — all three failures are unrelated flakes (with evidence)
AI-review majors #1–#5 — left for your call (they conflict with the PR's documented design)The remaining majors all argue for making the check stricter, which is the opposite of this PR's explicit "never a false positive, accept occasional false negatives, minimal backward-incompatible blast radius" philosophy. Each is a deliberate, documented decision (and is covered by the new test as intended), so I did not change them:
These are scope/policy questions for the backward-incompatible change rather than bugs in the current code, so they're yours to decide. |
|
Picked this up again (continue-pr, read-only — no code change). The head is still
No re-merge needed (merge-base is from today, <1 day old; the reds are not master-fixable). I did not touch AI-review majors #1–#5 — agreed they are the deliberate "never a false positive / minimal blast-radius" design you documented in the code and PR body. For a backward-incompatible change, the stricter alternatives the AI asks for would introduce real false positives on existing schemas (rejecting |
|
Re-checked after the
I re-ran the three failed jobs. No re-merge: the merge-base is from today ( The five AI-review majors (#1–#5) remain the deliberate scope/policy decisions documented in my previous comment and dismissed inline — they argue for a stricter check, the opposite of this PR's "never a false positive, accept occasional false negatives, minimal backward-incompatible blast radius" contract, which the changelog and PR body already spell out (create-time only, requires a measure, with the tuple-mode / expression-key / partition-key exceptions). Left for your call. |
…ensions-outside-sorting-key-751
Master added `04491_dict_get_keys_const_path_non_coordinator_layout` and `04491_table_readonly_move_partition_to_table` since this branch was created, colliding with this PR's `04491_aggregating_dimensions_in_sorting_key`. Move it to the next free prefix `04494` (the test content is unchanged). Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
|
Picked this up again (continue-pr). This time I did re-merge Why re-merge now
What I pushed
CI status — the two reds were the same tracked flakeBefore this push the only failures were AI-review majors #1–#5 — unchanged (your call)Still the deliberate scope/policy decisions you documented and dismissed inline: they argue for a stricter check, the opposite of this PR's "never a false positive, accept occasional false negatives, minimal backward-incompatible blast radius" contract (create-time only, requires a measure, with the tuple-mode / expression-key / partition-key exceptions). I did not touch them. Blocked on the fresh CI and your merge. |
|
Picked this up again (continue-pr, read-only — no code change). Head is unchanged at
The only non-green check across the whole rollup is I did not touch AI-review majors #1–#5 — they remain the deliberate 'never a false positive, accept occasional false negatives, minimal backward-incompatible blast radius' scope decisions you documented and dismissed inline. Blocked solely on the |
…ensions-outside-sorting-key-751 Resolve the sole conflict in `src/Storages/MergeTree/MergeTreeSettings.cpp`: master de-indented the R-string description of `allow_coalescing_columns_in_partition_or_order_key` (a whitespace-only reformat), while this branch added the new `allow_dimensions_outside_sorting_key` setting immediately after it. Kept master's de-indented `allow_coalescing_...` text and preserved this branch's new setting verbatim. The settings-history entry and the `checkDimensionsAreInSortingKey` logic auto-merged cleanly. Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
|
Picked this up again (continue-pr). Since the 07-01 16:20Z check the branch had gone Conflict resolvedSole conflict was in
Resolution: took master's de-indented The State
|
The last `master` merge (`294aaa6`) pulled in the `04413_documentation_no_indented_lines`
lint, which flags documentation lines indented by four or more columns (Markdown renders
them as an accidental code block in the in-server `/docs` UI). The new
`allow_dimensions_outside_sorting_key` setting was added with its `R"(...)"` description
indented by four spaces, so `Fast test` now fails with:
allow_dimensions_outside_sorting_key MergeTree Setting
De-indent the description to column zero, matching every other setting and the treatment
`master` already applied to the neighboring `allow_coalescing_columns_in_partition_or_order_key`
and `allow_summing_columns_in_partition_or_order_key` settings. Whitespace-only change to the
raw-string literal; the description content is unchanged.
CI report: https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=108087&sha=294aaa617831b97ada642b3d62d71f480573d7ce&name_0=PR&name_1=Fast%20test
Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
|
Picked this up (continue-pr) and pushed a fix for the sole real CI failure ( What was red
Your 07-02 03:31Z FixDe-indented the description to column zero — whitespace-only inside the raw-string literal, content unchanged, matching every other setting. The I did not touch AI-review majors #1–#5 — those remain the deliberate "never a false positive, minimal backward-incompatible blast radius" scope decisions you documented and dismissed inline. 0 unresolved review threads. |
…orting key
The create-time check `checkDimensionsAreInSortingKey` iterates
`getColumns().getAllPhysical()`, which includes stored `MATERIALIZED`
columns. A safe schema such as
CREATE TABLE t (key UInt64, d String MATERIALIZED toString(key), s AggregateFunction(sum, UInt64))
ENGINE = AggregatingMergeTree ORDER BY key
was therefore rejected as an off-key dimension, even though `d` is
functionally determined by the sorting key and background merges cannot
change its value. That contradicts this change's "never a false positive"
contract and introduces an avoidable backward-incompatible `CREATE`
failure.
Treat `MATERIALIZED` columns as covered: they are computed from an
expression, not supplied as raw data, so this extends the existing
"over-approximate the set of safe columns" approach and keeps the check
free of false positives (at the cost of not catching a materialized
column derived from an off-key column, the same accepted trade-off
already documented for the sorting and partition keys).
Add a regression case to `04494_aggregating_dimensions_in_sorting_key`.
Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
|
Picked this up (continue-pr) and pushed one fix ( Fixed: false positive on
|
|
Preview deployment for your docs. Learn more about Mintlify Previews.
|
LLVM Coverage Report
Changed lines: Changed C/C++ lines covered: 110/113 (97.35%) · Uncovered code |
…ating tags tables The new `AggregatingMergeTree` validation rejects schemas where a column is neither part of the sorting key nor an aggregate measure. A TimeSeries `tags` inner table keeps the tag columns (and the `tags`/`all_tags` Maps) outside the sorting key, so it needs `allow_dimensions_outside_sorting_key = 1`. The previous commit only set this on the generated default tags engine. When the inner tags engine is specified explicitly (`TAGS ENGINE=AggregatingMergeTree ...`), `generateInnerEngine` is not called, so the setting was missing and the inner table `CREATE` was rejected. Move the injection into a helper `allowOffKeyDimensionsForAggregatingTagsEngine` and apply it to both the generated and the explicit inner tags engine. For manually created external/standalone aggregating tags tables there is no TimeSeries normalization, so the setting must be added by the user. Update the integration tests `test_different_table_engines.py` and `test_upgrade_from_prealpha.py` and the docs to set it, mirroring what the stateless tests `04337` and `04202` already do. Fixes the consistently failing `test_prometheus_protocols` integration tests (`test_inner_engines`, `test_external_tables`, `test_data_keyword`, `test_upgrade_from_prealpha`, `test_upgrade_from_prealpha_ordinary_db`), and addresses the review feedback on the documented explicit inner-engine form. CI report: ClickHouse#108087 Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
…dimensions-outside-sorting-key-751 Reject AggregatingMergeTree dimensions outside the sorting key
AggregatingMergeTreecollapses, during background merges, all rows that share the same value of thesorting key into a single row and combines their aggregate states. A column that is neither part of
the sorting key nor an aggregate-state measure (
AggregateFunctionorSimpleAggregateFunction) isa dimension: after a merge it keeps an arbitrary value of one of the collapsed rows. This silently
produces wrong results for queries that
GROUP BYor filter on that column — before the first mergethe data looks correct, and after a merge it is quietly corrupted, with no error or warning.
This is a long-standing usability trap (issue #751, open since 2017): a materialized view whose
GROUP BYincludes a column that was not added to the target table'sORDER BY.This PR rejects such a schema when the table is created, with a clear message:
Details:
never prevents an already-existing table from starting up.
A table without any measures is not the scenario from AggregatingMergeTree shouldn't allow to have inconsistent GROUP BY and primary key by default #751 and is left alone.
allow_tuple_element_aggregationis enabled, because there a plain column (e.g. aTuple) can be an aggregated measure.MergeTreesettingallow_dimensions_outside_sorting_key(default0) restores the oldbehavior, for the legitimate case where the off-key column is functionally dependent on the sorting
key.
The check is intentionally limited to
AggregatingMergeTree. ForSummingMergeTree/CoalescingMergeTree, an explicit list of columns to sum/coalesce that leaves other columns off-key isdocumented behavior (you choose which columns are combined), so those engines are not affected.
Changelog category (leave one):
Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):
AggregatingMergeTreenow rejects, at table creation time, schemas where a column is neither part of the sorting key nor an aggregate-state measure (AggregateFunction/SimpleAggregateFunction). Such columns are silently collapsed to an arbitrary value during background merges, producing wrong results for queries thatGROUP BYor filter on them. Setallow_dimensions_outside_sorting_key = 1to restore the previous behavior. #751Documentation entry for user-facing changes
allow_dimensions_outside_sorting_keyis self-documented insystem.merge_tree_settings).Version info
26.7.1.633(included in26.7and later)