Skip to content

Support strides for the QBit data type - #108103

Merged
alexey-milovidov merged 27 commits into
masterfrom
qbit-strides
Jul 2, 2026
Merged

alexey-milovidov merged 27 commits into
masterfrom
qbit-strides

Conversation

@alexey-milovidov

@alexey-milovidov alexey-milovidov commented Jun 22, 2026 •

Copy link
Copy Markdown
Member

Adds an optional third parameter to the QBit data type — the stride — for example QBit(BFloat16, 4096, 1024). It partitions the dimension dimensions into dimension / stride contiguous groups and stores each group's bit planes in separate streams. A search over only the first D dimensions (a multiple of stride) then reads just the streams of the groups that cover them, which is useful for Matryoshka embeddings, where the leading dimensions form a usable lower-dimensional embedding.

Motivation: today every bit plane of a QBit spans all dimensions in a single stream, so a vector search can read fewer bits but not fewer dimensions. Strides make the lower-dimensional prefix cheap to read.

Details:

  • The nested storage becomes a Tuple of element_size * num_strides FixedString columns in group-major order, so positional subcolumns still read one stream each: q.N reads bit plane (N-1) % element_size of stride group (N-1) / element_size. For BFloat16, q.1 … q.16 read the first stride, q.17 … q.32 the second, and so on.
  • When stride == dimension (the default), the type is unchanged and byte-identical to before, including its binary type encoding, so existing tables and on-disk parts are unaffected.
  • The transposed distance functions L2DistanceTransposed and cosineDistanceTransposed gain an optional fourth argument used_dims — the number of leading dimensions to read: L2DistanceTransposed(q, ref, precision, used_dims). The DistanceTransposedPartialReadsPass is stride-aware and rewrites the call to read only precision * (used_dims / stride) plane streams. Verified via EXPLAIN that an 8-bit search over the first 2048 of 4096 dimensions reads 16 of 64 streams, with results identical to a non-strided 2048-dimensional QBit.
  • Validation: dimension must be a multiple of stride, and stride must be a multiple of 8 when it is smaller than dimension. For backward compatibility, a new binary type encoding QBitWithStride (0x37) is used only when stride != dimension.

Changelog category (leave one):

  • New Feature

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

Added an optional stride parameter to the QBit data type (QBit(T, dimension, stride)) that stores groups of dimensions in separate streams, so a vector search can read only the first dimensions efficiently (e.g. for Matryoshka embeddings). The transposed distance functions accept an optional fourth used_dims argument to read a reduced number of dimensions.

Documentation entry for user-facing changes

  • Documentation is written (the QBit data type page and the transposed distance functions are updated).

🤖 Generated with Claude Code

Version info

  • Merged into: 26.7.1.397 (included in 26.7 and later)

Add an optional third parameter to `QBit`, the stride, e.g.
`QBit(BFloat16, 4096, 1024)`. It partitions the `dimension` dimensions
into `dimension / stride` contiguous groups and stores each group's bit
planes in separate streams. A search over only the first `D` dimensions
(a multiple of `stride`) then reads just the streams of the groups that
cover them, which is useful for Matryoshka embeddings.

The nested storage becomes a `Tuple` of `element_size * num_strides`
`FixedString` columns in group-major order, so the positional subcolumns
keep reading one stream each: `q.N` reads bit plane `(N-1) % element_size`
of stride group `(N-1) / element_size`. When `stride == dimension` (the
default) the type is unchanged and byte-identical to before.

The transposed distance functions `L2DistanceTransposed` and
`cosineDistanceTransposed` gain an optional fourth argument `dims`, the
number of leading dimensions to read for a reduced-dimension search:
`L2DistanceTransposed(q, ref, precision, dims)`. The
`DistanceTransposedPartialReadsPass` is stride-aware and rewrites the call
to read only `precision * (dims / stride)` plane streams.

Validation: `dimension` must be a multiple of `stride`, and `stride` must
be a multiple of 8 when it is smaller than `dimension`. For backward
compatibility a new binary type encoding `QBitWithStride` is used only
when `stride != dimension`.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
@alexey-milovidov
alexey-milovidov requested a review from rienath June 22, 2026 06:05
@clickhouse-gh

clickhouse-gh Bot commented Jun 22, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [d3d694e]

Summary: ✅


