Repository navigation
Bound the vector search limit of mergeTreeAnalyzeIndexes by max_limit_for_vector_search_queries - #122154
Conversation
…_for_vector_search_queries The bound on a vector search limit is a plan-optimization precondition rather than a property of VectorSearchParameters, and the introspection table function builds those parameters itself without re-establishing it. useVectorSearch.cpp returns no_layers_updated when the LIMIT exceeds max_limit_for_vector_search_queries (default 1000), so a regular ORDER BY <distance> LIMIT 2147483648 never reaches the approximate search at all and falls back to brute force. That gate is the only thing keeping the value small: ReadFromMergeTree::setVectorSearchParameters is called from behind it, and the remote query that distributed index analysis formats can therefore only carry a limit that already passed it. TableFunctionMergeTreeAnalyzeIndexes is the second producer of the same struct, and it validates the type of the limit parameter without ever comparing it against the setting, so a fuzzer-sized value reached usearch unchanged. The one bound inside the index is conditional on additional_filters_present or on vector_search_with_rescoring, both false by default, so it did not apply either. usearch then reserves eight bytes per requested neighbour twice per granule searched (index.hpp computes expansion as max(config.expansion, wanted) and reserves both the next and the top candidate buffers). At 2147483648 neighbours that is 16.0 GiB per reservation and 32 GiB per granule search, taken through a raw aligned_alloc whose pages are never touched. On a server the memory tracker therefore charges 32 GiB while RSS stays at a few hundred MiB, the tracker is exhausted, and every later session fails with "(total) memory limit exceeded" including the hung check's own client. Measured on a debug server capped at 9.31 GiB: the query returned a normal result, tracked memory settled at 32.31 GiB against an RSS of 400 MiB, and the two stateless tests that ran next could not so much as create their database, both failing with code 241; afterwards even SELECT value FROM system.metrics failed the same way, so one SELECT leaves the server unable to answer anything. With this change the same query is rejected before any reservation and both of those tests pass. The check goes where the value enters, mirroring the planner's comparison exactly so that the introspection function accepts precisely the set of limits for which the optimization it reports on exists. It is a sixth per-parameter helper beside the five that already validate this argument list, so the error names the parameter from the same table they use, and the braced initializer keeps its left-to-right validation order: a list with several malformed parameters still reports the first of them rather than the limit. Both entry points share parseArgumentsForOptimizations, so mergeTreeAnalyzeIndexes and mergeTreeAnalyzeIndexesUUID are covered by the one comparison, and it runs before executeImpl, before any part is read and before anything is reserved. Making the in-index clamp unconditional instead would have let an introspection function report the ranges for limit 1000 when asked about 2147483648, and after this change both producers of VectorSearchParameters are bounded anyway. A raised max_limit_for_vector_search_queries still reaches a remote node with the query, so a legitimate distributed vector search cannot trip the new check: over a real remote connection a limit of 2000 succeeds at max_limit_for_vector_search_queries = 5000 and is rejected at the default 1000. Reported by alexey-milovidov on ClickHouse#112824 from a Stress test (arm_release) hung check, where the AST fuzzer mutated 02354_vector_search_distributed_index_analysis into mergeTreeAnalyzeIndexesUUID(..., array('vec', toFixedString('L2Distance', 10), 2147483648, ...)).
…e cap The in-bound arms select the analysed ranges rather than counting rows. A count is true even when vector index analysis produced nothing, because StorageMergeTreeAnalyzeIndexes also emits a row for every source part the analysis did not cover, with a default-constructed ranges column, so such an arm would only assert that the call did not throw and a change that made an in-bound limit silently stop using the index would keep it green. On this fixture a limit of 4 gives all_1_1_0 [(3,5)], two of the part's thirteen granules, where a limit large enough to cover every row gives [(0,13)], which is also what the unbounded call returns on a binary without the fix. The assertion therefore observes the narrowing rather than the absence of an exception. The exact ranges are stable because the table fixes index_granularity itself, which beats the test runner's randomized value: fifty randomized runs produced no reference mismatch. One arm sets the limit equal to the cap, immediately above the arm that rejects a limit one above its cap, so the pair pins both directions of the comparison rather than only its far side. This matters beyond style. Both plan optimizations gate with a strict comparison, so a regular vector search whose LIMIT is exactly the cap is rewritten, and distributed index analysis serializes that limit verbatim into the replica-side mergeTreeAnalyzeIndexesUUID query; a non-strict comparison here would fail such a query on every replica while succeeding on the initiator, and at the default cap of 1000 that is a plausible production LIMIT. Verified by mutation: rebuilding with a non-strict comparison reddens this arm and only this arm. Both boolean parameters are left false and vector_search_with_rescoring is left at its default, because those two conditions are what engage the separate, pre-existing bound inside the index, which would hide a missing bound here.
Internal second-model review: adjudication log (click to expand)Pre-publication review by an independent model (engine: codex), three rounds against three heads: one
One thing I looked at and am deliberately not treating as a defect: raising Severity: ❌ blocker / Session id: cron:clickhouse-review-slot-9:20260925-035100 |
|
Workflow [PR], commit [217b54c] Summary: ❌
AI ReviewSummaryThis PR makes Tests
Final Verdict
LLVM Coverage ReportMeasured on commit 217b54c.
Changed lines: Changed C/C++ lines covered: 16/16 (100.00%) · Uncovered code |
| -- The bound is the setting, and it is inclusive: the planner uses the index at a LIMIT equal to the | ||
| -- setting, so this function must accept exactly that. | ||
| SELECT * FROM mergeTreeAnalyzeIndexes(currentDatabase(), t_vector_index_analysis_limit, 1, [], | ||
| 'vector_search_index_analysis', array('vec', 'L2Distance', 4, [0.3, 0.3], false, false)) |
There was a problem hiding this comment.
The new check reads max_limit_for_vector_search_queries from the current Context, so the risky success case here is not just “mergeTreeAnalyzeIndexes and mergeTreeAnalyzeIndexesUUID share a parser”. It is whether a raised query-local cap reaches the replica-side mergeTreeAnalyzeIndexesUUID call used by distributed index analysis at all.
This test only exercises the local table-function path with a cap of 4. It will stay green even if distributed index analysis stops forwarding a larger max_limit_for_vector_search_queries and a valid query such as LIMIT 2000 SETTINGS max_limit_for_vector_search_queries = 5000 starts failing with BAD_ARGUMENTS on replicas. Please add a distributed case, likely by extending 02354_vector_search_distributed_index_analysis.sql, where the limit is above the default 1000 but below a query-local cap so the remote UUID path has to accept it.
Build profile diff (arm_release)Comparing ✅ No significant changes. Binary sizes
The official master build is compiled with Compile time of recompiled translation units7 translation units recompiled, 13 s compile time in total, 7 of them have a recent master baseline. |
Picks up ClickHouse#122073, which passes --stop-merges to the measured performance runs. Before it only the confirm_changes rerun stopped background merges, so the measured samples that feed the dashboard verdict were taken while merges ran. The two dashboard-confirmed regressions on the previous head, optimize_time_filter_with_preimage ClickHouse#6 and index_bulk_filtering ClickHouse#2, are of that noise class: the shard's own report calls the first unstable and the second successful, and neither query can reach this diff, which only parses the vector search arguments of mergeTreeAnalyzeIndexes.
CI finish ledger - 0b0017eEvery failure below has an owner. Only
Why merging master is the response to both performance rows rather than a change here: until #122073 merged this morning, only the Session id: cron:clickhouse-maint-slot-14:20260925-112800 |
CI finish ledger - c06c902Every failure below has an owner: a fixing PR (mine or external), or a full-effort fix task
All 173 check runs completed (129 pass, 41 not selected, 3 red), Session id: cron:our-pr-ci-monitor:20260925-182007 |
|
Fixing PR for the Correction to the reason in the ledger above: the crashing table was not the JSON one. The fuzzer had re-created |
|
Fixing PR for the |
Since ClickHouse#122073 the measured perf.py runs stop merges on both servers right after the fill. The old fill writes 54 parts in about a second, so each server keeps whatever part set its background merges reached, and the two servers of one run measure different layouts (21 vs 38 parts on ClickHouse#122222, 24 vs 44 on ClickHouse#122154, 22 vs 44 on master 52a67f8). FINAL ... ORDER BY x DESC LIMIT n reads the first reverse ranges of every part (about 23K rows each), so its time grows with the part count, and the dashboard scores the side with more parts as a confirmed regression. The fill now merges the first insert, stops merges on the table and writes the second insert as exactly one part, so both servers read the same two parts whatever the merge timing, like final_read_in_order_limit.xml: - OPTIMIZE ... FINAL waits for the running merges before it selects, so the background merges of the first insert cannot leave it partial, and optimize_throw_if_noop = 1 makes a no-op OPTIMIZE fail with its reason instead of surfacing as a wrong part count. - min_insert_block_size_rows = 16777216 (2^24, above the 10M rows) with min_insert_block_size_bytes = 0: the INSERT squashes on one stream before it fans out to the sinks and never reaches the minimum, so the whole insert is flushed as one part, independent of max_insert_threads, max_block_size and how the numbers_mt threads interleave. - The throwIf over system.parts fails the job unless exactly 2 parts are active, because SYSTEM STOP MERGES on a missing table is a silent no-op. Validated on two servers of one master release build with perf.py --stop-merges, 5 runs per side of the change: before, 14 to 19 parts, different on the two servers in every run, right/left up to 1.18; after, 2 parts and identical SelectedRows on both servers, right/left within 3%. Related: ClickHouse#122073 Related: ClickHouse#121937 Co-Authored-By: Claude Opus 5.5 <[email protected]>
| getVectorSearchStringArgument(vector_search_args, 0), | ||
| getVectorSearchStringArgument(vector_search_args, 1), | ||
| getVectorSearchUnsignedArgument(vector_search_args, 2), | ||
| getVectorSearchLimitArgument(vector_search_args, 2, |
There was a problem hiding this comment.
@groeneai can you do a quick check if this setting is not being respected elsewhere, plus the other max_ settings?
There was a problem hiding this comment.
I checked the current tree. For this surface there are only two VectorSearchParameters producers: the planner rewrite in src/Processors/QueryPlan/Optimizations/useVectorSearch.cpp:289 (already gated by n > settings.max_limit_for_vector_search_queries at src/Processors/QueryPlan/Optimizations/useVectorSearch.cpp:149) and this shared parser in src/TableFunctions/TableFunctionMergeTreeAnalyzeIndexes.cpp:366.
The distributed mergeTreeAnalyzeIndexesUUID path keeps using the same limit: buildAnalyzeIndexQuery serializes vector_search_parameters->limit into the remote SQL in src/Interpreters/ClusterProxy/distributedIndexAnalysis.cpp:157, and the query-local settings are still sent to replicas by RemoteQueryExecutor / MultiplexedConnections / Connection::sendQuery in src/QueryPipeline/RemoteQueryExecutor.cpp:693, src/Client/MultiplexedConnections.cpp:167, and src/Client/Connection.cpp:1068.
I did not find another producer in this path that bypasses the cap. The other max_limit_for_vector_search_queries uses I found are the two planner gates and the in-index fetch-multiplier cap in src/Storages/MergeTree/MergeTreeIndexVectorSimilarity.cpp:568.
There was a problem hiding this comment.
Checked. max_limit_for_vector_search_queries has no other bypass: a vector search limit comes only from the two planner gates (useVectorSearch.cpp:149, useVectorSearchWithQuantizedCodes.cpp:157) and this parser, which also serves the mergeTreeAnalyzeIndexesUUID call that distributedIndexAnalysis.cpp:157 sends to replicas with the query settings. Inside the index the fetch-multiplier product is capped by it (MergeTreeIndexVectorSimilarity.cpp:568), and vector_search_index_fetch_multiplier is bounded to [1, 1000].
There is one real bypass, through a setting with no upper bound: usearch reserves max(hnsw_candidate_list_size_for_search, limit) entries for two candidate heaps (contrib/usearch/include/usearch/index.hpp:3062-3066), and hnsw_candidate_list_size_for_search is only checked for != 0 (MergeTreeIndexVectorSimilarity.cpp:507). On master 468fbe0 with a 100-row table:
SELECT id FROM t ORDER BY L2Distance(vec, [0.3, 0.3]) LIMIT 4
SETTINGS hnsw_candidate_list_size_for_search = 2147483648, max_memory_usage = 4000000000;
-- Code: 241. DB::Exception: (total) memory limit exceeded: would use 32.08 GiBSo a regular query reaches the same 32 GiB reservation, and max_memory_usage does not stop it: the failure is the server-wide limit, not the per-query one. A LIMIT under a raised max_limit_for_vector_search_queries makes the same reservation.
I'll extend this PR to clamp both the neighbour count and the expansion passed to index->search (MergeTreeIndexVectorSimilarity.cpp:575) to the number of vectors in the index. Larger values cannot change the result, so the reservation follows the data instead of the request.
There was a problem hiding this comment.
Done in 135d32a: the limit and the expansion passed to usearch are clamped to the number of vectors in the index, and 05257 covers both cases through query_log (memory_usage 32.00 GiB before, under 1 MiB after). One visible consequence: a huge LIMIT that usearch used to refuse with INCORRECT_DATA now returns all rows, as without the index, so 02354_vector_search_bug100556 and 05099_vector_search_limit_multiplier_overflow now assert those rows.
There was a problem hiding this comment.
Reverted in 217b54c. The PR is back to the over-cap limit check in mergeTreeAnalyzeIndexes* only, and the description is restored to match.
USearch reserves memory for max(limit, expansion) candidates in two heaps
before searching. `hnsw_candidate_list_size_for_search` is only checked
for being non-zero, so an ordinary vector search query with
`hnsw_candidate_list_size_for_search = 2147483648` reserved 32 GiB on a
100-row table: the query failed with `(total) memory limit exceeded`, or,
under a higher server limit, finished with `memory_usage` 32 GiB charged.
`max_memory_usage` does not stop it. A `LIMIT` under a raised
`max_limit_for_vector_search_queries` reached the same reservation.
Neither value can change the result once it reaches the number of vectors
in the index, so clamp both to `index->size()` before the search. Result
sets for `hnsw_candidate_list_size_for_search` from 64 to 2^31 on a
2000-row table are identical before and after, and equal the exact search.
The test checks each clamp through `query_log` (`USearchSearchCount` proves
the index ran, `memory_usage` stays below 1 GB; 32 GiB without the clamp)
and reads only the newest attempt. Parallel replicas are pinned off for
those two queries, since they would move the search into secondary queries.
Dropping only the `LIMIT` clamp turns exactly the `LIMIT` case red.
A huge `LIMIT` that usearch used to refuse with `INCORRECT_DATA` ("Out of
memory!") now returns all rows, the same as without the index, so
`02354_vector_search_bug100556` and `05099_vector_search_limit_multiplier_overflow`
now assert those rows (by `id`) instead of the error, keeping the huge
inputs for their overflow coverage.
Found while auditing other bypasses of `max_limit_for_vector_search_queries`,
as asked in review.
Co-Authored-By: Claude Opus 5.5 <[email protected]>
…tors" This reverts commit 135d32a, as asked in review: clamping the limit and the expansion to the index size made huge values silently accepted instead of refused. The PR goes back to rejecting an over-cap limit in `mergeTreeAnalyzeIndexes*` only. Co-Authored-By: Claude Opus 5.5 <[email protected]>
6b5ed92
Changelog category (leave one):
Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):
The
mergeTreeAnalyzeIndexesandmergeTreeAnalyzeIndexesUUIDtable functions now reject avector_search_index_analysislimit abovemax_limit_for_vector_search_queries, the bound under which the plan optimization rewrites a vector search query. A larger limit previously made the vector similarity index reserve memory proportional to it and exhaust the server's memory.Description
Reported by @ alexey-milovidov on #112824: a
Stress test (arm_release)hung check, the AST fuzzer having givenmergeTreeAnalyzeIndexesUUIDa limit of 2147483648.Failing job: https://github.com/ClickHouse/ClickHouse/actions/runs/35800881752/job/107085295073
Root cause. The bound on a vector search limit is a plan-optimization precondition, not a property of
VectorSearchParameters:useVectorSearch.cppskips the rewrite when theLIMITexceedsmax_limit_for_vector_search_queries(default 1000).TableFunctionMergeTreeAnalyzeIndexesbuilds the same struct itself with no such comparison, and the bound inside the index is conditional on additional filters orvector_search_with_rescoring, both false by default. usearch then reserves 8 bytes per requested neighbour twice per granule: 16.0 GiB per reservation at 2147483648.Consequence. On a server capped at 9.31 GiB the query returned a normal result while tracked memory went from 235 MiB to 32.23 GiB at 194 MiB RSS; unrelated queries then failed with
(total) memory limit exceeded, which is how the hung check's client died. The surface needs onlySELECT.Change. Reject an over-cap limit where it enters, in
parseArgumentsForOptimizations, with the planner's comparison exactly (>, not>=), so the function accepts exactly the limits for which that optimization exists. One comparison covers both entry points, at parse time.Validation. The same query now returns
BAD_ARGUMENTSat once, tracked memory +0.41 MiB. The new test fails without the change, passes with it, and brackets the comparison at the cap. The setting travels with the query, so a distributed vector search cannot trip the check: over a remote connection a limit of 2000 succeeds at 5000 and is rejected at 1000.Improvement, notBug Fix: the defect is in 26.8 and 26.9, butmergeTreeAnalyzeIndexes*is an internal function absent fromdocs/, so not a documented surface.Workflow [PR]
Sync PR [sync-upstream/pr/122154]
Version info
26.10.1.1622-master(included in26.10and later)