Skip to content

sampling: catch C++ exceptions from sample/apply at the FFI boundary - #1093

Open
GuiBarradas wants to merge 1 commit into
utilityai:mainfrom
GuiBarradas:sampler-catch-ffi-exceptions
Open

sampling: catch C++ exceptions from sample/apply at the FFI boundary#1093
GuiBarradas wants to merge 1 commit into
utilityai:mainfrom
GuiBarradas:sampler-catch-ffi-exceptions

Conversation

@GuiBarradas

Copy link
Copy Markdown

Closes #1082

llama.cpp can throw a C++ exception during sampling, for example when a grammar masks every remaining candidate (a grammar sampler placed after a truncation sampler such as top-k). The exception unwinds across the FFI boundary, Rust cannot catch foreign exceptions, and the process aborts:

fatal runtime error: Rust cannot catch foreign exceptions, aborting

#874 added try/catch wrappers for grammar construction and accept. This extends the same pattern to the sampling path:

  • C++ shim (wrapper_common.cpp/.h): llama_rs_sampler_sample and llama_rs_sampler_apply, wrapping llama_sampler_sample / llama_sampler_apply in try/catch and returning llama_rs_status, mirroring the existing llama_rs_sampler_accept.
  • Rust: LlamaSampler::try_sample and LlamaTokenDataArray::try_apply_sampler, returning a new SamplerSampleError instead of aborting. Gated on the common feature, like try_accept. The existing sample/apply are unchanged.

Verified on Windows (CPU build): the crate compiles, and a chain of [top_k(1), grammar("root ::= \"unlikely\""), dist] that aborted the process via sample now returns Err(SamplerSampleError::FfiError(-3)) via try_sample, with the process surviving. This is the same failure real callers hit (nobodywho-ooo/nobodywho#421, whose generation loop uses sample).

No tests added, since the failure needs a loaded model and the crate's unit tests do not use one. Happy to add one under a feature/env gate if you prefer.

llama.cpp can throw during sampling (for example when a grammar masks
every remaining candidate, which happens when a grammar sampler runs
after a truncation sampler such as top-k). The exception unwinds across
the FFI boundary, which Rust cannot catch, and the process aborts with
"fatal runtime error: Rust cannot catch foreign exceptions".

PR utilityai#874 added try/catch wrappers for grammar construction and accept.
This extends the same pattern to the sampling path: wrap
llama_sampler_sample and llama_sampler_apply in the C++ shim
(llama_rs_sampler_sample / llama_rs_sampler_apply) and expose
LlamaSampler::try_sample and LlamaTokenDataArray::try_apply_sampler,
which return SamplerSampleError instead of aborting.

Closes utilityai#1082
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.

Grammar sampler: C++ exception during sampling crosses the FFI boundary and aborts the process

1 participant