Repository navigation
Add a WebAssembly build to CI: clickhouse-local runs in the browser - #113404
Conversation
PR #112911 made `emcmake cmake` configure this tree and the layers up to `clickhouse_common_io` compile to `wasm64`. Pin that state in CI so it cannot regress: a `Build (wasm64)` job among the special builds, running in both the PR and master workflows. The job configures through `emcmake` (Emscripten's toolchain file supplies `emcc`/`em++`, so no compiler is passed) and builds exactly the targets that are known to work: `common` and `clickhouse_common_io`. The compiler cache is disabled because `emcc` is a Python driver that sccache cannot cache. The binary-builder image gets the Emscripten SDK pinned to 6.0.5, the version the target was verified with, and pre-generates the wasm64 variant of the system libraries (`-sMEMORY64`, `-fwasm-exceptions` and `-pthread` are ABI flags, see cmake/target.cmake), so CI builds do not compile them lazily at first use. Verified with the exact CI configure and build commands: 2539 objects across 28 contrib libraries, base and src compile with zero warnings, and both archives link; `llvm-readobj` confirms `Arch: wasm64`. The whole build takes ~30 seconds of wall time on a 96-core machine, making it one of the cheapest build jobs. Co-Authored-By: Claude Fable 5 <[email protected]>
|
Preview deployment for your docs. Learn more about Mintlify Previews.
|
|
Workflow [PR], commit [eb0b421] Summary: ✅
AI ReviewSummaryThis PR adds a Missing context / blind spots
Final Verdict✅ No new inline findings on the current PR head. LLVM Coverage Report
Changed lines: Changed C/C++ lines covered: 48/48 (100.00%) · Uncovered code |
Everything above `clickhouse_common_io` turns out to need exactly two lines: `USE_MONGODB` off in the `OS_WASM` arm of cmake/target.cmake (raw sockets like the other disabled integrations, and its `mlib` has an explicit #error for platforms it does not recognize), and a suppression of `-Wlifetime-safety-return-stack-addr-moved` gated on clang >= 24, the way cmake/add_warning.cmake prescribes. That analysis is experimental, only exists in clang 24 (which nothing links today except Emscripten's bundled compiler), and flags the pervasive and correct idiom of taking a raw pointer out of a `unique_ptr`, moving the owner into a container and returning the pointer; its own diagnostic text concedes the report "could be a false positive". With those two, `ninja dbms` compiles all 3211 edges - Interpreters, Processors, Storages/MergeTree, the parsers, the compression codecs and their contribs - with zero errors and zero warnings, and links a wasm64 `libdbms.a`. The CI job's pinned target becomes `dbms`. Also verified at runtime, not just at link: a demo linked against the built archives - `parseQuery` producing and formatting a `SELECT` AST, `DB::Exception` thrown and caught through WebAssembly exceptions, and a `std::thread` on a Web Worker - runs to completion under Node.js 24 and in headless Chromium 149 served with cross-origin isolation. Co-Authored-By: Claude Fable 5 <[email protected]>
…wser The whole multicall `clickhouse` binary now compiles (11343 edges) and links (a 236 MB wasm64 module) with Emscripten, and `clickhouse local` executes queries correctly under Node.js >= 24 and in Chromium 149: MergeTree tables on the in-memory filesystem, aggregations over 100 million rows of `numbers` in ~2 seconds including engine startup, 1847 SQL functions, JSONEachRow from stdin, Pretty formats. The CI job's pinned target becomes `clickhouse` and the job provides the module as an artifact. What it took, beyond the `dbms` step: * `ENABLE_CAPNP` off for `OS_WASM`: its `kj` library calls `fallocate` unconditionally in its POSIX branch, which the Emscripten libc lacks. * Executable link options for `OS_WASM` in cmake/target.cmake: an 8 MiB shadow stack and 256 MiB of growable memory (the defaults are 64 KiB and a fixed 16 MiB, while `clickhouse` needs ~50 MiB for static data alone); `-g0` at the link, because binaryen's `wasm-opt` asserts in its DWARF bookkeeping (`AddrExprMap::add`) on a module with this much debug info; `-sPROXY_TO_PTHREAD` so `main`, which blocks its thread freely, runs on a pthread while the browser main thread keeps servicing the event loop that spawns the Web Workers backing new pthreads - without it the first blocking `pthread_create` deadlocks the page; and `-sEXIT_RUNTIME` so a finished query tears the runtime down. * The `dlopen`-blocking override in programs/main.cpp yields on `OS_WASM`: Emscripten's libc unconditionally defines `dlerror`, so the override was a duplicate symbol - and a sandbox cannot load libraries in the first place. * `initgroups` for `clickhouse-su`: the one libc symbol the entire binary found missing. Emscripten has the other identity stubs; this one fails closed with ENOSYS. * Explicit `Field::safeGet<unsigned long>` and `ColumnVector::indexImpl<size_t>` instantiations extend from `OS_DARWIN` to `OS_WASM`: both are LP64 platforms where `uint64_t` is `unsigned long long`, so `size_t` matches no `UInt*` type. * The `SignalListener` thread in `ClientApplicationBase` follows `OS_HAS_SIGNAL_HANDLERS`: without signals nothing ever writes to the signal pipe, and the blocking read of that pipe - all the thread does - fails with EAGAIN on Emscripten, which took the whole process down through `KillingErrorHandler`. Known wart, upstream: after the runtime reaches `exit(0)` (verified with `-sPTHREADS_DEBUG`), one Web Worker survives teardown and keeps the Node.js process alive; the browser does not care. Co-Authored-By: Claude Fable 5 <[email protected]>
…the wasm module under Node.js The `Build (wasm64)` link failed in CI: the image pre-warms Emscripten's system-library cache, but the pre-warm link did not pass `-sPROXY_TO_PTHREAD`, which selects the `crt1_proxy_main.o` startup object instead of `crt1.o` — so `em++` tried to generate it lazily into the root-owned cache and died with `PermissionError`. The pre-warm link flags now mirror the `clickhouse` link options from `cmake/target.cmake` exactly. Address review: the job now runs `clickhouse local` under Node.js 24 (added to the image) instead of merely linking it. The query executes from a directory holding only the two files the `CH_WASM64` artifact uploads, which also proves the artifact is complete — since Emscripten 3.1.58 the pthread worker code is embedded in the main JS file, so no `.worker.js` sidecar exists. Because of the known upstream wart where one Web Worker outlives runtime teardown and keeps the Node.js process alive, the query runs under `timeout` and success is judged by the produced output. Build log: https://s3.amazonaws.com/clickhouse-test-reports/PRs/113404/68886ff39afea772561db32e3e1ed3c2f067a3b4/build_wasm64/build_clickhouse/build_clickhouse.log PR: #113404 Co-Authored-By: Claude Fable 5 <[email protected]>
# Conflicts: # .github/workflows/master.yml # .github/workflows/pull_request.yml # src/Columns/ColumnVector.cpp # src/Core/Field.cpp
The `Build (wasm64)` job failed at the final link: `em++` tried to generate `libstubs.a` lazily into the root-owned image cache and got `PermissionError`. The pre-warm link in the `binary-builder` image mirrored the `add_link_options` of the `OS_WASM` branch but ran unoptimized, and the optimization level at the link is part of Emscripten's library-variant selection: `-O0` picks the `-debug` builds (`libstubs-debug.a`, `libc-mt-debug.a`, ...) while the `-O3 ... -g0` CI link needs the release ones (`libstubs.a`, `libc-mt.a`, `libdlmalloc-mt.a`, `libc++-mt-legacyexcept.a`, `libc++abi-mt-legacyexcept.a`). Add `-O3` and `-g0` to the pre-warm; verified against a fresh cache that the exact CI link line then generates nothing lazily. https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=113404&sha=9091d549a6cd034e6781f2db531e379030d3b245&name_0=PR&name_1=Build%20%28wasm64%29 #113404 Co-Authored-By: Claude Fable 5 <[email protected]>
The Node.js smoke test now runs a `--multiquery`: `CREATE TABLE ... ENGINE = MergeTree`, an `INSERT` of 1000 rows, and a deterministic aggregate over them, so the in-memory filesystem and the `CREATE`/`INSERT`/`SELECT` path are covered rather than only constant expression evaluation. Expected output verified against a native `clickhouse local`. Co-Authored-By: Claude Fable 5 <[email protected]>
|
🕵 The The remaining failures on that head are unrelated to this PR (it only touches the wasm build path and CI):
|
|
The
This failure is the skip-index marks read blocking past cancellation, which is already fixed in my open #113436. That PR makes Your remaining bullets need nothing from me: the |
The wasm64 link failed with `PermissionError` on `symbol_lists/<hash>.json.lock`: pre-warming cannot cover the `symbol_lists` cache entries, because their hash covers the resolved link settings and some settings are derived from the program being linked (e.g. `MAIN_READS_PARAMS`, from the signature of `main`), so the real `clickhouse` link always misses the entry cached by the trivial pre-warm program and generates its own - into a root-owned cache. Open the cache up for the unprivileged CI build user instead of chasing every lazily written file. Report: https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=113404&sha=b073abe0805ac673f00fd7d4099c217fb1dc9d60&name_0=PR&name_1=Build%20%28wasm64%29 PR: #113404
…ot browsers The wasm64 smoke test no longer hides every nonzero exit status behind `|| true`: it accepts only 0 and 124 (the known upstream wart - one Web Worker survives the runtime teardown and keeps the Node.js process alive, so the query runs under `timeout`), and any other status fails the job even when the expected output was produced. The comments and the CI documentation now state exactly what the job verifies: the build and query execution under Node.js >= 24; running in browsers works but is not covered by CI yet.
|
🕵 The The |
… as soon as it succeeds Two Majors from the AI review on f018f45: - `clickhouse disks` (shipped in the wasm multicall binary) still started and stopped `SignalListener` unconditionally; apply the same `OS_HAS_SIGNAL_HANDLERS` guard as in `ClientApplicationBase`. - The smoke test paid the full 300-second `timeout` on every green run because Node.js never exits (one Web Worker survives the runtime teardown). Node.js now runs in the background and is killed as soon as the expected output appears; the 300-second polling loop remains only as the worst-case deadline, and a process that dies on its own without the output still fails the job by its exit status.
Build profile diff (arm_release)No arm_release build profile data for commit eb0b421 - the build was skipped, reused from cache, or predates profile upload. |
…-inflicted kill (137) The predicate `[ "$found" -eq 1 ] || [ "$status" -eq 0 ]` made any nonzero exit status acceptable once `smoke.out` contained the expected line, so a wasm run that prints the result and then aborts during shutdown still made `Build (wasm64)` green. Now status 0 is always acceptable (the final grep still checks the output), and 137 (128+SIGKILL, our own early kill of the surviving-worker hang) is acceptable only when the expected output was seen first; any other status fails the job.
|
🕵 The three red checks on e3e2644 are unrelated to this PR (it only touches the wasm build path and CI;
Pushed cccc2ef addressing the remaining AI-review Major (the smoke test accepts only exit status |
… the SIGKILL The check claimed that only the harness's own `SIGKILL` is an acceptable non-zero status, but it never recorded whether its `kill -9` actually fired: a module that printed the expected line and was then `SIGKILL`ed by someone else - the out-of-memory killer, the job timeout, the CI infrastructure - also reached `found=1` and `137`, and passed. Now the `137` allowance is gated on this script being the sender: the kill is still always attempted so nothing is leaked, but `killed=1` is set only when the expected output was seen *and* the `kill` succeeded, and the predicate tests `killed` instead of `found`. Verified with stub processes: print-then-hang (our kill) and clean self-exit pass; print-then-external-`SIGKILL` now fails where the previous predicate returned success; print-then-`exit 7` and killed-before-any-output fail.
…IGNAL_HANDLERS` `ClientApplicationBase` and `DisksApp` no longer start a `SignalListener` on a platform without signals, but `BaseDaemon` still did - and the multicall `clickhouse` binary built for WebAssembly contains the daemon-style entry points too. `SignalListener::run` does nothing but block on a read of `HandledSignals::signal_pipe`, which nothing can ever write to when there are no signals, so the thread was pure overhead at best. The listener creation, the `StopThread` write and the thread join are now compiled out without `OS_HAS_SIGNAL_HANDLERS`; the surrounding `HandledSignals` setup and `reset` are already no-ops there. Since there is then no listener, and nothing could deliver a termination request to one anyway, `waitForTerminationRequest` throws `NOT_IMPLEMENTED` rather than blocking forever or dereferencing a null listener. Verified that `OS_HAS_SIGNAL_HANDLERS` is defined in this translation unit natively (dumped the macros with the real compile command), so native builds keep the listener, and that both arms compile.
|
🕵 CI on
Pushed |
|
📊 Cloud Performance Report ✅ AI verdict: This PR adds an experimental wasm64 (WebAssembly via Emscripten) build target: a new CI build job, Emscripten/Node toolchain in the builder image, an OS_WASM cmake branch, and C++ edits that are all guarded behind OS_WASM / OS_HAS_SIGNAL_HANDLERS (plus a trivial host.contains refactor). None of that changes the query-execution path in the standard build under test. The single flagged improvement on clickbench Q17 (-11.2%) cannot plausibly be caused by this change, so it is downgraded to not-sure as run-to-run variance rather than a real speedup. No regressions were flagged. clickbenchFlagged queries (1 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
|
Related: #112911
#112911 made
emcmake cmakeconfigure this tree and the layers up toclickhouse_common_iocompile towasm64. This PR takes that to its conclusion: the whole multicallclickhousebinary builds and links for WebAssembly, andclickhouse localexecutes queries under Node.js ≥ 24 and in the browser — and aBuild (wasm64)CI job among the special builds (PR and master workflows) pins the build and the Node.js execution path so they cannot regress. (The browser path is verified manually as below; CI does not cover it yet.) The job provides theemccoutput pair (clickhouse.wasm, 236 MB, plus theclickhouse.jsinstantiation script) as an artifact.What runs today, verified in both Node.js 24 and headless Chromium 149 (served with the COOP/COEP headers that
SharedArrayBuffer, and therefore pthreads-on-Workers, require):MergeTree parts written to the in-memory filesystem;
SELECT sum(number) FROM numbers(100000000)in ~2 seconds of wall time including engine startup and module instantiation; 1847 functions insystem.functions;JSONEachRowfrom stdin; Pretty formats; syntax errors with positions. In the browser, the same module aggregates 10 million rows in a page (~5 s from page load to result, including fetching and compiling the 236 MB module).The changes
The build system (
cmake/target.cmake, on top of thedbmsstep below):ENABLE_CAPNPoff forOS_WASM— itskjlibrary callsfallocateunconditionally in its POSIX branch, which the Emscripten libc lacks.USE_MONGODBoff — raw sockets like the other disabled integrations, and itsmlibhas an explicit#errorfor platforms it does not recognize.clickhouseneeds ~50 MiB for static data alone);-g0at the link, because binaryen'swasm-optasserts in its DWARF bookkeeping (AddrExprMap::add) on a module with this much debug info;-sPROXY_TO_PTHREAD, because this code blocks its calling thread freely and in a browser the main thread must keep running the event loop that spawns the Web Workers backing new pthreads — without it the first blockingpthread_createdeadlocks the page;-sEXIT_RUNTIMEso a finished query tears the runtime down.The platform arms (all small, in the spirit of #112911):
dlopen-blocking override inprograms/main.cppyields onOS_WASM: Emscripten's libc unconditionally definesdlerror, so the override was a duplicate symbol at the link — and a sandbox cannot load libraries in the first place.initgroupsforclickhouse-su— the one libc symbol the entire binary found missing. It fails closed withENOSYS.Field::safeGet<unsigned long>andColumnVector::indexImpl<size_t>instantiations extend fromOS_DARWINtoOS_WASM: both are LP64 platforms whereuint64_tisunsigned long long, sosize_tmatches noUInt*type.SignalListenerthread followsOS_HAS_SIGNAL_HANDLERS(the capability macro from Recognize an Emscripten/WebAssembly target #112911) in every entry point that starts one —ClientApplicationBase,DisksAppandBaseDaemon: without signals nothing ever writes to the signal pipe, and the blocking read of that pipe — all the thread does — fails withEAGAINon Emscripten, which took the whole process down throughKillingErrorHandler. With no listener,BaseDaemon::waitForTerminationRequesthas nothing to wait on and nothing could ever deliver a request to it, so it throwsNOT_IMPLEMENTEDinstead of blocking forever.The
dbmsstep (earlier commit): everything aboveclickhouse_common_ioneeded exactly two lines —USE_MONGODBoff, and a suppression of-Wlifetime-safety-return-stack-addr-movedgated on clang ≥ 24 incmake/warnings.cmake, the waycmake/add_warning.cmakeprescribes. That analysis is experimental, exists only in clang 24 (nothing links clang 24 today except Emscripten's bundled compiler), and flags the pervasive and correct idiom of taking a raw pointer out of aunique_ptr, moving the owner into a container and returning the pointer; its own diagnostic text concedes the report "could be a false positive".The CI job configures through
emcmake(Emscripten's toolchain file suppliesemcc/em++, so no compiler is passed), with the compiler cache disabled becauseemccis a Python driver that sccache cannot cache. Thebinary-builderimage gets the Emscripten SDK pinned to 6.0.5 and pre-generates thewasm64variant of the system libraries (-sMEMORY64,-fwasm-exceptionsand-pthreadare ABI flags), so CI builds do not compile them lazily at first use.Verification
Ran the exact CI configure and build on an arm64 machine (same architecture as the
arm-largerunners): all 11343 edges compile with-Weverything -Werrorand zero diagnostics; the link takes ~7 minutes at 13.4 GiB peak RSS;llvm-readobjreportsArch: wasm64, AddressSize: 64bit. Runtime verified as above, plus wasm exceptions (aDB::Exceptionthrown and caught through the native exception-handling proposal) andstd::threadon Web Workers.Known wart, upstream: after the runtime reaches
exit(0)(verified with-sPTHREADS_DEBUG: all threads clean up,exitRuntimeruns), one Web Worker survives Emscripten's teardown and keeps the Node.js process alive — a CLI invocation needs an external timeout for now. The browser does not care: results are delivered and the page keeps running.Node.js ≥ 24 is required at runtime (Emscripten 6 emits Memory64 code and refuses older engines); in browsers this means Chrome ≥ 133 or equivalent, plus cross-origin isolation for threads.
Changelog category (leave one):
Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):
Experimental: the
clickhousebinary builds for WebAssembly (wasm64, via Emscripten), andclickhouse localruns queries — includingMergeTreetables — under Node.js ≥ 24 and in the browser. A newBuild (wasm64)CI job pins the build and the Node.js execution path (the browser path is not covered by CI yet) and provides the WebAssembly module as an artifact.Version info
26.8.1.1188(included in26.8and later)