Skip to content

Fix LOGICAL_ERROR in DistanceTransposedPartialReadsPass with Nullable arguments - #105387

Closed
groeneai wants to merge 10 commits into
ClickHouse:masterfrom
groeneai:groeneai/fix-distance-transposed-pass-nullable-ref-vec
Closed

groeneai wants to merge 10 commits into
ClickHouse:masterfrom
groeneai:groeneai/fix-distance-transposed-pass-nullable-ref-vec

Conversation

@groeneai

Copy link
Copy Markdown
Collaborator

The DistanceTransposedPartialReadsPass rewrites L2DistanceTransposed and cosineDistanceTransposed by casting the reference vector argument to a non-nullable Array(element_type). When the original argument is NULL or a value of a nullable type (for example 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:

FUNCTION query tree node does not have a valid source node after running DistanceTransposedPartialReadsPass. Before: Nullable(Float64), after: Float64

Broaden the existing early-exit from onlyNull() to isNullable(). The latter is a strict superset, so the existing 03829_distance_transposed_pass_nullable_nothing test still exercises the same code path. The new 04258 regression test covers the broader if(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):

  • Bug Fix (user-visible misbehavior in an official stable release)

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

Fix a LOGICAL_ERROR in the DistanceTransposedPartialReadsPass analyzer pass when the reference vector argument of L2DistanceTransposed or cosineDistanceTransposed makes the function's result type Nullable (e.g. L2DistanceTransposed(vec, if(cond, NULL, ref), N)).

Documentation entry for user-facing changes

  • Documentation is not required.

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

Copy link
Copy Markdown
Collaborator Author

Pre-PR validation gate (per worker policy, session cron:clickhouse-ci-task-worker:20260520-001500):

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 cf4d9126fcb4 (debug build).

b) Root cause explained? if(cond, NULL, [...]) resolves to Variant(Array(UInt8)), and the function call's result type is Nullable(Float64). The pass unconditionally casts the reference vector to Array(qbit_element_type) (non-nullable), then re-resolves the function. The new function returns Float64 because the cast stripped the nullability. The post-rewrite check on line 145 detects the mismatch and throws LOGICAL_ERROR.

c) Fix matches root cause? Yes. The existing onlyNull() check only handles the narrow Nullable(Nothing) subcase. Broadening to isNullable() skips the optimization any time the rewrite could change the result's nullability. This is a strict superset of the existing check (so the existing 03829 test still passes) and prevents the cause from materializing.

d) Test intent preserved? / New test added? Yes. 03829_distance_transposed_pass_nullable_nothing (literal NULL) still passes. New 04258_distance_transposed_pass_nullable_ref_vec covers both L2DistanceTransposed and cosineDistanceTransposed with the if(cond, NULL, [...]) shape. Test output is deterministic.

e) Both directions demonstrated?

  • WITHOUT fix: server aborts with LOGICAL_ERROR, subsequent client connections refused.
  • WITH fix: 50/50 passes via clickhouse-test --test-runs 50 with full setting randomization.

f) Fix is general? Yes. The pass is the only call site; it handles both L2DistanceTransposed and cosineDistanceTransposed through the same code path (line 48), and both functions are covered by the new test. EXPLAIN QUERY TREE confirms: optimization still applied for non-nullable args (vec.1, vec.2, vec.3 subcolumns), correctly skipped for nullable args (uses vec directly).

@groeneai

Copy link
Copy Markdown
Collaborator Author

cc @rschu1ze @KochetovNicolai @alexey-milovidov could you review this? It extends the existing @alexey-milovidov fix (PR #96431) for nullable-arg crashes in DistanceTransposedPartialReadsPass to cover the broader case where any argument (not just a literal NULL) makes the function result Nullable. @rschu1ze for the QBit/distance optimization angle, @KochetovNicolai for the analyzer-pass mechanics.

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

clickhouse-gh Bot commented May 20, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [c4ab8b5]

Summary: ✅


AI Review

Summary

This PR fixes DistanceTransposedPartialReadsPass for null-bearing reference vectors by preserving the partial-read rewrite only when the reference can be safely evaluated multiple times and can only contain array values when non-NULL, then restoring the original Nullable(Float64) mask around the rewritten call. The added stateless test covers the original LOGICAL_ERROR, nullable precision preservation, eager if evaluation, non-deterministic references, expression-bearing ColumnNode references, Variant/Dynamic mismatch behavior, and nested nullability. I did not find any unresolved correctness or safety findings in the current code.

Final Verdict

Status: ✅ Approve

@clickhouse-gh clickhouse-gh Bot added the pr-bugfix Pull request with bugfix, not backported by default label May 20, 2026
groeneai added a commit to groeneai/ClickHouse that referenced this pull request May 20, 2026
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).
groeneai and others added 2 commits June 10, 2026 19:19
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]>
@groeneai

