Skip to content

fix(codegen): a user fn named like an intrinsic is called on wasm (#836) - #841

Merged
hyperpolymath merged 1 commit into
mainfrom
claude/fix-836-intrinsic-shadow
Dec 1, 2026
Merged

hyperpolymath merged 1 commit into
mainfrom
claude/fix-836-intrinsic-shadow

Conversation

@hyperpolymath

Copy link
Copy Markdown
Owner

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.

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

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

The intrinsic arms of gen_expr's ExprApp dispatch matched the callee by
spelling, before asking whether the program binds that name. On core wasm
`fn string_sub(s: String, a: Int, b: Int) -> Int { 7 }` was never called:
the intrinsic ran and the program printed a heap pointer (1024) where the
interpreter and Bun-ESM print 7.

All 26 arms now dispatch on `intrinsic_callee`, which is empty for a name
the program binds: a fn with a body or a const (here or imported), or a
local. A name that is only declared (`extern fn`) keeps its lowering, so
the WASI lowerings are unchanged; that is why the guard is a set of
user-defined names and not membership of func_indices.

The WASI import pre-scan skips a name the program defines, so no unused
import is emitted. The calls elaboration makes for `show` on Int and
`slice` on a String are renamed `__builtin:...`, which no program can
write, so a user int_to_string / string_slice does not capture them.

test/test_intrinsic_shadow.ml covers every name on the interpreter,
Bun-ESM and core wasm. docs/SOUNDNESS.adoc gains the #836 row and the
ground-truth stamp advances to 4248912.

Closes #836

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01J4QvDfoRYrnr6w2SMcxvze
@gitnotebooks

gitnotebooks Bot commented Dec 1, 2026

Copy link
Copy Markdown

@coderabbitai

coderabbitai Bot commented Dec 1, 2026 •

Copy link
Copy Markdown
Contributor

Warning

Review limit reached

You've used all free OSS reviews for now. Wait for the free limit to reset to keep reviewing this public repository.

Next included review available in 58 minutes.

Check out review usage here.

View limit details

Limit details: You’ve used the included review currently available.

Learn how review limits work.

Review configuration:

Run configuration

  • Source mode: Auto
  • Repository: Unavailable
  • Branch: Unavailable
  • File: No configuration file from this repository applied
  • Commit: Unavailable
  • Layers: Organization UI
  • Review profile: ASSERTIVE
  • Plan: Advanced
  • Run ID: 2b5f7049-0483-4270-8aa8-bc42c2aa7d6b
Commits

Reviewing files that changed from the base of the PR and between 4248912 and 98a4dff.

Files selected for processing: 7

  • docs/SOUNDNESS.adoc
  • lib/codegen.ml
  • lib/typecheck.ml
  • test/dune
  • test/test_intrinsic_shadow.ml
  • test/test_main.ml
  • tools/soundness-anchors.sha256
  • Autofix · Keep fixing CodeRabbit findings and required CI, and resolving merge conflicts

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

Share

@sonarqubecloud

sonarqubecloud Bot commented Dec 1, 2026

Copy link
Copy Markdown

@hyperpolymath
hyperpolymath marked this pull request as ready for review December 1, 2026 18:31
@chatgpt-codex-connector

Copy link
Copy Markdown
Codex Review Summary: ❌ Failed

This comment shows the latest Codex review activity on this pull request.

Review Status Commit Review trigger
📝 Code Review ❌ Failed 2026-12-01T18:31:09.498854Z
We couldn’t complete this review. Comment @codex review to try again.
98a4dff Draft marked ready
ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review" or "@codex security review".

Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings.

@chatgpt-codex-connector

Copy link
Copy Markdown

You have reached your Codex usage limits for code reviews. You can see your limits in the Codex usage dashboard.

@hyperpolymath
hyperpolymath merged commit 0cf73b2 into main Dec 1, 2026
18 checks passed
@hyperpolymath
hyperpolymath deleted the claude/fix-836-intrinsic-shadow branch December 1, 2026 18:31
hyperpolymath pushed a commit that referenced this pull request Dec 1, 2026
…dispatch

#841 (#836) routes every name-matched wasm intrinsic arm through
`intrinsic_callee`, using a stricter `user_binds` (user-defined fns and
consts, not externs). This branch's three Unicode arms carried their own
`user_binds` guard. Resolution:

- lib/codegen.ml: drop this branch's `user_binds` and keep main's; the
  three Unicode arms now match `Some id, _` like every other arm, with no
  per-arm guard.
- test/test_intrinsic_shadow.ml: add shadowing cases for
  utf8_byte_length, code_points and string_from_code_points. Fix the
  arm-coverage gate's name regex to allow digits: `[a-z_]+` could not see
  `utf8_byte_length`, so a digit-bearing intrinsic would have escaped the
  coverage check.
- test/dune: keep both main's `(file ../lib/codegen.ml)` and this
  branch's `../bin/main.exe` dependency.
- docs/UNICODE-STRINGS.adoc: the wasm-shadowing finding is now "fixed
  by #841".
- docs/SOUNDNESS.adoc: stamp to 0cf73b2 (main incl. #841), verified on
  the merged tree: dune runtest --force 811 + 32 + 3 pass; codegen
  corpora 48 + 42 + 8 pass; all 5 guards OK.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01J4QvDfgDTxx9Bumfa2XXcQ
hyperpolymath pushed a commit that referenced this pull request Dec 1, 2026
…adow change

40167ad changed test/test_intrinsic_shadow.ml, the anchor of #841's
ledger row, deliberately: it added shadowing cases for the three Unicode
primitives and let the arm-coverage regex accept digits. The ledger gate
(property 3) correctly flagged the digest drift. This reseals that one
anchor per "Keeping this honest". 40167ad was pushed before this reseal,
so it fails property 3 on its own; this commit restores the gate.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01J4QvDfgDTxx9Bumfa2XXcQ
hyperpolymath pushed a commit that referenced this pull request Dec 1, 2026
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
hyperpolymath pushed a commit that referenced this pull request Dec 1, 2026
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01J4QvDjPsKtu8zU9b32Cv1P
hyperpolymath added a commit that referenced this pull request Dec 1, 2026
…835)

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](https://claude.ai/code)_

---------

Co-authored-by: Claude <noreply@anthropic.com>
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.

wasm: a user fn named like an intrinsic (string_sub, …) is silently replaced by the intrinsic — wrong value

2 participants