Skip to content

fix: avoid Bun NAPI teardown crash on gateway exit#245

Merged
BYK merged 1 commit into
mainfrom
fix/bun-napi-teardown-crash
May 12, 2026
Merged

fix: avoid Bun NAPI teardown crash on gateway exit#245
BYK merged 1 commit into
mainfrom
fix/bun-napi-teardown-crash

Conversation

@BYK
Copy link
Copy Markdown
Owner

@BYK BYK commented May 12, 2026

Summary

  • Fix Bun 1.3.x crash ("A C++ exception occurred") on gateway shutdown caused by NAPI module teardown of onnxruntime-node (loaded by fastembed)
  • Add shared safeExit() utility using libc _exit() via bun:ffi to skip NAPI teardown on the Bun standalone binary
  • Add double-signal guards and graceful embedding worker shutdown

Problem

When the lore standalone Bun binary shuts down via process.exit(), Bun panics with a C++ exception during NAPI module teardown. The fastembed module loads onnxruntime-node (a NAPI addon with C++ bindings) on the main thread. When process.exit() fires, Bun's teardown invokes the C++ destructors which throw.

The codebase already had an inline FFI _exit() workaround in --check-embeddings, but it was not applied to normal shutdown paths.

Changes

File Change
packages/gateway/src/cli/exit.ts New shared safeExit(code) — uses bun:ffi to call libc _exit(), falls back to process.exit() on Node.js
packages/gateway/src/cli/start.ts Use safeExit(), add double-signal guard, shut down embedding worker in shutdown()
packages/gateway/src/cli/run.ts Use safeExit() for all exit paths, add double-signal guard
packages/gateway/src/cli/main.ts Replace 12-line inline FFI block in --check-embeddings with safeExit()

Verification

  • bun run typecheck — passes all 4 packages
  • bun test — 1087 tests pass, 0 failures
  • bun run build — all packages build successfully

Bun 1.3.x panics with a C++ exception when NAPI modules (onnxruntime-node
loaded by fastembed) are torn down during process.exit(). This affects the
standalone lore binary on every normal shutdown.

Fix:
- Add safeExit() utility that uses libc _exit() via bun:ffi to skip NAPI
  teardown entirely. Falls back to process.exit() on Node.js.
- Use safeExit() for all post-shutdown exit paths in start.ts and run.ts.
- Gracefully shut down the embedding worker in shutdown() before exiting.
- Add double-signal guards to prevent concurrent shutdown() from rapid
  Ctrl-C.
- Replace inline FFI _exit block in --check-embeddings with safeExit().
@BYK BYK enabled auto-merge (squash) May 12, 2026 12:26
@BYK BYK merged commit e2ebf9b into main May 12, 2026
7 checks passed
@BYK BYK deleted the fix/bun-napi-teardown-crash branch May 12, 2026 12:27
This was referenced May 13, 2026
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