Copy link
Copy Markdown
Collaborator Author

Pre-PR validation gate

Re-validated after narrowing the guard (commit 4d207ff) per the clickhouse-gh review.

# Question Answer
a Deterministic repro? Yes. On master fc73f46 (debug), L2DistanceTransposed(vec, if(id>0,[0,1,2],NULL), 3) over QBit(Float32,3) aborts every time (SIGABRT, rc=134) from the post-rewrite LOGICAL_ERROR. Also reproduced with cosineDistanceTransposed, a Dynamic reference vector, and an explicit Variant(Array,String) reference vector.
b Root cause explained? The function result becomes Nullable(Float64) for two independent reasons: (1) a nullable precision argument, which the pass already preserves by forcing the dimension constant nullable; (2) a null-bearing reference vector, whose nullability the rewrite strips when it casts the vector to a non-nullable Array(element_type). The post-rewrite sanity check then sees Before: Nullable(Float64), after: Float64 and throws. The earlier isNullable() guard bailed on BOTH, regressing case (1)'s partial-read optimization.
c Fix matches root cause? Yes. The guard now inspects the reference vector type alone (Nullable, LowCardinality(Nullable), Variant, Dynamic), which is the only argument whose nullability the cast cannot recover. Nullable precision keeps taking the optimized path. Strict superset of the original onlyNull() check.
d Test intent preserved / new tests added? Yes. 04258 now adds two EXPLAIN QUERY TREE assertions: nullable precision still reads vec.1/vec.2/vec.3 subcolumns (optimization preserved), nullable reference vector reads the whole vec column (optimization skipped, no crash). Existing 03829 (nullable-nothing) and 03375 (the pass optimization test) still pass.
e Both directions demonstrated? Yes. master fc73f46: rc=134 (abort). Patched binary: rc=0, correct values, and EXPLAIN confirms the optimization is preserved for nullable precision and skipped for nullable reference vector. 04258 passes when run in a random database and normalized exactly as clickhouse-test does.
f Fix is general, not a narrow patch? Yes. It targets the single root cause (reference-vector nullability the cast strips) across all null-bearing type kinds rather than guarding the one fuzzer query. Verified Nullable, LowCardinality(Nullable), Variant and Dynamic reference vectors all take the safe path; L2DistanceTransposed and cosineDistanceTransposed share the code path and are both covered. No related open issue found (fuzzer-only finding, STID 0250-3bee).

Session id: cron:clickhouse-worker-slot-15:20260610-184200

@groeneai

Copy link
Copy Markdown
Collaborator Author

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)

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.

Can't w gracefully handle nullable types?

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.

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?

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.

proper fix

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

@vdimir vdimir self-assigned this Jun 16, 2026
…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]>
@groeneai

Copy link
Copy Markdown
Collaborator Author

Pre-PR validation gate