AI Review

Summary

This PR adds stride to QBit, updates the serialization/cast paths, and extends the transposed distance functions with reduced-dimension reads via the fourth used_dims argument. The core runtime changes look coherent, but one important generator/fuzzing surface is still out of sync with the now-supported QBit(Int8, ...) variant, so I would keep this at request-changes until that carrier is updated too.

PR Metadata
  • Changelog category: New Feature is correct for the actual change.
  • Changelog entry: required and mostly specific, but it is stale relative to the current head: it still says dims and still frames the fourth argument as applying only to the original two transposed distance functions. Suggested replacement:
    Added an optional stride parameter to the QBit data type (QBit(T, dimension, stride)) that stores groups of dimensions in separate streams, so vector search can read a leading prefix of dimensions efficiently (for example with Matryoshka embeddings). The transposed distance functions accept an optional fourth used_dims argument for reduced-dimension search.
Findings

⚠️ Majors

  • [src/Client/BuzzHouse/Generator/SQLTypes.cpp:2129] QBit now publicly supports Int8, but the BuzzHouse QBit generator/proto/stringifier path still hardcodes floating-point subtypes. As a result QBit(Int8, ..., stride) cannot be generated or round-tripped there, which leaves one supported QBit variant outside this fuzzing surface and breaks representational parity with the runtime.
Final Verdict

⚠️ Request changes

@clickhouse-gh clickhouse-gh Bot added the pr-feature Pull request with new product feature label Jun 22, 2026
Comment thread src/DataTypes/DataTypesBinaryEncoding.h Resolved
`Build (arm_tidy)` failed with `cppcoreguidelines-pro-type-member-init`:
the local `InternalArguments res;` left its `size_t` members uninitialized.
Value-initialize it with `InternalArguments res{};`.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
The AST fuzzer found that `L2DistanceTransposed(vec, ref, precision, dims)`
with a nullable `dims` argument (e.g. `toNullable(8)`) tripped the pass's
own result-type guard: `A query tree node does not have a valid source
node after running DistanceTransposedPartialReadsPass. Before:
Nullable(Float64), after: Float64`.

The function's result is `Nullable` when any of its arguments is nullable.
The pass removes the precision and dims arguments, so to preserve the
result nullability it forces it onto the trailing size constant — but it
only checked the precision argument, not the new optional `dims` argument.
Now it converts the size constant to nullable when either the precision or
the dims argument is nullable.

CI: #108103 (AST fuzzer (amd_debug, targeted))

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
Comment thread src/DataTypes/DataTypeQBit.cpp Resolved
@rienath rienath self-assigned this Jun 22, 2026
Addresses the automated review feedback on the QBit strides PR:

- Bound the number of stride groups (`dimension / stride`) to `MAX_STRIDE_GROUPS`
  in the `DataTypeQBit` constructor. The nested storage materializes
  `element_size * num_strides` `FixedString` streams, so a huge dimension with a
  tiny stride (e.g. `QBit(Float32, 8000008, 8)`, also reachable via a crafted
  `QBitWithStride` binary type) could otherwise exhaust memory in `getNestedType`.
  A non-strided QBit always has just `element_size` streams, so it is unaffected.
- `04405_qbit_stride_distance`: prove the partial-read I/O contract. The test now
  counts the distinct `vec.N` streams referenced in the query plan, showing the
  reduced-dimension search reads only the covered groups' planes (16 of 64), the
  full search reads all 64, and with the optimization disabled none are read
  (the whole `vec` is read instead). Previously the numeric checks alone would
  pass even via the public QBit fallback without any stream reduction.
- Docs: the `stride % 8` rule applies only when `stride` is smaller than the
  dimension; add the `QBitWithStride` row (`0x37`) to the binary-encoding spec.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
# Conflicts:
#	src/Functions/FunctionsConversion.cpp
Comment thread src/DataTypes/DataTypeQBit.cpp Resolved
The in-source `Documentation` block registered for the `QBit` data type
still described the pre-stride layout: it listed a fixed number of
subcolumns per element type and did not mention the group-major `vec.N`
mapping or the optional fourth `dims` argument of the transposed distance
functions. With a strided `QBit` such as `QBit(BFloat16, 4096, 1024)`
there are 64 subcolumns, not 16, so the generated type-family
documentation disagreed with the user-facing `qbit.md`.

