Repository navigation
Fix aggregation hash table stats cache key for table functions - #109847
alexey-milovidov merged 16 commits into
Conversation
setAggregationHashTableCacheKeys stamps a plan-derived key over it during plan optimization anyway. The AST-based key survived only when plan hashing throws (e.g. in-order aggregation) - a case where the analyzer keeps key == 0 and skips preallocation; do the same. Co-Authored-By: Claude Fable 5 <[email protected]>
Co-Authored-By: Claude Fable 5 <[email protected]>
The key hashed a source step as serialization name + StorageID + PREWHERE, but a storage created by a table function has no UUID and its StorageID does not depend on the arguments: after GROUP BY over numbers(1e6), GROUP BY over numbers(100) preallocated a hash table for a million keys. Hash the table-expression subtree (function name and resolved arguments) for table functions; this also covers s3, url, generateRandom, etc. Co-Authored-By: Claude Fable 5 <[email protected]>
|
Workflow [PR], commit [a81e9b3] Summary: ✅
AI ReviewSummaryThis PR correctly restores Findings❌ Blockers
Tests
Final Verdict
|
…s-cache-key-table-functions
| /// numbers(1e6) would share a stats entry. | ||
| if (const auto & table_expression = read.getQueryInfo().table_expression) | ||
| { | ||
| if (table_expression->as<TableFunctionNode>()) |
There was a problem hiding this comment.
TableFunctionNode is not the only supported table-function shape here. QueryAnalyzer::resolveTableFunction rewrites parameterized views like my_view(x = 1) into a synthetic TableNode, and buildParameterizedViewStorage gives every instantiation the same StorageID(database, table). After that rewrite this branch is skipped, so different parameter values still fall back to storage_id.getFullTableName() and reuse each other's aggregation stats.
Please preserve and hash the original call arguments for that case as well, for example by carrying the original table-function subtree (or its resolved hash) through SelectQueryInfo.
There was a problem hiding this comment.
Good catch, and this one is a genuine gap (in analyzer mode too), not just the legacy path: QueryAnalyzer::resolveTableFunction rewrites view(x = ...) into a synthetic TableNode, buildParameterizedViewStorage reuses one StorageID(database, table) for every parameter set, and this branch only matches TableFunctionNode, so different parameters collapse to the same key.
Handling it properly means preserving the original table-function subtree (or a hash of its resolved arguments) across that rewrite and carrying it on SelectQueryInfo, then hashing it here even when the node has become a TableNode — an analyzer change on top of the plan-hash infrastructure rather than something local to this optimization. Since it is a separate correctness gap from the 01730_... flakiness this PR targets, I'd prefer to do it as a follow-up and would defer the scope/approach to @novikd. Flagging it here so it is not lost.
…s-cache-key-table-functions
…lized-plan path
`calculateHashFromStep` mixes the table function subtree into the aggregation
hash-table-stats cache key, but that subtree is only available when
`SelectQueryInfo.table_expression` is populated. `PlannerJoinTree` sets it on the
analyzer read path, but the `resolveStorages` reconstruction of a deserialized
`ReadFromTableFunctionStep` (distributed / `serialize_query_plan`) did not, so the
key hashed only the storage name (`_table_function.numbers` for any `numbers(N)`)
and different arguments shared one stats entry on the shard side.
Set `select_query_info.table_expression` to the resolved `TableFunctionNode` in
`resolveStorages` before `storage->read`, mirroring the analyzer path. The only
local consumers of `table_expression` check for `TableNode`, so a `TableFunctionNode`
is a no-op for them; the value is a preallocation hint and never affects results.
Extend `04509_hash_table_sizes_stats_table_functions` with a
`cluster('test_shard_localhost', numbers(...))` case under `serialize_query_plan=1`
that reads the shard-side (secondary) aggregation preallocation, so `numbers(1e6)`
and `numbers(800e3)` are shown to preallocate 1000000 and 800000 distinctly.
Verified locally: with the fix the secondary aggregations preallocate 1000000 and
800000; the extended test passes across repeated runs.
Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
…s-cache-key-table-functions
…an path ReadFromTableStep and ReadFromTableFunctionStep serialize FINAL / SAMPLE out-of-band from the table name / table function AST, and resolveStorages never put them back: - On the direct-read path, the TableFunctionNode reconstructed from serialized_ast carried no modifiers, so the hash-table-stats key could not tell modifier-bearing reads apart. - For remote / Merge storages, the query AST constructed for InterpreterSelectQueryAnalyzer dropped the modifiers entirely, so e.g. SELECT ... FROM cluster(..., merge(...)) FINAL read non-collapsed data under serialize_query_plan (verified: the FINAL query returned 1e6 groups instead of 600e3 before this fix), and both reads shared one aggregation-stats entry. Copy the modifiers onto the reconstructed TableFunctionNode and restore them on the constructed ASTTableExpression. Extend the test with a ReplacingMergeTree read through merge() with and without FINAL; the FINAL group count is kept above the 500e3 lower bound below which getSizeHint skips preallocation.
|
The |
|
The new test is too long for the flaky check. |
In the flaky check 04509_hash_table_sizes_stats_table_functions averaged ~75 seconds per run on amd_debug/amd_asan_ubsan (with a few runs above the 180 seconds limit), and its 50 sequential reruns chained to about an hour of that job. Shrink the aggregated group counts from 1e6/800e3 to 650e3/520e3 - they must stay above the 500e3 lower bound under which `getSizeHint` does not preallocate at all with a single hash table (and `max_threads = 1` is required for the exact reference values) - and move the FINAL table expression modifiers case (which additionally inserts and reads a two-part ReplacingMergeTree table) into a separate test 04613_hash_table_sizes_stats_table_expression_modifiers, so the flaky check reruns of the two halves proceed in parallel workers instead of one long sequential chain. Verified against a local server with process_query_plan_packet enabled: both tests plus 04612 pass 5/5 on a binary with the fix, and all three fail with the expected collision / dropped-modifier signatures on a master binary without it. ClickHouse#109847 (comment) Co-Authored-By: Claude Fable 5 <[email protected]>
|
Addressed #109847 (comment) in a938035: in the flaky check Two changes:
Verified locally against a server with |
The new test `04613_hash_table_sizes_stats_table_expression_modifiers` read `system.query_log` without a `current_database = currentDatabase()` condition, which the `various_checks.sh` style check requires in any test that queries `system.query_log`/`system.query_thread_log`. The Style check failure fail-fast-aborted the whole workflow, which is why every downstream job (builds, Bugfix validation) showed up as DROPPED and the `new_tests_check` post-hook then reported "No per-arch Bugfix Validation job validated the bug". The preallocation counters are read from the secondary (`is_initial_query = 0`) rows, and secondary queries on the executor run as the `default` user, so their `current_database` is `default` rather than the test database - filtering those rows directly by `current_database = currentDatabase()` would drop them all and break the test (the same reason 04509 does not filter its secondary block that way). Instead scope the secondary rows to this test via their initiator, which does run in `currentDatabase()`, mirroring the pattern in `04029_distributed_index_analysis_sampling` and `04201_max_bytes_ratio_before_external_join_distributed`. This both satisfies the style check and tightens the test's isolation from other tests' query_log. Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
|
Pushed
The preallocation counters are read from the secondary ( Verified locally against a binary without the fix: the reworked |
…s-cache-key-table-functions
Merging `master` (1512 commits) brought in new stateless tests at numbers `04612` and `04613`, which collided with this PR's `04612_serialize_query_plan_table_function_sample` and `04613_hash_table_sizes_stats_table_expression_modifiers`. Renumber the two tests added by this PR to `04624` and `04625` (updating their internal table names and query-id prefixes accordingly) to keep test numbers unique. Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
|
Merged The merge brought in two new stateless tests on The two CI reds on
Merging |
LLVM Coverage Report
Changed lines: Changed C/C++ lines covered: 43/45 (95.56%) · Uncovered code |
|
Status update on
No code changes needed this pass. Remaining: the standing parameterized-view cache-key design follow-up (deferred to @novikd) and human merge. |
In the flaky check 04509_hash_table_sizes_stats_table_functions averaged ~75 seconds per run on amd_debug/amd_asan_ubsan (with a few runs above the 180 seconds limit), and its 50 sequential reruns chained to about an hour of that job. Shrink the aggregated group counts from 1e6/800e3 to 650e3/520e3 - they must stay above the 500e3 lower bound under which `getSizeHint` does not preallocate at all with a single hash table (and `max_threads = 1` is required for the exact reference values) - and move the FINAL table expression modifiers case (which additionally inserts and reads a two-part ReplacingMergeTree table) into a separate test 04613_hash_table_sizes_stats_table_expression_modifiers, so the flaky check reruns of the two halves proceed in parallel workers instead of one long sequential chain. Verified against a local server with process_query_plan_packet enabled: both tests plus 04612 pass 5/5 on a binary with the fix, and all three fail with the expected collision / dropped-modifier signatures on a master binary without it. ClickHouse#109847 (comment) Co-Authored-By: Claude Fable 5 <[email protected]>
…ache-key-table-functions Fix aggregation hash table stats cache key for table functions
… its memory cap off the initiator peak The test asserts that its distributed_group_by_no_merge=0 query exceeds max_memory_usage. On master 22fae87 (Stateless tests (amd_tsan, parallel)) the query completed instead, so the negative assertion never fired and the test failed with "The query succeeded but the server error '241' was expected". The peak that assertion targets is correct and structural. With no_merge=0 each of the 10 shards aggregates its own numbers(1e6) single-stream, so AggregatingStep zeroes group_by_two_level_threshold and every block ships with bucket_num = -1. With purely single-level input GroupingAggregatedTransform cannot push anything until every input port has finished, so distributed_aggregation_memory_efficient buys nothing here and the initiator holds all 10 shards' output at once: 76.29 MiB of buffered blocks (10 x 1e6 x 8 B) plus the merged key64_void table and its 7.63 MiB result. The defect is that the test picked its cap equal to that peak. In the failing job's own query_log the initiator peaked at 99.14 MiB against the 100.00 MiB cap, a margin of 903,301 B (0.87%), while the server's per-thread untracked-memory quantum is 1 MiB. Whether the run crossed 104,857,600 B was therefore decided by allocation noise of the same magnitude as the margin, which is why 4 of 4 diagnosis reruns passed and the failure rate is roughly 1 in 180 days. Lower the cap shared by the two paired queries from 100Mi to 64Mi. The window is bounded above by the initiator peak (99.14 MiB) and below by query 1's own per-shard peak (41.00 MiB), which has to stay under the cap so the 241 is raised on the initiator and not on a shard. Query 2, the positive half of the pair, floors lower still at 30.22 MiB, so it keeps 2.12x headroom. 100Mi sat above the top of that window; 64Mi is its geometric middle, sqrt(41.00 x 99.14) = 63.76, so the binding margin grows from 0.87% to about 55% on both sides. Both queries keep the same cap, so the pair remains an honest A/B in which only distributed_group_by_no_merge differs, and the negative assertion becomes strictly harder to satisfy rather than easier. Queries 3 and 4 keep their own caps deliberately. Query 4's measured peak is 54.03 to 56.30 MiB, so at 64Mi its headroom would fall to about 1.18x and it would become the next flake. This test has one other live failure mode, which this change neither fixes nor disturbs: query 2's shard sometimes attempts a single 512.00 MiB allocation in AggregatingTransform and blows the cap outright, 256 times in the last 365 days. It stopped on every lane when ClickHouse#109847 merged on 2026-07-22, except Stateless tests (amd_asan_ubsan, distributed plan, parallel), where it last fired on 2026-09-03. The size is exactly 512.00 MiB in 256 of 256 samples, with none at 128 or 256 MiB, so it clears the old and the new cap identically and there is no intermediate regime that 100Mi absorbed and 64Mi would not. Validated on a debug build with the CI test configs installed: 50/50 runs, 5/5 with enable_analyzer=0 for the old analyzer lanes, and 5/5 with serialize_query_plan=1, the setting the distributed plan lanes install, which is also the only arm where query 1 has the initiator serialize the shard plan. Raising the cap back above the peak reproduces the original failure message, so the oracle is live rather than merely satisfied. Co-Authored-By: Claude Opus 5 <[email protected]>
Changelog category (leave one):
Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):
Fix wrong results for table-function reads with
FINAL/SAMPLEunderserialize_query_plan = 1, and fix the aggregation hash-table stats cache key for table functions (previously all table functions shared one preallocation entry).This should fix flakiness of 01730_distributed_group_by_no_merge_order_by_long (#109456)
Closes: #109456