Skip to content

Reject AggregatingMergeTree dimensions outside the sorting key - #108087

Merged
alexey-milovidov merged 17 commits into
masterfrom
fix-aggregating-dimensions-outside-sorting-key-751
Jul 7, 2026
Merged

alexey-milovidov merged 17 commits into
masterfrom
fix-aggregating-dimensions-outside-sorting-key-751

Conversation

@alexey-milovidov

@alexey-milovidov alexey-milovidov commented Jun 22, 2026 •

Copy link
Copy Markdown
Member

AggregatingMergeTree collapses, during background merges, all rows that share the same value of the
sorting 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 (AggregateFunction or SimpleAggregateFunction) is
a dimension: after a merge it keeps an arbitrary value of one of the collapsed rows. This silently
produces wrong results for queries that GROUP BY or filter on that column — 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.

This PR rejects such a schema when the table is created, with a clear message:

Column(s) <names> of the AggregatingMergeTree table are neither part of the sorting key nor aggregate
measures (AggregateFunction or SimpleAggregateFunction). During background merges, rows with the same
value of the sorting key are collapsed into one, so these columns keep an arbitrary value, which
silently produces wrong results for queries that GROUP BY or filter on them. Add them to the sorting
key (ORDER BY), or set 'allow_dimensions_outside_sorting_key = 1' if this is intentional (for example,
when the columns are functionally dependent on the sorting key).

Details:

  • The check runs only at table creation (not when an existing table is attached/loaded), so it
    never prevents an already-existing table from starting up.
  • It fires only when the table actually aggregates — i.e. it has at least one aggregate-state column.
    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.
  • It is skipped when allow_tuple_element_aggregation is enabled, because there a plain column (e.g. a
    Tuple) can be an aggregated measure.
  • Columns referenced by the partition key are treated as covered (they are constant within a part).
  • The new MergeTree setting allow_dimensions_outside_sorting_key (default 0) restores the old
    behavior, for the legitimate case where the off-key column is functionally dependent on the sorting
    key.

The check is intentionally limited to AggregatingMergeTree. For SummingMergeTree /
CoalescingMergeTree, an explicit list of columns to sum/coalesce that leaves other columns off-key is
documented behavior (you choose which columns are combined), so those engines are not affected.

Changelog category (leave one):

  • Backward Incompatible Change

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

AggregatingMergeTree now 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 that GROUP BY or filter on them. Set allow_dimensions_outside_sorting_key = 1 to restore the previous behavior. #751

Documentation entry for user-facing changes

  • Documentation is written (the new setting allow_dimensions_outside_sorting_key is self-documented in system.merge_tree_settings).

Version info

  • Merged into: 26.7.1.633 (included in 26.7 and later)

alexey-milovidov and others added 2 commits June 22, 2026 00:17
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]>
@clickhouse-gh

clickhouse-gh Bot commented Jun 22, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [7c7d7ed]

Summary: ✅


AI Review

Summary

This PR adds a create-time guard for AggregatingMergeTree schemas that keep ordinary dimensions outside the sorting key, wires in a compatibility setting, and updates TimeSeries/tests/docs to cope with the new validation. The core idea is good, but the current exceptions are still broad enough to leave silent wrong-result cases in paths the new check claims to make safe, so I would keep the verdict at request changes.

Findings

❌ Blockers

  • [src/Storages/MergeTree/MergeTreeData.cpp:1612-1622] [dismissed by author -- https://github.com/Reject AggregatingMergeTree dimensions outside the sorting key #108087#discussion_r3449316247] covered_columns is built from getRequiredColumns() of the sorting and partition expressions, which accepts source columns that are not actually part of the merge key. A table such as ORDER BY toDate(ts) now treats physical ts as covered even though background merges still group only by toDate(ts) and keep an arbitrary ts from the first row. Suggested fix: only auto-cover physical columns that are themselves key elements or are otherwise proven functionally determined; expression-source columns should require the opt-out setting.

  • [src/Storages/MergeTree/MergeTreeData.cpp:1620-1622] [dismissed by author -- https://github.com/Reject AggregatingMergeTree dimensions outside the sorting key #108087#discussion_r3449415480] Treating partition-key columns as safe only holds for background part merges. SELECT ... FINAL still uses AggregatingSortedTransform across all selected parts when do_not_merge_across_partitions_select_final = 0 (the default), and that transform groups only by the sorting key. An accepted schema such as PARTITION BY part_col ORDER BY key can therefore still collapse different part_col values into one row at read time and return an arbitrary part_col. Suggested fix: do not whitelist partition columns here, or make the exemption conditional on FINAL never merging across partitions.

  • [src/Storages/MergeTree/MergeTreeData.cpp:1858-1864] [dismissed by author -- https://github.com/Reject AggregatingMergeTree dimensions outside the sorting key #108087#discussion_r3449316244] Enabling allow_tuple_element_aggregation disables the new validation for the whole table, but AggregatingSortedAlgorithm::startGroup still copies every ordinary non-aggregate column from the first row. A schema like (key UInt64, name String, value AggregateFunction(sum, UInt64)) ... SETTINGS allow_tuple_element_aggregation = 1 is therefore still accepted and still corrupts name after a merge. Suggested fix: keep the validation active in tuple mode and decide “measure vs dimension” on flattened Tuple leaves instead of bypassing the check wholesale.

  • [src/Storages/TimeSeries/normalizeTimeSeriesDefinition.cpp:702-728] [dismissed by author -- https://github.com/Reject AggregatingMergeTree dimensions outside the sorting key #108087#discussion_r3511111148] allowOffKeyDimensionsForAggregatingTagsEngine force-enables allow_dimensions_outside_sorting_key for every inline aggregating tags engine, but the safety argument in the comment only holds for the canonical tag columns. When aggregate_min_time_and_max_time = 0, min_time/max_time are ordinary off-key Nullable(DateTime64) columns, and StorageTimeSeriesSelector later uses them for pruning (src/Storages/StorageTimeSeriesSelector.cpp:451-459). Background merges can keep an arbitrary first value there, so this auto-opt-out can turn selector pruning into wrong-result filtering. Suggested fix: inject the opt-out only for the known-safe aggregating tags layout, or reject inline aggregating tags engines whose off-key columns are not functionally determined by (metric_name, id).

Final Verdict

Request changes. The new validation is directionally correct, but the remaining exceptions still admit silent wrong-result cases in AggregatingMergeTree and TimeSeries.

@clickhouse-gh clickhouse-gh Bot added the pr-backward-incompatible Pull request with backwards incompatible changes label Jun 22, 2026
…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`).
alexey-milovidov and others added 6 commits June 26, 2026 15:06
…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]>
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]>
@alexey-milovidov

Copy link
Copy Markdown
Member Author

Picked this up to merge master and address the AI-review Request changes verdict.

Changes pushed

  • Synced the in-server TimeSeries documentation (StorageTimeSeries.cpp, exposed via system.documentation and the in-server /docs UI) with the docs/en page, which already had SETTINGS allow_dimensions_outside_sorting_key = 1. This was AI finding fix docs #6 (the only one that was a concrete consistency gap rather than a design choice) — the source docs were still advertising the explicit AggregatingMergeTree tags-table shape that the new validation rejects. Verified the changed TU with -fsyntax-only.
  • Merged master (was 250 commits behind and red): clean, no conflicts, no submodule bumps, no test-number collision (04491 is still free).

CI status — all three failures are unrelated flakes (with evidence)

  • 02985_dialects_with_distributed_tables (arm_binary, parallel) — Timeout flake, failed on unrelated PRs [105056, 106734, 96886, 108087] over the last weeks.
  • test_storage_kafka/.../test_kafka_formats_with_broken_message — flaky Kafka test, failed on 8 distinct unrelated PRs [107484, 107098, 108417, 108286, 107566, 107442, 108431, 108087]; its error MVs use ENGINE=MergeTree (not AggregatingMergeTree), so it cannot be caused by this PR.
  • Hung check failed, possible deadlock found (Stress, amd_tsan) — chronic master-wide flake #107941 (already linked by the CI bot).

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:

  1. No-measure tables not checked — documented in the PR ("fires only when the table actually aggregates"); a measure-less AggregatingMergeTree is effectively a dedup table.
  2. CREATE-only (ALTER can still reach the shape) — documented; extending to ALTER ADD COLUMN / MODIFY ORDER BY would newly reject very common operations on existing tables.
  3. allow_tuple_element_aggregation skips the check — documented ("a plain column can be a measure" in that mode).
  4. getRequiredColumns over-approximates safe columns (e.g. ORDER BY toDate(ts) treats ts as covered) — documented in the code comment as the intentional way to guarantee no false positive.
  5. Partition columns treated as covered vs. FINAL across partitions — documented; requiring partition columns in the sorting key too would reject the very common PARTITION BY date ORDER BY key pattern.

These are scope/policy questions for the backward-incompatible change rather than bugs in the current code, so they're yours to decide.

@alexey-milovidov

Copy link
Copy Markdown
Member Author

Picked this up again (continue-pr, read-only — no code change). The head is still 7ce7118d (your master merge), so I re-checked the current CI against your 01:21 triage. The two stateless flakes you listed (02985_dialects_with_distributed_tables, test_kafka_formats_with_broken_message) have since passed on rerun; the latest run shows three failures, all unrelated:

  • Hung check failed, possible deadlock found (Stress amd_tsan + arm_tsan) — chronic #107941, as the CI bot links. I downloaded both stress logs: the stuck threads are all in QueryAnalyzer::resolveQuery / executeASTFuzzerQueries / TCPHandler::runImpl — zero frames in the new dimension check, MergeTreeData::MergeTreeData, or AggregatingSortedAlgorithm. The only allow_dimensions_outside_sorting_key hits in the logs are the TimeSeries inner TAGS table being created successfully with the new setting (the PR's TimeSeries change working as intended), not a failure.
  • Logical error: Block structure mismatch in A stream: different columns: (STID: 0993-27f0) (AST fuzzer amd_debug) — this is new since your comment and is the pre-existing known fuzz issue #108142 (open since 2026-06-22, exact STID match). The stack is UnionStep::updateOutputHeader → checkHeaders during QueryPlan::optimize on a fuzzed SELECT ... UNION — a query-plan-optimization header mismatch that a create-time validation check cannot cause. Unrelated.

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 ALTER ADD COLUMN / MODIFY ORDER BY on live tables, or the very common PARTITION BY date ORDER BY key), which is more harmful than the documented false negatives. Those remain your maintainer call. Blocked solely on the Stress/AST-fuzzer reruns (or override) and your merge.

@alexey-milovidov

Copy link
Copy Markdown
Member Author

Re-checked after the master merge (HEAD 7ce7118). CI re-ran on the merge commit, so the three current failures differ from the set my previous comment analyzed — all three are unrelated, tracked flakes:

  • AST fuzzer (amd_debug) — Logical error: Block structure mismatch in A stream: different columns: (STID: 0993-27f0). Exact STID match to open issue #108142 (testing, fuzz). The failure is in UnionStep::updateOutputHeader → checkHeaders during query-plan optimization; this PR only adds a CREATE-time storage validation (checkDimensionsAreInSortingKey, gated on sanity_checks) and touches no query-planning code, so it cannot produce this.
  • Stress test (amd_tsan) and Stress test (arm_tsan) — both Hung check failed, possible deadlock found = the chronic master-wide stress hang #107941 (already linked by the CI bot); the stacks are generic analyzer/interpreter frames with nothing from this PR.

I re-ran the three failed jobs. No re-merge: the merge-base is from today (00:38Z) and these reds also fire on master, so a re-merge would not change them.

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.

alexey-milovidov and others added 2 commits July 1, 2026 04:46
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]>
@alexey-milovidov

Copy link
Copy Markdown
Member Author

Picked this up again (continue-pr). This time I did re-merge master and pushed a small fix — departing from my previous "no re-merge" calls (head was 7ce7118d, now f2c63e2).

Why re-merge now

  • The merge-base (d70da4f4137, 2026-06-30 00:38Z) is now >1 day old and the branch was 634 commits behind, with master having evolved the PR's central files since then: MergeTreeData.cpp (+44 commits — where checkDimensionsAreInSortingKey lives) and SettingsChangesHistory.cpp (+49 commits, the usual append hotspot). Re-merging validates the integration and gives a fresh binary + fresh CI run to re-roll the stress flakes.
  • More concretely, the merge surfaced a real test-number collision: master has since added 04491_dict_get_keys_const_path_non_coordinator_layout and 04491_table_readonly_move_partition_to_table, so 04491 is no longer free (it was when I last checked). Landing a third 04491_* would be poor hygiene.

What I pushed

  • Merged master — clean, no conflicts, no submodule bumps. Verified the PR's changes are intact and correctly placed: the net source diff is unchanged (+132/-6), checkDimensionsAreInSortingKey and the allow_dimensions_outside_sorting_key gate are present, and the MergeTree history entry is still under the latest 26.7 section in getMergeTreeSettingsChangesHistory.
  • Renumbered the test 04491_aggregating_dimensions_in_sorting_key → 04494_… (content unchanged; the next free prefix). This test was already passing on the prior run — only the stress reds below were red.

CI status — the two reds were the same tracked flake

Before this push the only failures were Hung check failed, possible deadlock found on Stress test (amd_tsan) and (arm_tsan) — the chronic master-wide stress hang #107941 (already linked by the CI bot). The stuck stacks are generic InterpreterSelectQueryAnalyzer / QueryAnalyzer::resolveQuery / TCPHandler::runImpl frames, with zero frames in the new dimension check, MergeTreeData::MergeTreeData, or AggregatingSortedAlgorithm. The fresh CI run on f2c63e2 will re-roll it.

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.

@alexey-milovidov

Copy link
Copy Markdown
Member Author

Picked this up again (continue-pr, read-only — no code change). Head is unchanged at f2c63e2, and the fresh CI run you were waiting on has come back fully green, confirming the 04:50Z prediction:

  • All Stress test jobs (amd_tsan, arm_tsan, and every other variant) are now SUCCESS — the chronic hung-check flake #107941 re-rolled green on f2c63e2.
  • All AST fuzzer jobs are SUCCESS — the block-structure-mismatch flake #108142 cleared as well.
  • The Praktika report shows 0 failed (151 passed, 19 skipped), and the AI Review verdict flipped to ✅ Approve on this head.

The only non-green check across the whole rollup is CH Inc sync (PENDING, a fresh private-sync run started 08:46Z) — in progress, not a failure. mergeable=MERGEABLE, mergeStateStatus=BLOCKED.

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 CH Inc sync run finishing, a human approval, and your merge.

…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]>
@alexey-milovidov

Copy link
Copy Markdown
Member Author

Picked this up again (continue-pr). Since the 07-01 16:20Z check the branch had gone CONFLICTING/DIRTY — master advanced 786 commits past the merge-base (d584c4a2, 07-01 04:14Z) and picked up a new conflict — so this time I re-merged master (head f2c63e2 → 294aaa6).

Conflict resolved

Sole conflict was in src/Storages/MergeTree/MergeTreeSettings.cpp. Using diff3 markers:

  • master de-indented the R-string description of allow_coalescing_columns_in_partition_or_order_key (whitespace-only reformat, to match allow_summing_columns_in_partition_or_order_key above it).
  • this branch kept the indented allow_coalescing_... text and added the new allow_dimensions_outside_sorting_key setting right after it.

Resolution: took master's de-indented allow_coalescing_... text (its reformat of an area this PR didn't mean to touch) and preserved the new allow_dimensions_outside_sorting_key setting verbatim.

The SettingsChangesHistory.cpp entry (correctly in the 26.7 getMergeTreeSettingsChangesHistory block, alongside master's allow_experimental_text_index_positions) and the checkDimensionsAreInSortingKey logic in MergeTreeData.cpp auto-merged cleanly. I re-read both — the check function and its call site use only stable metadata APIs and are coherent post-merge. No leftover conflict markers anywhere in the tree.

State

mergeable flipped CONFLICTING → MERGEABLE (mergeStateStatus=BLOCKED). Before the merge, CI on f2c63e2 was fully green (only CH Inc sync pending), 0 unresolved review threads, and the AI-review verdict was ✅ Approve. CI is re-running on the merge commit 294aaa6. Blocked solely on that run finishing, a human approval, and your merge.

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]>
@alexey-milovidov

Copy link
Copy Markdown
Member Author

Picked this up (continue-pr) and pushed a fix for the sole real CI failure (294aaa6 → 4297564).

What was red

Fast test failed on 04413_documentation_no_indented_lines:

allow_dimensions_outside_sorting_key	MergeTree Setting

Your 07-02 03:31Z master merge pulled the 04413 lint (which flags documentation lines indented four-or-more columns — Markdown renders them as an accidental code block in the in-server /docs UI) onto the branch, while the new allow_dimensions_outside_sorting_key setting kept its R"(...)" description indented by four spaces (preserved verbatim during the conflict resolution). So the lint that master already made you de-indent allow_coalescing_columns_in_partition_or_order_key/allow_summing_columns_in_partition_or_order_key for now caught this new setting too.

Fix

De-indented the description to column zero — whitespace-only inside the raw-string literal, content unchanged, matching every other setting. The Mergeable Check/PR reds were just aggregates of this one Fast-test failure; CH Inc sync was PENDING (not a failure).

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. mergeable=MERGEABLE. Blocked on the fresh CI run on 4297564, a human approval, and your merge.

…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]>
@alexey-milovidov

Copy link
Copy Markdown
Member Author

Picked this up (continue-pr) and pushed one fix (42975643 → e1f857a7751) for the fresh AI-review Request changes verdict that landed on the previous head after the master merge + doc-lint fix.

Fixed: false positive on MATERIALIZED columns (AI Major, MergeTreeData.cpp:1600)

checkDimensionsAreInSortingKey iterates getColumns().getAllPhysical(), which includes stored MATERIALIZED columns. A safe schema like

CREATE TABLE t (key UInt64, d String MATERIALIZED toString(key), s AggregateFunction(sum, UInt64))
ENGINE = AggregatingMergeTree ORDER BY key;

was rejected even though d is functionally determined by the sorting key and merges cannot change its value — a genuine false positive that contradicts this PR's "never a false positive" contract. The fix adds MATERIALIZED columns to the covered set (they are computed, not raw dimensions), extending the existing over-approximation and keeping the check false-positive-free. Regression case t_agg_materialized added to 04494_aggregating_dimensions_in_sorting_key. Verified the changed TU compiles; the functional test will run in CI.

Left for your call: the TimeSeries opt-out breadth (AI Blocker, normalizeTimeSeriesDefinition.cpp:728)

allowOffKeyDimensionsForAggregatingTagsEngine only disables the new check for aggregating tags engines, so it cannot produce a wrong result that wasn't already possible on master (where no check exists) — it's a false negative, not a regression. Narrowing it would make the new check newly reject TimeSeries tables that work today (a false positive), against the PR's stated philosophy. I replied inline and left the thread open; it reads as the same scope/policy decision as the previously-dismissed majors #1–#5.

CI: the one red is an unrelated flake

Stateless tests (amd_tsan, parallel, 2/2) failed on 02884_authentication_quota — a timing-sensitive auth/quota test unrelated to MergeTree storage validation. Per CIDB it fails sporadically (~1/day) across many unrelated PRs over the last 90 days (108731, 104902, 105249, 104964, 102444, 103444, …). Not caused by this PR; the fresh run on e1f857a7751 should re-roll it.

Blocked on the fresh CI run, your decision on the TimeSeries thread, a human approval, and your merge.

@mintlify

mintlify Bot commented Jul 7, 2026 •

Copy link
Copy Markdown
Contributor

Preview deployment for your docs. Learn more about Mintlify Previews.

Project Status Preview Updated (UTC)
ClickHouse-docs 🟢 Ready View Preview Jul 7, 2026, 2:47 PM

@clickhouse-gh

clickhouse-gh Bot commented Jul 7, 2026

Copy link
Copy Markdown
Contributor

LLVM Coverage Report

Metric Baseline Current Δ
Lines 85.70% 85.70% +0.00%
Functions 92.70% 92.70% +0.00%
Branches 77.90% 78.00% +0.10%

Changed lines: Changed C/C++ lines covered: 110/113 (97.35%) · Uncovered code

Full report · Diff report

@alexey-milovidov alexey-milovidov left a comment

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

Ok.

@alexey-milovidov alexey-milovidov self-assigned this Jul 7, 2026
@alexey-milovidov
alexey-milovidov added this pull request to the merge queue Jul 7, 2026
Merged via the queue into master with commit d80f960 Jul 7, 2026
175 checks passed
@alexey-milovidov
alexey-milovidov deleted the fix-aggregating-dimensions-outside-sorting-key-751 branch July 7, 2026 21:48
@robot-clickhouse robot-clickhouse added the pr-synced-to-cloud The PR is synced to the cloud repo label Jul 7, 2026
zeekay pushed a commit to hanzoai/datastore that referenced this pull request Sep 11, 2026
…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]>
zeekay pushed a commit to hanzoai/datastore that referenced this pull request Sep 11, 2026
…dimensions-outside-sorting-key-751

Reject AggregatingMergeTree dimensions outside the sorting key

This branch was successfully deployed

1 active deployment
staging - docs — 7c7d7ed6 Deployed Jul 7, 2026 by mintlify[bot]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

pr-backward-incompatible Pull request with backwards incompatible changes pr-synced-to-cloud The PR is synced to the cloud repo

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants