Skip to content

wasm gallery: 158/158 — every example builds and runs as a card - #464

Merged
godofecht merged 17 commits into
mainfrom
wip/sizeof-wasm-fix
Aug 16, 2026
Merged

godofecht merged 17 commits into
mainfrom
wip/sizeof-wasm-fix

Conversation

@godofecht

@godofecht godofecht commented Aug 13, 2026 •

Copy link
Copy Markdown
Contributor

Wasm gallery: 161/161 — every example builds and runs as a card

Rebased onto current main (ded3635). The earlier #248 (merged Aug 9) was built on a pre-rewrite main line; this PR carries the full gallery arc on top of the current tree.

What this PR does

The gallery (site/wasm/, built by scripts/build_wasm_gallery.py) went from 151/158 runnable to 161/161. The work breaks into two halves: make the compiler/linker produce valid wasm, then close the last host-bound gaps with real implementations rather than stubs.

Round 1 — build plumbing

  • sizeof_i32 redefinition fix in src/flow/monomorphize.py (generic/type-parameterized sizeof no longer duplicates concrete declarations) + regression test
  • EXTERN_STUBS mechanism in scripts/wasm_build.py: honest browser stubs for host-only externs, flagged as .degrade on cards
  • graphics.flow gained a demo main() so it builds as a runnable page
  • tiny-pointers "Abstract-claim coverage" card re-added via the extra_html hook

Round 2 — real pthreads (no stub)

  • digits_mlp_parallel and parallel_sum run on genuine Emscripten pthreads over SharedArrayBuffer (-pthread, cross-origin isolated serving)
  • parallel_scaling page shows the full 2/4/8-worker speedup curve (verified 3.8x/7.9x/17.3x in Chrome)

