Skip to content

Add higher-order array functions to pack bits. - #50053

Closed
Eridanus117 wants to merge 39 commits into
ClickHouse:masterfrom
Eridanus117:issue_48830
Closed

Eridanus117 wants to merge 39 commits into
ClickHouse:masterfrom
Eridanus117:issue_48830

Conversation

@Eridanus117

@Eridanus117 Eridanus117 commented May 21, 2023 •

Copy link
Copy Markdown
Contributor

Closes: #48830

Adds higher-order array functions that apply a lambda to each element of an array and pack the resulting bits into a compact representation. Useful for compression and quantization in vector-search workloads, where a single bit (or a small group of bits) is derived per dimension and packed into a fixed-width value.

Six functions are added:

  • arrayPackBitsToUInt64(f, arr) — pack one bit per element into a UInt64 (only the first 64 bits are used).
  • arrayPackBitsToString(f, arr) — pack one bit per element into a String of ceil(size / 8) bytes.
  • arrayPackBitsToFixedString(f, n, arr) — pack one bit per element into a FixedString(n).
  • arrayPackBitGroupsToUInt64(f, g, arr) — the same, but the lambda returns an integer whose low g bits form a group, and the groups are packed contiguously (N·g bits).
  • arrayPackBitGroupsToString(f, g, arr)
  • arrayPackBitGroupsToFixedString(f, n, g, arr)

Like the other higher-order array functions, several arrays of equal size can be passed, in which case the lambda takes one argument per array (arrayPackBitsToUInt64((x, y) -> x > y, lhs, rhs)).

Bits are packed most-significant-bit first within each byte and groups are packed contiguously, one after another (a group does not occupy a whole byte). The *ToUInt64 variants interpret the packed byte stream in little-endian byte order, as requested in the issue, so arrayPackBitsToUInt64(f, arr) = reinterpretAsUInt64(arrayPackBitsToString(f, arr)) and likewise for the group variants. The UInt64 and FixedString(n) results are always a prefix of the String byte stream: the stream is cut at 64 or n * 8 bits, so a group that straddles the boundary contributes only its leading bits. The implementation is a single ArrayPackBitsImpl template parameterized by the result column type and a PackGroups flag. FunctionArrayMapped is extended with a return_fixed_string trait so that an implementation returning a FixedString can forward the constant size argument to getReturnType.

Changelog category (leave one):

  • New Feature

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

Added higher-order array functions to pack bits: arrayPackBitsToUInt64, arrayPackBitsToString, arrayPackBitsToFixedString, arrayPackBitGroupsToUInt64, arrayPackBitGroupsToString, arrayPackBitGroupsToFixedString.

Documentation entry for user-facing changes

  • Documentation is written (mandatory for new features)

The functions carry embedded FunctionDocumentation (description, syntax, arguments, returned value, examples), from which the user-facing documentation is generated.


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

@Eridanus117

Copy link
Copy Markdown
Contributor Author

#48830

@Eridanus117 Eridanus117 changed the title A higher order array functions to pack bits. [WIP]A higher order array functions to pack bits. May 21, 2023
@clickhouse-ci

clickhouse-ci Bot commented May 21, 2023

Copy link
Copy Markdown

This is an automatic comment. The PR descriptions does not match the template.

Please, edit it accordingly.

The error is: More than one changelog category specified: 'New Feature', 'Improvement'

@clickhouse-ci

clickhouse-ci Bot commented May 28, 2023

Copy link
Copy Markdown

This is an automatic comment. The PR descriptions does not match the template.

Please, edit it accordingly.

The error is: Changelog entry required for category 'New Feature'

@Eridanus117 Eridanus117 changed the title [WIP]A higher order array functions to pack bits. A higher order array functions to pack bits. May 28, 2023
@clickhouse-ci

clickhouse-ci Bot commented May 28, 2023

Copy link
Copy Markdown

This is an automatic comment. The PR descriptions does not match the template.

Please, edit it accordingly.

The error is: Changelog entry required for category 'New Feature'

@Eridanus117
Eridanus117 marked this pull request as ready for review May 28, 2023 12:00
@Eridanus117
Eridanus117 marked this pull request as draft May 28, 2023 12:00
@Eridanus117
Eridanus117 marked this pull request as ready for review May 28, 2023 12:01
@Eridanus117
Eridanus117 marked this pull request as draft May 28, 2023 12:01
@Eridanus117
Eridanus117 marked this pull request as ready for review May 28, 2023 17:52
@Eridanus117
Eridanus117 marked this pull request as draft May 28, 2023 18:32
@Eridanus117
Eridanus117 marked this pull request as ready for review May 28, 2023 18:32
@Eridanus117 Eridanus117 changed the title A higher order array functions to pack bits. Add higher-order array functions to pack bits. May 28, 2023
@Eridanus117

Copy link
Copy Markdown
Contributor Author

@alexey-milovidov
Hello, I think this pull request can be reviewed preliminarily. I'm concerned about whether I've implemented the function in the way you wanted, so I hope you can take a look first. Then we can continue to review the code.

