Skip to content

Add support for small integer types and implicit numeric coercion in WASM UDFs - #8

Closed
bacek wants to merge 1 commit into
spr/master/6d3214c8from
spr/master/0d7a9272
Closed

bacek wants to merge 1 commit into
spr/master/6d3214c8from
spr/master/0d7a9272

Conversation

@bacek

@bacek bacek commented Mar 13, 2026 •

Copy link
Copy Markdown
Owner
  • Add WasmStorageType<T> trait and wasmKindFor<T> helper that map
    Int8, UInt8, Int16, UInt16 to the WASM i32 storage type
    (uint32_t), enabling ROW_DIRECT UDFs to accept and return small
    integer types via widening/narrowing static_cast.
  • Extend tryExecuteForColumnTypes to include the four small integer
    types, and update checkDataTypeWithWasmValKind and the column
    read/write lambdas accordingly.
  • Allow implicit numeric coercion in FunctionUserDefinedWasm::getReturnTypeImpl:
    when both the actual and declared argument types are numeric, accept
    the call without requiring an exact type match. The serialization
    layer (BUFFERED_V1) and WasmStorageType casting (ROW_DIRECT)
    handle the actual value conversion at runtime.
  • Add stateless tests:
  • 04006_wasm_small_int_types — single identity/add WASM
    function declared as Int32 exercised with Int8, UInt8,
    Int16, UInt16 boundary values and overflow wrapping.
  • 04007_wasm_mixed_types — BUFFERED_V1 function accepting
    (Int32, String) and returning String, called with uncast
    integer literals and boundary values.

Co-Authored-By: Claude Sonnet 4.6 [email protected]


Stack:


⚠️ Part of a stack created by spr. Do not merge manually using the UI - doing so may have unexpected results.

…WASM UDFs

- Add `WasmStorageType<T>` trait and `wasmKindFor<T>` helper that map
  `Int8`, `UInt8`, `Int16`, `UInt16` to the WASM `i32` storage type
  (`uint32_t`), enabling `ROW_DIRECT` UDFs to accept and return small
  integer types via widening/narrowing `static_cast`.
- Extend `tryExecuteForColumnTypes` to include the four small integer
  types, and update `checkDataTypeWithWasmValKind` and the column
  read/write lambdas accordingly.
- Allow implicit numeric coercion in `FunctionUserDefinedWasm::getReturnTypeImpl`:
  when both the actual and declared argument types are numeric, accept
  the call without requiring an exact type match. The serialization
  layer (`BUFFERED_V1`) and `WasmStorageType` casting (`ROW_DIRECT`)
  handle the actual value conversion at runtime.
- Add stateless tests:
  - `04006_wasm_small_int_types` — single `identity`/`add` WASM
    function declared as `Int32` exercised with `Int8`, `UInt8`,
    `Int16`, `UInt16` boundary values and overflow wrapping.
  - `04007_wasm_mixed_types` — `BUFFERED_V1` function accepting
    `(Int32, String)` and returning `String`, called with uncast
    integer literals and boundary values.

Co-Authored-By: Claude Sonnet 4.6 <[email protected]>

commit-id:0d7a9272
@bacek bacek closed this Mar 13, 2026
bacek pushed a commit that referenced this pull request May 14, 2026
…tion` regressions

`generate_table_function #1` (8 integer column types, 1B rows) regresses ~18% and `#5`
(Date/DateTime, 1B rows) regresses ~16% on AMD release.

`fillColumnWithRandomData` is a big switch over `TypeIndex` that constructs a fresh
column for every block.  At `-march=x86-64-v3` the SLP vectorizer lowers the implicit
~32-byte zero-init of each newly-allocated `ColumnVector`/`ColumnString` to a
`vpxor xmm0; vmovdqu ymm0` pair (29 occurrences in PR vs 0 in master).  Each YMM
store dirties the upper YMM state, so clang inserts a `vzeroupper` (30 inserted)
before every external call from the dispatcher (`operator new`,
`PODArrayBase::reallocPowerOfTwoElements`, etc.) - the per-block dispatch ends up
bracketed by ~30 SSE/AVX transitions for no benefit (the inner PCG generation loop
is byte-equivalent to master's).

The inlined PCG inner loop is the dominant per-row cost, but at v3 the broader
function bloats from 16654 to 18241 bytes (+10%) and the cumulative `vzeroupper`
overhead in the per-block dispatch is what surfaces as the +15-18% regression.
The integer/Date paths are uniformly affected; Decimal/Float paths (#7/#8/#9)
do not regress because they go through a different per-element loop with no YMM
zero-init.

Compiling at v2 keeps the XMM-only zero-init that does not require `vzeroupper`.
The hot PCG inner loop's quality is not affected (master is already at v2 and
generates the same scalar code).

Local Sapphire Rapids LTO (max_threads=12, 10 iter):
  - `#1`:                      master 0.521s, PR 0.521s  (was 0.614s, +18%)
  - `#5`:                      master 0.177s, PR 0.178s  (was 0.208s, +16%)

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
bacek pushed a commit that referenced this pull request Aug 21, 2026
…nger adds

The previous commit claimed the pruning was not measurable. That was measured on the wrong shape: a
20M x 5M join where every left row matches one right row is dominated by the probe, and the columns
that go away are a small part of the work. The win scales with the number of result rows, and CI found
it on the shapes that have many - `join_nullable_keys_small_table` #5 and #9 and `join_main_loop` #8,
all of them `count()` over a join with disjuncts, went -30%, -34% and -16% on ARM.

Reproduced locally against a build of the parent commit, min of five runs, `max_threads = 8`:

  200M left rows, 1000 right, two `UInt64` keys, count only   424 -> 243 ms
  20M left rows, `String` keys                                102 ->  83 ms,  31 -> 1 MiB
  one of the two keys selected, so only the other one goes    432 -> 390 ms
  RIGHT, which also emits the non-joined right rows           134 -> 138 ms (unchanged)

The test covers those four shapes.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
Claude-Session: https://claude.ai/code/session_016QJvAjMfovbKtDsMW9mDbF
bacek pushed a commit that referenced this pull request Nov 14, 2026
…up window

`NegativeLimitBySortedStreamTransform::consume` sent every group, even one
that starts and ends inside the current chunk, through the sliding window:
`append_run` pushed a `ChunkSlice` into the empty window deque (allocating the
deque map and a block, and copying the chunk `shared_ptr`), `finalizeWindow`
copied it into `pending` (a second `shared_ptr` copy) and then `window = {}`
(libc++: `clear(); shrink_to_fit();`) freed the block and the map. So each
one-row group cost two memory-tracked allocations, two frees and two atomic
increment/decrement pairs, plus one `pending` entry.

The window is only needed for a group that touches a chunk boundary. A group
that ends inside the chunk while the window is empty also started inside this
chunk, so its output is known when its end is found: the last
`min(L, length + offset)` rows of the run without the trailing `offset` rows,
the same rows `append_run` + `dropExcessRows` + `dropOffsetRows` keep for a
one-slice window. Such groups are now staged into `pending` directly, and
`appendToPending` extends the last pending slice when the new rows continue
it in the same chunk, so the one-row groups of a chunk become one slice.
`generate()` produces the same chunk for a merged slice (same rows, first
start and last end). Groups touching a chunk boundary still use the window.

Evidence that this path is what moves the `negative_limit_by_in_order`
queries #0, #1 and #8 (millions of groups): ClickHouse#125000, which changed only the
allocator of these deques, moved them by -19/-16/-17% on master d3ee313 while
#2-#7 stayed flat; and the ClickHouse#125013 perf job's prewarm counters for #0 show
equal instructions on both sides (10301M vs 10333M, ~1030 per group) and +15%
cycles on one build.

Local A/B (release build, `CMAKE_BUILD_TYPE=None`, no ThinLTO, the perf
test's tables and queries, 12 rotating rounds, geomean of per-round ratios
new/base with bootstrap 95% CI):

  #0 10M one-row groups      0.764 s -> 0.096 s  0.123 [0.113, 0.135]
  #1 1M groups of 10         0.098 s -> 0.049 s  0.457 [0.413, 0.510]
  #2 100k groups of 100      0.025 s -> 0.019 s  0.707 [0.642, 0.785]
  #3-#7 100 groups           0.86-1.03, no CI lower bound above 1.0 (4-15 ms)
  #8 5M two-key groups       0.447 s -> 0.116 s  0.250 [0.236, 0.265]

User-space instructions of 5 runs of #0: 60.3G -> 10.2G (~1190 -> ~190 per
group after subtracting 5 runs of #3), cycles 16.2G -> 3.1G; #8: 31.4G ->
6.4G instructions. In the base profile of #0 about half of the samples are
in the deque allocation, `shrink_to_fit`, `CurrentMemoryTracker` and
jemalloc; none of them is in the top 15 after the change.

Replacing only `window = {}` by `clear()` (keeps the deque blocks) gives
0.526 / 0.594 / 0.583 on #0 / #1 / #8, so the direct staging is 4.3x and
2.3x faster than that on #0 and #8.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
bacek pushed a commit that referenced this pull request Nov 16, 2026
filterWithBlanks copied the left key into the right key column of a LEFT JOIN
one row at a time, with a virtual insertFrom or insertDefault per row. It now
reads the filter 64 rows at a time (bytes64MaskToBits64Mask, as in
filterArraysImpl): a chunk whose rows are all kept is one insertRangeFrom, a
chunk whose rows are all blank is one insertManyDefaults, and any other chunk
keeps the per-row loop. ColumnNullable gets an insertManyDefaults override, so
a blank Nullable chunk fills the nested column and the null map in bulk instead
of 64 virtual insertDefault calls.

Measured on x86 release (8 pinned cores; wall = median of 21 runs, user-space
instructions = median of 3 perf stat runs minus startup), base -> this commit:
- join_nullable_keys_small_table #4: 0.61x wall, 0.47x instructions;
  #8: 0.71x / 0.55x; #3: 0.66x / 0.55x; #7: 0.80x / 0.66x.
- Alternating rows and runs of 2, 3 and 100 rows: 0.86x-0.99x instructions.
- Queries of the same test that do not reach filterWithBlanks: within 0.4%
  instructions (wall moves up to +23% between the two builds from code
  placement alone, with the same instruction count).

The added perf query covers the per-row path (alternating matched and
unmatched rows), which the existing queries of the test do not reach.
The test runs all its queries (`run_all_queries`), as it now has more than
the 10 that CI samples.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
bacek pushed a commit that referenced this pull request Nov 16, 2026
…all loop

With clang 23 the loop around the libm call in `FunctionMathUnary` is no longer
vectorized: clang 22 converted four `UInt64` arguments at a time and then made
four calls, clang 23 converts each argument with a scalar sequence right before
its call. `tan(number)` became 9% slower locally with the CI binaries and
20-23% slower in the CI performance comparison (`math_trig` #8); `sin`, `cos`
and `atan` have the same loop. Convert the whole column first and call the
function in place, as the `Decimal` path already does: 11% fewer cycles in a
microbenchmark of the two loop shapes.

`exp10`, `sqrt`, `degrees` and `radians` keep the old loop: the compiler sees
their bodies, and with LTO `exp10` of a `UInt64` folds into a comparison with 308.

CI: https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=117346&sha=8675465598566b9a2f459432b9831f33b2876b86&name_0=PR
PR: ClickHouse#117346

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant