Repository navigation
Split WASM UDF input blocks by estimated memory size - #116552
Conversation
|
Workflow [PR], commit [7826aa9] Summary: ✅
AI ReviewSummaryThis PR changes Findings
Tests
Final VerdictStatus: Minimum required actions:
LLVM Coverage ReportMeasured on commit 7826aa9.
Changed lines: Changed C/C++ lines covered: 155/170 (91.18%) · Uncovered code |
Build profile diff (arm_release)Comparing Binary sizes
The official master build is compiled with Object file sizes41 object files changed (+32.50 KiB total), 0 added.
716 more object files are built by the master warmup baseline only (it builds every object-file target, a pull request build only Compile time of recompiled translation units
|
…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; } |
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
🕵 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.
There was a problem hiding this comment.
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.
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
|
🕵 @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):
|
|
All three investigated.
Route pinned from that job's own artifacts, not from the message text. The aborting query is The two flaky-check The chain is identical in both jobs:
One observation I could not prove, offered because it sits on the path that froze: while |
|
🕵 Thanks — that triage was exactly what was needed, and both actionable points are now addressed in On the two tests over
Locally the whole wasm suite is 57/57 with I take the point that the two Also merged On the |
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)
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)
|
📊 Cloud Performance Report ✅ AI verdict: 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. clickbenchFlagged queries (7 of 43)
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
|
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
63046a5 to
ae9d874
Compare
| </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`. |
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
🕵 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 aDynamiccolumn:Illegal type of arguments, expected (Dynamic), got (UInt8).ARGUMENTS (x Variant(UInt8, String))called with aVariantcolumn:None of the Variant alternatives (String, UInt8) are compatible with function.ARGUMENTS (x Array(Dynamic))called with[1, 'a']::Array(Dynamic)andJSONEachRow: 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.
There was a problem hiding this comment.
🕵 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.
…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
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
|
🕵 Narrowed the pull request back to what it is about: dividing a
The follow-ups filed along the way stand on their own and are unaffected: #118293 and #117773. What remains is |
…c-input-splitting
|
🕵 @groeneai, investigate the failure and provide a fix in a separate PR. If a fix is already in progress, link it here.
This branch changes how a WebAssembly UDF divides its input block and touches nothing in compression: no file under a The reported size, 34569, is not a multiple of 8 for a codec that requires 8-byte alignment, which suggests a block reaching |
|
A fix is already merged in master: #118335, merged today at 15:26Z as It is not compression of stored data, and no INSERT is involved: the throwing frame is the read path's compressed-size estimator. Nothing for you to do here. The failing head |
vdimir
left a comment
There was a problem hiding this comment.
Great, I think all of my previous comments are addressed or answered, thanks
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]>
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]>
A WASM UDF with
ABI BUFFERED_V1serializes 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_formatinto aNullWriteBufferone row at a time, and each row's cost is read offBufferBase::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_ratioof the module's declared initial linear memory (default0.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_sizestill pins a fixed row count instead, and a ratio of0turns splitting off.Closes: #115124
Changelog category (leave one):
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_ratiocontrols how much of the linear memory one call's input may occupy.Workflow [PR]
Sync PR [sync-upstream/pr/116552]
Version info
26.9.1.882(included in26.9and later)