# Question Answer
a Deterministic repro? Yes. SELECT L2DistanceTransposed(vec, if(id>0,[0,1,2],NULL), 3) FROM qbit_test SETTINGS optimize_qbit_distance_function_reads=1 aborted with LOGICAL_ERROR ... Before: Nullable(Float64), after: Float64 (STID 0250-3bee) on master; reproduced for L2/cosine and for Variant and Dynamic reference vectors.
b Root cause explained? The pass rewrites the call to read vec.1..vec.p subcolumns and casts the reference vector to a non-nullable Array(element_type). That cast drops the row null mask a Nullable/Variant/Dynamic reference carries, so the rewritten result is Float64 while the original was Nullable(Float64); the post-rewrite type check then throws.
c Fix matches root cause? Yes. Instead of skipping the optimization for such reference vectors, the pass now keeps the subcolumn reads and reinstates the mask: if(isNull(ref), NULL, distance(vec.1..vec.p, dim, if(isNull(ref), dummy, CAST(assumeNotNull(ref), Array(elem))))). The result type matches the original Nullable(Float64) and the optimization is preserved.
d Test intent preserved / new tests added? 04258 rewritten: asserts optimized==unoptimized values+type (incl. NULL rows) for L2 and cosine, that the nullable-ref case reads vec.1 (not whole vec) and returns Nullable(Float64), that it survives short_circuit_function_evaluation='disable', and that the nullable-precision case still optimizes. 03829 (always-NULL subcase) still skipped and passing.
e Both directions demonstrated? Yes. Without the fix the listed query throws the LOGICAL_ERROR; with it 04258 passes 30/30 under full randomization and the four STID shapes (Variant/Dynamic/cosine/mixed) execute cleanly returning Nullable(Float64) with NULL on null rows.
f Fix is general, not a narrow patch? Covers both rewritten functions (L2DistanceTransposed, cosineDistanceTransposed) and all guard types (Nullable, LowCardinalityNullable, Variant, Dynamic); Nullable(Array)/LowCardinality(Nullable(Array)) are illegal types in ClickHouse so the realistic paths are Variant/Dynamic, both verified. A wrong-sized non-null reference still raises the genuine "wrong size" error (the dummy is substituted only on NULL rows), so no error is masked.

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

Copy link
Copy Markdown
Collaborator Author

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, assumeNotNull value), which is unsafe for a non-deterministic reference.

# Question Answer
a Deterministic repro? Yes. SELECT rand() AS a, rand() AS b FROM numbers(1000) shows ClickHouse currently CSE-merges identical non-deterministic subexpressions by action-node name (0 rows differ), which is why the wrapper happened to not misbehave yet, but correctness must not depend on that DAG optimization. The hazard is exercised deterministically via EXPLAIN QUERY TREE on L2DistanceTransposed(vec, if(rand() % 2 = 0, [0,1,2]::Array(Float32), NULL), 3).
b Root cause explained? The wrapper if(isNull(ref), NULL, distance(vec.1..vec.p, dim, if(isNull(ref), dummy, assumeNotNull(ref)))) references ref three times. If ref is non-deterministic (e.g. if(rand()%2,[...],NULL)), the three evaluations can sample different values per row, so the outer mask, the dummy guard and assumeNotNull disagree (a row kept non-NULL while the distance used the dummy, or the wrong-size path surfacing for a row the original made NULL).
c Fix matches root cause? Yes. The wrapper is gated on the reference expression being deterministic (isDeterministicExpression(ref_vec_node): functions must be isDeterministicInScopeOfQuery(), constants deterministic, columns fine). A non-deterministic null-bearing reference falls back to reading the whole column, so the expression is reused only when every evaluation yields the same value by definition. Mirrors the existing precedent in OptimizeRedundantFunctionsInOrderByPass.
d Test intent preserved / new tests added? Yes. 04258 keeps the existing deterministic-ref subcolumn-read + Nullable(Float64) + short-circuit + nullable-precision assertions, and adds a non-deterministic-ref assertion proving the optimization is skipped (reads_subcolumns = 0) and the query still returns Nullable(Float64).
e Both directions demonstrated? Yes. Non-deterministic ref: EXPLAIN shows whole-vec read (no vec.N), Nullable(Float64), no crash over 50k rows. Deterministic refs (STID if(id>1,[...],NULL) Variant/Dynamic, toNullable(precision)): still read vec.1/vec.2/vec.3 and stay Nullable(Float64). 04258 passes 30/30 under full randomization; QBit/distance sibling suite (03363-03380, 03730, 03829, 03926, 04104) passes.
f Fix is general, not a narrow patch? Yes. The guard is on the reference subtree as a whole, not a single function name, so any non-deterministic reference (nested functions, stateful functions) falls back. The determinism walk recurses through all argument subtrees. No sibling code path: L2DistanceTransposed and cosineDistanceTransposed share this single pass, both covered.

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

