Skip to content

Bound the vector search limit of mergeTreeAnalyzeIndexes by max_limit_for_vector_search_queries - #122154

Merged
PedroTadim merged 6 commits into
ClickHouse:masterfrom
groeneai:groeneai/bound-vector-search-limit-analyze-indexes
Oct 5, 2026
Merged

PedroTadim merged 6 commits into
ClickHouse:masterfrom
groeneai:groeneai/bound-vector-search-limit-analyze-indexes

Conversation

@groeneai

@groeneai groeneai commented Sep 25, 2026 •

Copy link
Copy Markdown
Collaborator

Changelog category (leave one):

  • Improvement

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

The mergeTreeAnalyzeIndexes and mergeTreeAnalyzeIndexesUUID table functions now reject a vector_search_index_analysis limit above max_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 given mergeTreeAnalyzeIndexesUUID a 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.cpp skips the rewrite when the LIMIT exceeds max_limit_for_vector_search_queries (default 1000). TableFunctionMergeTreeAnalyzeIndexes builds the same struct itself with no such comparison, and the bound inside the index is conditional on additional filters or vector_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 only SELECT.

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_ARGUMENTS at 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, not Bug Fix: the defect is in 26.8 and 26.9, but mergeTreeAnalyzeIndexes* is an internal function absent from docs/, so not a documented surface.


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

Version info

  • Merged into: 26.10.1.1622-master (included in 26.10 and later)

…_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.
@groeneai groeneai added can be tested Allows running workflows for external contributors groeneai-origin-request PR origin: a maintainer pinged or directed groeneai labels Sep 25, 2026
@groeneai

Copy link
Copy Markdown
Collaborator Author
Internal second-model review: adjudication log (click to expand)

Pre-publication review by an independent model (engine: codex), three rounds against three heads: one
gate finding plus six from my own cold reviews. Every substantive one landed in the regression test or
in the rebase; the shape of the src/ check was never altered.

# Sev Finding Verdict Evidence / action
1 ⚠️ The success arm asserted count() > 0, true even when index analysis narrowed nothing, since the analyze function also emits every part it did not narrow AGREE, fixed The arm now asserts the analysed ranges, two of the part's thirteen marks
2 ⚠️ No arm set the neighbour count equal to the setting, so relaxing the new comparison to >= would have left every assertion green AGREE, fixed Accept arm added at count equal to the cap, paired with the reject arm one below; rebuilding with >= reddens that arm and only that arm
3 💡 A test comment claimed any of three arguments engages the pre-existing bound; return distances does not, it only selects whether distances are dumped AGREE, fixed Comment restated over the two that do
4 ❌ The branch stopped being mergeable mid-review: #118644 merged and restructured this function, so the hunk's anchor no longer existed AGREE, fixed Rebased onto master; the check is now a sixth per-parameter helper beside the five that arrived with #118644, so the error names the parameter from the same table they use and the braced initializer keeps its left-to-right validation order. #118644's own test passes unchanged on both binaries
5 💡 Reword an in-diff comment DISAGREE The comment is correct and states a pre-existing property rather than the fix; rewording defensible text is churn
6 💡 The regression test drives mergeTreeAnalyzeIndexes only, while the reported failure entered through mergeTreeAnalyzeIndexesUUID Noted, not blocking Both entry points build these parameters in one shared argument parser, so the single comparison covers both and a regression reaching one reaches both
7 💡 Two figures for the same base-binary measurement differ in the second decimal between the PR body and the commit message Noted, not blocking Two genuine runs taken either side of the rebase; each entails the other's substance, tracked memory above 32 GiB at a few hundred MiB of RSS

One thing I looked at and am deliberately not treating as a defect: raising
max_limit_for_vector_search_queries itself still reaches the same reservation, identically through
this function and through a plain ORDER BY <distance> LIMIT. That setting documents itself as
"SELECT queries with LIMIT bigger than this setting cannot use vector similarity indices. Helps to
prevent memory overflows in vector similarity indices", so raising it switches off the documented
guard, and this change makes the introspection function honour exactly the bound the setting already
promises.

Severity: ❌ blocker / ⚠️ major / 💡 nit. DISAGREE verdicts carry recorded evidence and are terminal per
finding. Findings on hunks unchanged by a fix round are auto-dropped.

Session id: cron:clickhouse-review-slot-9:20260925-035100

@clickhouse-gh

clickhouse-gh Bot commented Sep 25, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [217b54c]

Summary: ❌

job_name test_name status info comment
Stateless tests (arm_asan_ubsan, azure, sequential) ERROR

AI Review

Summary

This PR makes mergeTreeAnalyzeIndexes and mergeTreeAnalyzeIndexesUUID reject vector_search_index_analysis limits above max_limit_for_vector_search_queries and adds a local regression test around the inclusive > comparison. The parser-side check itself matches the planner gate, but the regression coverage still stops at the local table-function path: the current diff does not pin the replica-side mergeTreeAnalyzeIndexesUUID case where a query-local max_limit_for_vector_search_queries is raised above the default and must be forwarded through distributed index analysis.

Tests
  • ⚠️ tests/queries/0_stateless/05257_vector_search_index_analysis_limit_cap.sql:33 Add one focused distributed case, preferably by extending tests/queries/0_stateless/02354_vector_search_distributed_index_analysis.sql, that runs vector search with distributed_index_analysis = 1, LIMIT 2000, and SETTINGS max_limit_for_vector_search_queries = 5000, then proves the same query is rejected at 1000. That is the smallest end-to-end check that locks down the new cross-component contract this PR now relies on.
Final Verdict
  • Status: ⚠️ Request changes
  • Minimum required action: add an end-to-end distributed regression test proving the raised query-local cap reaches the replica-side mergeTreeAnalyzeIndexesUUID call.

LLVM Coverage Report

Measured on commit 217b54c.

Metric Baseline Current Δ
Lines 88.20% 88.30% +0.10%
Functions 92.10% 92.10% +0.00%
Branches 79.70% 79.70% +0.00%

Changed lines: Changed C/C++ lines covered: 16/16 (100.00%) · Uncovered code

Full report · Diff report

@clickhouse-gh clickhouse-gh Bot added the pr-improvement Pull request with some product improvements label Sep 25, 2026
-- 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))

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.

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.

@clickhouse-gh clickhouse-gh Bot added the comp-table-functions Table functions for temporary read/write to external systems (FROM ... tableFunction()). label Sep 25, 2026
@clickhouse-gh

clickhouse-gh Bot commented Sep 25, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing 217b54c8d with master 76ec7cc60 (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

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

Job report

@PedroTadim

Copy link
Copy Markdown
Member

cc @alexey-milovidov

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

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - 0b0017e

Every failure below has an owner. Only CH Inc sync is exempt.

Check / test Reason Owner / fixing PR
Performance Comparison (arm_release, master_head, 3/6) / optimize_time_filter_with_preimage #6 dashboard confirmed_regression, client_time 0.411 -> 0.536 (+30.5%), on a query this shard's own report scores only unstable. The fixture declares no vector similarity index and no performance test calls mergeTreeAnalyzeIndexes, so the query cannot reach this diff #122156 (mine, open) deletes this query; also merged master @ c06c902 for #122073
Performance Comparison (arm_release, master_head, 4/6) / index_bulk_filtering #2 same gate, client_time 0.036 -> 0.049 (+36.5%), and here the shard's own report scores the query success (35 ms vs 49 ms). Also unreachable from this diff #122073 (external, merged), measured ABSENT from the tree that ran (744d142a04ab), so merged master @ c06c902 to pick it up
Upgrade check (amd_release) / Error message in clickhouse-server.log and Cannot check whether the mutation submitted before the upgrade was finished the release this check upgrades from persisted s AggregateFunction(quantile('0.5'), Float64) with a string parameter, so the upgraded server cannot attach test_1.t_pfl_05079 at startup: Code: 70 ... Cannot convert String to double ... (CANNOT_CONVERT_TYPE) in AsyncLoader::worker. The mutation row is that unusable server, not a second defect. 80 rows over 55 pull requests in 30 days, 0 on master a fix task owns this signature. #119810 (mine, merged) is measured PRESENT in the tree that ran and is therefore not the owner here: it stops new metadata of this shape from being written and cannot rescue a file the previous release already wrote, which is what the pending v26.9-must-backport request on it is for
CH Inc sync - CH Inc sync (private, not actionable by me)

Why merging master is the response to both performance rows rather than a change here: until #122073 merged this morning, only the confirm_changes rerun passed --stop-merges, so the measured samples that feed the dashboard verdict were taken while background merges ran. Head is now c06c902 and CI is re-running there. 4 too long is not a failure source in master_head mode, which is why sibling shards carry the same string and pass.

Session id: cron:clickhouse-maint-slot-14:20260925-112800

@groeneai

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - c06c902

Every failure below has an owner: a fixing PR (mine or external), or a full-effort fix task
whose fixing-PR link will be posted here when it opens. Only CH Inc sync is exempt.

Check / test Reason Owner / fixing PR
AST fuzzer (amd_debug, targeted, old_compatibility) / Assertion 'px != 0' failed (STID: 3358-52ae) crash (assertion abort in the debug build): a null column is dereferenced in MergeTreeReaderCompact::readData while reading a JSON compact part (object_serialization_version = 'v1', advanced_chunked shared data) of a table the fuzzer derived from 04420_json_shared_data_advanced_chunked_paths_indexes_2. The query never calls mergeTreeAnalyzeIndexes, the only code this PR changes. First occurrence in CI a fix task is created (investigating at full effort, fixing-PR link to follow here)
Performance Comparison (arm_release, master_head, 6/6) / read_in_reverse_order_final #0, #1 dashboard confirmed_regression, client_time +37.5% and +25.2%. On master these two FINAL queries went from 2-3 ms to 8-9 ms on both servers at the merge commit of #122073 (302e001eeb33), which stopped background merges during the measured runs, and since then they are flagged on unrelated PRs across several shards. The fixture never calls mergeTreeAnalyzeIndexes a fix task is created (investigating at full effort, fixing-PR link to follow here)
Upgrade check (amd_release) / Error message in clickhouse-server.log and Cannot check whether the mutation submitted before the upgrade was finished same signature as on the previous head: the release this check upgrades from persisted s AggregateFunction(quantile('0.5'), Float64) with a string parameter, so the upgraded server cannot attach test_3.t_pfl_05079 at startup (Code: 70 ... Cannot convert String to double). The mutation row is that same unusable server a fix task owns this signature. #119810 (mine, merged) is present in the tested tree: it stops new metadata of this shape from being written but cannot repair a file the previous release already wrote, which is what the pending v26.9-must-backport request on it is for
Mergeable Check, PR rollup rows, red only because of the rows above a fix task is created (the same owners as the three rows above)

All 173 check runs completed (129 pass, 41 not selected, 3 red), Finish Workflow is green and
CH Inc sync passed on this head.

Session id: cron:our-pr-ci-monitor:20260925-182007

@groeneai

Copy link
Copy Markdown
Collaborator Author

Fixing PR for the AST fuzzer (amd_debug, targeted, old_compatibility) failure STID 3358-52ae: #114335 (external, open).

Correction to the reason in the ledger above: the crashing table was not the JSON one. The fuzzer had re-created test__fuzz_3 as json Nullable(IPv4) with nullable_serialization_version = 'allow_sparse' and write_marks_for_substreams_in_compact_parts = 0, so reading json.null extracts the null map from the whole sparse column, and that extraction returns a null column. The core dump confirms the storage type, the sparse column and the missing substream marks; #114335 fixes exactly this extraction.

@groeneai

Copy link
Copy Markdown
Collaborator Author

Fixing PR for the read_in_reverse_order_final Performance Comparison rows created: #122335

pull Bot pushed a commit to Lobinson1/ClickHouse that referenced this pull request Sep 26, 2026
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]>
@PedroTadim PedroTadim self-assigned this Oct 5, 2026
getVectorSearchStringArgument(vector_search_args, 0),
getVectorSearchStringArgument(vector_search_args, 1),
getVectorSearchUnsignedArgument(vector_search_args, 2),
getVectorSearchLimitArgument(vector_search_args, 2,

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.

@groeneai can you do a quick check if this setting is not being respected elsewhere, plus the other max_ settings?

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.

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.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

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 GiB

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

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

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.

@PedroTadim PedroTadim Oct 5, 2026 •

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.

@groeneai let's revert the 135d32a change and finish this PR. The change makes it too permissive

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

Reverted in 217b54c. The PR is back to the over-cap limit check in mergeTreeAnalyzeIndexes* only, and the description is restored to match.

PedroTadim and others added 2 commits October 5, 2026 12:55
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]>
@PedroTadim
PedroTadim enabled auto-merge October 5, 2026 19:53
@PedroTadim
PedroTadim added this pull request to the merge queue Oct 5, 2026
Merged via the queue into ClickHouse:master with commit 6b5ed92 Oct 5, 2026
147 of 149 checks passed
@robot-clickhouse-ci-1 robot-clickhouse-ci-1 added the pr-synced-to-cloud The PR is synced to the cloud repo label Oct 5, 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 comp-table-functions Table functions for temporary read/write to external systems (FROM ... tableFunction()). groeneai-origin-request PR origin: a maintainer pinged or directed groeneai pr-improvement Pull request with some product 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.

3 participants