Round 3 — real fixes (155/158)

  • tape_mul: new extra_flow_runtime build option links lib/runtime/*.flow as library TUs — Flow's own autodiff tape runs in the browser
  • ga_flappy: real compiler bug in resolve_call (sole-overload fallback broke on a literal mismatch before seeing unknown-typed args → unmangled call) + regression test
  • blas_demo + lu_decomposition: new runtime/blas_wasm.c — plain, numerically correct Level 1/2/3 + dgesv_/dgetrf_, column-major per LAPACK. Verified x=[1,1,1] with zero residual; benchmarks 0.7→2.1 GFLOPS
  • clock() -> i64 → -> i32 fix across 5 files — the clock_t mismatch aborted every timing page with RuntimeError: unreachable (blas_demo heap-corruption trap, falling_sand_gfx FPS loop, fmm timing gates)

Round 4 — cooperative fibers (156/158)

  • runtime/fiber_wasm.c: full flow_fiber_* API (init/spawn/yield/park/unpark/run/run_main) on the Emscripten fiber API (Asyncify-based true stack switching) — M:1, per-fiber malloc'd C + Asyncify stacks, FIFO ready queue, wake-by-deadline sleepers
  • async_primitives.flow gained a FiberAsync section: three Flow task bodies registered via flow_rt_fiber_task_set_fn, strict round-robin interleaving verified in Chrome
  • Fixed the C generator's skip-listed POSIX externs (usleep etc.) never emitting their headers — <unistd.h> etc. now emitted when declared

Round 5 — Flow's own SHA-256 (157/158)

  • lib/runtime/crypto.flow links as a library TU: Flow's pure-Flow SHA-256 runs unchanged in the browser (verifies e3b0c442…), only the CSPRNG delegates to WebCrypto crypto.getRandomValues via new runtime/crypto_wasm.c
  • Card degradation-note mechanism (.degrade + note field in PAGE_EXTRAS)

Round 6 — CPU-emulated Metal GPU (161/161)

  • Six flow_gpu_* externs CPU-emulated in EXTERN_STUBS (unified buffers = malloc, flow_gpu_mul_f32 = elementwise loop). digits_mlp_metal's real correctness gate runs: relu backward gate: GPU == CPU, all benches (results match), PASS

Verification

  • 161 built / 0 failed, every page byte-identical except intended changes
  • Chrome-verified: async_primitives (9/9 checks, strict interleaving), runtime_sha256 (4/4), digits_mlp_metal (8/8), parallel_scaling (3.8x/7.9x/17.3x), tape_mul (dz/dx=4, dz/dy=3), ga_flappy, blas_demo, lu_decomposition, falling_sand_gfx (renders), fmm_selftest (residual 2.6e-16), fmm_adaptive
  • 1364 unit tests pass (rebased against current main's suite)
  • docs/demos/wasm.md + docs/language/wasm-crossings.md (new section 6: Cooperative fibers) updated

Known honest degradations (card-flagged)

  • digits_mlp_metal: GPU API emulated on CPU — nothing dispatches to a GPU
  • runtime_sha256: random bytes from WebCrypto CSPRNG instead of the native kernel (digest itself is Flow's own code)
  • pthreads pages need cross-origin isolation (served with COOP/COEP headers)

godofecht and others added 11 commits August 13, 2026 19:17
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]>
… pages

Four of the six remaining wasm-gallery failures were not host-bound after
all, and are now runnable pages with real (non-stubbed) behavior, bringing
the gallery to 155 built / 3 failed:

- 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() — and tape_mul now computes dz/dx=4, dz/dy=3
  in the browser.

- ga_flappy: a real compiler bug. Its fly() call sites pass an int literal
  for a u32 parameter 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.
  The example was broken natively too; regression test added.

- blas_demo / lu_decomposition: new runtime/blas_wasm.c provides 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_decomp
  solves x=[1,1,1] with zero residual; blas_demo benchmarks 0.7→2.1 GFLOPS.

- clock(): the examples' `clock() -> i64` externs mismatched emscripten's
  i32 clock_t, so any page that timed something aborted with
  "RuntimeError: unreachable" (blas_demo's first benchmark, falling_sand's
  FPS loop, the fmm timing gates). Declared -> i32 in blas_demo.flow,
  falling_sand_gfx.flow, render3d.flow, fmm2d.flow, planet.flow; µs-scale
  values fit i32 on both platforms. falling_sand_gfx and the fmm pages now
  run without console errors.

Verified in Chrome: tape_mul, ga_flappy, blas_demo, lu_decomposition,
falling_sand_gfx, fmm_selftest, fmm_adaptive. 1202 unit tests pass; other
pages byte-identical. docs/demos/wasm.md refreshed (155/158, three that do
not build: fibers, Metal GPU, flow_sha256).
…wasm)

The last "host-bound" failure was not one. The fiber runtime is pure Flow +
portable C; only the context switch was native assembly. The wasm port uses
the Emscripten fiber API — setjmp/longjmp-family machinery backed by
Asyncify, which rewinds a full wasm+JS call stack onto a private stack (plain
setjmp/longjmp cannot move between stacks, and wasm cannot hand-switch the
stack pointer).

- runtime/fiber_wasm.c (new): the whole flow_fiber_* surface on
  emscripten_fiber_* — init/set_maxprocs/maxprocs/spawn/yield/park/unpark/
  run/run_until/current_id/prepare_park/finish_park/shutdown/steal_stats/
  run_main, plus fiber-aware flow_netpoll_fiber_sleep_ms, flow_rt_usleep and
  flow_rt_call_task_fn. Per-fiber malloc'd C + Asyncify stacks (no shared
  stack clobbering), FIFO ready queue, wake-by-deadline sleepers. M:1 —
  wasm has one OS thread.
- async_primitives.flow gains a FiberAsync section: three Flow task bodies
  registered via flow_rt_fiber_task_set_fn (a Flow function passed as
  ptr<void> — @flow_api keeps the plain C ABI name), each printing a step
  and parking on async_delay. Chrome prints a strict round-robin trace
  (T100:0 T101:0 T102:0 T100:1 ...) with join(100..102) = 3039, exit 0,
  zero console errors. Native ./flow run behaves identically (M:1 pinned).
- src/flow/c_generator.py: skip-listed POSIX externs (usleep, gettimeofday,
  ...) were never declared because the generated C never included their
  headers — the first program to call one (BlockingAsyncIO.sleep_ms) could
  not compile anywhere. The generator now emits the header when such an
  extern is present.
- Gallery: PAGE_EXTRAS async_primitives entry (extra_c fiber_wasm.c +
  flow_rt_fiber_async.c, extra_flow_runtime fiber_async.flow,
  -sASYNCIFY=1) + emcc_flags plumbing in build_one. 156/158 examples build;
  remaining two are Metal GPU and flow_sha256.
- Docs: wasm.md (verified row, Fibers row, 2-not-3 failures, 7th fix entry)
  and wasm-crossings.md (new section 6: Cooperative fibers).
runtime_sha256 was a stub candidate until it turned out lib/runtime/crypto.flow
is pure Flow — SHA-256 included, zero externs. Linking it as a library TU
(extra_flow_runtime) runs Flow's own hashing implementation in the browser,
and the page verifies the known empty-string digest: `crypto runtime ok`,
exit 0, zero console errors in Chrome.

The only host-bound piece is the OS CSPRNG (flow_rt_random_bytes →
arc4random/getrandom natively). runtime/crypto_wasm.c supplies it via
WebCrypto's synchronous crypto.getRandomValues — a genuine CSPRNG, the
non-async half of the crypto.subtle API.

- scripts/build_wasm_gallery.py: runtime_sha256 PAGE_EXTRAS entry; cards for
  built-but-different examples can now carry an honest `.degrade` note via a
  `note` field (rendered in amber, carried in the manifest).
- docs/demos/wasm.md: verified row, Systems 14/14, the failures section drops
  to a single row (Metal GPU only), eighth fix entry.
The last non-builder. Its Metal runtime is genuinely Apple-only, so the
flow_gpu_* surface is CPU-emulated in EXTERN_STUBS: flow_gpu_alloc returns
malloc'd memory (unified-buffer semantics), flow_gpu_host_ptr is the
identity, flow_gpu_mul_f32 runs the elementwise loop on the CPU, and the
backend reports "cpu-emulated (wasm)" in the page's own output.

The example was already written with a CPU reference on the other side of
every check, so it runs the full correctness gate on wasm: the relu backward
dh = da * mask verifies "GPU == CPU" on 8000 elements, and the four sizing
benches (up to 16M elements) all report "(results match)" — in Chrome, with
`PASS`, exit 0, and zero console errors. The card carries a .degrade note
saying the "gpu ms" rows measure a CPU loop, not a GPU dispatch.
flow_rt_support.c supplies the monotonic clock for the timing rows (same as
tiny_pointers/digits_mlp).

docs/demos/wasm.md: the whole gallery now builds — intro, Learning 12/12,
verified row, "Every example builds" section, ninth fix entry.
@cursor

cursor Bot commented Aug 13, 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.

godofecht and others added 5 commits August 13, 2026 19:34
…d build flags

The rebase onto ded3635 dropped two blocks from wasm_build.py during
conflict resolution: the extra_c -> extra_link merge (needed by
blas_demo/lu_decomposition/async_primitives/runtime_sha256) and the
--wasm32 flag in flow_to_llvm_ir. Restore both, then regenerate the
full gallery from a clean tree: 161 built, 0 failed.

The count is 161, not 158: the rebase base carried three new smoke
examples (bigint_smoke, checked_arith_smoke, hashmap_i64_smoke) that
the committed manifest predates. Every example now builds and runs as
a card; artifacts are re-emitted against the rebased compiler.

🤖 Generated with Codebuff
Co-Authored-By: Codebuff <[email protected]>
Tier-2 transpile was failing on immutable nb/tag/cls assignments.

Co-authored-by: Cursor <[email protected]>
@godofecht

Copy link
Copy Markdown
Contributor Author

Triage note (2026-08-16): backlog of ~35 overlapping Freebuff/Jules PRs was closed or merged. This wasm gallery PR is the only large remaining open item.

Left open intentionally — prior CI failures on FLOW tier-2 / self-host / overall CI, and it’s a ~20k-line gallery rebuild. Please re-sync with main and get CI green before merge.

@godofecht
godofecht merged commit 38e0e1c into main Aug 16, 2026
18 checks passed
@godofecht
godofecht deleted the wip/sizeof-wasm-fix branch August 16, 2026 22:12
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.

1 participant