Skip to content

fix(codegen): start the wasm heap after the last data segment (#830) - #835

Merged
hyperpolymath merged 8 commits into
mainfrom
claude/wasm-heap-literals
Dec 1, 2026
Merged

hyperpolymath merged 8 commits into
mainfrom
claude/wasm-heap-literals

Conversation

@hyperpolymath

@hyperpolymath hyperpolymath commented Dec 1, 2026 •

Copy link
Copy Markdown
Owner

Closes #830

The hole

On main (ee211d3), the core-wasm heap-pointer global started at a fixed 1024, while string literals were laid out from a fixed 2048. Any program that bump-allocates more than about 1 KiB overwrites its own literals. Found by #829.

Reproduction on main. main makes 60 calls of println("label_number_N" ++ " ok"). Compiled with affinescript compile repro.affine -o repro.wasm and run with bun run repro.wasm:

label_number_1 ok
…
label_number_21 ok
label_number_22abe
RuntimeError: Out of bounds memory access (evaluating 'instance')
exit=1

affinescript eval prints all 60 lines. This was silent corruption: the wrong line is printed before anything traps.

With this PR, the same program prints all 60 lines, exits 0, and its stdout matches the interpreter's output line for line (after removing the interpreter's quotes; see #833).

The fix (lib/codegen.ml, "Linear-memory layout")

  • Layout: scratch [0, 1024), then static data from static_data_base = 1024, then the heap from heap_base = align8(max(1024, data_end)).

  • generate_module calls memory_layout_of_datas after code generation, so every literal has already been laid out. It sets the heap global to heap_base and sizes the memory to cover it (max 1 (ceil(heap_base / 64 KiB)) pages).

  • check_memory_layout refuses the module with a compile-time error if:

    • the heap base is below the end of static data;
    • two segments overlap;
    • a segment lies in the scratch region;
    • the memory does not hold the static data.

    I checked that this gate alone catches the old layout. With the old layout restored and the gate kept, the compiler refuses the repro: internal error (wasm memory layout): heap base 1024 is below the end of static data 3186; allocations would overwrite literals.

  • Memory growth: there is no memory.grow path. If a program allocates past the module's pages, it gets an out-of-bounds trap, not a write into the literal region. A test pins this behaviour.

  • Other wasm emitters: I checked them and they are not affected. tea_bridge, tea_cs_bridge and tea_router have no data segments. WasmGC uses no linear memory for strings. Wasm_dtoa and the clock use the heap global.

  • Docs: the invariant is written up in docs/WASM-MEMORY-LAYOUT.adoc.

Tests (test/test_wasm_heap_layout.ml, part of dune runtest)

The last three run under Bun's WASI. They SKIP without bun, as in CI's coverage job.

Test Old layout Fix
test_wasm_heap_base_below_data_end_refused: the check refuses heap 1024 with a literal at 2048, overlapping segments, and a segment in scratch n/a: the check is new. Its assertion is the old layout. pass
test_wasm_heap_after_literals_static: the heap global equals heap_base, no mutable global starts inside static data, and memory covers data FAIL pass
test_wasm_heap_repro_runs: the #829 repro prints all 60 lines FAIL pass
test_wasm_heap_literals_intact_after_alloc: about 40 KiB of allocation, then every literal is reprinted FAIL pass
test_wasm_heap_exhaustion_traps: past one page, it traps loudly and only the pre-loop literal is printed pass (characterisation) pass

For the "old layout" column, I restored literals at 2048 and the heap at 1024 and removed the check, then ran the suite. The result was 3 failures! … 5 tests run.

Gates (run locally on this branch)

just check                         → exit 0
  test_main: Test Successful, 667 tests run (incl. 5 new)
  res-to-affine walker: 32 tests run
  OK: soundness ledger — all 5 properties hold (anchors exist + back-links + content-bound + stamp-fresh + pins live)
  OK: doc-truthing / DEED gates / capability anchors / no extension.ts
tools/run_codegen_wasm_tests.sh    → All codegen WASM tests passed (48 JS harnesses)
tools/run_codegen_deno_tests.sh    → All codegen Bun-ESM (legacy codegen-deno corpus) tests passed (42 harnesses)
tools/run_codegen_bun_tests.sh     → All native Bun-ESM tests passed (8 harnesses)

#836. An earlier version of this PR pinned #836 as open (tracked) with an xfail test. #841 has since fixed #836 on main and added its own fixed row and tests, so the rebase dropped the pin and fixture. The audit marks #836 as fixed by #841.

Soundness ledger. I added a new docs/SOUNDNESS.adoc row (#830, fixed), anchored to the suite and the five named tests. After #840 and #841 merged, I rebased onto 0cf73b2 and advanced the stamp to 0cf73b2 / 2026-12-01, the main commit I verified against. I resealed tools/soundness-anchors.sha256, which now has 30 anchors. On the rebased branch, just check exits 0 with 772 tests and the ledger reports all 5 properties; the wasm (48), Bun-ESM legacy (42) and native Bun (8) runners all pass.

Coordination with #829 (stamp collision)

#829 advances the stamp to the same ee211d3 / 2026-12-01. I did a test merge of the two branches. It is textually clean, and the build and tests pass. However, ledger property 4 fails on the merged tree: #829's soundness-path edits come after the last stamp advance, and the merge leaves the stamp line unchanged. Whichever PR lands second must re-advance :ground-truth-sha: to the newer main commit it was verified against. If #829 lands first, I will rebase this branch and re-stamp.

Audit of the other #829 divergences

The full audit is in docs/reports/AUDIT-2026-12-01-backend-divergences.adoc. I reproduced every finding on main ee211d3. Only #830 is implemented here.

Finding Evidence Class Recommended fix (most elegant and correct) Tracking
String indices are octets on interp and wasm, UTF-16 units on Bun-ESM len("🦜") is 4 / 4 / 2; string_char_code_at("🦜",0) is 240 / 240 / 55358 Silent divergence, not type unsoundness Octet offsets everywhere, failing loudly off a character boundary. Pair with an opaque Utf8Offset type (the dependable, type-led option). Changes semantics: owner decision. #831
Plain-JS backend has no string builtins .js compiles; then ReferenceError: int_to_string is not defined Loud, but at run time instead of compile time A closed-world check at codegen: each backend declares which builtins it lowers, and any other free identifier is a codegen Error. Share the Bun lowering table. #832
eval fails on self-recursion and let mut Unbound variable: g; Expected mutable reference. Also new: forward and mutual references are refused as type errors, because eval folds check_decl without check_program's forward pass. println prints quotes. Loud divergence of the reference interpreter. No silent wrong value found. eval uses check_program; a two-phase recursive top-level environment; let mut binds a VMut cell #833
Added later: a user fn named like a wasm-intercepted intrinsic (e.g. string_sub) is silently replaced by the intrinsic Wasm prints a heap pointer (1024 on main); interp and Bun print 7 Soundness hole (silent wrong value) Fixed by #841 (merged): all 26 arms go through intrinsic_callee #836
Added later: an intrinsic used as a value (len) on Bun-ESM ReferenceError: len is not defined; wasm refuses at compile time Loud, at the wrong phase Eta-expand intrinsics in value position in a shared pass #837
Added later: a local or parameter does not shadow a same-named top-level fn on wasm wasm 7, interp and Bun 9 Soundness hole (silent wrong value) Look up locals first, and intern call_indirect types. Fixed by #840 (merged), with 4 run tests that fail first #838
Added later: a named fn passed as a value wasm refuses it with UnboundVariable "nine"; interp and Bun print 9 Loud (compile time) Lower it to a closure with a null environment and a trampoline #839

The audit also notes a proof route. The layout invariant is a small frame lemma (no allocation store aliases a data segment) that could sit beside K-1 in formal/. It is not claimed here: the fix is tested, not proved.

Beyond this repo

#834 tracks rebuilding core-wasm artefacts that were built before this fix. In this repo, editors/vscode/out/extension.cjs is affected: its embedded module has the heap at 1024 and literals at 2048–2761. I did not regenerate it here, because the committed file is already stale relative to main (a rebuild differs by more than the layout), so the rebuild should be its own reviewed change.

Notes

  • Signatures. The commit is signed with the session key. The owner re-signs before merge.
  • Licences. No licence or SPDX edits. The new files carry the repo's usual headers.
  • Languages. No TypeScript and no new JavaScript. The tests are OCaml and drive Bun's built-in WASI.

https://claude.ai/code/session_01J4QvDjPsKtu8zU9b32Cv1P


Generated by Claude Code

@gitnotebooks

gitnotebooks Bot commented Dec 1, 2026

Copy link
Copy Markdown

hyperpolymath added a commit that referenced this pull request Dec 1, 2026
…direct types (#838) (#840)

Closes #838

Found by the #829 thread; reproduced independently on `main` `ee211d3`.
This is split off from #835, which fixes the heap and literal layout, so
each PR stays reviewable.

## The holes

**1. Silent wrong value.**

```affine
fn helper(s: String) -> Int { 7 }
fn call(helper: fn(String) -> Int) -> Int { helper("x") }
fn main() -> () { println(int_to_string(call(|s| 9))); }
```

The interpreter and Bun-ESM print `9`. Core wasm printed **`7`**: the
call went to the top-level `helper`, and the argument was silently
ignored. The same happens with a let-bound closure.

Cause: the generic `ExprApp` arm of `gen_expr` (`lib/codegen.ml`)
consulted `func_indices` before `ctx.locals`. The `ExprVar` value paths
already looked up locals first.

**2. Invalid wasm (found while fixing 1).**

`fn call(f: fn(String) -> Int) -> Int { f("x") }`, followed by `call(|s|
9)`, failed with `CompileError: WebAssembly.Module doesn't validate`.

Cause: the three `CallIndirect` sites looked up the signature in the
type section but never added it. If the signature was absent, they
returned the next free index, and a later, different type took that
slot. On `main`, this breaks any higher-order function compiled before a
function with its closure signature exists.

## The fix

- **Call resolution:** the call arm and `expr_val_type`'s `ExprApp` case
now check locals first, so a local shadows a same-named top-level
function. A name that is not a local resolves as before.
- **Type interning:** a shared `intern_type` helper adds a missing
signature, and all three `CallIndirect` sites now use it.

This complements #824, which only stopped a parameter from pulling in a
module import. It is consistent with #824: a parameter is never a
reference to a top-level or imported function.

## Tests (`test/test_wasm_call_resolution.ml`, run under Bun's WASI;
SKIP without `bun`)

| Test | `main` `ee211d3` | This PR |
|---|---|---|
| `test_wasm_param_shadows_fn` | **FAIL**: got `7` | pass: `9` |
| `test_wasm_let_shadows_fn` | **FAIL**: got `7` | pass: `9` |
| `test_wasm_unshadowed_fn_still_direct` (direct call plus closure,
`16`) | **FAIL**: invalid wasm (bug 2) | pass |
| `test_wasm_call_indirect_type_interned` (every `call_indirect` type
index is in the section, and the program runs) | **FAIL** | pass |

## Gates (local, this branch)

```
just check                         → exit 0 (test_main: 666 tests; soundness ledger: all 5 properties hold)
tools/run_codegen_wasm_tests.sh    → All codegen WASM tests passed (48 JS harnesses)
tools/run_codegen_deno_tests.sh    → All codegen Bun-ESM (legacy codegen-deno corpus) tests passed (42 harnesses)
tools/run_codegen_bun_tests.sh     → All native Bun-ESM tests passed (8 harnesses)
```

The new `SOUNDNESS.adoc` row for #838 is `fixed`. The stamp is set to
`ee211d3` / 2026-12-01, and the anchors are resealed.

## Coordination

- **#835:** adds ledger rows at the same place in `docs/SOUNDNESS.adoc`.
It also changes `tools/soundness-anchors.sha256` and
`test/test_main.ml`. Whichever PR lands second needs a rebase and a
reseal. I own both and will do it.
- **#829:** sets the same stamp.

## Not in this PR

- #839: a named function passed as a value (`call(nine)`) is refused at
compile time with `UnboundVariable`. That fails loudly, and the fix is a
feature (named functions as null-environment closures).
- #836: a user function named like an intrinsic is silently replaced by
the intrinsic. It is pinned in #835. Each of its 20 interceptions needs
checking first.

---
- **Commit signature:** signed with the session key. The owner re-signs
before merge.
- **Constraints:** no licence or SPDX edits, and no TypeScript or JS.

---
_Generated by [Claude Code](https://claude.ai/code)_

Co-authored-by: Claude <noreply@anthropic.com>
@hyperpolymath
hyperpolymath force-pushed the claude/wasm-heap-literals branch from c131d9c to 7f1f965 Compare December 1, 2026 16:51
@hyperpolymath
hyperpolymath marked this pull request as ready for review December 1, 2026 17:30
hyperpolymath added a commit that referenced this pull request Dec 1, 2026
…) (#841)

Closes #836

## The bug

On core wasm, the intrinsic arms of `gen_expr`'s `ExprApp` dispatch
(`lib/codegen.ml`) matched the callee by spelling, before asking whether
the program binds that name. A user function named like an intrinsic was
compiled but never called.

```affine
fn string_sub(s: String, a: Int, b: Int) -> Int { 7 }
pub fn main() -> () { println(int_to_string(string_sub("x", 0, 1))); }
```

| Backend | `main` `4248912` | this PR |
|---|---|---|
| interp | 7 | 7 |
| Bun-ESM | 7 | 7 |
| core wasm | **1024** (a heap pointer) | 7 |

## The fix

- A new `user_fns` set in the codegen context holds the names the
program *defines*: a `fn` with a body or a `const`, in this module or
imported. An `extern fn` is not in it.
- `user_binds ctx name` is true for a name in that set or a local.
`intrinsic_callee ctx callee` returns the callee's ident only when the
program does not bind it.
- All 26 arms now match on `intrinsic_callee`, not on the raw callee. An
arm added later gets the guard without asking for it.
- The WASI import pre-scan skips a name the program defines. Without
this, a user `fn net_accept` left an unused `sock_accept` import that
Bun's WASI cannot satisfy.
- `Typecheck.elab_poly_builtin` rewrites `show` on Int and `slice` on a
String into intrinsic calls. Those calls are now named
`__builtin:int_to_string` and `__builtin:string_slice`, which no program
can write. Otherwise, once a user `int_to_string` wins, `show(5)` would
call it.

`user_binds` has the name and signature of the helper in #829, with a
stricter body (#829 tests membership of `func_indices`, which also holds
externs). Whichever lands second keeps this definition; #829's three
guards then work unchanged, and become redundant because its arms go
through `intrinsic_callee`.

## Classification of the name-matched arms

A definition with a body wins in both classes. The classes differ in
what an `extern fn` of the same name means: for class (b) the arm *is*
the lowering of that declaration, so a guard on `func_indices` would
break it.

| Class | Names | wasm on `4248912` with a user fn returning 7 |
|---|---|---|
| (a) pure intrinsic | `print` | invalid module (loud) |
| (a) | `println` (0 and 1 argument) | prints the argument; user fn not
called |
| (a) | `string_length`, `len` | 3 |
| (a) | `string_char_code_at`, `char_to_int` | 97 |
| (a) | `string_from_char_code`, `string_slice`, `string_sub`,
`to_lowercase`, `to_uppercase`, `trim`, `float_to_string` | 1024 |
| (a) | `string_find` | 1 |
| (a) | `int_to_string` (user fn returns `"seven"`) | 1 |
| (b) WASI lowering | `clock_now_ms` | 6 |
| (b) | `net_shutdown`, `net_send` | 52 |
| (b) | `file_open` | -44 |
| (b) | `file_fd_write` | writes `d`, prints 0 |
| (b) | `file_read`, `net_recv` | 1042 |
| (b) | `file_close` | prints nothing |
| (b) | `net_accept` | fails to instantiate (loud) |
| (b) | `env_count`, `arg_count` | 186, 1 |
| (b) | `env_at`, `arg_at` | 12221, 1136 |
| internal | `__show_unsupported:<T>` | not writable in source |

The interpreter returns 7 for every row. Bun-ESM prints 7 for every row
except a user `print` or `println`, which it refuses at compile time
(#801). With this PR core wasm gives 7 (`seven`) on every row.

`print`, `println`, `int_to_string` and `string_length` are also
declared `extern fn` in `stdlib/effects.affine`, so the extern rule
matters for them too.

## Tests

`test/test_intrinsic_shadow.ml`, 95 cases:

- every name on the interpreter, Bun-ESM and core wasm (29 cases each);
- a check that reads the arms out of `lib/codegen.ml` and fails if an
arm has no case;
- class (b): each of the 13 WASI names still lowers to its import; an
`extern fn` in scope keeps the lowering and its `env` import is not
called; the lowerings run under Bun's WASI;
- `show` / `slice` are not captured by a user `int_to_string` /
`string_slice`;
- a local and an imported definition win.

```
[OK] 0 every name-matched arm has a case....
[OK] 1 user `print` wins (interp)....
...
[OK] 59 user `print` wins (wasm)....
[OK] 60 user `println/0` wins (wasm)....
...
[OK] 87 user `arg_at` wins (wasm)....
[OK] 88 no WASI import for a user-defined name....
[OK] 89 class (b): WASI names still lower....
[OK] 90 class (b): an extern in scope keeps the lowering....
[OK] 91 class (b): the lowerings run (bun)....
[OK] 92 show/slice are not captured by user fns (bun)....
[OK] 93 a local shadows an intrinsic (bun)....
[OK] 94 an imported definition wins....
Test Successful in 0.505s. 95 tests run.
```

### Mutation checks

| Mutation | Failing tests |
|---|---|
| `lib/codegen.ml` and `lib/typecheck.ml` as on `4248912` | 34: all 29
wasm cases, the arm-coverage check, unused WASI import, `show`/`slice`,
local, imported |
| `intrinsic_callee` ignores `user_binds` | 29 (three wasm cases pass by
accident, see below) |
| `user_binds` tests `func_indices` (the blanket guard) | "an extern in
scope keeps the lowering" |
| elaboration emits the plain names again | `show`/`slice`, arm-coverage
|
| imported definitions not recorded | "an imported definition wins" |
| WASI pre-scan ignores user definitions | "no WASI import for a
user-defined name", `net_accept` on wasm |

Under the second mutation alone, `net_shutdown` and `file_close` still
pass: with no WASI import the arm falls back to function index 1, which
happens to be the user's function. `string_slice` passes because the
plain name is no longer an arm. All three fail under the first mutation.

### Gates

| Gate | Result |
|---|---|
| `dune runtest --force` | pass (767 tests in the main suite) |
| `just check` | pass. The `lint` step printed "ocamlformat not
installed; skipping format check", so formatting was not checked here |
| `tools/run_codegen_wasm_tests.sh` | pass (48 harnesses) |
| `tools/run_codegen_deno_tests.sh` | pass (42 harnesses) |
| `tools/run_codegen_bun_tests.sh` | pass (8 harnesses) |

`docs/SOUNDNESS.adoc` gains a `fixed` row for #836, the stamp advances
to `4248912`, and the manifest is resealed.

## Interaction with open PRs

- #835 adds an xfail pin for #836. Once both are merged that pin reports
`XPASS`; its row should then be dropped in favour of the row here.
- #829: see the note on `user_binds` above. `test/dune` and
`docs/SOUNDNESS.adoc` will conflict trivially.

## Found, not fixed here

1. `print("hi")` on core wasm emits an invalid module. The arm lowers
`print` as an integer print, but its type is `String -> Unit`. Loud.
2. With an in-file `extern fn clock_now_ms(c: Int) -> Int;` the call is
lowered to WASI, but the unused `env.clock_now_ms` import is still
emitted, so a WASI-only host cannot instantiate the module. Same on
`4248912`. Loud.
3. The interpreter does not bind the WASI builtins (`file_fd_write`,
`clock_now_ms`, ...): they type-check and then fail with "Unbound
variable" at run time. Loud.
4. `is_string_concat_operand` in `lib/codegen.ml` still recognises
String-returning builtins by spelling and has no context, so a user `fn
trim` that returns an array is treated as a String operand of `++`. It
is a rejection heuristic, so the effect is a loud refusal.
5. `tools/run_codegen_bun_tests.sh` leaves an untracked
`tests/codegen-bun/deno-removed.json` behind.

---
_Generated by [Claude Code](https://claude.ai/code)_

Co-authored-by: Claude <noreply@anthropic.com>
@hyperpolymath
hyperpolymath enabled auto-merge (squash) December 1, 2026 18:35
The core-wasm heap-pointer global was initialised to a fixed 1024 while
string literals were laid out from a fixed 2048, so any program that
bump-allocated more than ~1 KiB overwrote its own literals: #829's
60-concatenation repro printed 21 lines, then `label_number_22abe`, then
trapped out of bounds. The interpreter printed all 60.

Fix at source in lib/codegen.ml ("Linear-memory layout"):
- literals start at static_data_base (= scratch_end = 1024);
- after code generation, memory_layout_of_datas computes data_end from
  the emitted segments, and the heap global is set to
  align8(max(scratch_end, data_end)); the memory's initial page count
  covers it;
- check_memory_layout refuses (compile-time error) any module whose heap
  base is below the end of static data, whose segments overlap or dip into
  the scratch region, or whose memory does not hold the static data.

There is no memory.grow path; heap exhaustion stays a loud OOB trap.

Tests: test/test_wasm_heap_layout.ml (layout check, static layout of
compiled programs, and under Bun's WASI: the #829 repro, literals intact
after ~40 KiB of allocation, exhaustion traps loudly). Three fail on the
old layout; the gate alone refuses the old layout at compile time.

Docs: docs/WASM-MEMORY-LAYOUT.adoc (invariant), SOUNDNESS.adoc row #830
(stamp ee211d3, resealed), audit of the other #829 divergences in
docs/reports/AUDIT-2026-12-01-backend-divergences.adoc (follow-ups

Closes #830

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01J4QvDjPsKtu8zU9b32Cv1P
Both were reported by the #829 thread after the first version of the audit.
#836 (a user fn named like an intrinsic is replaced on wasm) has since been
fixed on main by #841, so no pin is added here; #837 (an intrinsic used as a
value on Bun-ESM) is a loud divergence, tracked by its issue.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01J4QvDjPsKtu8zU9b32Cv1P
… and #839 (fn as value) to the divergence audit

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01J4QvDjPsKtu8zU9b32Cv1P
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01J4QvDjPsKtu8zU9b32Cv1P
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01J4QvDjPsKtu8zU9b32Cv1P
@hyperpolymath
hyperpolymath force-pushed the claude/wasm-heap-literals branch from 7f1f965 to 2f46ef0 Compare December 1, 2026 18:37
@hyperpolymath
hyperpolymath enabled auto-merge (squash) December 1, 2026 19:17
Repository owner deleted a comment from coderabbitai Bot Dec 1, 2026
Repository owner deleted a comment from chatgpt-codex-connector Bot Dec 1, 2026
Repository owner deleted a comment from chatgpt-codex-connector Bot Dec 1, 2026
Repository owner deleted a comment from coderabbitai Bot Dec 1, 2026
@sonarqubecloud

sonarqubecloud Bot commented Dec 1, 2026

Copy link
Copy Markdown

@hyperpolymath
hyperpolymath merged commit 083fa74 into main Dec 1, 2026
19 checks passed
@hyperpolymath
hyperpolymath deleted the claude/wasm-heap-literals branch December 1, 2026 19:35
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

2 participants