Copy link
Copy Markdown
Collaborator Author

Pre-PR validation gate

(HEAD 2c0855e67ec — test-only addition on top of the determinism guard 4586a34a.)

# Question Answer
a Deterministic repro? The reported "read/planning error" does NOT reproduce. On HEAD, a Variant/Dynamic ALIAS reference vector (ALIAS if(id > 1, [0,1,2]::Array(Float32), NULL)) and the same expression as an ARRAY JOIN column both execute correctly (no crash, no planning error), opt=1 == opt=0.
b Root cause explained? The bot's premise is incorrect: the pass calls ref_vec_node->clone() = IQueryTreeNode::clone(), which re-copies the children array and deep-clones each child after cloneImpl() (cloneAndReplace: node_clone->children = node_to_clone->children; + per-child clone loop). So an expression-bearing ColumnNode's alias expression and its id dependency survive the clone. ColumnNode::cloneImpl omitting the child is the same contract FunctionNode::cloneImpl follows.
c Fix matches root cause? No source change. The determinism guard from 4586a34a is already correct for COLUMN nodes: a column is materialized once / reused by name in the DAG, so the wrapper's three references read the same value even for a non-deterministic alias expression. Treating COLUMN as deterministic is therefore correct, not an oversight.
d Test intent preserved / new tests added? Added 04258 section 6: an expression-bearing Variant ALIAS reference vector. Asserts the optimization still reads vec.1 subcolumns, returns Nullable(Float64), and matches the unoptimized result. Existing sections 1-5 unchanged.
e Both directions demonstrated? EXPLAIN QUERY TREE shows every cloned ref COLUMN node retaining its EXPRESSION child with the id dependency; subcolumn reads preserved; result Nullable(Float64); values match opt=0. Non-deterministic named alias verified consistent over 1,000,000 rows x 5 runs under all short_circuit_function_evaluation modes (no wrong size path).
f Fix is general, not a narrow patch? Covered both expression-bearing ColumnNode sources the bot named (table ALIAS columns and ARRAY JOIN expressions). The preserved-expression behavior comes from the generic clone() contract, so it holds for every node type, not just this pass.

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

Copy link
Copy Markdown
Collaborator Author

Pre-PR validation gate for HEAD 2923ba418a6:

# Question Answer
a Deterministic repro? Yes. Variant(Array(Float32), String) with rows [0,1,2] (array) and '[0,1,2]' (string) under variant_throw_on_type_mismatch = 0: unoptimized returns 1, \N; the previous wrapper returned 1, 1 (string parsed into an array). A Variant(Array(UInt8), Array(Float32), String) with a string row, or a Dynamic ref, made the previous wrapper throw CANNOT_READ_ARRAY_FROM_TEXT / CANNOT_PARSE_TEXT. All reproduce on demand.
b Root cause explained? The graceful-handling wrapper reinstates the null mask with isNull(ref) only, then casts assumeNotNull(ref) to Array(element_type). The unoptimized function routes the ref through the default Variant/Dynamic adaptor, which (with *_throw_on_type_mismatch = 0) turns a non-array active alternative into NULL. The wrapper instead casts that non-array value to an array, so it computes a bogus distance or fails to parse, diverging from the unoptimized NULL.
c Fix matches root cause? Yes. The rewrite is now applied only when the reference always yields an array where it is not NULL: a Nullable / LowCardinalityNullable array, or a Variant whose alternatives are all arrays. A Dynamic ref, or a Variant with any non-array alternative, skips the optimization and reads the whole QBit column, matching the unoptimized adaptor exactly.
d Test intent preserved / new tests added? Preserved and extended. Section 6 now uses an all-array Variant(Array(Float32)) ALIAS so it still exercises the optimized clone-preservation path. New section 7 covers Variant(Array(Float32), String) and Dynamic references, asserting opt == unopt (NULL on non-array rows) and that the optimization is skipped (whole-vec read). Sections 1-6 unchanged.
e Demonstrated in both directions? Yes. Without the fix the bot's Variant(Array(Float32), String) repro returns 1, 1 (and the 3-alternative / Dynamic cases throw); with the fix opt == unopt for every case (1, \N, \N), confirmed on a debug binary (build id 1ed0152b).
f Fix is general, not a narrow patch? Yes. nonNullValueIsAlwaysArray covers the whole type family, not just the reported Variant(Array(Float32), String): all-array Variants of any arity keep the optimization, mixed Variants and Dynamic skip it, Nullable/LowCardinalityNullable arrays are handled by the nested-type check. The original LOGICAL_ERROR (STID 0250-3bee), the non-deterministic-ref guard, and the ALIAS-clone path all remain covered; the full QBit/distance sibling suite (03363-03380, 03730, 03829, 03926, 04104) passes.

Verification: 04258 passes 10/10 under the runner with full randomization; the QBit/distance sibling suite passes 24/24 (1 feature-gated skip).

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

Copy link
Copy Markdown
Collaborator Author

Pushed fb91a686 to fix a self-inflicted CI failure on the new 04258 regression test.

The previous CI run was green on every new-analyzer shard but failed on Stateless tests (amd_llvm_coverage, old analyzer, ...):

Code: 48. DB::Exception: EXPLAIN QUERY TREE is only supported with the analyzer. SET enable_analyzer = 1. (NOT_IMPLEMENTED)

04258 asserts on EXPLAIN QUERY TREE, which the old analyzer does not support, and the pass it covers (DistanceTransposedPartialReadsPass) is an analyzer-only rewrite anyway. Fix: pin SET enable_analyzer = 1 at the top of the test, matching the sibling 03375_l2_distance_transposed_partial_reads_pass.sql (which passes 3000x on that same old-analyzer shard). Test-only change, source untouched.

Verified locally (debug binary, capped server): with the session forced to the old analyzer (--enable_analyzer 0, as the shard injects via the default profile), the test now matches its reference; the pre-fix test reproduces the exact Code: 48 there. New-analyzer runs are unchanged (3/3 stable).

/// 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();

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.

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.

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.

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?

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.

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))?

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.

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 with ILLEGAL_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-nullable Array, so ref_vec_is_nullable is 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)) is Float64 with both optimize_qbit_distance_function_reads = 0 and = 1. The rewrite casts the reference to Array(element_type) and the result type is unchanged, so the optimization still applies (reads vec.1) and the values match the unoptimized path. An actual NULL element inside the array ([0, NULL, 2]) throws the same CANNOT_INSERT_NULL_IN_ORDINARY_COLUMN on 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]>
@clickhouse-gh

clickhouse-gh Bot commented Jun 24, 2026

Copy link
Copy Markdown
Contributor

LLVM Coverage Report

Metric Baseline Current Δ
Lines 85.30% 85.40% +0.10%
Functions 92.60% 92.60% +0.00%
Branches 77.50% 77.50% +0.00%

Changed lines: Changed C/C++ lines covered by tests: 66/78 (84.62%) | Lost baseline coverage: none · Uncovered code

Full report · Diff report

@groeneai

Copy link
Copy Markdown
Collaborator Author

CI finish ledger — c4ab8b5

CI 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 CH Inc sync, not part of the public gate). Nothing to own.

Check / test Reason Owner / fixing PR
(none) — All checks green
Sync — CH Inc sync (private, not actionable)

Session id: cron:our-pr-ci-monitor:20260624-193000

@groeneai

groeneai commented Jul 2, 2026

Copy link
Copy Markdown
Collaborator Author

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 function_node->getResultType() is Nullable. So for a nullable / Variant / Dynamic reference vector the rewritten result type stays identical (Nullable) while the partial-read subcolumn optimization is preserved, and there is no separate null-mask wrapper (the reference is still a single argument, so there is no multiple-evaluation concern). That is the graceful-handling direction requested in this thread, done more simply, which makes this PR redundant and it now conflicts with the merged code.

Master shows no further hits of this signature since that fix; the single 2026-07-01 sighting was on a base that predated f4c3622.

@groeneai groeneai closed this Jul 2, 2026
zeekay pushed a commit to hanzoai/datastore that referenced this pull request Sep 11, 2026
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).
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

can be tested Allows running workflows for external contributors pr-bugfix Pull request with bugfix, not backported by default

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants