Skip to content

Split WASM UDF input blocks by estimated memory size - #116552

Merged
vdimir merged 7 commits into
ClickHouse:masterfrom
bacek:bacek/wasm-dynamic-input-splitting
Sep 7, 2026
Merged

vdimir merged 7 commits into
ClickHouse:masterfrom
bacek:bacek/wasm-dynamic-input-splitting

Conversation

@bacek

@bacek bacek commented Aug 26, 2026 •

Copy link
Copy Markdown
Contributor

A WASM UDF with ABI BUFFERED_V1 serializes its whole input block into the guest's linear memory in one piece. A block that does not fit fails the call, even though the same rows would succeed in smaller batches.

This sizes the calls by what the input actually occupies on the wire: the block is written through the configured serialization_format into a NullWriteBuffer one row at a time, and each row's cost is read off BufferBase::count. The measurement is the serializer's own output rather than a model of it, so it holds for every format and type without per-type arithmetic.

Rows are accumulated until the next one would take the call past webassembly_udf_input_split_memory_ratio of the module's declared initial linear memory (default 0.5, leaving the rest to the guest's own data, stack and allocator). Splitting stops at one row per call: a row too large on its own is passed alone and fails inside the guest's allocator. webassembly_udf_max_input_block_size still pins a fixed row count instead, and a ratio of 0 turns splitting off.

Closes: #115124

Changelog category (leave one):

  • Experimental Feature

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

WebAssembly UDFs now split an input block that would not fit into the guest's linear memory into smaller batches, sized by the input's measured serialized size. The new setting webassembly_udf_input_split_memory_ratio controls how much of the linear memory one call's input may occupy.


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

Version info

  • Merged into: 26.9.1.882 (included in 26.9 and later)

@bacek bacek mentioned this pull request Aug 26, 2026
1 task done
@alexey-milovidov alexey-milovidov added the can be tested Allows running workflows for external contributors label Aug 26, 2026
@clickhouse-gh

clickhouse-gh Bot commented Aug 26, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [7826aa9]

Summary: ✅


AI Review

Summary

This PR changes ABI BUFFERED_V1 WebAssembly UDF batching from a row-count cap to dynamic batching by measured serialized input size, adds webassembly_udf_input_split_memory_ratio, and covers several zero-page / capped-memory cases. The overall direction looks right, but one supported serialization format still breaks the new batching contract, so I would request changes before merge.

Findings

⚠️ Majors

  • [src/Functions/UserDefined/UserDefinedWebAssembly.cpp:698] measureRows assumes the serialized input size is the sum of one-row write calls, but that is false for serialization_format = 'Buffers'. BuffersWriter::write serializes each column as a whole Native block, and NativeWriter::writeData has block-scoped state such as LowCardinality dictionaries that is emitted once per block, not once per row. Subtracting only the outer Buffers framing still overcharges such inputs heavily, so the splitter can cut a block into much smaller batches than the true on-wire size requires. Because the guest sees num_rows, this changes observable behavior, not just performance. Suggested fix: either exclude Buffers from size-based splitting until it has a correct measurement path, or measure Buffers on the actual accumulating batch instead of summing one-row probes.
Tests
  • ⚠️ Add one focused Buffers regression test that uses serialization_format = 'Buffers' with a non-row-additive Native payload such as LowCardinality(String) and a guest that returns the batch row count. That is the smallest proof that the new measurement path matches the real Buffers wire size instead of the sum of one-row Native serializations.
Final Verdict

Status: ⚠️ Request changes

Minimum required actions:

  1. Make the size-based splitter correct for serialization_format = 'Buffers', or explicitly keep Buffers on the old row-count-only path.
  2. Add the focused Buffers regression test above.

LLVM Coverage Report

Measured on commit 7826aa9.

Metric Baseline Current Δ
Lines 88.80% 88.80% +0.00%
Functions 91.80% 91.80% +0.00%
Branches 81.20% 81.10% -0.10%

Changed lines: Changed C/C++ lines covered: 155/170 (91.18%) · Uncovered code

Full report · Diff report

@clickhouse-gh clickhouse-gh Bot added the pr-improvement Pull request with some product improvements label Aug 26, 2026
@clickhouse-gh

clickhouse-gh Bot commented Aug 26, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing 7826aa9f7 with master b2bb5c518 (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: compile time of recompiled translation units.

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

41 object files changed (+32.50 KiB total), 0 added.

Object file Master PR Δ
src/CMakeFiles/dbms.dir/Functions/UserDefined/UserDefinedWebAssembly.cpp.o 565.54 KiB 584.83 KiB +19.29 KiB (+3.41%)

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 ⚠️

2449 translation units recompiled, 2760 s compile time in total, 32 of them have a recent master baseline.

Translation units without a recent master baseline:

  • contrib/arrow-cmake/__/arrow/cpp/src/arrow/compute/kernels/scalar_temporal_unary.cc: 22.3 s
  • contrib/grpc-cmake/__/grpc/src/core/ext/transport/chttp2/transport/chttp2_transport.cc: 11.5 s
  • contrib/llvm-project-cmake/__/llvm-project/llvm/lib/CodeGen/SelectionDAG/DAGCombiner.cpp: 11.0 s
  • contrib/llvm-project-cmake/__/llvm-project/llvm/lib/Transforms/Vectorize/LoopVectorize.cpp: 10.3 s
  • contrib/grpc-cmake/__/grpc/src/core/ext/transport/chttp2/transport/frame_settings.cc: 9.5 s
  • contrib/google-protobuf-cmake/__/google-protobuf/src/google/protobuf/descriptor.cc: 9.4 s
  • contrib/grpc-cmake/__/grpc/src/core/ext/transport/chttp2/transport/frame_ping.cc: 9.4 s
  • contrib/grpc-cmake/__/grpc/src/core/server/server.cc: 9.3 s
  • contrib/llvm-project-cmake/__/llvm-project/llvm/lib/Passes/PassBuilderPipelines.cpp: 9.3 s
  • contrib/grpc-cmake/__/grpc/src/core/call/server_call.cc: 9.1 s
  • contrib/llvm-project-cmake/__/llvm-project/llvm/lib/CodeGen/SelectionDAG/SelectionDAGBuilder.cpp: 9.0 s
  • contrib/grpc-cmake/__/grpc/src/core/client_channel/retry_interceptor.cc: 9.0 s
  • contrib/grpc-cmake/__/grpc/src/core/ext/transport/chttp2/transport/frame_goaway.cc: 8.9 s
  • contrib/grpc-cmake/__/grpc/src/core/ext/transport/chttp2/server/chttp2_server.cc: 8.8 s
  • contrib/grpc-cmake/__/grpc/src/core/load_balancing/grpclb/grpclb.cc: 8.6 s
  • contrib/llvm-project-cmake/__/llvm-project/llvm/lib/Transforms/IPO/SampleProfile.cpp: 8.6 s
  • contrib/llvm-project-cmake/__/llvm-project/llvm/lib/Frontend/OpenMP/OMPIRBuilder.cpp: 8.4 s
  • contrib/grpc-cmake/__/grpc/src/core/load_balancing/rls/rls.cc: 8.4 s
  • contrib/arrow-cmake/__/arrow/cpp/src/arrow/compute/kernels/aggregate_mode.cc: 8.2 s
  • contrib/google-protobuf-cmake/__/google-protobuf/src/google/protobuf/compiler/cpp/message.cc: 8.2 s
  • ... and 42 more

Job report

bacek added a commit to bacek/ClickHouse that referenced this pull request Aug 28, 2026
…ize cache

The style check rejects a bare `std::vector` member:

    src/Functions/UserDefined/UserDefinedWebAssembly.cpp:1232:    std::vector<size_t> declared_default_row_bytes;
    Use an -WithMemoryTracking alternative or mark these usages with STYLE_CHECK_ALLOW_STD_CONTAINERS

https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=116552&sha=d2d5951c63097e6cdb2f18572403d7a5e83617c9&name_0=PR&name_1=Style%20check
ClickHouse#116552

Co-Authored-By: Claude Opus 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01Y3AfR6X54hSXJRvNDJTNc5
/// `Variant` argument to its active alternative, and a UDF declaring `ARGUMENTS (x String)`
/// would stop accepting `Variant(UInt8, String)`. The opt-out concerns the `Nullable`
/// wrapper only, so keep the `Variant` dispatch enabled unconditionally.
bool useDefaultImplementationForVariant() const override { return true; }

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

useDefaultImplementationForVariant() is now forced on for every WASM UDF that opts out of default null handling, but BUFFERED_V1 still supports a real top-level Variant parameter. A signature like ARGUMENTS (x Variant(UInt8, String)) RETURNS Array(UInt32) used to work because the raw Variant reached getReturnTypeImpl(). After this change, IFunctionOverloadResolver::build() always inserts FunctionBaseVariantAdaptor for that argument (src/Functions/IFunction.cpp:847-865), and the adaptor then rebuilds the function once per alternative (src/Functions/FunctionVariantAdaptor.cpp:783-804). getReturnTypeImpl() compares String / UInt8 against the declared Variant(...), rejects every branch with ILLEGAL_TYPE_OF_ARGUMENT, and the UDF becomes uncallable.

This needs the same kind of escape hatch that useDefaultImplementationForDynamic() already has for declared Dynamic parameters, otherwise the fix here trades one supported signature family for another.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🕵 Fixed in a4185dbfaac. useDefaultImplementationForVariant now returns false when any argument is declared Variant, so the whole Variant value reaches the module instead of FunctionBaseVariantAdaptor rebuilding the function per alternative and rejecting every branch. Regression test: 05073_wasm_abi_declared_variant_argument.sh.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The current head still has the original regression. IFunctionOverloadResolver::build() still installs FunctionBaseVariantAdaptor whenever the actual argument type is Variant (src/Functions/IFunction.cpp:848-865), and FunctionUserDefinedWasm::getReturnTypeImpl() still only accepts exact type equality or numeric WasmValKind coercions (src/Functions/UserDefined/UserDefinedWebAssembly.cpp:535-544).

So a declared raw Variant(...) parameter is again rebuilt per alternative and every branch is rejected before the module sees the whole carrier value. The a4185dbfaac escape hatch is not present on the current head.

bacek added a commit to bacek/ClickHouse that referenced this pull request Aug 29, 2026
Three stateless tests added for the dynamic input splitting failed CI with
`Reason: Test runs too long (> 180s). Make it faster.` They fed the splitter a
large number of narrow rows, so the exact per-row estimator walked tens of
thousands of rows per block.

Exercise the same behaviour with far fewer, wider rows: a 2000-byte enum label
instead of 200, sixteen `JSON` paths instead of eight, and correspondingly
smaller `numbers` and `max_block_size`. Locally:
`05055` 56.25s -> 1.82s, `05069` 20.20s -> 1.74s, `05056` 10.28s -> 1.37s.

CI report: https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=116552&sha=478a6833fae84c2edb0526c6690057c6fe90b9d2&name_0=PR
Related: ClickHouse#116552
@bacek

bacek commented Aug 29, 2026

Copy link
Copy Markdown
Contributor Author

🕵 @groeneai, three failures on the previous run look unrelated to this PR — please investigate and provide fixes in separate PRs (or link the ones already in progress):

Report: https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=116552&sha=478a6833fae84c2edb0526c6690057c6fe90b9d2&name_0=PR

@groeneai

Copy link
Copy Markdown
Collaborator

All three investigated.

Stress test (amd_msan) Not-ready Set ... globalIn: fix already in progress, #114058 ("Build the row policy's IN-subquery sets when reading a Merge table").

Route pinned from that job's own artifacts, not from the message text. The aborting query is SELECT * FROM merge(currentDatabase(), 't.*') ORDER BY id ASC (fatal.log, query_id 6db92538-adb2-46e5-b095-ada2c623a053). Its query_log row carries log_comment = 04509_row_policy_arrayjoin_filter.sh-... and used_row_policies = ['...row_policy_table.all'], with system.one among the read tables. The policy live at that point in 04509 is USING value IN (SELECT arrayJoin([10, 20])), and system.one is that subquery's source. The abort is in FunctionIn::executeImpl (src/Functions/in.cpp:128) under FilterTransform::doTransform (src/Processors/Transforms/FilterTransform.cpp:254), which is the row-policy filter step. globalIn is the stress fuzzer's rewrite of the policy's in. Pre-existing on master: 38 true-master hits plus 506 across 381 other PRs in 30 days. Note that #107619's message spans several distinct root causes, so not every hit of it is this route; this one is.

The two flaky-check Server died verdicts: nothing for me to fix in a separate PR, and they are not unrelated to this PR. The server did not die in either job. Server died there is the synthetic leaf that ci/jobs/scripts/functional_tests_results.py appends when the runner is killed by a signal (ABORTED_RUN_DEFAULT_LEAF at :31, -signal.SIGTERM in ABORTED_RUN_EXIT_CODES at :62), and the same branch demotes the real per-test rows to UNKNOWN, which is why they read as blank.

The chain is identical in both jobs: StopTesting: reached --max-failures limit (5) on five of this PR's own new tests, then a wind-down that never completed (workers force-killed one at a time with a 10s grace each, [Errno 16] Device or resource busy from the cgroup cleanups, and in amd_binary the --capture-client-stacktrace lldb attach timing out after 30s), then praktika's outer safety net firing at WARNING: Timeout exceeded [2471], sending SIGTERM to process group and the runner exiting -15. No <Fatal>, no Received signal and no sanitizer report in either clickhouse-server.err.log; dmesg.log clean and the job's own OOM in dmesg gate found nothing. The amd_tsan and amd_debug flaky checks in the same run hit the same five failures on the same tests but exited with MAX_FAILURES_EXIT_CODE, which that set deliberately excludes, so those reported them as real FAILs plus Too many test failures.

91fd42e14e5c covers three of the five. The two it does not touch were both over TEST_MAX_RUN_TIME_IN_SECONDS (tests/clickhouse-test:207): 05062_wasm_abi_buffered_dynamic_enum_block_estimate at 230-257s in four separate runs, and 05064_wasm_abi_buffered_dynamic_shared_variant_enum at 187s. Those are the tests' own cost rather than co-scheduling: allow_oversubscription returns False for a flaky check for exactly that reason. Worth noting that 05069_wasm_abi_buffered_constant_argument_cut also failed in Stateless tests (amd_tsan, parallel, selected tests) and in its s3 storage variant, where the report's own diagnosis reads Test also fails without randomized settings (not a randomization issue), so that one was never a flaky-check artifact; the numbers(8192) to numbers(512) trim addresses it.

One observation I could not prove, offered because it sits on the path that froze: while 05069 was being cancelled the server logged Cannot deallocate memory in wasm, ptr: 65560: Code: 770 ... Failed to execute clickhouse_destroy_buffer ... WASM execution was stopped by request. (WASM_ERROR). I did not establish that this is what held the wind-down open.

@bacek

bacek commented Aug 29, 2026

Copy link
Copy Markdown
Contributor Author

🕵 Thanks — that triage was exactly what was needed, and both actionable points are now addressed in 074bb4ad51c.

On the two tests over TEST_MAX_RUN_TIME_IN_SECONDS: you were right that this is their own cost, not co-scheduling. Both split all the way down to one row per batch, so the runtime tracks the row count, not the bytes per row — every row is a separate guest invocation. Trading rows for bytes keeps the property each test asserts (an unsplit block that does not fit the guest's 1 MiB heap) while cutting the invocation count:

  • 05062_wasm_abi_buffered_dynamic_enum_block_estimate: 4096 rows of a 1000-byte label → 256 rows of a 5000-byte label (unsplit wire ~1.28 MiB). 6.19s → 1.95s locally.
  • 05064_wasm_abi_buffered_dynamic_shared_variant_enum: 512 rows → 128 rows of a 25-element Array(Enum8(...)) (unsplit wire ~3.2 MiB). 4.61s → 1.74s locally.

Locally the whole wasm suite is 57/57 with 05062 at 0.95s and 05064 at 0.90s.

I take the point that the two Server died verdicts were not unrelated to this PR — that was my misreading, and the synthetic-leaf explanation is convincing. Thank you for chasing the msan globalIn route down to 04509 and the row policy rather than stopping at the #107619 label; nothing needed from you on that one now that #114058 has it.

Also merged upstream/master forward (ab995d5e5a8), taking the removal of WasmEdgeRuntime.cpp from 5f87dd85700; the memory-ceiling overrides this PR added there are already present in WasmTimeRuntime.cpp. That unblocks CI, which had not been scheduling because the PR was dirty.

On the Cannot deallocate memory in wasm ... WASM execution was stopped by request line during the 05069 cancellation: noted, and I have not been able to tie it to the wind-down either. It is the guest's clickhouse_destroy_buffer being called on an already-cancelled compartment, so the host reports the failed free and moves on; I do not see a path where it blocks. Leaving it as an observation rather than acting on it.

bacek added a commit to bacek/ClickHouse that referenced this pull request Aug 29, 2026
A WASM UDF parameter declared `Dynamic` or `Variant` must reach the module as a
whole value, so the function opts out of `FunctionBaseDynamicAdaptor` /
`FunctionBaseVariantAdaptor` for it. `useDefaultImplementationForDynamic` and
`useDefaultImplementationForVariant` answer for the whole overload, though, so
opting out there also disabled dispatch for sibling parameters that still need
it: `ARGUMENTS (x Variant(UInt8, String), y String)` called with a `Variant` in
`y` reached `getReturnTypeImpl` with the raw `Variant` and failed with
`ILLEGAL_TYPE_OF_ARGUMENT`, and the same held for a declared `Dynamic`
parameter beside a `Dynamic` argument that should have been dispatched.

Add per-argument hooks - `useDefaultImplementationForDynamicArgument` and
`useDefaultImplementationForVariantArgument`, both defaulting to the
whole-function setting - and have `IFunctionOverloadResolver::build` skip only
the argument positions the function claims, in the same way it already skips a
custom-named `Variant` through `useDefaultImplementationForVariantWithCustomName`.
The chosen index is now passed to `FunctionBaseDynamicAdaptor` instead of being
rediscovered there, matching `FunctionBaseVariantAdaptor`. Behaviour is
unchanged for every function that does not override the new hooks.

Reported in review: ClickHouse#116552 (comment)
bacek added a commit to bacek/ClickHouse that referenced this pull request Aug 29, 2026
The element names of a named `Tuple` live in `DataTypeTuple`, not in
`ColumnTuple`, so `byteSize` cannot see them and `objectPathNameBytes`,
which walks the column, cannot either. With
`output_format_json_named_tuples_as_objects` the tuple is serialized as a
JSON object and every key is emitted on every row, so a tuple of one tiny
value under a long key was priced at its numeric width alone: the O(1)
block estimate stayed under the budget, the exact per-row pass was
skipped, and the call failed late in guest allocation with
`Cannot allocate buffer of size ...` - exactly what the splitter exists to
avoid.

Add `namedTupleKeyBytes`, which walks the column and the declared type in
parallel and charges `objectPathWireBytes` per explicitly named element,
recursing through `Nullable`, `LowCardinality`, `Array` (scaled by the
block's average element count), `Map`, `Tuple`, `Variant` and `Dynamic`.
It is charged in both estimators outside their branch chain, because a
`Tuple` of fixed-width elements takes the fixed-size branch, and only when
`wire_size_expansion_factor > 1`, because the binary wires do not write
element names.

Addresses ClickHouse#116552 (comment)
@clickhouse-gh

clickhouse-gh Bot commented Sep 3, 2026 •

Copy link
Copy Markdown
Contributor

📊 Cloud Performance Report

✅ AI verdict: no_change — no significant changes across 40 queries analysed

This PR is scoped entirely to the WebAssembly UDF path: it adds dynamic input-block splitting (the new webassembly_udf_input_split_memory_ratio setting) plus related memory-limit preflights and tests. None of the flagged ClickBench queries (Q18, Q28, Q30-Q34) invoke a WebAssembly UDF, so the server's query-execution hot path they exercise is untouched and none of these deltas — including the eye-catching -48.2% on Q32 — can plausibly be caused by this change. All flagged improvements have been downgraded to not_sure as off-diff variance; most of these queries also carry a noisy history signal, consistent with run-to-run variation rather than a real effect. No genuine regression is present.

clickbench

⚠️ 7 inconclusive

Flagged queries (7 of 43)
Query Verdict Baseline median (ms) PR median (ms) Change q-value Hint
⚠️ 18 not_sure 1101 866 -21.3% <0.0001 This PR only touches WebAssembly UDF input-splitting; ClickBench Q18 runs no WASM UDF, so the -21.3% is run-to-run variance on a noisy query, not a PR effect.
⚠️ 28 not_sure 1099 1041 -5.3% <0.0001 Already not_sure with mixed signals from the two tests. The WASM-UDF-only diff cannot touch Q28's path, so the small delta is noise.
⚠️ 30 not_sure 234 199 -15.0% <0.0001 The diff only changes WebAssembly UDF batching, which Q30 never exercises, so this -15.0% on a noisy query is variance rather than a real improvement.
⚠️ 31 not_sure 309 248 -19.7% <0.0001 Q31 runs no WASM UDF, and the PR touches nothing else in the execution hot path, so the -19.7% is run-to-run variance on a noisy query.
⚠️ 32 not_sure 1376 713 -48.2% <0.0001 Despite the large -48.2% delta the hard override did not lock this, and the WASM-UDF-only diff cannot touch Q32's path, so this is unrelated variance.
⚠️ 33 not_sure 1256 1131 -9.9% <0.0001 Q33 does not call any WebAssembly UDF, so the -9.9% cannot be attributed to this diff and reads as measurement variance.
⚠️ 34 not_sure 1259 1124 -10.8% <0.0001 Same as Q33: no WASM UDF on this path, so the -10.8% is off-diff variance despite the trending history signal.

Change = percent below ×2; the ratio of medians (×N faster/slower) beyond, where percent understates the scale. q-value = BH-FDR adjusted p; smaller is stronger evidence. MIRAI flags a query when q < fdr_q (default 0.10) — the value the verdict is based on.

tpch_adapted_1_official

🟢 No significant changes

Debug info
  • StressHouse run: 12661c2c-198d-4730-a9cb-2ea70b5c3323
  • MIRAI run: c24455ff-3624-4174-bf23-e68f93a1675e
  • PR check IDs:
    • clickbench_1436220_1788727025
    • clickbench_1436233_1788727025
    • clickbench_1436239_1788727025
    • tpch_adapted_1_official_1436245_1788727025
    • tpch_adapted_1_official_1436256_1788727025
    • tpch_adapted_1_official_1436291_1788727025

@clickhouse-gh clickhouse-gh Bot added the comp-udf User-defined functions (SQL UDFs, executable UDFs) and UDF framework. label Sep 4, 2026
A `LANGUAGE WASM` UDF using the `BUFFERED_V1` ABI serializes a whole input
block into the guest's linear memory. A block that does not fit made the call
fail, so the block size had to be guessed by hand through
`webassembly_udf_max_input_block_size`.

Size the input batch from the module itself instead. `getInputBudget` derives a
byte budget from the declared initial linear memory scaled by
`webassembly_udf_input_split_memory_ratio` (default `0.5`), and rows are
measured, not predicted: `measureRows` writes them through the real output
format into a `NullWriteBuffer`, so the split reflects the bytes the guest will
actually receive. Setting the ratio to `0` opts out, and
`webassembly_udf_max_input_block_size` still pins a fixed row count when set.

Also name the result type of a call whose argument arrives as `Dynamic`:
`getReturnTypeForDefaultImplementationForDynamic` answers the declared
`RETURNS` type, so the framework's adaptor types the call as the definition
states rather than as `Dynamic`. A result type that can neither be put inside
`Nullable` nor carry a null itself keeps the `Dynamic` result, so a null row is
never traded for a fabricated default.

Closes: ClickHouse#115124

Co-Authored-By: Claude Opus 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01Y3AfR6X54hSXJRvNDJTNc5
@bacek
bacek force-pushed the bacek/wasm-dynamic-input-splitting branch from 63046a5 to ae9d874 Compare September 5, 2026 17:52
</Note>

Processes entire blocks at once using a (de)serialization through WASM memory. Supports any argument and return types.
Processes entire blocks at once using a (de)serialization through WASM memory. Supports the argument and return types that the chosen `serialization_format` can encode: the default `MsgPack` has no encoding for `Dynamic`, `Variant` or `JSON` / `Object` values, so a signature declaring one of those - including nested inside another type - needs a format that does, such as `JSONEachRow` or a text format like `CSV`.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

BUFFERED_V1 still does not support raw top-level Dynamic / Variant parameters just because the chosen wire format can encode them. With a declaration like ARGUMENTS (x Dynamic) or ARGUMENTS (x Variant(UInt8, String)), IFunction::build() still installs the Dynamic / Variant adaptor from the actual argument type (src/Functions/IFunction.cpp:830-865), and FunctionUserDefinedWasm::getReturnTypeImpl() still only accepts exact type equality or numeric coercions (src/Functions/UserDefined/UserDefinedWebAssembly.cpp:525-553). So the call is rejected before the buffered serializer ever gets a chance to use JSONEachRow / CSV.

This sentence should be narrowed to the shapes the resolver accepts today (concrete declared types and nested carriers), or the whole-value path for raw carrier parameters needs to be restored and covered by a focused test.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🕵 Verified and fixed in 49e950a.

The claim holds. IFunctionOverloadResolver::build installs the Dynamic / Variant adaptor from the actual argument type, so the function is called with the concrete alternative, which getReturnTypeImpl rejects on exact equality before the serializer is reached. Against a local server:

  • ARGUMENTS (x Dynamic) called with a Dynamic column: Illegal type of arguments, expected (Dynamic), got (UInt8).
  • ARGUMENTS (x Variant(UInt8, String)) called with a Variant column: None of the Variant alternatives (String, UInt8) are compatible with function.
  • ARGUMENTS (x Array(Dynamic)) called with [1, 'a']::Array(Dynamic) and JSONEachRow: returns [1].

So the nested half of the sentence was right and the top-level half was not. The sentence is now narrowed to the nested carriers, naming Array(Dynamic) as the shape that works, and states outright that a bare top-level Dynamic or Variant argument is not accepted whatever the format, with the reason.

Restoring a whole-value path for raw carrier parameters is a feature, not a wording fix, and is out of scope here — this PR is about input splitting.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🕵 Reverted in e97e31d: the sentence is back to what master says.

Nothing here was wrong. master's "Supports any argument and return types" is inaccurate, and a bare top-level Dynamic or Variant argument is indeed not accepted — both verified. But the inaccuracy predates this pull request, and this pull request divides an input block by its serialized size; it does not change how types are resolved. Narrowing the claim here, and then narrowing it again for carrier arguments, turned a change about batching into a change about the type system.

The type-support wording deserves its own pull request, with the ILLEGAL_TYPE_OF_ARGUMENT cases above as its test.

bacek and others added 2 commits September 6, 2026 06:04
…pted

The `BUFFERED_V1` section said a signature declaring `Dynamic`, `Variant` or
`JSON` needs a `serialization_format` that can encode it, "including nested
inside another type". That reads as if a bare top-level `Dynamic` or `Variant`
argument works once the format is right, and it does not: `build` installs the
`Dynamic` / `Variant` adaptor from the actual argument type, so the function is
called with the concrete alternative, which no longer equals the declared
argument type and is rejected with `ILLEGAL_TYPE_OF_ARGUMENT` before the
serializer is reached.

Narrow the sentence to the nested carriers that do work, such as
`Array(Dynamic)`, and state the top-level restriction outright.

Co-Authored-By: Claude Opus 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01Y3AfR6X54hSXJRvNDJTNc5
The `BUFFERED_V1` and settings prose spelled out implementation detail that a
reader does not need: why the declared initial memory is used rather than the
current one, that the row count reaches the guest as the second `i32` argument,
that the adaptor dispatches a carrier argument to its concrete alternative, and
the same opt-out restated in three places.

Say what the settings do and leave the reasoning out.

Co-Authored-By: Claude Opus 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01Y3AfR6X54hSXJRvNDJTNc5
bacek and others added 3 commits September 6, 2026 12:19
The claim that the ABI supports any argument and return types is inaccurate,
since the default `MsgPack` cannot encode `Dynamic`, `Variant` or `JSON` values,
but it was inaccurate before this change and has nothing to do with dividing an
input block by its serialized size. Narrowing it here, and then narrowing it
again for top-level carrier arguments, turned a change about batching into a
change about the type system.

Leave the sentence as it was and keep this change to what it is about.

Co-Authored-By: Claude Opus 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01Y3AfR6X54hSXJRvNDJTNc5
`05132` was written to answer the review, not to cover this change: it states
that a `Variant` or `Dynamic` value is dispatched to the declared type and that
a null row answers `NULL` without reaching the guest. That is the framework's
behaviour for any function, no part of it is touched here, and the test passes
unchanged on `master`.

It has also been read as a claim that this change owns the null handling of
carrier types, which it does not.

Co-Authored-By: Claude Opus 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01Y3AfR6X54hSXJRvNDJTNc5
`getReturnTypeForDefaultImplementationForDynamic` names a call whose argument
arrives as `Dynamic` by the declared `RETURNS` type instead of leaving it typed
`Dynamic`. That is a fix, but it is a fix to how a WASM UDF is typed, not to how
an input block is divided by its serialized size, and it arrived here only
because a review question led to it.

Take it out along with `05136`, so this change is about input splitting alone.
It will come back on its own, with its own test.

Co-Authored-By: Claude Opus 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01Y3AfR6X54hSXJRvNDJTNc5
@bacek

bacek commented Sep 6, 2026

Copy link
Copy Markdown
Contributor Author

🕵 Narrowed the pull request back to what it is about: dividing a BUFFERED_V1 input block by its serialized size. Three things that had accumulated in answer to review questions are now out, so some earlier replies on this page cite code that is no longer here.

  • e97e31d restores the BUFFERED_V1 type-support sentence in wasm_udf.mdx. master's "Supports any argument and return types" is inaccurate, but it was inaccurate before this branch and describes type resolution, not batching.
  • 7e2aa89 removes 05132_wasm_udf_dynamic_and_null_arguments. It pinned the framework's own handling of Nullable, Variant and Dynamic arguments, which nothing here touches — it passes unchanged on master. It was also read as a claim that this pull request owns the null handling of carrier types, which prompted the Variant comments on this page.
  • b8daa2e reverts the getReturnTypeForDefaultImplementationForDynamic override and removes 05136. Typing a call by its declared RETURNS under a Dynamic argument is a real fix and will come back in its own pull request with its own test; it is not part of input splitting.

The follow-ups filed along the way stand on their own and are unaffected: #118293 and #117773.

What remains is getInputBudget and measureRows in UserDefinedWebAssembly.cpp, the memory accessors they need in WasmEngine.h / WasmTimeRuntime.cpp, the webassembly_udf_input_split_memory_ratio setting with its history entry, the splitting documentation, and the WASM tests for it. Local run: 42/42 of the WASM suite.

@bacek

bacek commented Sep 6, 2026

Copy link
Copy Markdown
Contributor Author

🕵 @groeneai, investigate the failure and provide a fix in a separate PR. If a fix is already in progress, link it here.

Stateless tests (arm_binary, parallel) on b8daa2e failed one test, 04035_alp_rd_codec_special_values:

Code: 270. DB::Exception: Cannot compress with ALP(RD) codec, data size 34569 is not aligned to 8:
While executing MergeTreeSelect(pool: ReadPoolInOrder, algorithm: InOrder). (CANNOT_COMPRESS)

https://github.com/ClickHouse/ClickHouse/actions/runs/34006549929/job/101418482160

This branch changes how a WebAssembly UDF divides its input block and touches nothing in compression: no file under a Compression path, and no codec, is in its diff. The test and the codec both come from master, most recently through 19f5e9843ea "Promote ALP to beta". I could not find an open issue or pull request for it, so this may be the first report.

The reported size, 34569, is not a multiple of 8 for a codec that requires 8-byte alignment, which suggests a block reaching ALP(RD) after being cut on a boundary the codec does not expect; the run randomises block and compression settings, so it may well be flaky rather than deterministic.

@groeneai

groeneai commented Sep 6, 2026

Copy link
Copy Markdown
Collaborator

A fix is already merged in master: #118335, merged today at 15:26Z as 6c335833c268.

It is not compression of stored data, and no INSERT is involved: the throwing frame is the read path's compressed-size estimator. estimateCompressedColumnSize in RuntimeDataflowStatistics.cpp serializes a row-limited sample of a column into one buffer and runs the column's own CODEC over it. The serialization is chosen per block from the column at hand, so for a Sparse column, or one whose part still holds a pre-ALTER type, that buffer holds a layout the type-specific codec was never resolved for. ALP(RD) validates its input, so it rejects a sample byte count that is not a whole number of doubles, as with the 34569 here. #118335 applies a type-specific codec only when the sample really is a single stream of the column type, so the randomised settings are incidental rather than the cause.

Nothing for you to do here. The failing head b8daa2ee908 is from 02:20Z, before that merge, but the master merge you pushed as 7826aa9f75 at 18:14Z already contains it, and 04035_alp_rd_codec_special_values passed in the Fast test on that commit.

@vdimir vdimir left a comment

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.

Great, I think all of my previous comments are addressed or answered, thanks

@vdimir
vdimir added this pull request to the merge queue Sep 7, 2026
Merged via the queue into ClickHouse:master with commit 05c53c1 Sep 7, 2026
175 checks passed
@robot-ch-test-poll4 robot-ch-test-poll4 added the pr-synced-to-cloud The PR is synced to the cloud repo label Sep 7, 2026
bacek added a commit to bacek/ClickHouse that referenced this pull request Sep 9, 2026
The input splitter priced a call by serializing every row on its own through
the real output format and subtracting a fixed per-write framing term. A row
has no cost of its own under a block-scoped wire, so that model over-prices
every such batch: `ColumnBinary` writes a frame header, one descriptor per
column and a `COL_LOWCARD` dictionary per batch, and `BuffersWriter` runs
`NativeWriter::writeData` once per block, which emits a fresh dictionary and
the `Dynamic` / `Variant` structure prefixes for whatever rows the block holds.
Even a plain `String` column is over-charged by one `uint64` offset per row,
because `8 * (n + 1) + chars` is not `n * (8 * 2 + 1)`. No fixed subtraction
can remove state whose size depends on which rows the batch carries.

`measureBatchBytes` now measures the candidate batch itself, using
`precomputeSerializedSize` where the format states its own size - the same
primitive `executeOnBlock` sizes the guest buffer with, so the measurement and
the allocation cannot disagree - and serializing it otherwise. `chooseBatchRows`
brackets the largest prefix that fits the budget: the cost of a batch is
monotone in its row count, so each probe rescales the next candidate by how far
it landed from the budget, and the rows that fit form a prefix. The batch that
is sent has always been measured, so a row is never understated and the row
count carried across calls is a hint that only saves probes.

Probing starts from a single row rather than from the whole block: a probe
serializes its candidate, and for a wire that does not carry constness a
`ColumnConst` argument is materialized to do it, so a first probe of the whole
block would expand exactly the input the splitting exists to rescue.

This also replaces one serialization per row with a logarithmic number per
batch.

Promised in ClickHouse#116552 and filed as
ClickHouse#118466, which asked for the
batch-level measurement to be done together with the `ColumnBinary` work.

Closes: ClickHouse#118466

Co-Authored-By: Claude Opus 5 <[email protected]>
inakisoriamrf pushed a commit to inakisoriamrf/ClickHouse that referenced this pull request Sep 30, 2026
The `BUFFERED_V1` splitter priced a batch by serializing every row on its own and
adding the results up, minus a fixed per-write framing constant. That costs one
serialization per row - 65536 format writes for a default-sized block - and it
over-prices any wire whose cost is not additive in the rows: `NativeWriter::writeData`
runs once per block under `Buffers` and emits a fresh `LowCardinality` dictionary and
the `Dynamic` / `Variant` structure prefixes for whatever rows the block holds, so
summing one-row probes charges every row a whole dictionary. No fixed per-write
subtraction can remove state whose size depends on which rows the batch carries.

A batch is now measured as a batch. Its cost is monotone in the row count, so the rows
that fit a budget form a prefix: `chooseBatchRows` brackets that prefix, measuring each
candidate exactly with `measureBatchBytes` and rescaling the next candidate by how far
the last one landed from the budget. A batch filling three quarters of its budget is
taken as it is, and the row count that fitted is kept as the first candidate for the
next call. That reduces the serializations per block from one per row to a handful,
and what the budget is compared against is now the stream the guest is really handed
rather than a bound on it.

The probing starts at a single row rather than at the whole block: a probe materializes
a `ColumnConst` argument to serialize it, so a first probe of the whole block would
expand exactly the input the splitting exists to rescue.

Related: ClickHouse#116552

Co-Authored-By: Claude Opus 5 <[email protected]>
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-udf User-defined functions (SQL UDFs, executable UDFs) and UDF framework. pr-experimental Experimental 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.

Iceberg: stale open-time table UUID as metadata content cache key can serve a previous table's metadata

5 participants