Skip to content

Fix C emission when a native effect invokes a Bend callback - #1286

Merged
Lorenzobattistela merged 3 commits into
bendlang:mainfrom
mizchi:fix/ffi-runtime-segment-ids
Oct 5, 2026
Merged

Lorenzobattistela merged 3 commits into
bendlang:mainfrom
mizchi:fix/ffi-runtime-segment-ids

Conversation

@mizchi

@mizchi mizchi commented Oct 3, 2026 •

Copy link
Copy Markdown
Contributor

A native C effect should be able to call a callback received from Bend. This can currently fail at compile time because the compiler resolves the runtime helper's ID before registering it.

What you did

Saved the two files below and compiled on upstream main @ 947db722, still the latest HEAD when checked on 2026-10-03:

bend main.bend -o main.c

The C effect calls the Bend callback with 40; the callback adds 2.

What happened

C emission fails before clang runs:

Error: FID(Clo~apply) names no constructor or def

Expected: compilation succeeds and the native program prints 42.

The file

main.bend:

import Base

def native.apply(step: U32 -> U32, value: U32) -> IO(Unit):
  import "./native.c"

def main() -> IO(Unit):
  native.apply(x => (x + 2 : U32), 40)

native.c:

static Term native_apply_run(Env e, Term* f, IoWork* w) {
  (void)w;
  u64 at = task_node(e, FID(Clo~apply), TERM_HOLE, 0, 0);
  e.mem[at] = f[0];
  e.mem[at + 1] = f[1];
  Term result = corpus_eval(e.mem, term_tsk(FID(Clo~apply), at));
  if (err_seen(e.mem)) err_fail("foreign closure application failed");
  printf("%u\n", (u32)result);
  return term_pak(CID(Unit), 0);
}

static void __attribute__((constructor)) native_apply_use(void) {
  io_eff(CID(native.apply), native_apply_run, 0);
}

Why

Clo~apply applies a closure in the generated runtime; it is not declared in the Bend book.

compile_book reads foreign C sources through effect_srcs inside the fixpoint loop, before the runtime segments have been created. When no emitted Bend call has registered Clo~apply yet, c_ids rejects the valid runtime name.

Change

Read the foreign C sources in the final runtime_c call, after every segment and ID exists. This reads each source once and preserves the existing ID assignment order, including user definitions whose C macro names collide with runtime names.

foreign_runtime_apply returns the callback's result as IO(U32) and prints it from Bend with IO.print. Both foreign implementations return the callback's value.

foreign_runtime_apply_tail uses the same C/JS sources with the foreign call as main's only effect. It retains coverage of the original missing-ID failure: adding an IO.bind continuation to print the result can itself register Clo~apply on unpatched main. This test succeeds without output, as an IO main's return value is discarded.

Verification

Local checks against upstream main @ 565d7fde on Apple M5/macOS:

  • The original two-file reproducer and foreign_runtime_apply_tail fail C emission on main with FID(Clo~apply) names no constructor or def. Both compile with this patch; the original reproducer prints 42 with 1/4 threads and GPU off.
  • Both new fixtures and twelve existing controls match their expected output in the interpreter, Bun, Node and C with 1/4 threads: fourteen programs, seventy executions. Controls include ids_unique, name_owned_def, foreign values and namespaces, and the two ownership regressions.
  • Across 851 existing runnable-test candidates, emitted C is byte-identical for 701 programs and JS for 724 programs. The 277 compiler refusals across the two backends are also unchanged.
  • gates/repo.ts: PASS 50/50. comp.ts: 63,951 → 63,938 ttok (cap 64,000, unchanged).

The cluster gates/test.ts could not start because this machine cannot resolve cluster. Full cluster test/perf/safe/ping gates and CUDA were not run locally.

bend --version

Output of bun bend2/main.ts version (tested compiler):

bend 2.0.35

Base: 565d7fdec289b1f2f5f5037bb58b5afb6738ff1d; PR head: 72cfbe97de41add3cb993d924ccc14a37bfbab6b.

uname -sm

Darwin arm64

Apple M5, macOS 26.6.2.

clang --version (the first line)

Apple clang version 21.0.0 (clang-2100.0.123.102)

Created with AI assistance (Codex).

@mizchi mizchi changed the title Foreign C sources can name runtime segments before any emitted call uses them Fix C emission when a native effect invokes a Bend callback Oct 3, 2026
@Lorenzobattistela Lorenzobattistela self-assigned this Oct 4, 2026

@Lorenzobattistela Lorenzobattistela left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks for the report and the repro. The bug is real: foreign C can't name Clo~apply unless the Bend code happens to apply a closure itself.

The cause is order. compile_book reads the .c sources inside the fixpoint loop, before seg_new(IO_EMIT) / seg_new(CLO_APPLY) create the runtime segments. Registering the two names up front works, but it leaves the order as it is. It also hands the unsuffixed macro name to the runtime when a user def's name collides (tests/run/ids_unique and tests/check/name_owned_def swap FID_CLO_APPLY and FID_CLO_APPLY_1). And any future runtime segment would need the same treatment.

Nothing in the loop uses reqs, so the sources can be read where they're used, after every ID exists:

   let was: number;
-  let reqs: string;
   do {
 ...
-    reqs = effect_srcs(fl, ".c", "no .c import: ").join("");
 ...
   return c_ids(fl, runtime_c([tabs, ...desc].join("\n\n"), spins, segs,
-    reqs));
+    effect_srcs(fl, ".c", "no .c import: ").join("")));

This also reads the sources once instead of on every loop iteration.

The budget matters too. On current main (60b6c5f), comp.ts is at 63,979 ttok, and with this PR merged it comes to 64,007, which fails gates/repo.ts. The diff above brings it to 63,966.

I ran the diff above with your two tests on 60b6c5f:

  • repo: 50/50. test: 1545/1545. ping: 46/46. safe: same as main, plus your two foreign tests as unsafe.
  • perf: same as main; the reds were the usual PAR-GPU noise.
  • _run: three runs; the test gate went over the 30 s cap in one of them, the other two passed.
  • Emitted C: byte-identical to main for all 736 programs.
  • Your tests: both print 42 under C, bun, node and the interpreter.

Could you swap the seg_fid lines for this? A few smaller things on the tests:

  • foreign_runtime_emit: nothing in user code needs to spell IO~emit, which is io_spawn's final continuation. The test locks in its private result layout, including the heap_free(e, 0, loc) size class, and its JS twin is just console.log(42). I'd drop it and keep foreign_runtime_apply.
  • foreign_runtime_apply: returning the callback's result to Bend (an IO(U32) effect, printed with IO.print) instead of printf would also check that the value makes it back into Bend. It would also avoid skipping io_out's short-write check.

mizchi added 2 commits October 5, 2026 12:03
Read each source once after segment emission, without pre-registering runtime names or changing ID assignment order. Return the callback result through IO and print it from Bend. Keep a sole-effect regression without an IO.bind continuation, and remove the IO~emit layout test.
@Lorenzobattistela
Lorenzobattistela merged commit 1159f0b into bendlang:main Oct 5, 2026
1 check passed
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.

2 participants