@ucasfl ucasfl added the can be tested Allows running workflows for external contributors label May 31, 2023
@robot-clickhouse-ci-2 robot-clickhouse-ci-2 added the pr-feature Pull request with new product feature label May 31, 2023
alexey-milovidov and others added 2 commits July 7, 2026 04:25
… truncating

Address review: the `n` (FixedString size) and `g` (group size) fixed
parameters were accepted for any integer type via `isInt`/`isUInt`, then
read through the 64-bit `getInt`/`getUInt` accessors. A 128/256-bit
constant was therefore silently truncated to its low 64 bits, so
`arrayPackBitGroupsToUInt64(x -> x, toUInt128('18446744073709551620'), ...)`
(the value is 2^64 + 4) behaved as `g = 4` instead of being rejected as a
group size greater than 64; the same truncation could shrink an oversized
`FixedString` size.

Restrict these fixed parameters to native integers with
`WhichDataType::isNativeInteger`, mirroring how `arrayTopK` validates its
`K` argument. This throws `ILLEGAL_TYPE_OF_ARGUMENT` for wide constants
before any range check, so an out-of-range value can no longer slip
through by truncation. Added focused rejection tests for `UInt128`/
`UInt256` constants passed as the group size and the `FixedString` size,
and updated the documented argument types to the native-integer subset.

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

Update the embedded `FunctionDocumentation` argument types for `n` and `g`
from `(U)Int*` to `(U)Int8/16/32/64` to reflect that these fixed
parameters are now restricted to native integers, matching `arrayTopK`.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
Comment thread src/Functions/array/arrayPackBits.cpp Resolved
Comment thread src/Functions/array/arrayPackBits.cpp Resolved
alexey-milovidov and others added 2 commits July 14, 2026 13:22
…e with current APIs

The branch for the `arrayPackBits*` / `arrayPackBitGroups*` higher-order
array functions (PR ClickHouse#50053, issue ClickHouse#48830) was ~45000 commits behind
`master`, so a plain merge produced conflicts across unrelated
subsystems. This commit brings the branch up to the current `master`
while keeping the feature exactly as reviewed: the net change against
`master` is still only `src/Functions/array/arrayPackBits.cpp`, the
`return_fixed_string` hook in `src/Functions/array/FunctionArrayMapped.h`,
and the `02769_array_pack_bits` test.

The feature already targets the current documentation API
(`FunctionDocumentation` with `IntroducedIn`/`Category`, matching
`arrayTopK`), so no source changes were needed beyond the merge.

Verified against current `master`: `clickhouse` links, `arrayPackBits.cpp`
compiles without warnings, all 24 value queries of `02769_array_pack_bits`
match the reference, and all 10 error cases throw the expected
`BAD_ARGUMENTS` / `ILLEGAL_TYPE_OF_ARGUMENT` codes.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
The AI review flagged that the lambda-type gate accepts `Int128`/`UInt128`/
`Int256`/`UInt256` while `execute` reads the result via `IColumn::getUInt` /
`getBool`, claiming those accessors throw for `wide::integer` columns.

Verified against current `master` that they do not: `getBool` evaluates the
full wide value (so `2^64` is truthy even though its low 64 bits are zero) and
`getUInt` returns the low 64 bits, of which only the low `g` bits are used for
groups. The functions therefore handle wide-integer lambda results correctly.
These regression tests lock in that behavior for the `UInt128` / `UInt256`
cases.

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

Copy link
Copy Markdown
Member

Brought this branch up to current master. It was ~45000 commits behind, so instead of a plain merge (which conflicted across unrelated subsystems) I merged master in and reconciled the feature so that the net change against master is still exactly arrayPackBits.cpp, the return_fixed_string hook in FunctionArrayMapped.h, and the 02769_array_pack_bits test. The feature already targets the current FunctionDocumentation API, so no source changes were needed beyond the merge.

Verified locally against current master: clickhouse links, arrayPackBits.cpp compiles without warnings, all value queries of 02769_array_pack_bits match the reference, and every error case throws the expected BAD_ARGUMENTS / ILLEGAL_TYPE_OF_ARGUMENT code.

Addressed the AI review:

  • PR description staleness — fixed the wording that said grouped variants write each g-bit group into a separate byte; groups are packed contiguously, matching the code/docs/tests.
  • Wide-integer lambda results (flagged as a blocker) — verified that getUInt/getBool do not throw for wide::integer columns on current master; wide results are handled correctly (2^64 is truthy, groups keep their low g bits). Added UInt128/UInt256 regression cases rather than restricting the lambda result type. Details in the inline reply.

The previous red checks were the known-flaky JoinStep "Block structure mismatch" (Stress amd_msan / AST fuzzer), unrelated to this change; CI is re-running on the refreshed branch.

One open item remains for @alexey-milovidov: the byte order of the *ToUInt64 variants (currently big-endian; issue #48830 suggests little-endian, i.e. arrayPackBitsToUInt64 == reinterpretAsUInt64(arrayPackBitsToString)). I left the current behavior unchanged since that's a design decision.

@clickhouse-gh

clickhouse-gh Bot commented Jul 31, 2026

Copy link
Copy Markdown
Contributor

LLVM Coverage Report

Metric Baseline Current Δ
Lines 86.50% 86.40% -0.10%
Functions 91.90% 91.90% +0.00%
Branches 78.70% 78.60% -0.10%

Changed lines: Changed C/C++ lines covered: 191/195 (97.95%) · Uncovered code

Full report · Diff report

alexey-milovidov and others added 2 commits August 7, 2026 07:32
The `arrayPackBitsToUInt64` and `arrayPackBitGroupsToUInt64` variants
previously accumulated the packed bits as a big-endian bitstream integer,
while issue ClickHouse#48830 explicitly asks for little-endian byte order. Now the
`UInt64` variants produce exactly the same byte stream as the `String` /
`FixedString` variants (most-significant-bit first within each byte) and
interpret it in little-endian byte order, so:

    arrayPackBitsToUInt64(f, arr) == reinterpretAsUInt64(arrayPackBitsToString(f, arr))
    arrayPackBitGroupsToUInt64(f, g, arr) == reinterpretAsUInt64(arrayPackBitGroupsToString(f, g, arr))

Updated the embedded documentation, the stateless test references, and
added explicit equivalence tests with `reinterpretAsUInt64`.

Addresses the AI review blocker:
https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=50053&sha=latest&name_0=PR

Co-Authored-By: Claude Fable 5 <[email protected]>
@clickhouse-gh

clickhouse-gh Bot commented Aug 7, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing f8a0d5620 with master 365470f5a (stripped binary size, per-symbol sizes and ThinLTO time; compile times per translation unit against the most recent warmup build that recompiled it).

⚠️ Significant changes: object file sizes.

Binary sizes

programs/clickhouse-stripped: smaller than the master baseline by the known offset between the two builds, so the difference is not shown. A delta that differs from the offset by more than 50% of it is shown, in either direction.

The official master build is compiled with -g and a pull request build is not, and XRay counts debug instructions towards its instrumentation threshold, so master instruments thousands of functions more and its binary is ~0.4% larger no matter what the pull request does.

Object file sizes ⚠️

10 object files changed (+896.79 KiB total), 1 added.

Object file Master PR Δ
src/Functions/array/CMakeFiles/clickhouse_functions_array.dir/arrayPackBits.cpp.o new 896.79 KiB +896.79 KiB

716 more object files are built by the master warmup baseline only (it builds every object-file target, a pull request build only clickhouse-bundle) and not compared.

Compile time of recompiled translation units

24 translation units recompiled, 105 s compile time in total, 23 of them have a recent master baseline.

Job report

Comment thread src/Functions/array/arrayPackBits.cpp Resolved
Comment thread src/Functions/array/arrayPackBits.cpp Resolved
The bit-packing higher-order array functions set `needOneArray` to `true`,
which rejected calls like `arrayPackBitsToUInt64((x, y) -> x > y, lhs, rhs)`
even though the implementation only needs the lambda result and the offsets of
the first array. All sibling `FunctionArrayMapped` functions accept parallel
arrays, so the restriction is dropped and regression tests are added, including
one for the `SIZES_OF_ARRAYS_DONT_MATCH` case.

Also bump `FunctionDocumentation::IntroducedIn` from `26.7` to `26.8`, because
`26.7` was already cut without these functions.
Comment thread src/Functions/array/arrayPackBits.cpp Resolved
@abashkeev abashkeev added the comp-regular-function Regular scalar functions: string processing, data conversion, arithmetic, math, comparison, condi... label Sep 3, 2026
alexey-milovidov and others added 3 commits September 15, 2026 23:15
…ixedString` variants

Address review: `arrayPackBitGroupsToUInt64` is documented as
`reinterpretAsUInt64(arrayPackBitGroupsToString(...))`, but it kept only the
leading whole groups that fit into 64 bits (`max_groups = 64 / g`), so for a
group size that does not divide 64 (e.g. `g = 3` with 22 groups = 66 bits) the
group straddling bit 64 was dropped and zero-padded instead of contributing its
leading bits. The `FixedString(n)` variants had the same whole-group truncation.

Both now share one packing routine with a bit limit (64 for `UInt64`, `n * 8`
for `FixedString`, unlimited for `String`), so a shorter result is always a
prefix of the byte stream of the `String` variant. The embedded documentation
describes the new rule, and `02769_array_pack_bits` gets regressions with
`g = 3` for both the `UInt64` and the `FixedString` variants.

Co-Authored-By: Claude Fable 5.1 <[email protected]>
@alexey-milovidov

Copy link
Copy Markdown
Member

🕵 Superseded by #123478. The source fork is archived and can no longer be pushed to. The new PR keeps @Eridanus117's commits (authorship preserved), merges current master, and addresses the remaining review comment (introduced_in bumped to 26.10). Thank you for the contribution!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

can be tested Allows running workflows for external contributors comp-regular-function Regular scalar functions: string processing, data conversion, arithmetic, math, comparison, condi... pr-feature Pull request with new product feature

Projects

None yet

Development

Successfully merging this pull request may close these issues.

A higher order array functions to pack bits.

5 participants