Skip to content

Evaluate randomHadamardTransform once for a constant vector - #112921

Merged
alexey-milovidov merged 11 commits into
masterfrom
random-hadamard-transform-const
Aug 13, 2026
Merged

alexey-milovidov merged 11 commits into
masterfrom
random-hadamard-transform-const

Conversation

@alexey-milovidov

@alexey-milovidov alexey-milovidov commented Aug 1, 2026 •

Copy link
Copy Markdown
Member

randomHadamardTransform did not use the default implementation for constant arguments, so it called convertToFullColumnIfConst on its first argument and ran the transform for every row of the block even when the vector was a constant. It also returned a plain ColumnArray rather than a ColumnConst, so the analyzer could not fold the call to a literal either (resolveFunction.cpp only folds when the executed column is a ColumnConst).

This matters for the intended vector search usage, where the query vector has to be rotated the same way as the stored vectors:

WITH randomHadamardTransform([...]) AS target
SELECT id FROM t
ORDER BY cosineDistanceTransposedQuantized(vec_quantized, target, 2, 384)
LIMIT 100

On 2 million 768-dimensional vectors (QBit(Int8, 768, 128), 2 bits and 384 dimensions, 64-core machine, warm cache):

before after
transform written inline in the query 2.744 s 0.144 s
transform hidden in a scalar subquery (computed once) 0.148 s 0.126 s

The whole difference was the transform of the constant query vector being repeated for every row; after the change the inline form costs the same as the hand-rolled workaround.

The fix sets useDefaultImplementationForConstants and declares seed and output_dims in getArgumentsThatAreAlwaysConstant, so an all-constant call is executed on a single row and wrapped in a ColumnConst. The constant check for seed and output_dims now comes from the base class, with the same ILLEGAL_COLUMN error code as before.

Related: #103466

Changelog category (leave one):

  • Performance Improvement

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

randomHadamardTransform of a constant vector is now evaluated once instead of once per row. This speeds up vector search queries that rotate the query vector with randomHadamardTransform before comparing it against a QBit column.

Version info

  • Backported to: 26.7.4.41

`randomHadamardTransform` did not use the default implementation for
constant arguments, so it called `convertToFullColumnIfConst` on its
first argument and ran the transform for every row of the block even
when the vector was a constant. It also returned a plain `ColumnArray`
rather than a `ColumnConst`, which prevented the analyzer from folding
the call to a literal.

This matters for the intended vector search usage, where the query
vector has to be rotated the same way as the stored vectors:

    WITH randomHadamardTransform([...]) AS target
    SELECT id FROM t
    ORDER BY cosineDistanceTransposedQuantized(vec_quantized, target, 2, 384)
    LIMIT 100

On 2 million 768-dimensional vectors this query took 2.744 s, while the
same query with the transform hidden in a scalar subquery (so that it is
computed once) took 0.148 s.

Set `useDefaultImplementationForConstants` and declare `seed` and
`output_dims` in `getArgumentsThatAreAlwaysConstant`, so that an
all-constant call is executed on a single row and wrapped in a
`ColumnConst`. The constant check for `seed` and `output_dims` now comes
from the base class; its error code is still `ILLEGAL_COLUMN`.

Related: #103466
@clickhouse-gh

clickhouse-gh Bot commented Aug 1, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [ae40953]

Summary: ✅


AI Review

Summary

This PR switches randomHadamardTransform onto the default constant-argument path so a constant vector is evaluated once, returned as a ColumnConst, and foldable by the analyzer. I re-checked the current code, the prior review thread, the added stateless coverage, and the latest PR CI report; I did not find any remaining correctness, compatibility, or performance-contract issues.

Final Verdict

✅ Approve

LLVM Coverage Report

Metric Baseline Current Δ
Lines 86.70% 86.70% +0.00%
Functions 92.00% 92.00% +0.00%
Branches 79.00% 79.10% +0.10%

Changed lines: Changed C/C++ lines covered: 18/20 (90.00%) · Uncovered code

Full report · Diff report

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

clickhouse-gh Bot commented Aug 1, 2026 •

Copy link
Copy Markdown
Contributor

📊 Cloud Performance Report

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

This PR only modifies the randomHadamardTransform function used in vector search (constant-folding a fully-constant call). No ClickBench query exercises that path, so the flagged -11.6% improvement on Q17 (GROUP BY UserID/SearchPhrase) cannot plausibly be attributed to this change and is downgraded to not_sure as measurement variance. Both the private and public diffs are identical and touch only this one function plus its test and docs, so no per-query performance effect is expected.

clickbench

⚠️ 1 inconclusive

Flagged queries (1 of 43)
Query Verdict Baseline median (ms) PR median (ms) Change q-value Hint
⚠️ 17 not_sure 556 492 -11.6% <0.0001 This PR only changes randomHadamardTransform (a vector-search function), which ClickBench Q17 never calls, so the -11.6% shift cannot come from this diff and reads as run-to-run variance.

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

🟢 No significant changes

Debug info
  • StressHouse run: 5eb606fe-f25e-42f8-9b18-a2d48798d59e
  • MIRAI run: 1071f3f1-307a-491e-9f38-a2e628403cf6
  • PR check IDs:
    • clickbench_961148_1786568693
    • clickbench_961159_1786568694
    • clickbench_961166_1786568694
    • tpch_adapted_1_official_961178_1786568693
    • tpch_adapted_1_official_961205_1786568693
    • tpch_adapted_1_official_961219_1786568693

@clickhouse-gh

clickhouse-gh Bot commented Aug 1, 2026

Copy link
Copy Markdown
Contributor

LLVM Coverage Report

Metric Baseline Current Δ
Lines 86.50% 86.50% +0.00%
Functions 91.90% 91.90% +0.00%
Branches 78.70% 78.70% +0.00%

Changed lines: Changed C/C++ lines covered: 9/11 (81.82%) · Uncovered code

Full report · Diff report

@alexey-milovidov

Copy link
Copy Markdown
Member Author

🕵 Merged master into the branch.

The two CI reds — Logical error: Query context must be created after authentication in PostgreSQLHandler::cancelRequest on Stress test (amd_tsan) and Stress test (arm_asan_ubsan) — are unrelated to this PR (it only touches randomHadamardTransform). They come from the PostgreSQL handler change in #110760, which has since been reverted on master, and the reapply with the cancel-request fix is #112940. Merging master should clear them on the next run.

The Q23 +97.4% ClickBench regression in the cloud benchmark report is off-path as well (ClickBench does not execute randomHadamardTransform); the report itself flags it as environmental and asks for a rerun.

Related: #112940

@clickhouse-gh

clickhouse-gh Bot commented Aug 3, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing ae40953ce with master bb1bd3074 (stripped binary size, per-symbol sizes and ThinLTO time; object sizes against the warmup build of 2e330af4c; compile times per translation unit against the most recent warmup build that recompiled it).

✅ No significant changes.

Binary sizes
Binary Master PR Δ
programs/clickhouse-stripped 692.05 MiB 689.04 MiB -3.01 MiB (-0.43%)

Only the stripped binary is compared: the official master build keeps debug symbols while PR builds strip them, so the other binaries differ by construction.

Compile time of recompiled translation units

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

Job report

@alexey-milovidov

Copy link
Copy Markdown
Member Author

🕵 Merged master into the branch again.

The only CI red on the previous run — AST fuzzer (amd_debug) failing with Logical error: '!part.empty()' on EXPLAIN AST optimize = 1 over a Distributed table with an empty remote database under distributed_product_mode = 'local' — is unrelated to this PR (which only touches randomHadamardTransform). The same failure hits many unrelated PRs (#110975, #110633, #110493, #109768), and a fix is already open: #110677.

alexey-milovidov and others added 2 commits August 4, 2026 19:50
…ransform

Address review: `output_dims` is documented to never exceed the transform
length, but the `k > working_dim` check lives inside the `length != 0`
branch, so a positive `output_dims` on an empty vector silently returned
`[]` instead of throwing. Throw `ARGUMENT_OUT_OF_BOUND` for that case and
cover both the constant and the per-row paths in the test.

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

Copy link
Copy Markdown
Member Author

🕵 Addressed the AI review finding: an explicit output_dims on an empty vector is now rejected with ARGUMENT_OUT_OF_BOUND instead of silently returning [] (it exceeds the transform length 0), with test coverage for both the constant and the per-row paths. Also merged master into the branch again.

The only CI red on the previous run — Stress test (arm_release) failing with Test script failed — is unrelated to this PR: the stress harness's install_thread_pool_fault_injection verification query (clickhouse client -q "SELECT value FROM system.server_settings WHERE name = 'cannot_allocate_thread_fault_injection_probability'") timed out after SYSTEM RELOAD CONFIG under thread-fuzzer load and killed the whole script before any test could run. A fix is already open: #113248 (retries that verification query on client timeout).

alexey-milovidov and others added 2 commits August 5, 2026 17:17
The previous commit made an explicit `output_dims` on an empty vector
throw `ARGUMENT_OUT_OF_BOUND`. That behavior change broke the existing
`04408_random_hadamard_transform`, which pins the released behavior:
an empty input array yields an empty array and `output_dims` does not
apply to it. Rejecting it would also turn a column that merely contains
some empty arrays into a query-wide error, so restore the original
semantics and assert them in the new test instead.

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

Copy link
Copy Markdown
Member Author

🕵 The only CI red on a8477070 was the Fast test failure of 04408_random_hadamard_transform, and it was caused by this PR: the previous commit made an explicit output_dims on an empty vector throw ARGUMENT_OUT_OF_BOUND, but that test pins the released behavior (an empty input array yields an empty array (output_dims does not apply)).

Reverted that behavior change in 22c8469c3a9 - the empty-vector semantics are back to what 26.7 shipped, the embedded docs state them explicitly, and the new test asserts them for both the constant and the per-row paths. Details in the review thread reply. Also merged master into the branch again.

Verified locally with a RelWithDebInfo build: both 04408_random_hadamard_transform and 04660_random_hadamard_transform_constant_folding match their references.

@alexey-milovidov

Copy link
Copy Markdown
Member Author

🕵 Merged master into the branch again. Both CI reds on the previous run are unrelated to this PR (it only touches randomHadamardTransform):

@alexey-milovidov

Copy link
Copy Markdown
Member Author

🕵 The only CI red on 1e13d781 — Stress test (arm_tsan) failing with Logical error in IColumn::assertTypeEquality from IColumn::insertFrom inside buildAdditionalFilter (src/Interpreters/HashJoin/HashJoinMethodsImpl.h) — is unrelated to this PR (it only touches randomHadamardTransform). It is the known type mismatch when a mixed JOIN ON condition is evaluated over right columns resolved by name against the stored right blocks; the fix is already in progress: #113534. I will merge master into this branch once that fix lands.

Report: https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=112921&sha=1e13d78186159302285c682c8d7c34137e04fac9&name_0=PR&name_1=Stress%20test%20%28arm_tsan%29

Otherwise the PR is ready: AI review verdict is "✅ Approve" and there are no unresolved review threads.

kute1654 pushed a commit to kute1654/ClickHouse that referenced this pull request Aug 10, 2026
…viewIfPermitted

The parser accepts only a function call after ELSE in `viewIfPermitted`
(the argument is a table function such as `null('structure')`), but the
formatter used the generic expression path for it, so a function that is
normally written as an operator (e.g. `not`) was formatted as `ELSE NOT x`,
which cannot be parsed back. Found by AST fuzzer: the query
`... viewIfPermitted(SELECT ... ELSE not(...)) ...` failed the AST
formatting consistency check with a logical error.

Format the ELSE argument with `allow_operators = false` so it keeps the
function-call form.

Report: https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=112921&sha=22a3a1e446758ffbb12704d86470c4c27a4e73a2&name_0=PR&name_1=AST%20fuzzer%20%28amd_debug%29
Found in: ClickHouse#112921

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

Copy link
Copy Markdown
Member Author

🕵 CI on ba9c3d4c had a single red: Stateless tests (amd_debug, sequential) — 00180_no_seek_avoiding_when_reading_from_cache (CachedReadBufferReadFromSourceBytes was 10667287 instead of 0, i.e. the filesystem cache was not fully warm after the two warm-up queries). Unrelated to this PR, which only touches randomHadamardTransform. The harness itself labelled it flaky and all 7 reruns with the same randomized settings passed, and this test has a long history of the same flakiness (#66190, #66683, #67467 — all closed, no open tracking issue).

@groeneai, please investigate this flake: https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=112921&sha=ba9c3d4cc9183c01f61bc5383eabc5f5d42adc22&name_0=PR&name_1=Stateless%20tests%20(amd_debug,%20sequential) and provide a fix in a separate PR (open a tracking issue too, since the previous ones are closed). If a fix is already in progress, link it here.

Merged master (6th time, 72460eea6438, clean) to get a fresh CI run; src/Functions/randomHadamardTransform.cpp still compiles and the PR diff is unchanged (3 files).

@groeneai

Copy link
Copy Markdown
Collaborator

No fix in progress: no open PR touches this test, and the three earlier issues are closed. I opened #114213 to track it, and I am working on the fix.

Root cause from the failing run: the cache was already full of non-releasable segments when the test warmed up, so nothing could be evicted for its own data.

CachedOnDiskReadBufferFromFile(...): No space left in cache to reserve 234949 bytes,
reason: cannot evict enough space (stat: releasable size: 0, releasable count: 0,
non-releasable size: 209715200, non-releasable count: 40, ...
total size: 209715200/209715200, total elements: 41/10000000), will continue without cache download

non-releasable size is exactly max_size (200 MiB in 40 segments of 5 MiB) with releasable size: 0, and the background thread agrees: Free space ratio keeping thread finished with status CANNOT_EVICT, evicted 0 file segments. With nothing reservable, the read falls back to REMOTE_FS_READ_BYPASS_CACHE and increments CachedReadBufferReadFromSourceBytes, so both warm-up queries failed to populate the cache and the measured query genuinely read from S3.

The test's SYSTEM CLEAR FILESYSTEM CACHE cannot recover from this: it calls removeAllReleasable, so segments another reader holds survive it.

In that same job, of the 8 runs of the measured query only the failing one logged any cache-pressure lines (18 of them); all 7 reruns logged zero. That is what makes it look random.

The test already has no-parallel, no-random-settings, no-flaky-check and no-asan, so this is neither settings randomization nor same-set parallelism: the sequential job still runs the parallel group alongside, sharing one 200 MiB s3_cache.

The assertion is on an absolute byte counter that requires a fully warm cache, which the test cannot guarantee on a shared cache. I will fix it by giving the test its own cache disk, or by verifying the warm-up instead of assuming it, and will link the PR on #114213 and here.

@groeneai

Copy link
Copy Markdown
Collaborator

Fix: #114245, tracked by
#114213.

The table is CREATE TABLE hits_s3_sampled AS test.hits_s3, so it inherits
storage_policy = 's3_cache' and shares the one 200 MiB cache with everything else on the server,
including the background merges of test.hits_s3 that write through it. Once those hold every
segment non-releasable, reservation has nothing to evict, both warm-ups silently continue without
caching, and the measured query reads from S3. SYSTEM CLEAR FILESYSTEM CACHE cannot help, since it
removes only releasable segments.

The PR gives the table its own inline cache disk and leaves the assertion, the reference file and the
tags alone. I reproduced the failure locally with a concurrent workload that keeps the shared cache
full of held segments: the unfixed test failed 18 of 20 runs, the fixed one passed 50 of 50 under the
same workload.

@alexey-milovidov

Copy link
Copy Markdown
Member Author

🕵 The three Stress test failures on 72460ee are unrelated to this PR (it only changes constant handling of randomHadamardTransform plus a test; none of the failing runs involve the function):

@groeneai, the fixes are already in progress (linked above) — once they land on master, a re-merge should clear these reds.

@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.

Trivial.

@alexey-milovidov alexey-milovidov self-assigned this Aug 13, 2026
@alexey-milovidov
alexey-milovidov added this pull request to the merge queue Aug 13, 2026
Merged via the queue into master with commit 3ef0098 Aug 13, 2026
180 checks passed
@alexey-milovidov
alexey-milovidov deleted the random-hadamard-transform-const branch August 13, 2026 00:42
@robot-ch-test-poll robot-ch-test-poll added the pr-must-backport-synced The `*-must-backport` labels are synced into the cloud Sync PR label Aug 13, 2026
@robot-clickhouse-ci-1 robot-clickhouse-ci-1 added pr-backports-created Backport PRs are successfully created, it won't be processed by CI script anymore pr-synced-to-cloud The PR is synced to the cloud repo labels Aug 13, 2026
clickhouse-gh Bot added a commit that referenced this pull request Aug 14, 2026
Backport #112921 to 26.7: Evaluate randomHadamardTransform once for a constant vector
@PedroTadim

Copy link
Copy Markdown
Member

@alexey-milovidov are there performance tests for randomHadamardTransform?

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

Labels

pr-backports-created Backport PRs are successfully created, it won't be processed by CI script anymore pr-must-backport-synced The `*-must-backport` labels are synced into the cloud Sync PR pr-performance Pull request with some performance improvements pr-synced-to-cloud The PR is synced to the cloud repo v26.7-must-backport

Projects

None yet

Development

Successfully merging this pull request may close these issues.

5 participants