Repository navigation
wasm gallery: real pthreads over SharedArrayBuffer, host-extern stubs, sizeof fix - #248
Merged
Merged
Conversation
arena_frame and manual_memory could not build in the wasm gallery: the monomorphizer synthesized a second sizeof_i32 next to the stdlib's concrete one whenever a program called a sizeof intrinsic, so the generated C redefined the symbol. A generic specialization now resolves to an existing concrete declaration instead of synthesizing a twin, and sizeof_ptr maps to void* instead of invalid C. The wasm build gained a generic extern-stub mechanism: host-only symbols the generated C references but does not define get browser-facing definitions (os_is_* and num_cores read real values from the tab via EM_ASM, CPU feature flags degrade honestly, print_kv_* map to printf). system_info now builds, and tiny_pointers/digits_mlp link runtime/flow_rt_support.c for the monotonic clock. Full gallery rebuild: 147 built / 9 failed, and all seven systems examples build; docs/demos/wasm.md's failure table is updated accordingly. Includes the tiny-pointers example, docs and bench script from the session branch. 🤖 Generated with Codebuff Co-Authored-By: Codebuff <[email protected]>
graphics.flow was library-shaped (no main), so its wasm-gallery card failed with 'undefined symbol main'. A demo entry point now exercises the color constructors and constants, the normalized-color conversion chain, the clamps, and the point/rect helpers, prints the results, and gates its exit code on a self-check. The gallery now builds 148 of 156 examples; the failure table in docs/demos/wasm.md is updated (eight remain, all host-dependent). 🤖 Generated with Codebuff Co-Authored-By: Codebuff <[email protected]>
The card (a collapsed <details class=coverage> mapping each of the paper's abstract promises to its theorem, phases and paper section, each row linking to the doc anchor) was lost in a workspace reset; re-wire it. write_page()/build() gain an optional extra_html fragment injected between the page header and the run body, with details.coverage styles in PAGE_CSS (inert for pages without the card). PAGE_EXTRAS tiny_pointers carries the card next to its existing extra_link runtime file, and build_one threads it through. The tiny_pointers page was rebuilt directly (wasm/js bytes unchanged; only index.html differs), and the 7 doc anchors verify against the wiki's headingSlug algorithm. docs/library/stdlib-api.md is an unrelated regeneration timestamp picked up by the wiki rebuild. Generated with Codebuff Co-Authored-By: Codebuff <[email protected]>
digits_mlp_parallel was the last ml example that did not build. Its thread pool is pthreads; the wasm build now supplies browser stubs: flow_parallel_for_i32 runs the loop body inline on the main thread (correct, just single-threaded, with stride handling and a body/stride guard) and flow_rt_par_workers honestly reports 1 worker, so the example's serial == parallel accuracy check is what proves the fallback matches the threaded result. Gallery rebuilt: 149 built / 7 failed (was 148 / 8). The rebuild changed no wasm or js bytes for any other example — the only page diffs are the details.coverage CSS block from the tiny-pointers card re-wiring propagating to the remaining pages. docs/demos/wasm.md updated: failure table eight -> seven, digits_mlp_parallel moved to the now-building list, category counts and the browser-verified table refreshed from the new manifest.
…ffer Replace the synchronous inline fallback for flow_parallel_for_i32 with a genuine emscripten pthreads build. wasm_build gains a threads mode (-pthread -sPROXY_TO_PTHREAD -sPTHREAD_POOL_SIZE=N, one pre-spawned worker per shard plus the proxied main): the parallel-for orchestration in lib/runtime/concurrency_parallel.flow compiles in as a library TU and lands on pthread_create, backed by runtime/flow_rt_parallel.c and the monotonic clock. The page ships the COI service worker (browsers only grant SharedArrayBuffer to cross-origin-isolated pages) and completes on onExit, since with PROXY_TO_PTHREAD the module factory resolves before main() runs. The gallery builds digits_mlp_parallel in threads mode (8 workers, 128 MB heap) and its 'Threads and channels' row moves from wip to runs, noting the card must be opened in a tab because an iframe cannot become isolated. The example's batch size rises 250 -> 1000 so each spawn carries real work: a proxied spawn costs ~1 ms, and the shards were ~150 us before. Chrome under COOP/COEP headers measures a true multi-worker speedup (1.9-2.7x across runs, 8 runtime workers, serial == parallel accuracy, PASS, exit 0); the non-isolated case shows an honest 'needs cross-origin isolation' message. docs/demos/wasm.md updated (verified-table row, capability row, now-build list); all other gallery pages byte-identical; 1178 unit tests pass.
…d cards parallel_sum.flow (previously only in the wasm-crossings build) joins the gallery through the same threads mode: its 12,000,000-iteration shards are the coarse grain the crossing docs prescribe, so it is the more dramatic threaded demo — measured 6.1-7.9x in Chrome under COOP/COEP isolation, 8 runtime workers, serial sum == threaded sum, PASS, exit 0. The gallery marks threaded examples: their manifest entries carry a 'threads' flag and their cards show a 'threads' tag alongside console. The 'Threads and channels' status row now names both examples. docs/demos/wasm.md refreshed (157 compiled / 150 runnable, Basics row 23 of 23, Learning payload, verified-table row for parallel_sum) and the grain caveat in docs/language/wasm-crossings.md rewritten to match the example's new batch size (the old 0.46x / 5,760-spawn numbers described the pre-fix example).
…-worker speedup curve Third real-pthreads gallery card. One build, one page: the program partitions 64M Monte Carlo samples into w disjoint shards and times passes at w = 2, 4, 8. Each shard seeds its own LCG and writes only its own hit-count slot, so threaded runs are race-free; each worker count is timed against its own serial baseline (a different shard count is a different random sample). PASS gates on the pi estimate, serial == threaded determinism at every count, and a monotone speedup curve. Measured in Chrome under cross-origin isolation: ~3.8x -> ~7.5x -> ~15x across 2/4/8 workers (8 runtime workers), 3/3 deterministic rows, exit 0, zero console errors. Native run: 1.97x -> 3.97x -> 5.84x. Gallery manifest and index refreshed (158 examples, 151 built, 7 failed; the threads tag now appears on all three threaded cards). docs/demos/wasm.md updated (intro, Basics row, verified-browser table, Threads status row, changelog) and docs/language/wasm-crossings.md's grain caveat cross-references the curve card. Generated with Codebuff 🤖 Co-Authored-By: Codebuff <[email protected]>
Main had already absorbed two of this branch's commits via #245 (the sizeof_i32 redefinition fix in monomorphize.py and the tiny-pointers coverage card), plus the 0.10.0 release (LSP/MLIR rework, doctests) and the MLIR->emcc --wasm32 ABI fix (#230/#247). This merge reconciles the overlap: - src/flow/monomorphize.py, src/flow/c_generator.py: take main's CI-tested versions (concrete_function_names sizeof fix, aligned_alloc + ptr lowering, statement-level #line handling). - examples/systems/tiny_pointers.flow: take main's (identical except the three `let` -> `let mut` fixes from the CI sort-out). - scripts/wasm_build.py: our version (extern stubs, threads mode, coverage CSS) + main's --wasm32 flag in flow_to_llvm_ir and the extra_c param. - scripts/build_wasm_gallery.py: our version (threaded entries + tags) which already carries main's coverage card. - site/wasm/* regenerated with the merged scripts: 158 examples, 151 built, 7 failed (the same host-bound set), all three threaded cards tagged. Unit suite: 1201 passed. Generated with Codebuff 🤖 Co-Authored-By: Codebuff <[email protected]>
Contributor
|
Bugbot is not enabled for your account, so this pull request was not reviewed. Enable Bugbot in the Cursor dashboard to get automatic reviews on future PRs. |
4 of 5 tasks
Co-authored-by: Abhishek Shivakumar <[email protected]>
godofecht
pushed a commit
that referenced
this pull request
Aug 9, 2026
wasm gallery: real pthreads over SharedArrayBuffer, host-extern stubs, sizeof fix
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Summary
Real threading and honest degradation for the WASM gallery, plus four rounds of real (non-stubbed) fixes that took the gallery from 132 stale pages to 158 examples, 158 runnable, 0 failed — every example builds and runs as a card. The branch reconciles with main (0.10.0 release, CI sort-out #245, MLIR→emcc wasm32 ABI fix #230/#247) and lands the remaining wasm-gallery work:
Real pthreads over SharedArrayBuffer (new
threadsmode inscripts/wasm_build.py)digits_mlp_parallel,parallel_sum, and the newparallel_scalingbuild with-pthread -sPROXY_TO_PTHREAD: Flow's parallel-for orchestration compiles as a library TU and lands onpthread_createover Web Workers.digits_mlp_parallel: ~1.9× (batch raised 250→1000 so shards clear the ~1 ms proxied spawn cost)parallel_sum: ~6.1–6.5×parallel_scaling(one page, 2/4/8 workers): ~3.8× → ~7.5× → ~15×, serial == threaded determinism at every countflow_parallel_for_i32is retired.Host-extern stubs —
EXTERN_STUBSinwasm_build.pyappends browser-facing definitions for host-only symbols (os_is_linux,num_cores,print_kv_*, …) so host-bound examples build; genuinely unprobeable facts degrade honestly (CPU feature flags → false,current_cpu→ "web browser"). Built-but-different pages carry an amber.degradenote on their card (viaPAGE_EXTRAS.note, also carried in the manifest).Round 2 — real fixes (155/158)
Four of the remaining six failures turned out not to be host-bound, and are now runnable pages with real behavior — no stubs:
tape_mul— the autodiff tape is pure Flow (lib/runtime/tape.flow, which replaced the deletedruntime/flow_tape.c); the wasm build never linked it. Newextra_flow_runtimebuild option compileslib/runtime/*.flowas library TUs — the wasm analogue of the native launcher'sflow_runtime_flow_sources(). The page computesdz/dx = 4, dz/dy = 3in Chrome.ga_flappy— a real compiler bug (broken natively too, now fixed).fly()'s call sites pass an int literal for au32param plus an untyped constant; the sole-overload fallback inOverloadResolver.resolve_callbreak-ed on the literal mismatch before discovering the unknown-typed argument, so the call emitted unmangled while the definition was mangled (undefined symbol fly). The fallback now discovers unknown arg types up front, and_types_compatibleguardsNone. Regression test added (tests/unit/test_strict_gaps.py); the example's own PASS gate runs in Chrome.blas_demo/lu_decomposition— newruntime/blas_wasm.c: plain, numerically correct implementations of exactly the routines the stdlib calls (daxpy/dcopy/ddot/dnrm2/dscal/dgemv/dgemm+ LAPACKdgesv_/dgetrf_, column-major per the LAPACK contract), linked viaextra_c.lu_decompositionsolvesx = [1,1,1]with zero residual;blas_demobenchmarks 0.7→2.1 GFLOPS.clock() → i64signature mismatch (caught by the BLAS verification) — emscripten'sclock_tisi32, so every page that timed anything aborted withRuntimeError: unreachable. Fixed to-> i32in all five files (blas_demo,falling_sand_gfx,lib/stdlib/{render3d,fmm2d,planet}.flow);falling_sand_gfx's FPS loop and the fmm timing gates now run.Round 3 — cooperative fibers (156/158)
async_primitivesnow runs with real interleaving. Newruntime/fiber_wasm.cimplements the fullflow_fiber_*API (init/spawn/yield/park/unpark/run/run_until/current_id/run_main) plus fiber-awareflow_netpoll_fiber_sleep_ms,flow_rt_usleep, andflow_rt_call_task_fnon the Emscripten fiber API: per-fiber malloc'd C and Asyncify stacks, FIFO ready queue, wake-by-deadline sleepers → deterministic M:1 round-robin. The example gained a FiberAsync section registering three Flow task bodies (a Flow function passed asptr<void>via@flow_api); Chrome shows strictT100 T101 T102rotation andjoin(100..102) = 3039, exit 0, zero console errors.usleepbut never included their headers — it now emits<unistd.h>/<sys/time.h>etc. when such an extern is present (this is also why the example never compiled natively); and the old example'sflow_fiber_run_mainwrapper was never linked to a runtime on the wasm path.Round 4 — SHA-256 in the browser (157/158)
runtime_sha256runs Flow's own SHA-256 (lib/runtime/crypto.flow, which is pure Flow with zero externs) linked as a library TU — the digest check verifies the exact code the example exists to test, not a WebCrypto substitute. Only the OS CSPRNG needed a browser backend: newruntime/crypto_wasm.cimplementsflow_rt_random_byteswith WebCrypto's synchronouscrypto.getRandomValues. Card note (amber): "SHA-256 runs Flow's own implementation, same code as native; only the random bytes come from the browser's WebCrypto CSPRNG instead of the native OS kernel." Verified:e3b0c442…digest, exit 0, zero console errors.Round 5 — Metal GPU, CPU-emulated (158/158)
digits_mlp_metalgets sixflow_gpu_*EXTERN_STUBS that emulate the unified-buffer API on CPU:flow_gpu_alloc→malloc,host_ptr→ identity,mul_f32→ elementwise CPU loop,available()→ 1,backend_name()→"cpu-emulated (wasm)". Because the example reports the GPU present, its real correctness gate executes:relu backward gate: 8000 elements, GPU == CPU, all four elementwise benches (up to 16M elements) report results match, PASS, exit 0 — 8/8 Chrome checks. Card note flags honestly that buffers are plain memory and nothing dispatches to a GPU.Fixes (Round 1)
sizeof_i32redefinition: monomorphizer skips synthesizing specializations whose mangled name collides with a concrete declaration (stdlibsizeof_i32vs genericsizeof<T>).graphics.flowgets a demomain()so the library-shaped example builds as a runnable page.site/wasm/was stale (132 examples).Verification
tape_mul,ga_flappy,blas_demo,lu_decomposition,falling_sand_gfx,fmm_selftest(residual 2.6e-16),fmm_adaptive, all three threaded cards,async_primitives(fiber interleaving),runtime_sha256(digest), anddigits_mlp_metal(GPU == CPU gate).Files
New
runtime/{fiber_wasm,crypto_wasm}.c,runtime/blas_wasm.c;scripts/wasm_build.py(EXTERN_STUBS,extra_flow_runtime,extra_c, threads mode),scripts/build_wasm_gallery.py(PAGE_EXTRAS,.degradecard notes); compiler fixes insrc/flow/overload.py(call-resolution fallback) +src/flow/monomorphize.py(sizeof redefinition) +src/flow/c_generator.py(POSIX header emission) with regression tests; the fiveclock()fixes acrossexamples/andlib/stdlib/;examples/effects/async_primitives.flow(FiberAsync section); rebuilt gallery pages (site/wasm/) for every fixed example; anddocs/demos/wasm.md.