Repository navigation
Conversation
|
Workflow [PR], commit [13a4e8b] Summary: ❌
|
ab8b049 to
3bff9f8
Compare
bcbf392 to
61e1686
Compare
61e1686 to
9e90750
Compare
37e3d14 to
1437f6e
Compare
1437f6e to
08c80fc
Compare
8cc9006 to
e804968
Compare
| When enabled together with `read_in_order_use_virtual_row`, emit a virtual row after each block read (not only at the beginning of each part). | ||
| This allows `MergingSortedTransform` to reprioritize sources more frequently, which is useful when downstream filters discard many rows and data is distributed unevenly across parts. | ||
| Note that it disables `read_in_order_use_buffering` optimization and preliminary merge (`read_in_order_two_level_merge_threshold`) for reading. | ||
| )", 0) \ |
There was a problem hiding this comment.
💡 This PR adds a new user-facing setting, optimize_trivial_group_by_count_query, but the PR body currently uses a non-template documentation checkbox (- [ ] Documentation is not required).
Please align the PR metadata with .github/PULL_REQUEST_TEMPLATE.md (- [ ] Documentation is written (mandatory for new features)) and either add docs for the new setting or clearly justify why docs are unnecessary.
There was a problem hiding this comment.
setting documentation is self-included.
There was a problem hiding this comment.
The PR still does not follow the required template field for docs.
Documentation is not required is not a valid checkbox from .github/PULL_REQUEST_TEMPLATE.md; for this user-facing setting change, please keep the template line and mark it accordingly:
- [x] Documentation is written (mandatory for new features)
(Using source-level setting docs is fine, but the PR body still needs to use the template checkbox.)
…g and old analyzer aggregation-in-order test
- Drop no-parallel: test uses independent table names - Drop no-random-settings: EXPLAIN checks now use explicit SETTINGS clauses (optimize_aggregation_in_order=0, force_aggregation_in_order=0, allow_experimental_parallel_reading_from_replicas=0, force_aggregate_partitions_independently=0) to ensure optimization triggers regardless of random settings - toStartOfInterval queries use SETTINGS session_timezone='UTC'
- Restore no-random-settings tag: command-line random settings override query-level SETTINGS clauses, causing EXPLAIN checks to fail when optimize_aggregation_in_order is randomly enabled (confirmed flaky in ASAN flaky check with 50 runs) - Simplify prewhere input validation to strict equality: only accept when input names exactly match PK column names, bail out on qualified names (e.g. __table1.k) to prevent UNKNOWN_IDENTIFIER errors
Instead of relying on canUseProjection() (which fails when random settings enable force_aggregation_in_order), add requestOnlyMergeForCountByGranularity that clears sort_description_for_merging before switching to merge-only mode. Also simplify prewhere input check to strict PK name equality (bail out on qualified names like __table1.k).
Use bucket expression DAG's INPUT node names (which may be qualified like __table1.k) when building blocks, instead of unqualified PK column names. This ensures the expression can execute correctly regardless of whether the analyzer adds table prefixes.
- Move parts_with_ranges binding after selectRangesToRead to avoid stale reference when analyzed_result_ptr is replaced - Make filter column fetch strict: getByName throws if column is missing instead of silently counting all rows - Handle qualified vs unqualified column names: build block with both PK names (for filter) and bucket_inputs names (for bucket expression) when they differ
- Precompute InputToPKMapping once per source instead of per-granule string matching for qualified name -> PK column resolution - Determine KeyMode (SingleNumeric/MultiNumeric/Generic) once in makePipe via dummy block execution, pass as enum to sources - Precompute key column positions in output header for buildChunk - Reuse aggregate state buffer across buckets instead of per-bucket vector allocation - Reserve ColumnAggregateFunction capacity - Separate filter/no-filter paths completely: countGranuleByReading vs countGranuleWithFilter, processMarkRangesNoFilter vs processMarkRangesWithFilter — zero branches on hot path - Extract executeBucketExpression, computeNonExactMarks, buildIndexBlock helpers to reduce duplication - Fix multi-key GROUP BY: map bucket inputs to PK columns by name instead of assuming positional correspondence - Fix PREWHERE SEGV: capture filter_col as ColumnPtr value instead of dangling reference invalidated by bucket_expression->execute - Use absl::flat_hash_map for all bucket count maps
- For single-column numeric GROUP BY, dispatch on TypeIndex to concrete ColumnVector<T> at processTask entry, then use getData()[row] / getData().push_back() — zero virtual calls on the hot path for both reading and inserting keys - Remove MultiNumeric (vector<UInt64>) specialization — multi-key numeric GROUP BY falls back to the generic Field path; the allocation overhead of vector<UInt64> per row was not meaningfully better than Field, and the extra code/template instantiation was not worth it - NumericCounts<T> uses the native key type (e.g. UInt32) as hash map key, avoiding UInt64 truncation and enabling smaller map entries for narrow types
- Extend numeric fast path to Date (UInt16), Date32 (Int32), DateTime (UInt32), DateTime64 (ColumnDecimal<DateTime64>); these are the most common GROUP BY key types for log histogram queries like toStartOfHour(ts) - Use FilterDescription instead of raw getBool for filter column: handles Nullable, LowCardinality, Const, Sparse, and wider-than- 8-bit filter columns correctly — accesses the underlying UInt8 array directly without virtual dispatch - Template processTaskNumeric on both value type T and column type ColumnType to support ColumnVector<T> for integers/floats and ColumnDecimal<DateTime64> for DateTime64
- Detect Nullable wrapping in bucket expression output type and unwrap to get the nested TypeIndex for dispatch - Add processTaskNullableNumeric: extracts nested ColumnVector<T> data + null_map from ColumnNullable, counts null rows separately into null_count, non-null rows into NumericCounts<T> - Add countGranuleByReadingNullable / countGranuleWithFilterNullable for granule-level processing with null awareness - Add buildChunkNullable: inserts non-null keys via ColumnNullable nested + null_map, then appends the null bucket via insertDefault - Use FilterDescription for PREWHERE filter column to correctly handle Nullable/LowCardinality/Const/Sparse filter results - Add test case for Nullable PK with allow_nullable_key
…atch, add tests - Use make_unique<char[]> for aggregate state buffer instead of vector<char> to avoid unaligned access (count state needs 8-byte alignment) - Remove Float32/Float64 from numeric fast path — NaN equality semantics in absl::flat_hash_map differ from ClickHouse bitwise equality, producing wrong GROUP BY results for NaN keys - Cache per-part bucket columns: precompute bucket_expression on each part's index in makePipe once, store in CountTask; eliminates redundant O(marks_in_part) expression execution per task - Fix ambiguous suffix match in buildInputToPKMapping: use first-dot split instead of ends_with to avoid matching t.n.x to PK column x when the actual column is n.x - Add comprehensive tests: DateTime/Date/DateTime64 key types, signed integers, reverse sorting key (ORDER BY k DESC), Nullable with WHERE, all-null part, single row, ON/OFF comparison for all new cases
…ests - convertToFullIfNeeded on bucket columns to handle ColumnSparse wrapping that occurs with random sparse serialization settings; fixes Bad cast from ColumnSparse to ColumnNullable crash - Validate all bucket expression inputs map to PK columns in the optimization; bail out if any input is unresolvable to prevent NOT_FOUND_COLUMN_IN_BLOCK at runtime - Clear group_by_sort_description and explicit_sorting_required_for_aggregation_in_order in requestOnlyMergeForCountByGranularity to keep AggregatingStep in consistent state for plan serialization paths - Add optimize_trivial_group_by_count_query=0 to 01231_distributed_aggregation_memory_efficient_mix_levels - Fix reverse key test: add explicit SETTINGS to avoid flaky behavior from random optimize_aggregation_in_order - Fix reference file for new test cases
- Rename bucket expression DAG input nodes from qualified names (__tableN.col_name) to bare PK column names during optimization, before constructing ExpressionActions - Remove InputToPKMapping, buildInputToPKMapping, and all alias handling — no longer needed since DAG inputs match PK names - Simplify readGranule: just insert PK columns by name, no aliases - Simplify makePipe index_block: iterate PK columns directly - Fix Nullable get_key: use typeid_cast to handle both ColumnNullable and unwrapped columns in get_key_unwrap lambda - Restore multi-key GROUP BY support with correct reference file
88856fe to
e2d6ede
Compare
…ated index In `processTaskNullableNumeric` the row count formula for the last mark of the non-null section used `part.rows_count - getRowsCountInRange(0, mark)`, which is the residual to the end of the part. When `first_null_mark` is not the last mark in the part, that boundary granule overlaps the row range of subsequent NULL granules, so `countBlockNullable` over-counted NULLs into the non-null mark and the dedicated boundary handler then counted them again. Use `getRowsCountInRange(mark, mark + 1)` for marks that are not the actual last mark of the part; only the true final granule may have a partial row count. Pin `index_granularity = 64` in the `nullable_pk_on` test case so the boundary granule is exercised deterministically. Also bail out of `optimizeCountByGranularity` when any part's primary index has fewer columns than the PK. With the `primary_key_ratio_of_unique_prefix_values_to_skip_suffix_columns` setting (default `0.9`), suffix columns are dropped from the in-memory index when their cardinality ratio meets the threshold, and the bucket expression then fails with `NOT_FOUND_COLUMN_IN_BLOCK` on the dropped column. CI report: ClickHouse#103490 Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
LLVM Coverage Report
Changed lines: 90.79% (651/717) · Uncovered code |
Before this change, `tests/docker_scripts/stress_runner.sh` exported
`THREAD_POOL_FAULT_INJECTION=1` before `configure`, so install.sh
symlinked `tests/config/config.d/cannot_allocate_thread_injection.xml`
into the server's `config.d/` and the server started with
`cannot_allocate_thread_fault_injection_probability=0.0001` already
active. `stress.py` then ran a small smoke check (two canary tests)
to validate the setup. The smoke check did, among other things:
CREATE DATABASE IF NOT EXISTS test_N
ON CLUSTER test_cluster_database_replicated
ENGINE = Replicated(...)
When thread-pool fault injection fired during the async load of the
Replicated database (`Code: 439. Cannot schedule a task: fault
injected`), the server raised the exception after it had already
started streaming the HTTP response, so
`WriteBufferFromHTTPServerResponse` deliberately broke the chunked
encoding. The client (`clickhouse-test` → `clickhouse_execute_http`)
saw `http.client.IncompleteRead`, the per-test retry was exhausted,
and the smoke check aborted the whole stress test job.
The protocol break is by design — the server uses it to signal that a
streamed response is incomplete and must not be consumed as if it were
successful. Retrying it on the client (the previous attempt) would mask
genuine server failures.
Instead, this commit applies @azat's prescription: run the smoke check
against a server that does *not* have the thread-pool fault injector
installed, then enable it only once the smoke check has passed.
- `tests/docker_scripts/stress_runner.sh` no longer exports
`THREAD_POOL_FAULT_INJECTION=1` before `configure`. install.sh leaves
`cannot_allocate_thread_injection.xml` uninstalled. The server starts
with `cannot_allocate_thread_fault_injection_probability=0` (default),
so the smoke check runs deterministically.
- `stress.py` gains `--enable-thread-pool-fault-injection`. When set,
`run_func_test` calls a new `install_thread_pool_fault_injection()`
helper after the smoke-check loop. The helper symlinks the canonical
config and runs `SYSTEM RELOAD CONFIG` with retries (the reload can
itself transiently fail under ZooKeeper fault injection and
ThreadFuzzer). `stress_runner.sh` passes the flag; the upgrade runner
does not. If the smoke check raises, the install path is not reached
and the post-stress cleanup `rm -f`s any stale symlink.
- The obsolete `CANNOT_SCHEDULE_TASK` / `Fault injection` entries are
removed from the smoke-check `ignored_errors` list. Tolerating them
would now mask a genuine setup failure since the injector is not
active during the smoke check.
The failure mode recurs ~weekly across unrelated master PRs (e.g.
ClickHouse#104058, ClickHouse#103490, ClickHouse#102351, ClickHouse#102610, ClickHouse#102203, and master CI on
2026-04-28). Tracked by @alexey-milovidov's directive on PR ClickHouse#96844:
ClickHouse#96844 (comment)
Failing report example (PR ClickHouse#96844, commit 9c4f6f5, MSan stress):
https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=96844&sha=9c4f6f5a34d4bb45fcf73f20c464ba8d855a0c1f&name_0=PR&name_1=Stress%20test%20%28arm_msan%29
Validation: `tmp/test_install_thread_pool_fault_injection.py` (not
committed) covers (a) the symlink+reload mechanics, (b) fail-close when
the source config is missing, (c) flag off → no install, (d) flag on →
install runs once after smoke check, (e) install does not run when
smoke check raises an unrecoverable error, (f) the obsolete entries
are gone from `ignored_errors`. All six pass.
|
Dear @amosbird, this PR hasn't been updated for a while. Will you continue working on it? If not, please close it. Otherwise, ignore this message. |
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. - retargeted PR record [email protected] to 26.10 (settings-history check rule) Also resolved conflicts in: - `src/Processors/QueryPlan/Optimizations/QueryPlanOptimizationSettings.cpp` - `src/Processors/QueryPlan/Optimizations/optimizeTree.cpp` - `tests/queries/0_stateless/04058_explain_pretty_aggregation_sorting.sql` Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
Summary
A generalization of the exact-ranges trivial count optimization (#60463) to
GROUP BYqueries: optimizeSELECT monotonic_f(pk_col), count() FROM t GROUP BY 1by computing counts directly from MergeTree primary key index and granularity metadata, avoiding full table scans.This is particularly useful for log histogram scenarios (e.g.,
SELECT toStartOfInterval(ts, INTERVAL 1 HOUR), count() FROM logs GROUP BY 1) where the primary key is a timestamp. It also lays the groundwork for combining histogram counting with full-text index filtering in future work.For granules fully within a single bucket, row counts come from
MergeTreeIndexGranularity::getRowsCountInRange(zero data I/O). For granules that cross a bucket boundary, only the PK column of that granule is read to determine the exact split point. WithPREWHERE/WHEREon PK range conditions,exact_rangesfromselectRangesToReadidentify granules where all rows match — these use metadata counting. Non-exact boundary granules read the PK column and apply the filter.Changes:
optimize_trivial_group_by_count_query(defaulttrue)optimizeCountByGranularity: pattern-matchesAggregatingStep+ExpressionStep+ReadFromMergeTree, validates GROUP BY keys are monotonic functions of the sorting key prefix viamatchTrees, rewrites the subtree toReadFromCountByGranularityand switchesAggregatingStepto merge-only mode viarequestOnlyMergeForAggregateProjectionISourceStepsubclassReadFromCountByGranularitywith parallelCountByGranularitySourceinstances sharing an atomic work pool, tasks split by mark ranges for load balancing across threadsPREWHERE/WHEREon PK range conditions, distributed queries (outputsColumnAggregateFunctionintermediate states)Benchmark (50M rows, 20 parts, RelWithDebInfo):
Changelog category (leave one):
Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):
Add
optimize_trivial_group_by_count_querysetting that optimizesGROUP BY monotonic_function(primary_key) + count()queries by computing counts from primary key index and granularity metadata instead of reading data columns.Documentation entry for user-facing changes
Workflow [PR]
Sync PR [sync-upstream/pr/103490]