Skip to content

Process exact full chunks in const array distance kernels - #104625

Merged
alexey-milovidov merged 17 commits into
ClickHouse:masterfrom
skuznetsov:sk/ch-vector-array-full-chunks
Jun 14, 2026
Merged

alexey-milovidov merged 17 commits into
ClickHouse:masterfrom
skuznetsov:sk/ch-vector-array-full-chunks

Conversation

@skuznetsov

@skuznetsov skuznetsov commented May 11, 2026 •

Copy link
Copy Markdown
Contributor

The remaining diff fixes the exact full-chunk boundary in the hand-written AVX-512 const-left arrayDistance kernels. This is the path used when a constant query vector is compared with an array column.

The affected kernels are L2Distance and cosineDistance for Array(Float32), Array(Float64), and Array(BFloat16). The previous loop condition used <, so when the array length was exactly one vector-width multiple (16 elements for Float32, 8 for Float64, 32 for BFloat16), the last full chunk was skipped by the intrinsic loop and handled by the scalar tail. The new <= condition processes that full chunk while still staying within the exclusive end offset.

The stateless and performance tests are now scoped to these const-left exact-chunk cases, including BFloat16.

Changelog category (leave one):

  • Performance Improvement

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

Improved performance of the AVX-512 const-left paths for L2Distance and cosineDistance on Array(Float32), Array(Float64), and Array(BFloat16) when the array length is exactly divisible by the vectorized processing width.

Documentation entry for user-facing changes

  • Documentation is written (mandatory for new features)

Version info

  • Merged into: 26.6.1.795

Use inclusive full-chunk loop bounds in `arrayNorm` and `arrayDistance` so inputs whose length is exactly divisible by the vector width do not fall back to the scalar tail.

Add exact-boundary stateless coverage and a focused performance test for norm and distance functions.
@CLAassistant

CLAassistant commented May 11, 2026 •

Copy link
Copy Markdown

CLA assistant check
All committers have signed the CLA.

@alexey-milovidov alexey-milovidov added the can be tested Allows running workflows for external contributors label May 11, 2026

@alexey-milovidov alexey-milovidov left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Thanks, amazing finding!

@clickhouse-gh

clickhouse-gh Bot commented May 11, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [ce75632]

Summary: ✅


AI Review

Summary

This PR now narrows to processing exact full chunks in the AVX-512 const-left arrayDistance kernels for L2Distance and cosineDistance, with focused stateless coverage and a new performance test. I did not find a concrete correctness or safety defect in the changed loop bounds: the const-left caller verifies each right-hand array has the same length as the constant left array before the AVX-512 helper advances i_x and i_y together.

Missing context / blind spots
  • ⚠️ The current PR report for ce756329a0a0044eecfb97fc249fc74cc8fa0d70 still has all Performance Comparison shards in PENDING, and the corresponding all-query-metrics.tsv files are not available yet. Completed performance comparison output, or equivalent before/after numbers for tests/performance/array_distance_const_exact_chunks.xml, would close this gap.
  • ⚠️ There is no local clickhouse binary or build directory in this checkout, so I could not run 04107_array_distance_const_full_chunk or the new performance test locally.
Tests
  • ⚠️ The stateless test is useful as a const-left boundary smoke test, but it would still produce the same results if this performance-only < to <= change were reverted and the exact chunk fell back to the scalar tail. The material evidence for this Performance Improvement is therefore the performance comparison for array_distance_const_exact_chunks, which is still pending for the current SHA.
Final Verdict

Status: ⚠️ Request changes

Minimum required action: provide completed before/after performance evidence for the current head, preferably from the new array_distance_const_exact_chunks performance test. No code-line blocker found in the current diff.

@alexey-milovidov alexey-milovidov self-assigned this May 11, 2026
@clickhouse-gh clickhouse-gh Bot added the pr-performance Pull request with some performance improvements label May 11, 2026
Update the existing `arrayNorm` reference for the new accumulation order.

Add exact and near-exact `cosineDistance` boundary checks to cover the modified loop bounds.
@clickhouse-gh clickhouse-gh Bot added the manual approve Manual approve required to run CI label May 29, 2026
These changes to CI workflow / infrastructure files were unrelated to the
purpose of this pull request and were introduced accidentally (stale base
branch). Restoring them to match `master`.
@alexey-milovidov alexey-milovidov removed the manual approve Manual approve required to run CI label May 31, 2026
@alexey-milovidov

Copy link
Copy Markdown
Member

Merged master into the branch (it was 709 commits behind; no conflicts). This picks up the noexcept fix for the chronic QueryPlanResourceHolder::operator= terminate (Assertion 'px != 0' failed, STID 3678) that was hitting the px != 0 stress failures here.

Verified the change locally on an ARM build:

  • 04107_vector_norm_full_chunk — matches reference.
  • 02283_array_norm — matches the updated reference; the single changed digit (...68000 → ...70000) is the expected floating-point summation-order drift from now processing the exact-divisible final chunk with the vectorized multi-accumulator loop instead of the scalar tail. The change reads only within the exclusive end offset, so it does not read past the array.

Remaining CI failures are unrelated to this loop-bound change and not invoking the affected functions:

  • Coordination mode mismatch (STID 7334) — ParallelReplicasReadingCoordinator internals (master recently added 04278_parallel_replicas_coordinator_mode_collision).
  • Bad cast (STID 3524) — Aggregator::executeOnBlock via AST fuzzer.
  • Server died — chronic stress/stateless flake.

@clickhouse-gh

clickhouse-gh Bot commented Jun 3, 2026 •

Copy link
Copy Markdown
Contributor

📊 Cloud Performance Report

🟢 AI verdict: improvement — 3 query(s) improved out of 38 analysed

This PR is a narrow off-by-one fix to the AVX-512 kernels of L2Distance/cosineDistance (arrayDistance.cpp), plus new performance and stateless tests. None of the flagged ClickBench or TPC-H queries use vector-distance functions, so none of these deltas can be attributed to the change. The smaller-magnitude flags (clickbench Q15/Q22 and tpch Q8) were downgraded as environment variance; a few large deltas (clickbench Q23, tpch Q7/Q20) clear the automatic high-confidence trust bar and stay flagged, but they are equally unrelated to the diff and should be read as run-to-run/build variance.

clickbench

🟢 1 improved · ⚠️ 2 inconclusive

Flagged queries (3 of 43)
Query Verdict Baseline med (ms) PR med (ms) Change q-value Hint
🟢 23 improvement 297 207 -30.3% <0.0001 Large consistent -30% delta clears the auto-trust bar, but PR only touches vector-distance kernels Q23 never calls
⚠️ 15 not_sure 246 220 -10.6% <0.0001 PR only fixes AVX-512 vector-distance kernels; Q15 calls no array-distance funcs, off-path delta
⚠️ 22 not_sure 334 261 -21.9% <0.0001 Off-path: PR touches only L2/cosineDistance SIMD loops, not Q22's execution path

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

🟢 2 improved · ⚠️ 2 inconclusive

Flagged queries (4 of 22)
Query Verdict Baseline med (ms) PR med (ms) Change q-value Hint
🟢 7 improvement 113 77 -31.9% <0.0001 Clear -32% delta locks the verdict, but PR only edits vector-distance SIMD; read as build/env variance
🟢 20 improvement 248 129 -48.0% <0.0001 -48% on a noisy query clears auto-trust bar, but off-path from this SIMD-only diff; treat cautiously
⚠️ 4 not_sure 3015 3282 +8.9% 0.0477 Borderline and off-path; PR is a SIMD array-distance fix unrelated to this query
⚠️ 8 not_sure 156 188 +20.9% <0.0001 Off-path: PR fixes arrayDistance kernels; Q8 uses no vector-distance funcs, +21% is env variance

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: 95b45517-4537-4b3f-abd6-6a9e6c393332
  • MIRAI run: 6fad1190-77f3-4e60-b802-80a8772c42ea
  • PR check IDs:
    • clickbench_111136_1781459289
    • clickbench_111150_1781459289
    • clickbench_111154_1781459289
    • tpch_adapted_1_official_111162_1781459289
    • tpch_adapted_1_official_111175_1781459289

…full-chunks

# Conflicts:
#	src/Functions/array/arrayNorm.cpp
@alexey-milovidov

Copy link
Copy Markdown
Member

Merged master and resolved a conflict in arrayNorm.cpp.

While this PR was open, master independently refactored the array norm functions into the multitarget normBatchImpl, which already processes every full chunk correctly (count / unroll_count * unroll_count). The off-by-one this PR fixed in the norm loop is therefore already gone on master, so I took master's version of arrayNorm.cpp and reverted the 02283_array_norm.reference change (the value differs only by float-rounding due to a different accumulation order).

The distance functions in arrayDistance.cpp were not rewritten on master, so the < → <= fix there is still valid and needed. After the merge this PR is scoped to the distance functions; I narrowed the description and changelog entry accordingly. The new functional test still exercises the norm functions as well, as a regression guard.

Verified locally (built clickhouse, ran 04107_vector_norm_full_chunk and 02283_array_norm via clickhouse local): both pass.

The remaining CI red is an unrelated Logical error: Column identifier A is already registered from the AST fuzzer, hit on a random ALTER ... mutation with an IN subquery (MutationsInterpreter::validate → buildSubqueryPlansForSetsAndAdd). This is a known master-wide issue tracked and fixed by #106414, unrelated to this change.

The shared vectorized loops in `arrayDistance` are instantiated for every
distance kernel, so the exact-full-chunk boundary change affects `L1Distance`,
`L2SquaredDistance`, `LpDistance`, and `LinfDistance` too, not only
`L2Distance` and `cosineDistance`.

Extend the stateless test `04107_vector_norm_full_chunk` with exact-boundary
(length 16) and one-past-the-boundary (length 17) assertions for the other
distance functions, exercising both the materialized and the
`executeWithLeftArgConst` const-left paths, and extend the performance test
`norm_distance_exact_chunks` to measure all changed kernels.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
@alexey-milovidov

Copy link
Copy Markdown
Member

Status: all review threads are resolved and CI is green except a single failure in BuzzHouse (arm_asan_ubsan): Logical error: Mutation of Memory table produced incomplete output: A (STID 2380-3043), triggered by ALTER TABLE ... APPLY PATCHES in StorageMemory::mutate. It is unrelated to this PR (which only changes loop bounds in arrayDistance.cpp plus tests) and fails across dozens of PRs and master daily.

Related: #106846
Related: #106621
Related: #105286

No further changes are needed here; the PR is ready to merge once that flake is disregarded or fixed.

@alexey-milovidov

Copy link
Copy Markdown
Member

Restarted the failed BuzzHouse (arm_asan_ubsan) job. The failure (STID 2380-3043, StorageMemory::mutate abort on APPLY PATCHES) is the known unrelated issue #106846; the fixes (#105286, #106621) are not merged yet, but the fuzzer only hits it on a fraction of runs, so a rerun should go green. No code changes needed.

…full-chunks

# Conflicts:
#	src/Functions/array/arrayDistance.cpp
@alexey-milovidov

Copy link
Copy Markdown
Member

Merged master again and resolved a conflict in arrayDistance.cpp.

While this PR was open, master refactored the array distance functions into the multitarget executeDistanceImpl, which processes every full chunk correctly (count / unroll_count * unroll_count) — the same refactor that earlier subsumed the norm part of this PR via normBatchImpl. So the off-by-one fix this PR applied to the generic hand-written VEC_SIZE loops is no longer needed there, and I took master's side for those two regions (the loops are gone, replaced by the executeDistance/executeDistanceConst calls).

However, master still carries the off-by-one in the hand-written AVX-512 intrinsic kernels (accumulateCombineF32F64, accumulateCombineBF16 for L2Distance and CosineDistance), which are reached from the const-left path — the common vector-search case (constant query vector against a column). The PR's < i_max -> <= i_max fix is preserved there, so after the merge the diff vs master is exactly those 4 one-character changes plus the tests:

 src/Functions/array/arrayDistance.cpp            |  8 +--
 tests/performance/norm_distance_exact_chunks.xml | 60 ++++++++++++++++++
 .../04107_vector_norm_full_chunk.reference       | 24 ++++++++
 .../0_stateless/04107_vector_norm_full_chunk.sql | 31 +++++++++++

Compiled arrayDistance.cpp locally after the merge (clean, no warnings).

Scope the stateless and performance tests to the remaining PR surface: the AVX-512 const-left paths for `L2Distance` and `cosineDistance`.

Add exact-boundary coverage for `Array(Float32)`, `Array(Float64)`, and `Array(BFloat16)`, including BF16 coverage with `allow_experimental_bfloat16_type`.

Related: ClickHouse#104625
@skuznetsov skuznetsov changed the title Process exact full chunks in vector array functions Process exact full chunks in const array distance kernels Jun 14, 2026
@clickhouse-gh

clickhouse-gh Bot commented Jun 14, 2026

Copy link
Copy Markdown
Contributor

LLVM Coverage Report

Metric Baseline Current Δ
Lines 84.80% 84.70% -0.10%
Functions 92.40% 92.30% -0.10%
Branches 77.30% 77.30% +0.00%

Changed lines: Changed C/C++ lines covered by tests: 12/12 (100.00%) | Lost baseline coverage (was covered on master, now uncovered in this PR): 7 line(s) · Uncovered code

Full report · Diff report

@alexey-milovidov
alexey-milovidov added this pull request to the merge queue Jun 14, 2026
Merged via the queue into ClickHouse:master with commit 92a53f9 Jun 14, 2026
166 checks passed
@robot-ch-test-poll2 robot-ch-test-poll2 added the pr-synced-to-cloud The PR is synced to the cloud repo label Jun 14, 2026
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 pr-performance Pull request with some performance improvements 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.

4 participants