Mirror the subcolumn, group-major ordering, and reduced-dimension search
wording from `docs/en/sql-reference/data-types/qbit.md` into the block.

Addresses the AI review finding on `src/DataTypes/DataTypeQBit.cpp`.
alexey-milovidov and others added 8 commits June 28, 2026 15:30
Resolve conflicts between the QBit stride feature and the QBit(Int8)
support that landed in master (#108105):
- QueryFuzzer: keep Int8 in the element-type list and the strided branch.
- convertFieldToType: combine the Int8 element conversion (with the
  wrap/reject contract) with the per-stride-group transpose.
- ColumnQBit::getName, DataTypeQBit/qbit.md docs: list Int8 alongside the
  per-stride-group subcolumn counts.
- distanceTransposed: accept Int8 reference vectors in the internal form
  and bound the int8 SimSIMD int32 accumulator by 'dims' (the number of
  dimensions actually read) instead of the removed 'qbit_size'.
Address review feedback: the strided `QBit` adds the `0x37`
`QBitWithStride` binary type encoding and changes the Native column
stream shape to `element_size * (dimension / stride)` `FixedString`
streams grouped by stride. Update `docs/en/interfaces/specs/NativeFormat.md`
so third-party Native readers do not have to rediscover this from the
C++ source.
The format spec deliberately scopes the `QBit` family's on-wire payload
out ("outside the scope of this page"), the same as `AggregateFunction`.
Documenting the strided stream layout there would contradict that
sentence, so limit the spec change to the type spelling
`QBit(T, N[, stride])` and leave whether to bring the whole QBit family
in-scope (and how) to the spec author.
Address review feedback on the `Native` format spec: a strided `QBit`
changes the on-wire stream shape and adds the `0x37` `QBitWithStride`
binary type encoding, and the reviewer asked that third-party `Native`
readers not have to recover this from the C++ source.

The `QBit` payload is deliberately scoped out of
`docs/en/interfaces/specs/NativeFormat.md` (the same as
`AggregateFunction`), so rather than inlining the layout there — which
would contradict that boundary — the out-of-scope note now cross-links
to the two pages that already document it in full: the `QBit` data type
page (strided stream layout, group-major `FixedString` streams) and the
binary type encoding reference (tags `0x36` and `0x37`).

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
…e reference vector

The AST fuzzer hit a `LOGICAL_ERROR` while running
`DistanceTransposedPartialReadsPass`:

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

`L2DistanceTransposed` and `cosineDistanceTransposed` use the default NULL
implementation, so the original (user-facing) call is `Nullable` whenever any
of its arguments is `Nullable` - including the reference vector (for example,
a `Variant`-typed reference vector produced by the fuzzer via `multiIf`). When
the pass rewrote the call into its internal form it dropped the precision and
`dims` arguments and cast the reference vector to a plain `Array`, losing the
nullability, and then the post-rewrite type-check threw.

The pass only forced the nullability back onto the trailing size constant when
the precision or `dims` arguments were `Nullable`, missing the reference-vector
(and any other) case. Drive the decision off the actual original result type
instead: force the size constant to `Nullable` whenever the original result was
`Nullable`, which keeps the rewritten result type identical.

Found by the AST fuzzer:
https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=108103&sha=de8225ac7b3fe0ee2f55270b83780a767be2321b&name_0=PR&name_1=AST%20fuzzer%20%28amd_debug%2C%20targeted%29

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

Copy link
Copy Markdown
Member Author

The AST fuzzer (amd_debug, targeted) failure (Logical error: ... DistanceTransposedPartialReadsPass. Before: Nullable(Float64), after: Float64, STID 0250-3bee) is fixed in f4c36228cef.

Root cause: the fuzzer produced a call whose reference vector has a type that makes the result Nullable (a Variant built via multiIf). L2DistanceTransposed/cosineDistanceTransposed use the default NULL implementation, so the original call is Nullable(Float64). DistanceTransposedPartialReadsPass rewrites the call into its internal form — dropping the precision/dims arguments and casting the reference vector to a plain Array — which lost the nullability, so the post-rewrite type check threw.

The pass only restored nullability when the precision or dims arguments were Nullable, missing the reference-vector (and any other) case. Fixed by driving the decision off the actual original result type: force the trailing size constant to Nullable whenever the original result was Nullable.

Verified on a local debug build: the exact fuzzer query now returns Nullable(Float64) instead of throwing; added regression test 04493_qbit_distance_nullable_reference; existing QBit tests (04489-04492, 04405_qbit_int8_distance, 03368_qbit_subcolumns, ...) still pass. Also merged the latest master.

@alexey-milovidov

Copy link
Copy Markdown
Member Author

CI triage (commit a6745c96)

Public CI on the latest commit is green except two unrelated flakes, and the AI Review verdict is ✅ Approve with 0 unresolved review threads. Diff-line coverage is 86.57% (+0.10% lines overall). No code changes were needed.

The two reds, both confirmed unrelated to this PR:

  1. Stateless tests (arm_asan_ubsan, azure, parallel) → 03748_join_on_complex_condition_result_memory — Code: 241 ... (total) memory limit exceeded: would use 4.55 GiB ..., current RSS: 54.38 GiB, maximum: 53.69 GiB ... While executing JoiningTransform. (MEMORY_LIMIT_EXCEEDED). This is the server-wide OvercommitTracker stopping a query because the whole loaded parallel/azure box was over its memory budget (54 GiB RSS), not a per-query limit set by the test. The test exercises ConcurrentHashJoin; this PR touches no JOIN code. It is a known memory-pressure flake on this lane: in the last 30 days it failed on master itself (PR=0, 2026-06-10) and on unrelated PRs 104965, 107555, 97452, 103088. Needs a rerun.

  2. Stress test (amd_tsan) → Hung check failed, possible deadlock found — the known, open issue #107941 (linked by CI itself). The hung thread goes through executeASTFuzzerQueries; there are no QBit/DistanceTransposed/stride frames in the dump. The QBit test [ FAIL ] markers in the stress runner logs are expected AST-fuzzer noise (e.g. __fuzz_* mutations hitting a hardcoded-UUID TABLE_ALREADY_EXISTS collision and an Array(UInt32) NULL illegal-type error), not the reported failure. Needs a stress rerun (or override).

Other notes:

  • MERGEABLE / UNSTABLE, no conflicts with master (dry-run merge clean); merge-base is from today (00:38Z) and the branch already merged master at 02:09Z, so no re-merge is warranted.
  • The Native format spec (docs/en/interfaces/specs/NativeFormat.md) and the binary type encoding reference are updated and self-consistent: the new QBitWithStride tag 0x37 carries <element_type_encoding><var_uint_dimension><var_uint_stride>, the non-strided QBit stays byte-identical on 0x36 (decode defaults stride = dimension), and encodeDataTypeImpl/decodeDataType are symmetric.

Blocked only on: rerunning the two flaky checks (or overriding #107941), the requested human review (@rienath), and merge.

@alexey-milovidov

Copy link
Copy Markdown
Member Author

@groeneai, provide a fix for 03748_join_on_complex_condition_result_memory

alexey-milovidov and others added 4 commits July 1, 2026 15:53
…e groups with BAD_ARGUMENTS

Two fixes for `@rienath`'s review of `DataTypeQBit`:

- `updateHashImpl` hashed the derived nested `Tuple` structure plus
  `dimension` and `stride`. That is more expensive (it materializes the
  nested tuple) and less precise than hashing the element type directly,
  since the tuple only encodes the element *size*. Hash `element_type`,
  `dimension` and `stride` directly, matching the fields `equals` compares.

- The `MAX_STRIDE_GROUPS` limit is reachable from ordinary user input (a
  `CREATE TABLE` with a well-formed AST but a dimension/stride combination
  producing too many groups), so it is a bad argument rather than an
  unexpected AST structure. Throw `BAD_ARGUMENTS` instead of
  `UNEXPECTED_AST_STRUCTURE`. The stride divisor and multiple-of-8 checks
  keep `UNEXPECTED_AST_STRUCTURE` (their behavior is pinned by existing tests).

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
…d SQL test

`@rienath` noted the `MAX_STRIDE_GROUPS` bound was only exercised in the
`gtest`, so it was not verified through the full SQL path. Move it to a new
stateless test `04497_qbit_stride_max_groups.sql` that creates tables and
checks that exactly `MAX_STRIDE_GROUPS` groups is accepted, one group over
is rejected with `BAD_ARGUMENTS`, and a non-strided `QBit` is unaffected by
the bound regardless of dimension.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
…nsposed distance functions

`@rienath` pointed out that `parseInternalArguments` in
`distanceTransposed.cpp` hand-rolled the same supported-element-type check
(`Int8`, `BFloat16`, `Float32`, `Float64`) that the new
`DataTypeQBit::isSupportedElementType` helper now provides. Reuse the helper
so the whitelist lives in one place.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
`@rienath` asked that the comment on the `stride` field be written as if the
feature is already merged rather than referring to the previous behavior
("behaves exactly as before"). Describe the non-strided default directly:
every bit plane spans all dimensions in a single stream.

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

Copy link
Copy Markdown
Member Author

continue-pr pass — addressed @rienath's review (commits 79ac4a2e8cd..711ddc16008)

Thanks for the review! Addressed the actionable items:

  • updateHashImpl (79ac4a2e8cd): now hashes element_type, dimension and stride directly instead of the derived nested tuple structure — cheaper and captures the element type identity precisely (matches what equals compares).
  • MAX_STRIDE_GROUPS error code (79ac4a2e8cd): reachable from ordinary user input, so it now throws BAD_ARGUMENTS rather than UNEXPECTED_AST_STRUCTURE. (The stride divisor / multiple-of-8 checks keep UNEXPECTED_AST_STRUCTURE because 03364_qbit_negative and the serialization gtest pin them — can switch those too for consistency if you prefer.)
  • End-to-end test for the stride-group bound (544898a15a7): moved out of the gtest into the stateless test 04497_qbit_stride_max_groups.sql, which checks it via CREATE TABLE.
  • isSupportedElementType reuse (43d65918458): parseInternalArguments in distanceTransposed.cpp now uses the shared helper instead of the hand-rolled TypeIndex check.
  • stride field comment (711ddc16008): reworded in present tense.

The bot's remaining distanceTransposed.cpp:413 "Blocker" is a false positive — offsets[i - 1] for i == 0 reads offsets[-1], which is the standard ColumnArray::Offsets (PaddedPODArray) idiom: operator[] takes a signed index and permits -1, pad_left is PADDING_FOR_SIMD and alloc zero-initializes element -1, so it is real, zero-valued memory (exactly what ColumnArray::sizeAt(0) relies on). It is pre-existing L2DistanceTransposed code, not an OOB read, and no sanitizer flags it. Replied and resolved that thread.

Left open as your calls (design/preference, not mechanical):

  • Restructuring / simplifying the qbit.md reduced-dimension section (qbit.md:119).
  • An illustration of bit planes vs. stride groups (qbit.md:134).
  • Renaming dims to avoid confusion with dim (DataTypeQBit.cpp), which would ripple across code and docs.

CI note: the only red is AST fuzzer (amd_debug, targeted) with Logical error: Reading from materialized CTE 'A' before its materialization completed - DelayedPortsProcessor gate is missing (STID 2467-2c2d). The stack is entirely ReadFromMemoryStorageStep / MemorySource / DelayedPortsProcessor with no QBit / distance frames; it reproduces on master and unrelated PRs, so it is not caused by this change.

@groeneai, please investigate this unrelated failure and provide a fix (or link an existing one) in a separate PR: https://github.com/ClickHouse/ClickHouse/actions/runs/28522483922/job/84558982345 — Logical error: Reading from materialized CTE 'A' before its materialization completed - DelayedPortsProcessor gate is missing (STID 2467-2c2d). It is master-wide (not QBit-specific) and I don't see a dedicated tracking issue for this site.

Comment thread src/Functions/vectorFunctions.cpp Resolved
…ublic docs

The AI Review on #108103 (head
`711ddc16`) flagged that the structured documentation of the transposed
distance functions still described the vector argument as the pre-stride
two-argument form `QBit(T, UInt64)`, contradicting the `QBit` data type page
which now documents the optional third `stride` parameter this PR adds. The
same staleness affected the other public `QBit` syntax references in
`annindexes.md` and the RowBinary `QBit` section.

Update the `L2DistanceTransposed`, `cosineDistanceTransposed`, and
`dotProductTransposed` argument docs in `vectorFunctions.cpp` to
`QBit(T, UInt64[, UInt64])`, and add the optional `[, stride]` to the `QBit`
syntax in `annindexes.md` (with a short bullet pointing at the `QBit` page) and
in the RowBinary format doc (noting that `stride` is a server-side storage
grouping and does not change the RowBinary wire format). Docs/docstring only; no
behavior change.

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

Copy link
Copy Markdown
Member Author

continue-pr pass — synced the remaining public QBit docs with the stride parameter (commit 10349e8a52d)

The latest AI Review (head 711ddc16) was a ⚠️ Request changes with a single Major: the structured docs of the transposed distance functions still advertised the vector argument as the pre-stride two-argument form QBit(T, UInt64), contradicting the QBit data type page that this PR updated, and the same staleness affected the other public QBit syntax references.

Fixed:

  • src/Functions/vectorFunctions.cpp — the vectors argument of L2DistanceTransposed, cosineDistanceTransposed, and dotProductTransposed now reads QBit(T, UInt64[, UInt64]), matching the optional third stride parameter (the dims argument only applies to a strided QBit).
  • docs/en/engines/table-engines/mergetree-family/annindexes.md — the QBit declaration syntax is now QBit(element_type, dimension[, stride]), with a short bullet describing stride and linking the QBit data type page.
  • docs/en/interfaces/formats/RowBinary/RowBinary.md — the QBit syntax shows the optional [, stride], with a note that stride is a server-side storage grouping and does not change the RowBinary wire format (still the full Array of dimension elements).

Docs/docstring only; no behavior change, no reference-test impact. Replied to and resolved the clickhouse-gh review thread.

Still left open as @rienath's calls (design/preference, not mechanical), as noted earlier: restructuring the qbit.md reduced-dimension section, an illustration of bit planes vs. stride groups, and the dims/dim naming.

alexey-milovidov and others added 2 commits July 1, 2026 18:27
The AI review flagged that the rendered `RowBinary` and binary-encoding
pages now advertise the optional `QBit` `stride` argument, but the
source doc blocks they are maintained from were still out of sync:

- `BinaryRowInputFormat.cpp`: the embedded `QBit` `RowBinary` doc block
  still showed `QBit(element_type, dimension)` without the optional
  `stride`; add it and note that `stride` is a server-side storage
  grouping that does not change the `RowBinary` wire format.
- `DataTypesBinaryEncoding.h`: the source comment table listed the
  `0x36`/`0x37` rows but lacked the note that `stride == N`
  canonicalizes to the two-argument `0x36` form; add the same note the
  rendered `data-types-binary-encoding.md` already carries.

No behavior change.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
Per review, `dim` (the `QBit` dimension) and `dims` (the optional fourth
argument of `L2DistanceTransposed`, `cosineDistanceTransposed` and
`dotProductTransposed` selecting how many leading dimensions to read for
a Matryoshka-style search) were easy to confuse.

Rename the latter to `used_dims` consistently across the user-facing docs
(`qbit.md`, the `DataTypeQBit` documentation), the function documentation
and syntax strings in `vectorFunctions.cpp`, the error messages, and the
internal variables, struct members and comments in `distanceTransposed.cpp`
and `DistanceTransposedPartialReadsPass.cpp`. The arguments stay positional,
so this is a documentation and naming change with no behavior change.

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

Copy link
Copy Markdown
Member Author

continue-pr pass — synced source-level format docs and renamed the fourth distance-function argument (commits 5594ba8b876, d3d694e3181)

The latest AI Review flipped to ✅ Approve with two documentation-sync follow-up nits, and one of @rienath's threads had a resolved naming decision. Addressed all three:

  • Source-level format docs (5594ba8b876): the rendered RowBinary and binary-encoding pages advertise the optional QBit stride argument, but the source doc blocks they are maintained from were still stale.
    • BinaryRowInputFormat.cpp: the embedded QBit RowBinary doc block now shows QBit(element_type, dimension[, stride]) and notes that stride is a server-side storage grouping that does not change the RowBinary wire format.
    • DataTypesBinaryEncoding.h: added the same stride == N → 0x36 canonicalization note the rendered data-types-binary-encoding.md already carries.
  • dims → used_dims rename (d3d694e3181): per @rienath's thread (and the agreed name), renamed the transposed distance functions' optional fourth argument from dims to used_dims to avoid confusion with the QBit dim. Applied consistently across the docs (qbit.md, the DataTypeQBit documentation), the function documentation/syntax strings, the error messages, and the internal variables/struct members/comments in distanceTransposed.cpp and DistanceTransposedPartialReadsPass.cpp. The arguments stay positional, so there is no behavior change; -fsyntax-only passes on both changed translation units.

The three corresponding review threads are resolved. Left open for the author's call are @rienath's two documentation-presentation suggestions on qbit.md (restructuring the internals section and adding an illustration).

@groeneai

groeneai commented Jul 1, 2026

Copy link
Copy Markdown
Collaborator

Investigation: materialized-CTE DelayedPortsProcessor gate is missing (STID 2467-2c2d)

Confirming this is unrelated to the QBit change and is a pre-existing chronic AST-fuzzer flake.

Spread (CIDB, 45d). The is_built == false fail-fast at ReadFromMemoryStorageStep.cpp:87 fires only in AST fuzzer (amd_debug, targeted*) jobs, 0 on master, across 8 unrelated PRs (this one, #108859, #107888, #108384, #102308, #106881, #105959, #105041). No dedicated open tracking issue (the original #100628 is closed; the assertion text changed with #105041 so that issue predates this form).

Failing query (report: https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=108103&sha=8334740836cd1b984376811f48b2e21640589511&name_0=PR&name_1=AST%20fuzzer%20%28amd_debug%2C%20targeted%29 , fuzzing step 474, query_id 64bbac1e):

WITH rs AS MATERIALIZED (
  SELECT DISTINCT 0 FROM t_04227
  PREWHERE intDiv(c, bech32Encode(toString(NULL, 100)))
  GLOBAL NOT IN (SELECT DISTINCT c FROM ct LIMIT -2147483649)   -- ref 1
  WHERE c IN (SELECT c FROM ct LIMIT 2147483647, 65536)          -- ref 2 (c is the PK)
  GROUP BY 1),
  ct AS MATERIALIZED (SELECT c FROM t_04227 GROUP BY ... HAVING 2147483646)  -- empty
SELECT DISTINCT count() IGNORE NULLS FROM rs AS a QUALIFY 2

Mechanism. The materialized CTE ct is referenced by two set-subqueries inside rs:

  • ref 1 GLOBAL NOT IN builds its set at runtime via DelayedCreatingSetsStep::makePlansForSets, which calls removeAllDelayedMaterializingCTEsStep on the sub-plan and relies on the outer MaterializingCTEsStep gate.
  • ref 2 c IN (...) on the PK column builds its set during KeyCondition analysis via FutureSetFromSubquery::buildOrderedSetInplace.

is_materialization_planned is a single shared claim on the one MaterializedCTE. With debug tracing I see the claim flow: whichever path claims is_materialization_planned first materializes ct; the other path's makePlansForCTEs sees already_planned == true, plan == nullptr and skips both the writer and the gate. In the passing case the inplace buildOrderedSetInplace path wins and fully materializes ct synchronously before any read, so is_built is already true. The crash is the ordering where a reader on a branch whose gate was stripped (ref 1) or skipped is scheduled before the winning path has set is_built. It is a plan-shape + scheduling race between the two set-build paths over one shared claim and one stripped gate.

Reproduction. I could not make it deterministic locally despite: the exact query and literals; the exact preceding fuzzer step sequence; ~160 concurrent runs with randomized max_threads/serialize_query_plan/prewhere/max_block_size; a ThreadFuzzer-enabled server; and 3000 AST-query-fuzzer runs on the crash-shaped seed under ThreadFuzzer. All returned correct results; the fail-fast never fired. It reproduces only as a rare timing coincidence in CI.

Per the guidance to not push planner changes I cannot back with a deterministic repro, I would rather not guess at the gate wiring here, since it is the machinery you added in #105041. @novikd, is the intended invariant that a single is_materialization_planned claim plus one canonical outer gate must cover every reader, or should a CTE reachable from a gate-stripped runtime set (ref 1) plus an inplace PK set (ref 2) get an independent gate? I can prepare a fix and a regression test once the intended direction is clear. I have the core dump, fuzzer.log, and server.log from the failing run if useful.

@alexey-milovidov

Copy link
Copy Markdown
Member Author

continue-pr pass — addressed the flipped AI Review

The AI Review re-ran on d3d694e3181 and flipped back to ⚠️ Request changes with one new Major (BuzzHouse SQLTypes.cpp:2129) plus a note that the changelog entry was stale. Triage:

  • Changelog entry (valid, in-scope): it still referred to the fourth distance-function argument as dims, which was renamed to used_dims in a previous commit. Updated the PR description (both the details bullet and the changelog entry) to used_dims.

  • BuzzHouse QBit(Int8, …) Major (pre-existing, out of scope): this gap exists on master and is orthogonal to the stride feature — Int8 was already a supported QBit element type before this branch, and master's BuzzHouse QBit generator/proto already modeled only FloatingPoints subtypes (via randomFloatType), so it could never generate QBit(Int8, …). This PR only adds the orthogonal stride axis and does not touch QueryFuzzer.cpp (which has no QBit handling on master). Rebutted with the code evidence in the inline thread and left it open — broadening the BuzzHouse QBit fuzzer to integer subtypes is a separate coverage improvement.

Remaining unresolved threads are the two @rienath documentation suggestions (qbit.md:119 restructure, qbit.md:134 add an illustration), left for the author.

CI is green on the current head (0 failures). No re-merge needed (merge-base ~14h old, no conflicts, MERGEABLE).

@alexey-milovidov
alexey-milovidov requested a review from rienath July 1, 2026 21:54
@clickhouse-gh

clickhouse-gh Bot commented Jul 1, 2026

Copy link
Copy Markdown
Contributor

LLVM Coverage Report

Metric Baseline Current Δ
Lines 85.40% 85.40% +0.00%
Functions 92.60% 92.60% +0.00%
Branches 77.60% 77.60% +0.00%

Changed lines: Changed C/C++ lines covered: 630/712 (88.48%) · Uncovered code

Full report · Diff report

@alexey-milovidov
alexey-milovidov added this pull request to the merge queue Jul 2, 2026
Merged via the queue into master with commit 086d402 Jul 2, 2026
176 checks passed
@alexey-milovidov
alexey-milovidov deleted the qbit-strides branch July 2, 2026 01:16
@robot-ch-test-poll3 robot-ch-test-poll3 added the pr-synced-to-cloud The PR is synced to the cloud repo label Jul 2, 2026
zeekay pushed a commit to hanzoai/datastore that referenced this pull request Sep 11, 2026
The AST fuzzer found that `L2DistanceTransposed(vec, ref, precision, dims)`
with a nullable `dims` argument (e.g. `toNullable(8)`) tripped the pass's
own result-type guard: `A query tree node does not have a valid source
node after running DistanceTransposedPartialReadsPass. Before:
Nullable(Float64), after: Float64`.

The function's result is `Nullable` when any of its arguments is nullable.
The pass removes the precision and dims arguments, so to preserve the
result nullability it forces it onto the trailing size constant — but it
only checked the precision argument, not the new optional `dims` argument.
Now it converts the size constant to nullable when either the precision or
the dims argument is nullable.

CI: ClickHouse#108103 (AST fuzzer (amd_debug, targeted))

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
zeekay pushed a commit to hanzoai/datastore that referenced this pull request Sep 11, 2026
…ublic docs

The AI Review on ClickHouse#108103 (head
`711ddc16`) flagged that the structured documentation of the transposed
distance functions still described the vector argument as the pre-stride
two-argument form `QBit(T, UInt64)`, contradicting the `QBit` data type page
which now documents the optional third `stride` parameter this PR adds. The
same staleness affected the other public `QBit` syntax references in
`annindexes.md` and the RowBinary `QBit` section.

Update the `L2DistanceTransposed`, `cosineDistanceTransposed`, and
`dotProductTransposed` argument docs in `vectorFunctions.cpp` to
`QBit(T, UInt64[, UInt64])`, and add the optional `[, stride]` to the `QBit`
syntax in `annindexes.md` (with a short bullet pointing at the `QBit` page) and
in the RowBinary format doc (noting that `stride` is a server-side storage
grouping and does not change the RowBinary wire format). Docs/docstring only; no
behavior change.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
zeekay pushed a commit to hanzoai/datastore that referenced this pull request Sep 11, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

pr-feature Pull request with new product feature 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.

4 participants