Repository navigation
Conversation
The pass rewrites L2DistanceTransposed/cosineDistanceTransposed by casting the reference vector argument to a non-nullable Array(element_type). When the original argument is a NULL constant or a value of nullable type (e.g. an if(cond, NULL, [...]) expression produced by the AST fuzzer), the original function returns Nullable(Float64), but the cast strips the nullability and the rewritten function returns Float64. The post-rewrite sanity check then aborts with a LOGICAL_ERROR. Broaden the existing early-exit from onlyNull() to isNullable(); the latter is a strict superset, so the existing 03829 test still exercises the same code path, and the new 04258 regression test covers the if(cond, NULL, [...]) shape (STID 0250-3bee). Report: https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=100177&sha=74122559110ec3bfd4459ff04717507062e7f6ac&name_0=PR&name_1=AST%20fuzzer%20%28amd_debug%29
|
Pre-PR validation gate (per worker policy, session a) Deterministic repro? Yes. Minimal: CREATE TABLE qbit_test (id UInt64, vec QBit(Float32, 3)) ENGINE = Memory;
INSERT INTO qbit_test VALUES (1, [0,1,2]), (2, [1,2,3]), (3, [2,3,4]);
SELECT L2DistanceTransposed(vec, if(id > 0, [0,1,2], NULL), 3) FROM qbit_test;Fails 100% of the time on master b) Root cause explained? c) Fix matches root cause? Yes. The existing d) Test intent preserved? / New test added? Yes. e) Both directions demonstrated?
f) Fix is general? Yes. The pass is the only call site; it handles both |
|
cc @rschu1ze @KochetovNicolai @alexey-milovidov could you review this? It extends the existing @alexey-milovidov fix (PR #96431) for nullable-arg crashes in |
|
Workflow [PR], commit [c4ab8b5] Summary: ✅
AI ReviewSummaryThis PR fixes Final VerdictStatus: ✅ Approve |
CI feedback on PR ClickHouse#105386: 1. Style check failed: test file name contains the substring "fail" (ci/jobs/check_style.py:181 rejects any name with "fail" in it). 2. Bugfix validation passed on master HEAD without the fix, meaning the reproducer was not aggressive enough to trigger the crash in the CI environment. 3. Test number 04258 collides with PR ClickHouse#105387. Changes: - Rename `04258_client_segfault_insert_send_failure_105292.sh` to `04259_client_segfault_send_error_105292.sh` (drops the "failure" substring and avoids the 04258 collision). - Strengthen the TCP-proxy reproducer: * Increase INSERT VALUES payload from 20k to 200k rows (~40 MB) so the client write loop overflows any realistic loopback send buffer. * Set SO_LINGER with timeout 0 on the proxy sockets after the cutoff, forcing a TCP RST so the client's next write observes ECONNRESET immediately instead of waiting for the kernel to push out the auto-tuned send buffer. * Stop the server->client relay once the cutoff fires. Verified locally: * 10/10 OK against the fixed binary (~1.8s per run). * Deterministic SIGSEGV at Address 0x108 in ReadBufferFromPocoSocketChunked::poll when run against the pre-fix binary (matches the original crash signature).
…-nullable-ref-vec
The previous fix skipped the partial-read optimization whenever the function result type was Nullable. That was too broad: a nullable result can also come from a nullable precision argument (e.g. toNullable(3)), and that case is already handled correctly by forcing the dimension constant nullable, so the optimization should still apply. Skipping it there regressed optimize_qbit_distance_function_reads to a full QBit-column read instead of the vec.1/vec.2/... subcolumn reads (clickhouse-gh review on PR ClickHouse#105387). Only the reference vector's own nullability is unrecoverable, because the rewrite casts it to a non-nullable Array(element_type). Guard on that argument alone, covering Nullable, LowCardinality(Nullable), Variant and Dynamic (the if(cond, NULL, [...]) fuzzer shape resolves to Variant(Array(...))). This is still a strict superset of the original onlyNull() check, so the existing 03829 regression test keeps passing. Extend 04258 with EXPLAIN QUERY TREE assertions proving the optimization is preserved for a nullable precision argument and skipped for a nullable reference vector. Co-Authored-By: Claude Opus 4.8 <[email protected]>
Pre-PR validation gateRe-validated after narrowing the guard (commit 4d207ff) per the clickhouse-gh review.
Session id: cron:clickhouse-worker-slot-15:20260610-184200 |
|
CI fully finished (Finish Workflow passed). Failures, all pre-existing chronic classes, none PR-caused (this PR is the DistanceTransposedPartialReadsPass Nullable fix, vector-search analyzer code):
|
| /// Precision nullability is handled separately (on the dimension constant below), so | ||
| /// only the reference vector's own nullability blocks the optimization here. | ||
| const auto & ref_vec_type = ref_vec_node->getResultType(); | ||
| if (ref_vec_type->isNullable() || ref_vec_type->isLowCardinalityNullable() || isVariant(ref_vec_type) |
There was a problem hiding this comment.
Can't w gracefully handle nullable types?
There was a problem hiding this comment.
Yes, it is feasible.
The subcolumn form already returns Nullable(Float64) by itself: FunctionArrayDistance uses the default null implementation, so for a nullable/Variant reference vector it auto-wraps the result and yields NULL on null rows. The only thing forcing the result back to non-nullable is this pass casting the reference vector to a non-nullable Array(element_type), which drops the row null mask.
To keep both the partial reads and the nullability, the rewrite can lift the mask out of the call:
if(ref_vec IS NULL, NULL,
L2DistanceTransposed(vec.1, ..., vec.p, dimension, CAST(assumeNotNull(ref_vec), 'Array(element_type)')))
Verified on this branch: it reads only vec.1..vec.p (no full-column read), returns Nullable(Float64), and matches the unoptimized result row-for-row, including the NULL rows. (A literally-NULL Nullable(Nothing) reference vector has no array to normalize and still just yields NULL, as today.)
The only open question is whether the extra wrapper is worth it for this shape: a nullable/Variant/Dynamic reference vector is essentially fuzzer-only, and when the whole vector is NULL the distance is NULL regardless. The current commit takes the simpler route and skips the optimization there.
I can push the graceful-handling wrapper if you prefer to keep the optimization, or leave the skip as-is. Which would you prefer?
There was a problem hiding this comment.
Done in 9b40315. The pass no longer skips: for a nullable/Variant/Dynamic reference vector it keeps the vec.1..vec.p subcolumn reads and reinstates the row null mask around the call:
if(isNull(ref), NULL,
distance(vec.1, .., vec.p, dim,
if(isNull(ref), <dim-sized dummy>, CAST(assumeNotNull(ref), Array(elem)))))
The inner if matters: assumeNotNull(ref) yields an empty array on NULL rows, so a dummy of the right size is substituted there. That keeps the rewritten call correct even when short_circuit_function_evaluation='disable' (CI randomizes it), and a wrong-sized non-null reference still raises the normal "wrong size" error since the dummy only replaces NULL rows.
04258 now asserts the nullable-ref case reads vec.1 (not the whole vec) and returns Nullable(Float64), matches the unoptimized path for L2 and cosine including NULL rows, and survives short_circuit_function_evaluation='disable'. The always-NULL Nullable(Nothing) case is still skipped (no element type, distance is NULL on every row).
…tialReadsPass
Previously the pass skipped the partial-read optimization whenever the reference
vector could carry NULL (Nullable / LowCardinalityNullable / Variant / Dynamic),
because casting it to a non-nullable Array(element_type) drops the row null mask
and turns the Nullable(Float64) result into Float64, tripping the post-rewrite
type check (LOGICAL_ERROR, STID 0250-3bee from the AST fuzzer).
Instead of skipping, keep reading the vec.1..vec.p subcolumns and reinstate the
null mask around the rewritten call:
if(isNull(ref), NULL,
distance(vec.1, .., vec.p, dim,
if(isNull(ref), <dim-sized dummy>, CAST(assumeNotNull(ref), Array(elem)))))
The inner if substitutes a correctly sized dummy only on NULL rows, where
assumeNotNull(ref) would otherwise yield an empty array. This keeps the rewritten
call independent of short_circuit_function_evaluation (randomized in CI) while
still surfacing the genuine "wrong size" error for non-null references. An
always-NULL reference (Nullable(Nothing)) is still skipped: it carries no element
type and the distance is NULL on every row regardless.
This addresses the reviewer request to gracefully handle nullable reference
vectors rather than bailing out of the optimization.
Co-Authored-By: Claude Opus 4.8 <[email protected]>
Pre-PR validation gate
Session id: cron:clickhouse-worker-slot-0:20260623-134500 |
… reference vectors The graceful-handling wrapper references the reference-vector expression at several places (the row null mask, the assumeNotNull value and the NULL-row dummy guard). For a non-deterministic reference such as if(rand() % 2, [...], NULL) those sites could sample different values, making the mask, the dummy guard and the distance argument inconsistent. Gate the wrapper on the reference expression being deterministic; a non-deterministic nullable reference now falls back to reading the whole column. Co-Authored-By: Claude Opus 4.8 <[email protected]>
Pre-PR validation gate (HEAD 4586a34)Addresses the clickhouse-gh review: the graceful-handling wrapper evaluated the reference-vector expression at three sites (outer null mask, inner null dummy-guard,
Session id: cron:clickhouse-worker-slot-0:20260623-151000 |
A null-bearing reference vector to L2DistanceTransposed/cosineDistanceTransposed can be an expression-bearing ColumnNode (a table ALIAS column or an array-join expression), not only a plain stored column. The pass clones that node; IQueryTreeNode::clone() re-copies and deep-clones the children array after ColumnNode::cloneImpl(), so the alias expression and its column dependency are preserved and the partial-read optimization still applies. Add a regression section using a Variant ALIAS column over if(id > 1, [...], NULL) to lock that behavior in. Co-Authored-By: Claude Opus 4.8 <[email protected]>
Pre-PR validation gate(HEAD
04258 passes 30/30 with full randomization; QBit/distance sibling suite (03363-03380, 03730, 03829, 03926, 04104) all pass; STID 0250-3bee shapes (Variant L2/cosine, Dynamic) stay fixed. Session id: cron:clickhouse-worker-slot-2:20260623-163500 |
… non-array The graceful-handling wrapper reinstates the row null mask with isNull(ref) and otherwise casts assumeNotNull(ref) to Array(element_type). That faithfully matches the unoptimized function only when every non-NULL row holds an array. For a Variant reference with a non-array alternative (e.g. the String alternative of Variant(Array(Float32), String)), or a Dynamic reference, a non-null row whose active value is not an array is turned into NULL by the default Variant/Dynamic adaptor (under variant_throw_on_type_mismatch = 0 / dynamic_throw_on_type_mismatch = 0). The wrapper instead cast that value to an array, returning a wrong distance or failing to parse it (CANNOT_READ_ARRAY_FROM_TEXT). Restrict the rewrite to references that always yield an array where not NULL: a Nullable or LowCardinalityNullable array, or a Variant whose alternatives are all arrays. Other nullable references skip the optimization and read the whole QBit column, matching the unoptimized result. The common nullable reference vector if(cond, [...], NULL) is a single-array Variant, so it keeps the optimization. Addresses a clickhouse-gh review on PR ClickHouse#105387.
|
Pre-PR validation gate for HEAD
Verification: Session: cron:clickhouse-worker-slot-1:20260623-172600 |
The test asserts on EXPLAIN QUERY TREE output, which is only supported with the analyzer, and the pass it covers (DistanceTransposedPartialReadsPass) is an analyzer-only rewrite. On the old analyzer shard the EXPLAIN QUERY TREE queries failed with NOT_IMPLEMENTED (code 48). Pin enable_analyzer = 1 at the top of the test, matching sibling 03375_l2_distance_transposed_partial_reads_pass. Co-Authored-By: Claude Opus 4.8 <[email protected]>
|
Pushed The previous CI run was green on every new-analyzer shard but failed on
Verified locally (debug binary, capped server): with the session forced to the old analyzer ( |
| /// optimization for such reference vectors but reinstate the mask around the rewritten call | ||
| /// (the `ref_vec_is_nullable` branches below). An always-NULL reference (Nullable(Nothing)) | ||
| /// carries no element type to cast to and yields a NULL distance on every row, so skip it. | ||
| const auto & ref_vec_type = ref_vec_node->getResultType(); |
There was a problem hiding this comment.
But previous comment said that
/// and rewriting the function with cast arguments would change the result type.
for onlyNull (Nullable(Nothing)) case, but not for any Nullable. So, did we support nullable types before? If we didint' then skipping it is proper solution, otherwise we need to implement consistent behavior.
There was a problem hiding this comment.
No. The pass crashed on nullable reference vectors before this PR; that crash is the STID 0250-3bee LOGICAL_ERROR being fixed here.
On master the onlyNull() guard caught only the all-NULL constant case (Nullable(Nothing)). Any other nullable reference (Variant(Array), Dynamic, ...) passed it and reached the rewrite, which casts the reference to a non-nullable Array(element_type). The original call returns Nullable(Float64) for such a reference (the function inherits the default Nullable/Variant/Dynamic adaptor), the rewritten call returns Float64, so the post-rewrite type check threw ... Before: Nullable(Float64), after: Float64 (the master binary aborts, rc 134, on L2DistanceTransposed(vec, if(c, [..], NULL), 3)). So that comment's reasoning ("cast would change the result type") applies to every nullable reference, not just onlyNull; the guard just did not cover them, which is the bug. The only nullable input master handled was a nullable precision argument (toNullable(3)), preserved via dimension_constant->convertToNullable(), and that is the third argument, not the reference vector.
So by your rule (not supported before -> skip is proper), a plain skip of all nullable reference vectors is correct and much simpler. The current HEAD instead implements the consistent behavior: it keeps the subcolumn optimization for the common single-array Variant reference (if(cond, [..], NULL)) returning Nullable(Float64), and reads the whole column only where the mask cannot be reproduced faithfully (non-deterministic reference, or Dynamic / multi-alternative Variant that can hold a non-array value).
Which do you prefer: keep the consistent-handling wrapper, or simplify to a plain skip now that nullable references are confirmed to have never been supported?
There was a problem hiding this comment.
Is it case for all Nullable types or just for complex ones? Also, how does it work when nullable inside a composite time (e.g. Tuple(Nullable) or Array(Nullable))?
There was a problem hiding this comment.
The guard catches all top-level nullable types, not just the complex ones: isNullable() (Nullable(T)), isLowCardinalityNullable() (LowCardinality(Nullable(T))), isVariant(), isDynamic().
Composite types where nullability is nested:
-
Tuple(Nullable(T)): never reaches the pass. The reference vector must be an Array, so a Tuple is rejected at function resolution withILLEGAL_TYPE_OF_ARGUMENT("Second argument of function L2DistanceTransposed must be an Array") before any optimization runs. -
Array(Nullable(T)): the top-level type is a non-nullableArray, soref_vec_is_nullableis false and it takes the plain (non-masked) path, which is correct. The original function does not propagate the element nullability to its result:toTypeName(L2DistanceTransposed(vec, [0,1,2]::Array(Nullable(Float32)), 3))isFloat64with bothoptimize_qbit_distance_function_reads = 0and= 1. The rewrite casts the reference toArray(element_type)and the result type is unchanged, so the optimization still applies (readsvec.1) and the values match the unoptimized path. An actual NULL element inside the array ([0, NULL, 2]) throws the sameCANNOT_INSERT_NULL_IN_ORDINARY_COLUMNon both paths, since the function itself rejects NULL elements regardless of the optimization.
So the result type only carries nullability when it is at the top level of the reference, which is exactly what the guard checks. Added a regression section (8) covering the Tuple rejection and the Array(Nullable) case (values, type, and subcolumn read identical to opt = 0).
The DistanceTransposedPartialReadsPass guard checks only top-level nullability, so verify composite reference types keep working through the plain (non-masked) path: - Tuple(...) is rejected at function resolution (the reference must be an Array), so it never reaches the pass. - Array(Nullable(T)) has a non-nullable top-level type, so the original function returns a non-nullable Float64 (nested nullability is not propagated to the result type). The rewrite casts to Array(element_type) and the result type is unchanged, so the optimization correctly applies (reads vec.1) and matches the unoptimized path. Test-only addition (section 8); sections 1-7 are unchanged. Co-Authored-By: Claude Opus 4.8 <[email protected]>
LLVM Coverage Report
Changed lines: Changed C/C++ lines covered by tests: 66/78 (84.62%) | Lost baseline coverage: none · Uncovered code |
CI finish ledger — c4ab8b5CI fully finished on this head (Config Workflow + Finish Workflow SUCCESS). No failing checks: every test/job is green or skipped (the only non-completing entry is the private
Session id: cron:our-pr-ci-monitor:20260624-193000 |
|
Closing as superseded by the merged fix on master. The same LOGICAL_ERROR this PR targets ("... does not have a valid source node after running DistanceTransposedPartialReadsPass. Before: Nullable(Float64), after: Float64", found by the AST fuzzer) is now fixed on master by commit f4c3622, which landed with #108103 (merged 2026-07-02 01:16 UTC). That fix drives the nullability decision off the original result type: it forces the trailing size constant to Nullable whenever Master shows no further hits of this signature since that fix; the single 2026-07-01 sighting was on a base that predated f4c3622. |
CI feedback on PR ClickHouse#105386: 1. Style check failed: test file name contains the substring "fail" (ci/jobs/check_style.py:181 rejects any name with "fail" in it). 2. Bugfix validation passed on master HEAD without the fix, meaning the reproducer was not aggressive enough to trigger the crash in the CI environment. 3. Test number 04258 collides with PR ClickHouse#105387. Changes: - Rename `04258_client_segfault_insert_send_failure_105292.sh` to `04259_client_segfault_send_error_105292.sh` (drops the "failure" substring and avoids the 04258 collision). - Strengthen the TCP-proxy reproducer: * Increase INSERT VALUES payload from 20k to 200k rows (~40 MB) so the client write loop overflows any realistic loopback send buffer. * Set SO_LINGER with timeout 0 on the proxy sockets after the cutoff, forcing a TCP RST so the client's next write observes ECONNRESET immediately instead of waiting for the kernel to push out the auto-tuned send buffer. * Stop the server->client relay once the cutoff fires. Verified locally: * 10/10 OK against the fixed binary (~1.8s per run). * Deterministic SIGSEGV at Address 0x108 in ReadBufferFromPocoSocketChunked::poll when run against the pre-fix binary (matches the original crash signature).
The
DistanceTransposedPartialReadsPassrewritesL2DistanceTransposedandcosineDistanceTransposedby casting the reference vector argument to a non-nullableArray(element_type). When the original argument isNULLor a value of a nullable type (for example anif(cond, NULL, [...])expression produced by the AST fuzzer), the original function returnsNullable(Float64), but the cast strips the nullability and the rewritten function returnsFloat64. The post-rewrite sanity check then aborts with aLOGICAL_ERROR:Broaden the existing early-exit from
onlyNull()toisNullable(). The latter is a strict superset, so the existing03829_distance_transposed_pass_nullable_nothingtest still exercises the same code path. The new04258regression test covers the broaderif(cond, NULL, [...])shape (STID 0250-3bee).Chronic AST fuzzer trunk bug: 10 unrelated PRs hit it in the last 30 days; survives the earlier PR #96431 fix (NULL-only arguments).
Latest report: https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=100177&sha=74122559110ec3bfd4459ff04717507062e7f6ac&name_0=PR&name_1=AST%20fuzzer%20%28amd_debug%29
Changelog category (leave one):
Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):
Fix a
LOGICAL_ERRORin theDistanceTransposedPartialReadsPassanalyzer pass when the reference vector argument ofL2DistanceTransposedorcosineDistanceTransposedmakes the function's result typeNullable(e.g.L2DistanceTransposed(vec, if(cond, NULL, ref), N)).Documentation entry for user-facing changes