Skip to content

wasm gallery: real pthreads over SharedArrayBuffer, host-extern stubs, sizeof fix - #248

Merged
cursor[bot] merged 9 commits into
mainfrom
wip/sizeof-wasm-fix
Aug 9, 2026
Merged

cursor[bot] merged 9 commits into
mainfrom
wip/sizeof-wasm-fix

Conversation

@godofecht

@godofecht godofecht commented Aug 9, 2026 •

Copy link
Copy Markdown
Contributor

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 threads mode in scripts/wasm_build.py)

  • digits_mlp_parallel, parallel_sum, and the new parallel_scaling build with -pthread -sPROXY_TO_PTHREAD: Flow's parallel-for orchestration compiles as a library TU and lands on pthread_create over Web Workers.
  • Pages ship a COI service worker and must be opened in a tab (an iframe cannot become cross-origin-isolated); non-isolated embeds get an honest "open in a tab" message instead of hanging.
  • Browser-verified in Chrome under real cross-origin isolation:
    • 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 count
  • The earlier synchronous fallback stub for flow_parallel_for_i32 is retired.

Host-extern stubs — EXTERN_STUBS in wasm_build.py appends 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 .degrade note on their card (via PAGE_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 deleted runtime/flow_tape.c); the wasm build never linked it. New extra_flow_runtime build option compiles lib/runtime/*.flow as library TUs — the wasm analogue of the native launcher's flow_runtime_flow_sources(). The page computes dz/dx = 4, dz/dy = 3 in Chrome.
  • ga_flappy — a real compiler bug (broken natively too, now fixed). fly()'s call sites pass an int literal for a u32 param plus an untyped constant; the sole-overload fallback in OverloadResolver.resolve_call break-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_compatible guards None. Regression test added (tests/unit/test_strict_gaps.py); the example's own PASS gate runs in Chrome.
  • blas_demo / lu_decomposition — new runtime/blas_wasm.c: plain, numerically correct implementations of exactly the routines the stdlib calls (daxpy/dcopy/ddot/dnrm2/dscal/dgemv/dgemm + LAPACK dgesv_/dgetrf_, column-major per the LAPACK contract), linked via extra_c. lu_decomposition solves x = [1,1,1] with zero residual; blas_demo benchmarks 0.7→2.1 GFLOPS.
  • clock() → i64 signature mismatch (caught by the BLAS verification) — emscripten's clock_t is i32, so every page that timed anything aborted with RuntimeError: unreachable. Fixed to -> i32 in 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_primitives now runs with real interleaving. New runtime/fiber_wasm.c implements the full flow_fiber_* API (init/spawn/yield/park/unpark/run/run_until/current_id/run_main) plus fiber-aware flow_netpoll_fiber_sleep_ms, flow_rt_usleep, and flow_rt_call_task_fn on 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 as ptr<void> via @flow_api); Chrome shows strict T100 T101 T102 rotation and join(100..102) = 3039, exit 0, zero console errors.
  • Two real bugs fixed along the way: the C generator skip-lists POSIX externs like usleep but 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's flow_fiber_run_main wrapper was never linked to a runtime on the wasm path.

Round 4 — SHA-256 in the browser (157/158)

  • runtime_sha256 runs 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: new runtime/crypto_wasm.c implements flow_rt_random_bytes with WebCrypto's synchronous crypto.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_metal gets six flow_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_i32 redefinition: monomorphizer skips synthesizing specializations whose mangled name collides with a concrete declaration (stdlib sizeof_i32 vs generic sizeof<T>).
  • graphics.flow gets a demo main() so the library-shaped example builds as a runnable page.
  • Full gallery regeneration — main's committed site/wasm/ was stale (132 examples).

Verification

  • 158 built / 0 failed; gallery rebuild idempotent for all non-threaded examples, every unchanged page byte-identical.
  • 1202 unit tests pass (includes main's 0.10.0 suite).
  • Browser-verified in Chrome (exit 0, zero console errors): 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), and digits_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, .degrade card notes); compiler fixes in src/flow/overload.py (call-resolution fallback) + src/flow/monomorphize.py (sizeof redefinition) + src/flow/c_generator.py (POSIX header emission) with regression tests; the five clock() fixes across examples/ and lib/stdlib/; examples/effects/async_primitives.flow (FiberAsync section); rebuilt gallery pages (site/wasm/) for every fixed example; and docs/demos/wasm.md.

godofecht and others added 8 commits August 8, 2026 05:51
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]>
@cursor

cursor Bot commented Aug 9, 2026

Copy link
Copy Markdown
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.

@cursor
cursor Bot merged commit bc1a0ec into main Aug 9, 2026
16 checks passed
@cursor
cursor Bot deleted the wip/sizeof-wasm-fix branch August 9, 2026 16:31
godofecht pushed a commit that referenced this pull request Aug 9, 2026
wasm gallery: real pthreads over SharedArrayBuffer, host-extern stubs, sizeof fix
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

MLIR: lower doom-flow.doom.flow end-to-end (post-#221)

2 participants