Skip to content

Apply optimize_functions_to_subcolumns in WHERE/PREWHERE on shards of distributed queries - #114204

Open
andyzzhao wants to merge 10 commits into
ClickHouse:masterfrom
andyzzhao:map-subcolumns-distributed
Open

andyzzhao wants to merge 10 commits into
ClickHouse:masterfrom
andyzzhao:map-subcolumns-distributed

Conversation

@andyzzhao

@andyzzhao andyzzhao commented Aug 10, 2026 •

Copy link
Copy Markdown
Contributor

Closes: #114174
Related: #109188
Related: #99200
Related: #107988

Changelog category (leave one):

  • Performance Improvement

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

Applies optimize_functions_to_subcolumns inside WHERE/PREWHERE on the shards of distributed queries, so that e.g. map['key'] reads a single key subcolumn instead of the whole Map column. Previously the optimization never applied when querying through a Distributed table.

Documentation entry for user-facing changes

  • Documentation is written (mandatory for new features)

Description

The optimization never applies through a Distributed table: the initiator declines it (StorageDistributed::supportsOptimizationToSubcolumns is false — it cannot see the shards' real schema #108299 or skipping indexes #108874), and shards run only the resolve passes. So e.g. WHERE tags['k0'] != '' reads and decodes the whole Map on every shard instead of a single key subcolumn.

Fix: shards run FunctionToSubcolumnsPass in a new only_filter_clauses mode that restricts all rewrites (direct and chained, e.g. json.a[1].b) to WHERE/PREWHERE, where they cannot change the header expected by the initiator. Applied on remote shard queries (SECONDARY_QUERY), the prefer_localhost_replica local plan, and the serialized query plan path. On the shard the pass sees the real MergeTree metadata, so the index guard and subcolumn resolution are safe where the initiator-side rewrite was not.

Also fixes stale metadata of lazily loaded tables (lazy_load_tables = 1), which would let the rewrite defeat skipping indexes: StorageTableProxy's storage snapshot was built from the pre-materialization stub (columns only — no keys, indices, or virtuals) although building it materializes the nested table anyway; it now uses the nested storage's metadata.

The stateless tests check correctness, header stability, and read amplification (via system.query_log) across all three shard paths and the lazy-table case; tests/performance/map_subcolumns_prewhere.xml gets a remote() case.


Workflow [PR]
Sync PR [sync-upstream/pr/114204]

… distributed queries

FunctionToSubcolumnsPass never applied through a Distributed table: the
initiator declines it because StorageDistributed does not support the
optimization (ClickHouse#109188 - the initiator cannot see the shards' schema and
indexes), and shards skip all optimization passes to keep the block
header expected by the initiator stable. As a result, e.g. map['key']
read and decoded the whole Map column on every shard instead of a
single key subcolumn.

Rewrites inside WHERE and PREWHERE cannot change the header, so apply
them on the shard, where the real storage metadata is known: the pass
gets an only_filter_clauses mode that restricts all rewrites to
WHERE/PREWHERE, and the interpreter runs it after the resolve passes
for queries executed on shards of distributed queries.

Closes: ClickHouse#114174

Co-Authored-By: Claude Fable 5 <[email protected]>
@SmitaRKulkarni SmitaRKulkarni added the can be tested Allows running workflows for external contributors label Aug 11, 2026
@clickhouse-gh

clickhouse-gh Bot commented Aug 11, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [39a1abe]

Summary: ✅


AI Review

Summary

This PR moves FunctionToSubcolumnsPass onto distributed-query shard plans in WHERE/PREWHERE and fixes lazy StorageTableProxy snapshots to expose real metadata. The lazy-table snapshot fix looks sound, but the shard-only analyzer pipeline still skips the empty-string normalization that existing string subcolumn rewrites depend on, so the promised filter-side optimization parity is still incomplete.

Findings

⚠️ Majors

  • [src/Interpreters/InterpreterSelectQueryAnalyzer.cpp:288-301] The new shard-only path runs runOnlyResolve() and then only FunctionToSubcolumnsPass, but the normal analyzer pipeline reaches FunctionToSubcolumnsPass only after ConvertEmptyStringComparisonToFunctionPass (src/Analyzer/QueryTreePassManager.cpp:278-280). Because of that, distributed filters such as name != '' / name = '' never become notEmpty(name) / empty(name) on shards, so the existing string-size rewrite still does not fire there. That leaves one of the already-supported optimize_functions_to_subcolumns carriers on the old full-column path, which means the shard-side WHERE/PREWHERE optimization contract in this PR is still incomplete. Suggested fix: apply a filter-scoped ConvertEmptyStringComparisonToFunctionPass before FunctionToSubcolumnsPass on the shard path, or teach FunctionToSubcolumnsPass's only_filter_clauses mode to recognize equals/notEquals(..., '') directly. Then add a focused distributed String regression with optimize_empty_string_comparisons = 1 pinned; tests/queries/0_stateless/04510_functions_to_subcolumns_distributed_type_mismatch.sql already documents this carrier.
Final Verdict
  • Status: ⚠️ Request changes
  • Minimum required action: preserve shard-side parity for the empty-string filter form (= '' / != '') instead of running only FunctionToSubcolumnsPass.
  • Minimum required action: add a focused distributed regression for that carrier so the gap cannot reopen.

LLVM Coverage Report

Measured on commit 39a1abe.

Metric Baseline Current Δ
Lines 88.80% 88.80% +0.00%
Functions 91.80% 91.80% +0.00%
Branches 81.20% 81.20% +0.00%

Changed lines: Changed C/C++ lines covered: 40/42 (95.24%) · Uncovered code

Full report · Diff report

@clickhouse-gh clickhouse-gh Bot added the pr-performance Pull request with some performance improvements label Aug 11, 2026
@clickhouse-gh

clickhouse-gh Bot commented Aug 11, 2026 •

Copy link
Copy Markdown
Contributor

📊 Cloud Performance Report

✅ AI verdict: no_change — no significant changes across 39 queries analysed

Release-transition baseline: compared against the last 26.8 master because no 26.9 master baseline exists at or before the trusted base-commit anchor.

This PR narrowly scopes the function-to-subcolumns optimizer so that distributed-query shards can rewrite Map/JSON accessors inside WHERE/PREWHERE (plus a StorageTableProxy snapshot fix for lazy-loaded tables). None of the flagged ClickBench or TPC-H queries execute that path — they contain no Map/JSON subcolumn filters through Distributed tables — so the code change cannot plausibly move their medians in either direction. Every flagged row also carries a thin baseline (as few as 11-33 base samples) and, for most, a noisy history, which is why the deltas look large; the extreme ones (TPCH Q4 ×20.9 faster on n=12, Q7 ×6.9 faster on n=25) are classic thin-baseline artifacts. All flagged rows are downgraded to not-sure: the real behavior this PR targets is only visible in the dedicated map_subcolumns_prewhere distributed test, not in these standard benchmarks.

clickbench

⚠️ 10 inconclusive

Flagged queries (10 of 43)
Query Verdict Baseline median (ms) PR median (ms) Change q-value Hint
⚠️ 13 not_sure 427 349 -18.3% <0.0001 This PR only rewrites Map/JSON functions to subcolumns inside WHERE/PREWHERE on distributed shards; ClickBench Q13 does not exercise that path, and the query is intrinsically noisy, so the delta is run-to-run variance.
⚠️ 15 not_sure 192 157 -18.2% <0.0001 The diff only affects function-to-subcolumns rewriting for distributed shard filters; Q15 does not touch that code path, and this query is intrinsically noisy, so treat the improvement as variance.
⚠️ 16 not_sure 711 543 -23.6% <0.0001 Q16 does not use the distributed-shard subcolumn rewrite this PR adds, and history shows the query is flaky, so this improvement is not attributable to the diff.
⚠️ 17 not_sure 462 245 -47.0% <0.0001 The -47.0% swing sits on a very unstable baseline and Q17 does not exercise the WHERE/PREWHERE subcolumn rewrite; the change is not plausibly caused by this PR.
⚠️ 18 not_sure 1196 877 -26.6% <0.0001 Measurements here are highly noisy on both sides and Q18 does not touch the distributed-shard subcolumn path this PR changes, so the improvement is variance rather than a PR effect.
⚠️ 23 not_sure 170 85 ×2.0 faster <0.0001 The source-side measurements are extremely noisy and Q23 does not exercise the code this PR changes, so the ×2.0 faster reading is run-to-run variance, not attributable to the diff.
⚠️ 30 not_sure 276 224 -18.8% <0.0001 Q30 does not use the shard-side function-to-subcolumns rewrite added here, and the query is intrinsically noisy, so this improvement is variance.
⚠️ 31 not_sure 404 264 -34.7% <0.0001 The diff only touches WHERE/PREWHERE subcolumn rewriting on distributed shards; Q31 does not exercise it, and history flags the query as flaky, so the delta is unrelated to this PR.
⚠️ 32 not_sure 1313 730 -44.4% <0.0001 Both sides are very noisy here and Q32 does not touch the changed code path, so the -44.4% reading is run-to-run variance rather than a PR effect.
⚠️ 33 not_sure 1218 1144 -6.1% 0.0032 The -6.1% delta is small and Q33 does not exercise the distributed-shard subcolumn rewrite this PR adds, so it is not plausibly caused by the diff.

Change = percent below ×2; the ratio of medians (×N faster/slower) beyond, where percent understates the scale. q-value = BH-FDR adjusted p; smaller is stronger evidence. MIRAI flags a query when q < fdr_q (default 0.10) — the value the verdict is based on.

tpch_adapted_1_official

⚠️ 6 inconclusive

Flagged queries (6 of 22)
Query Verdict Baseline median (ms) PR median (ms) Change q-value Hint
⚠️ 1 not_sure 55 66 +20.0% <0.0001 TPCH Q1 is a scan/aggregation with no Map/JSON subcolumn filters, so the changed rewrite cannot affect it; with very noisy measurements the +20.0% is run-to-run variance.
⚠️ 2 not_sure 67 50 -25.4% <0.0001 Q2 does not use the WHERE/PREWHERE function-to-subcolumns path this PR changes, and the query is intrinsically noisy, so the improvement is variance.
⚠️ 4 not_sure 1064 51 ×20.9 faster <0.0001 The ×20.9 faster reading rests on a tiny, noisy baseline (n=12) and TPCH Q4 does not exercise the changed subcolumn rewrite, so this is a thin-baseline artifact, not a PR effect.
⚠️ 7 not_sure 565 82 ×6.9 faster <0.0001 Q7 does not touch the distributed-shard subcolumn rewrite, and the ×6.9 faster reading sits on a thin, noisy baseline (n=25), so it is not attributable to the diff.
⚠️ 8 not_sure 177 89 -49.7% <0.0001 Q8 does not exercise the changed WHERE/PREWHERE rewrite path and the query is intrinsically noisy, so the -49.7% reading is run-to-run variance.
⚠️ 17 not_sure 109 68 -37.6% <0.0001 The baseline here is highly unstable and Q17 does not use the Map/JSON subcolumn rewrite this PR adds, so the improvement is variance rather than a PR effect.

Change = percent below ×2; the ratio of medians (×N faster/slower) beyond, where percent understates the scale. q-value = BH-FDR adjusted p; smaller is stronger evidence. MIRAI flags a query when q < fdr_q (default 0.10) — the value the verdict is based on.

Debug info
  • StressHouse run: b143d290-5039-4384-a5c9-7a12c93700f9
  • MIRAI run: 55c7a0d8-7162-4d63-9e45-70f5e54c33be
  • PR check IDs:
    • clickbench_84999_1788908176
    • clickbench_85012_1788908176
    • clickbench_85018_1788908176
    • tpch_adapted_1_official_85030_1788908176
    • tpch_adapted_1_official_85055_1788908177
    • tpch_adapted_1_official_85069_1788908176

The guard collected primary key and secondary index columns from the
resolution-time storage snapshot. For a table in a database with
lazy_load_tables = 1, that snapshot is built from the StorageTableProxy
stub, which has columns only - no primary key and no secondary indices -
so no column was index-protected and rewrites broke index analysis.
Read the storage's current metadata instead: the nested storage is
materialized by the time the pass runs, so the proxy forwards the real
metadata.

The pre-existing bug was observable on master with a direct query on a
freshly attached lazy table (verified on 26.8.1.1235: INDEX_NOT_USED
with force_data_skipping_indices). Running the pass on shards extended
the exposure to Distributed queries, caught by
02346_text_index_bug108874.

Co-Authored-By: Claude Fable 5 <[email protected]>
…h in test

With only_filter_clauses, the chained branch of the second visitor (e.g.
the JSON array rewrite for json.a[1].b) never fired because it accepted
only identifiers from the everywhere bucket, which the mode empties.
Honor filter_only inside WHERE/PREWHERE there, same as the direct
branch.

The test's serialized-plan case used prefer_localhost_replica = 1,
which takes the local-stream branch and never exercises the
build_logical_plan path. Add a case with prefer_localhost_replica = 0
and a chained JSON rewrite case (both validated on 26.8.1.1250: only
the read-amplification booleans fail pre-fix).

Also trim overly verbose comments.

Co-Authored-By: Claude Fable 5 <[email protected]>
if (is_query_on_shard && !select_query_options.is_create_view)
{
QueryTreePassManager function_to_subcolumns_pass_manager(context);
function_to_subcolumns_pass_manager.addPass(std::make_unique<FunctionToSubcolumnsPass>(/*only_filter_clauses=*/ true));

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Adding only FunctionToSubcolumnsPass here still leaves the existing empty-string filter form on the old full-column path. On a direct query, name != '' / name = '' first goes through ConvertEmptyStringComparisonToFunctionPass (notEquals/equals -> notEmpty/empty), and only then can FunctionToSubcolumnsPass rewrite it to name.size; this shard-only branch never runs that earlier pass, so a distributed query like 04510_functions_to_subcolumns_distributed_type_mismatch.sql stays as notEquals(name, '') and never gets the subcolumn read. If the goal is parity for shard-side WHERE/PREWHERE optimization, this path needs the same filter-scoped empty-string conversion (or equivalent direct handling in FunctionToSubcolumnsPass).

@clickhouse-gh

clickhouse-gh Bot commented Aug 12, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing 39a1abe80 with master 73cd94f72 (stripped binary size, per-symbol sizes and ThinLTO time; compile times per translation unit against the most recent warmup build that recompiled it).

✅ No significant changes.

Binary sizes

programs/clickhouse-stripped: smaller than the master baseline by the known offset between the two builds, so the difference is not shown. A delta that differs from the offset by more than 50% of it is shown, in either direction.

The official master build is compiled with -g and a pull request build is not, and XRay counts debug instructions towards its instrumentation threshold, so master instruments thousands of functions more and its binary is ~0.4% larger no matter what the pull request does.

Compile time of recompiled translation units

10 translation units recompiled, 36 s compile time in total, 10 of them have a recent master baseline.

Median compile-time ratio to the baselines is ×1.09 (machine-speed difference or a change affecting every TU); per-TU deltas below are relative to that ratio.
The matched translation units cost +3.4 s (+10%) in total before that adjustment.

Job report

@andyzzhao

andyzzhao commented Aug 12, 2026 •

Copy link
Copy Markdown
Contributor Author

The AST fuzzer (arm_asan_ubsan) failure is unrelated to this PR: Logical error: Reading from materialized CTE 'A' before its materialization completed - DelayedPortsProcessor gate is missing in the query plan (STID: 2467-2c2d).

Known issue, failing daily on master and on dozens of unrelated PRs over the last 90 days per CIDB.
Related: #113184
Fix in progress: #113558 (see the investigation below)

@groeneai, investigate the failure: https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=114204&sha=833228d5fdaee4da8246fb5d39aa55bb77f0dad5&name_0=PR&name_1=AST%20fuzzer%20%28arm_asan_ubsan%29 and provide a fix in a separate PR. If the fix is already in progress, link it here.

@groeneai

Copy link
Copy Markdown
Collaborator

Investigated. The fix is already in progress: #113558 (@ alexey-milovidov, open). Measured, it covers this exact shape, so nothing new is needed from my side here.

The failing query on your run is

WITH t AS MATERIALIZED (SELECT number AS c FROM numbers(257))
SELECT count() FROM merge(REGEXP('.*'), '^') WHERE (x IN (t)) OR (x IN (t))

ReadFromMerge::createChildrenPlans optimizes each child plan on its own, and resolveMaterializingCTEs claims a CTE globally, so the first child to be optimized takes the CTE's plan into its own tree. The writer then sits in one child's pipeline and the readers in another, with no DelayedPortsProcessor between them, and ReadFromMemoryStorageStep reports the missing gate. #113558 strips those steps from the children so the outer plan is the single gating owner.

A/B on your carrier query, debug build, master 93e2851fddb5add vs master + #113558 b9fe1650232abf4f:

binary carrier query 04811 (#113558's own test)
master abort, signal 6, 3/3 abort, signal 6
master + #113558 passes 3/3, returns the correct count passes, output matches its reference

Controls: the same merge() read without a CTE, and with a single-reference (inlined) CTE, pass on both binaries, so the oracle is not simply "any merge() query dies". nm shows the fix's symbols absent on master and present on the patched binary.

Two notes. #113558 no longer merges cleanly onto current master: one textual conflict in MaterializingCTEStep.cpp, because master changed makePlansForCTEs to return ClaimedCTE while the PR adds eraseCTEs immediately above it. It is trivial to resolve (keep master's signature, keep the new function), and that is how I built the arm above. Also, the report URL in your comment carries sha=833228d5fda57e8e4d92b9b6db22053417497de9, which does not exist; the head that produced the failure is 833228d5fdaee4da8246fb5d39aa55bb77f0dad5.

@andyzzhao

Copy link
Copy Markdown
Contributor Author

The Stress test (arm_tsan) failure is also unrelated to this PR: Logical error: Digest does not match in DatabaseReplicated::assertDigestWithProbability during a concurrent fuzzed CREATE TABLE — this PR only touches SELECT-side analyzer passes. The same failure family hits stress checks on many unrelated PRs and has been ramping up since the week of 2026-07-26.

Filed: #114819

@groeneai, investigate the failure: https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=114204&sha=833228d5fdaee4da8246fb5d39aa55bb77f0dad5&name_0=PR&name_1=Stress%20test%20%28arm_tsan%29 and provide a fix in a separate PR. If the fix is already in progress, link it here.

@groeneai

Copy link
Copy Markdown
Collaborator

Investigated. The fix for that failure is already merged: #113794 (merged today at 09:09Z). It is a test-isolation defect, not a DatabaseReplicated bug: 04365_create_as_select_cluster_function_replicated_db.sql re-engined the shared test_3 database as Replicated and never restored it, then 04545_attach_projection_part_offset_setting_disabled.sh had its DETACH refused with Code: 80, ignored the failure, and sed-rewrote the metadata of a still-attached table. The digest assertion then correctly reported the divergence.

Your run predates the fix: the job's master_commits list does not contain the merge commit fdba33b3d91a. A re-run on current master should not reproduce it.

Full artifact timeline and the family numbers are in #114819 (comment) - no need to duplicate them here.

andyzzhao and others added 5 commits August 24, 2026 10:42
…ributed

# Conflicts:
#	src/Analyzer/Passes/FunctionToSubcolumnsPass.cpp
…Snapshot

Move the fix for stub metadata of lazily loaded tables from
FunctionToSubcolumnsPass into StorageProxy::getStorageSnapshot. The
resolution-time snapshot was built around caller-supplied base_metadata,
which for a not-yet-materialized StorageTableProxy is the stub (columns
only - no keys, no indices, no virtuals), even though getNested()
materializes the nested table in the same call. Build the snapshot from
the nested storage's metadata instead, so every consumer of the snapshot
sees real metadata, and the pass reads storage_snapshot->metadata like
the rest of the code again.

Co-Authored-By: Claude Fable 5 <[email protected]>
Building the snapshot from nested metadata in the StorageProxy base
broke CREATE TABLE ... AS table_function() with an explicit structure
(01457_create_as_table_function_structure): StorageTableFunctionProxy
declares a structure intentionally different from the nested storage
and converts on read, so its base_metadata is authoritative. Only
StorageTableProxy, whose stub describes the same table, should use the
nested storage's metadata.

Co-Authored-By: Claude Fable 5 <[email protected]>
Under flaky-check randomization the test drew index_granularity = 1,
making the 10000-row insert write one granule per row and exceed the
180s limit. Randomized min_bytes_for_wide_part could also force compact
parts, where subcolumn reads may not reduce read_bytes and the
read-amplification assertions would not hold.

Co-Authored-By: Claude Fable 5 <[email protected]>
@andyzzhao

Copy link
Copy Markdown
Contributor Author

The AST fuzzer (arm_asan_ubsan) failure on this run is unrelated to this PR (the previous CTE one is fixed since #113558 merged): UBSan float-to-integer overflow in WorkloadSettings.cpp:366 when a fuzzed CREATE WORKLOAD supplies a huge max_concurrent_threads_ratio_to_cores. Same failure hits unrelated PRs about weekly per CIDB.

Filed: #116200

@groeneai, investigate the failure: https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=114204&sha=845dbd64b87c2c764a9660ced6b06c9e819a44e5&name_0=PR&name_1=AST%20fuzzer%20%28arm_asan_ubsan%29 and provide a fix in a separate PR. If the fix is already in progress, link it here.

@andyzzhao

Copy link
Copy Markdown
Contributor Author

The Stress test (amd_msan) failure is unrelated to this PR: the server cannot restart mid-stress because 04238_storage_alias_missing_target_merge.sql leaves an Alias → Alias chain in metadata and StorageAlias enforces its CREATE-time chain check at ATTACH. New on master since 2026-08-22; 7 stress failures with this signature today across master and unrelated PRs.

Filed: #116207

@groeneai, investigate the failure: https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=114204&sha=845dbd64b87c2c764a9660ced6b06c9e819a44e5&name_0=PR&name_1=Stress%20test%20%28amd_msan%29 and provide a fix in a separate PR. If the fix is already in progress, link it here.

@groeneai

Copy link
Copy Markdown
Collaborator

#116200 (WorkloadSettings.cpp:366): no fix is in progress. I wrote one, #113206, which clamps the ratio in the Float64 domain before narrowing, matching the max_memory_ratio block a few lines below it. @ PedroTadim closed it unmerged on 2026-08-24 as not worth fixing, so reviving it is his call rather than mine. #113697 also fixes a workload overflow, but at ThrottlerConstraint.h:175 rather than this site, so it will not clear this signature.

#116207 (Alias chain rejected at ATTACH): fix in progress, #116153, open since 2026-08-24 16:41 UTC. It moves both Alias target checks out of the storage constructor into the factory, behind the fresh-definition predicate, so metadata load stops re-validating a definition this server already wrote and accepted. It also drops the outer alias in 04238_storage_alias_missing_target_merge right after the read that needs it, so the chain is no longer left in metadata. That arm of the test is mine, from #115896, which merged on 2026-08-24.

@andyzzhao

Copy link
Copy Markdown
Contributor Author

The Stateless tests (amd_llvm_coverage, ParallelReplicas, s3 storage, parallel) failure is a job-level infra error, unrelated to this PR: the runner died before the Tests stage started ("Failed to get start time for [Tests]", container canceled, memory-tracker diagnostics in the tail), so no test ran. Per CIDB this job class fails daily on master and many unrelated PRs.

@groeneai, investigate the failure: https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=114204&sha=845dbd64b87c2c764a9660ced6b06c9e819a44e5&name_0=PR&name_1=Stateless%20tests%20%28amd_llvm_coverage%2C%20ParallelReplicas%2C%20s3%20storage%2C%20parallel%29 and provide a fix in a separate PR. If the fix is already in progress, link it here.

@groeneai

Copy link
Copy Markdown
Collaborator

The tests did run. Correcting the premise first, because it changes what needs fixing.

Failed to get start time for [Tests] is not a failure marker: it is ci/praktika/result.py:149, printed whenever a Result is built without a stopwatch. The passing sibling Stateless tests (amd_llvm_coverage, ParallelReplicas, s3 storage, sequential) at this same commit prints the identical line in its own job.log.

The parallel shard's job.log shows the Tests stage completing: All tests have finished. and No queries hung. at 00:14:49Z, with 13164 tests accounted for across the 9 worker processes (11369 OK, 1795 skipped, 1 FAIL). So that job holds two separate things, not one.

1. One real test failure. 04411_memory_profiler_sample_probability_sql_settings failed on SYSTEM FLUSH LOGS trace_log with Code: 159. DB::Exception: Timeout exceeded (180 s) while flushing system log 'DB::SystemLogQueue<DB::TraceLogElement>'. This is the known LLVM-coverage flush-timeout family: coverage instrumentation slows the server enough to miss the 180 s deadline at src/Common/SystemLogBase.cpp:191. The near-sibling 02818_memory_profiler_sample_min_max_allocation_size.sh already carries no-llvm-coverage, and its tag comment describes this mechanism verbatim. 04411 has the same memory_profiler_sample_probability = 1 plus SYSTEM FLUSH LOGS trace_log shape and is untagged. The precedent fix for this family is that tag (#103219). Nothing in progress covers it, so I will confirm the lever and open a PR, and link it here.

2. The job-level error is a teardown docker-daemon death, and it is the signal loss. After the tests finished, at 00:15:01Z the daemon went away mid-teardown: Error waiting for container: Canceled: grpc: the client connection is closing: context canceled, then docker.sock _ping EOF, then Job killed, exit code [125]. ci/praktika/runner.py:536 converts a still-RUNNING result plus a non-zero exit into ERROR, so a job that executed 13164 tests published 1 CIDB row where the passing sibling published 964. That is what makes the red unattributable.

In progress for this half: #109673 labels exactly this signature infra so retry_infra_failures.yml re-runs the job on a fresh runner. Its predicate requires both Error waiting for container: Canceled and grpc: the client connection is closing; this job's teardown line carries both, so it would have covered this run.

Also relevant to why the shard is exposed at all: #116209 splits these two un-batched coverage parallel shards into 2 batches. This job ran 132 min.

Not caused by this PR: the diff touches none of tests/queries/0_stateless/04411*, praktika, or the coverage job config.

One more correction: the memory-tracker block in the tail is a diagnostic, not a cause. tests/clickhouse-test:6361 prints it whenever MemoryAllocatedWithoutCheck exceeds 1 GiB over the run.

@groeneai

Copy link
Copy Markdown
Collaborator

Fixing PR for the first defect: #116242 (adds no-llvm-coverage to 04411_memory_profiler_sample_probability_sql_settings).

One correction to my earlier comment. I said 04411 was [ FAIL ] 191.35 s in this job at 845dbd64. That is not supportable: the original 22:13:32Z run recorded a single CIDB row with no per-test results, and the artifact I read has since been overwritten by a re-run which shows 04411 [ OK ] 99.32 sec. The failures the PR is about are the two preserved ones, 2026-08-20 in amd_llvm_coverage, 3/3 (#115623) and 2026-07-23 in this same ParallelReplicas, s3 storage, parallel lane (#109174), both Code: 159 ... while flushing system log 'DB::SystemLogQueue<DB::TraceLogElement>'. At 845dbd64 the test passed slowly rather than failing, which is the same defect one step short: over 30 days its p95 in coverage lanes is 185.5 s against a hardcoded 180 s flush deadline, with 2310 of 37668 runs already past it.

The second defect, the job-level error from the docker daemon dying in teardown, needs nothing new from me: #109673 labels that exact signature infra, and #116209 splits these two un-batched coverage parallel shards.

rorylshanks pushed a commit to rorylshanks/ClickHouse that referenced this pull request Aug 25, 2026
04411_memory_profiler_sample_probability_sql_settings runs a query with
memory_profiler_sample_probability = 1, then SYSTEM FLUSH LOGS trace_log,
then asserts a MemorySample row is visible.

SystemLogQueue::waitFlush uses a hardcoded timeout_seconds = 180
(src/Common/SystemLogBase.cpp:191) and waits for getLastLogIndex(), a
server-global queue position, so the flush drains the trace rows of every
concurrently running parallel test rather than only this test's. Under LLVM
source-based coverage instrumentation the server is slow enough that this
crosses 180 s, waitFlush throws at :213 with

  Code: 159. Timeout exceeded (180 s) while flushing system log
  'DB::SystemLogQueue<DB::TraceLogElement>'. (TIMEOUT_EXCEEDED)

and the following SELECT count() > 0 then reads 0, so the coverage lane
reports a false negative rather than only contaminating stderr.

Over 30 days of coverage-lane runs that PASSED, this test has p50 9.6 s and
p95 183.6 s (max 202.3 s) against p50 5.1 s / p95 11.1 s in every other lane,
and 2307 of 37648 coverage runs already exceed 180 s. Two crossed it on the
flush: Stateless tests (amd_llvm_coverage, 3/3) on 2026-08-20 (PR ClickHouse#115623)
and (amd_llvm_coverage, ParallelReplicas, s3 storage, parallel) on 2026-07-23
(PR ClickHouse#109174).

Report for the 2026-08-20 failure:
https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=115623&sha=9b52646c82721f24b7dfb1ddc58d949beef5a7d0&name_0=PR&name_1=Stateless%20tests%20%28amd_llvm_coverage%2C%203%2F3%29

no-llvm-coverage is the established remedy for this mechanism: 36 stateless
tests carry it, and commit 36decd6 ("Mark tests that timed out under LLVM
coverage as no-llvm-coverage") applied it to five tests including this test's
direct sibling 02818_memory_profiler_sample_min_max_allocation_size, whose
shape is identical. 04411 was created two months after that commit, which is
why it was missed.

Coverage is relocated, not lost: the inverse filter at
tests/clickhouse-test:2967-2971 makes Stateless tests
(amd_binary_excluded_from_llvm) run exactly the tagged complement, and the
two flags are mutually exclusive by construction
(ci/jobs/functional_tests.py:608-612). Over 14 days in that job the tagged
siblings 02818 and 01473_event_time_microseconds are OK 4367 and 4365 times
while 04411 is SKIPPED 4367 times. The same intervention on 01473 (ClickHouse#103219,
merged 2026-08-04) took its coverage-lane failures from 5 to 0.

Raising or parameterizing the 180 s constant was rejected: it is a
server-wide change for one test, the constant is already a deliberate
concession to parallel-test load, and because the drain is global a larger
value only moves the threshold.

Validated with the real runner. With the tag, --llvm-coverage skips and
--excluded-from-llvm runs; with the tag removed both verdicts invert, which
is the liveness proof that the arms measure the tag. Without any coverage
flag the test still runs, 10/10.

Related: ClickHouse#114204
@andyzzhao

Copy link
Copy Markdown
Contributor Author

Hey @SmitaRKulkarni are you able to give this a review?

@clickhouse-gh clickhouse-gh Bot added the comp-query-analyzer Semantic analysis + logical/physical planning + rewrites (Analyzer and Planner modules). label Sep 4, 2026
@andyzzhao

Copy link
Copy Markdown
Contributor Author

@PedroTadim are you able to take a look at this?

@PedroTadim

Copy link
Copy Markdown
Member

@andyzzhao I am no expert in this area to review 😞

@andyzzhao

Copy link
Copy Markdown
Contributor Author

Hey @Avogar, do you think you can review this?

@maxknv maxknv added the external Author is not a member of the ClickHouse organization label Nov 2, 2026

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

can be tested Allows running workflows for external contributors comp-query-analyzer Semantic analysis + logical/physical planning + rewrites (Analyzer and Planner modules). external Author is not a member of the ClickHouse organization pr-performance Pull request with some performance improvements

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Map key subcolumn optimization (optimize_functions_to_subcolumns) never applies through Distributed tables

5 participants